Python - Print Stream Redirection

Manual stream redirection

The sys.stdout print equivalent is the basis of a common technique in Python.

In general, print and sys.stdout are directly related as follows. This statement:

print(X, Y)                    # Or, in 2.X: print X, Y 

is equivalent to the longer:

import sys 
sys.stdout.write(str(X) + ' ' + str(Y) + '\n') 

To make your print operations send their text to other places. For example:

import sys 
sys.stdout = open('log.txt', 'a')       # Redirects prints to a file 
print(x, y, x)                          # Shows up in log.txt 

Here, we reset sys.stdout to a manually opened file named log.txt in append mode.

Related Topic