It's possible to "intercept" calls to sys.stdout.write
with a mock_write
function which writes the text to a file and calls the original real_write
function, afterwards.
import sys
def mock_write(text):
with open("test.txt", "a") as fh:
fh.write(text)
real_write = type(sys.stdout).write
real_write(sys.stdout, text)
sys.stdout.write = mock_write
print("TEST")
It's rather unlikely, but this solution might stop working with future versions of Python in case the original write
method of sys.stdout
is changed and becomes incompatible with our mock function.
Also, some functions, like subprocess.Popen
for example, don't use sys.stdout.write
but directly write to the fileno
file descriptor of a file object. So the mock write won't catch that output.
By the way, this approach of replacing existing methods of an object with another function has its limits: For instance, it won't work with magic methods and __slots__
. See Adding a Method to an Existing Object Instance for example, for further reading.