Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Revert sys.stdout to default

I wanted to write output to file and hence I did

sys.stdout = open(outfile, 'w+')

But then I wanted to print back to console after writing to file

sys.stdout.close()
sys.stdout = None

And I got

AttributeError: 'NoneType' object has no attribute 'write'

Obviously the default output stream can't be None, so how do I say to Python:

sys.stdout = use_the_default_one()
like image 667
Saravanabalagi Ramachandran Avatar asked Jul 14 '18 14:07

Saravanabalagi Ramachandran


1 Answers

You can revert to the original stream by reassigning to sys.__stdout__.

From the docs

contain[s] the original values of stdin, stderr and stdout at the start of the program. They are used during finalization, and could be useful to print to the actual standard stream no matter if the sys.std* object has been redirected.

The redirect_stdout context manager may be used instead of manually reassigning:

import contextlib

with contextlib.redirect_stdout(myoutputfile):
    print(output) 

(there is a similar redirect_stderr)

Changing sys.stdout has a global effect. This may be undesirable in multi-threaded environments, for example. It might also be considered as over-engineering in simple scripts. A localised, alternative approach would be to pass the output stream to print via its file keyword argument:

print(output, file=myoutputfile) 
like image 177
snakecharmerb Avatar answered Oct 20 '22 05:10

snakecharmerb