32

At the beginning of my python program I have the following line:

sys.stdout = open('stdout_file', 'w')

Halfway through my program I would like to set stdout back to the normal stdout. How do I do this?

tadasajon
  • 14,276
  • 29
  • 92
  • 144
  • 2
    Related: http://stackoverflow.com/questions/14197009/how-can-i-redirect-print-output-of-a-function-in-python/14197079#14197079 – mgilson Jan 09 '13 at 19:52
  • See also [How to capture stdout output from a Python function call? - Stack Overflow](https://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call) for other options e.g. context manager. – user202729 Nov 16 '22 at 09:49
  • See also [How to capture stdout output from a Python function call? - Stack Overflow](https://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call) for other options e.g. context manager. – user202729 Nov 16 '22 at 09:50

4 Answers4

48

The original stdout can be accessed as sys.__stdout__. This is documented.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • I use this style (where there are no namespace conflicts) whenever I overload any module attribute. eg `io.__file__ = io.file; def io_file(*args, **kwargs): ... else return io.__file__(*args, **kwargs) ; io.file = io_file` – ThorSummoner Apr 24 '16 at 06:41
  • Hm, this is not helpful if I only overwrite one method of stderr though (`sys.stderr.write = logger.error` for example) – xjcl Feb 15 '21 at 13:04
  • 1
    @xjcl: First, the question is asking about replacing stdout, not replacing individual methods on it. Second, it's probably not a great idea to do that; instead just replace the whole object with a new one that has the method you want. You can try it if you want but monkeypatching individual methods on objects isn't the kind of thing that's going to be supported to the same degree that replacing stream objects is. – BrenBarn Feb 19 '21 at 06:30
  • Thank you, this helped me finish some code! – Jessie Wilson May 13 '22 at 16:13
6

Another common practice is to store the default stdout and / or stdin and then return them once you are finished with sending your output / input to custom streams. For instance:

orig_stdout = sys.stdout
sys.stdout = open('stdout_file', 'w')
sys.stdout = orig_stdout
trozzel
  • 479
  • 5
  • 12
5

The same holds for stderr, of course. At the end, these lines are needed to get the original streams.

sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
Philipp
  • 222
  • 3
  • 9
1

open file and exchange sys variable with file variable

f = open("sample.txt", "w")

sys.stdout, f = f, sys.stdout
print("sample", flush=True)

and take it back

f, sys.stdout = sys.stdout, f
print("sample")
armancj2
  • 108
  • 1
  • 4