How to reset stdout to the normal stdout after temporarily reassigning it?
I have a script that reassigns stdout to print a file like this:
sys.stdout = open('output_file', 'w')
Later I want to reset it back to normal and I use this:
sys.stdout = sys.__stdout__
But it doesn't work. The output doesn't go the file any longer but it also doesn't go to the console. It seems to just disappear. I have to restart the app to get the output working properly again.
I noticed this previous post where omz mentioned a special StdoutCatcher class needed to allow Pythonista to redirect output to the console. I'm guessing this is involved in why sys.__stdout__ doesn't do what it normally would.
Is there something I can do in my script to restore stdout to (Pythonista's version of) working properly again? Can StdoutCatcher be used explicitly for this?
Just save the current stdout to a variable before reassigning it:
default_stdout = sys.stdout file_handle = open('output_file', 'w') try: sys.stdout = file_handle sys.stdout.write('foo bar') finally: # make sure to restore stdout, even if an exception occurs. sys.stdout = default_stdout
Too easy! Thanks!