Reputation: 479
In below programming, first we redirect all print to log files, then we close the file object and then again restort print command to interactive prompt.
import sys
temp = sys.stdout # store original stdout object for later
sys.stdout = open('log.txt', 'w') # redirect all prints to this log file
print("testing123") # nothing appears at interactive prompt
print("another line") # again nothing appears. it's written to log file instead
sys.stdout.close() # ordinary file object
sys.stdout = temp # restore print commands to interactive prompt
print("back to normal") # this shows up in the interactive prompt
Why python doesn't support a method something like this, to restore the command to interactive mode
sys.stdout.default()
Upvotes: 0
Views: 353
Reputation: 148965
Well it almost exists: sys.stdout = sys.__stdout__
reset stdout to its original value at the start of program.
Simply it but might not do what you want. You might stack sys.stdout
redirections, and in that case, it would make sense to revert to previous redirection instead of the original one. A real use case for it in the IDLE interactive interpretor. The original stdout will be None on Windows because it is a GUI program, and will be directed to the terminal from where you started it on Linux. In either case after a redirection, you certainly do not want to use that default original value, but the one that was setup by IDLE.
That is the reason why you should always save the original standard output when you redirect it, and restore it when you no longer need the redirection.
Upvotes: 1