8

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()
Saravanabalagi Ramachandran
  • 8,551
  • 11
  • 53
  • 102
  • one way is to store it as `default_sysout` before assigning to `outfile` and then assign it back using `default_sysout` after outfile is closed, but just in case I didn't where can I get it? – Saravanabalagi Ramachandran Jul 14 '18 at 14:21

3 Answers3

8

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) 
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
6

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)
VPfB
  • 14,927
  • 6
  • 41
  • 75
1

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.