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()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With