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()

Upvotes: 8

Views: 6023

Answers (3)

snakecharmerb
snakecharmerb

Reputation: 55679

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) 

Upvotes: 8

VPfB
VPfB

Reputation: 17282

In Python3 use redirect_stdout; a similar case is given as an example:

To send the output of help() to a file on disk, redirect the output to a regular file:

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)

Upvotes: 6

Anubhav Srivastava
Anubhav Srivastava

Reputation: 229

As per the answer here you don't need to save a reference to the old stdout. Just use sys.__stdout__.

Also, you might consider using with open('filename.txt', 'w+') as f and using f.write instead.

Upvotes: 1

Related Questions