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