PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

[FIXED] How to get last python output?

 August 13, 2022     console, output, printing, python     No comments   

Issue

I´m trying to get last python output and I dont know how to do it.

Basically what Iím trying to do is detect the last output so, for example:

print("Hello World")
last_output = get_last_output()
print() # For avoiding confutions

print(last_output)
# Would print "\n"


print("Hello World", end="")
last_output = get_last_output()
print() # For avoiding confutions

print(last_output)
# Would print "Hello World"

I would also love this awnser would work independently of the console


Solution

Assuming "the last output" is the last not empty string written to sys.stdout, one option is to assign an object with the write(data) and flush() methods to sys.stdout, so you can save what should be the output:

import sys


class StdoutHandler:
    def __init__(self):
        self.last_output = ""
    
    def start(self):
        self._handled_stdout = sys.stdout
        sys.stdout = self
    
    def write(self, data: str):
        # write(data="") is called for the end kwarg in print(..., end="")
        if data:
            self.last_output = data
            self._handled_stdout.write(data)

    def end(self):
        sys.stdout = self._handled_stdout
    
    def flush(self):
        self._handled_stdout.flush()



stdout_handler = StdoutHandler()
stdout_handler.start()


print("Hello World")
last_output = stdout_handler.last_output
print(repr(last_output))
# Prints '\n'


print("Hello World", end="")
last_output = stdout_handler.last_output
print()
print(repr(last_output))
# Prints 'Hello World'

print("Hello", "World", end="")
last_output = stdout_handler.last_output
print()
print(repr(last_output))
# Prints 'World'

I got the idea from How to duplicate sys.stdout to a log file?

Disclaimer: @Baelfire18 asked me to help him answer this question



Answered By - Benjamín V
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing