-1

I know that if you want to redirect stdout to a file, you can simply do it like this.

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

But how can I switch back stdout to write on the terminal?

MetallicPriest
  • 29,191
  • 52
  • 200
  • 356
  • 4
    first `temp = sys.stdout` and later `sys.stdout = temp` – furas Dec 09 '19 at 20:03
  • 1
    yous write at the end `sys.stdout = sys.__stdout__` ( https://stackoverflow.com/questions/14245227/python-reset-stdout-to-normal-after-previously-redirecting-it-to-a-file ) So I think your question is a duplicate – gelonida Dec 09 '19 at 20:07
  • 1
    Does this answer your question? [Python - reset stdout to normal, after previously redirecting it to a file](https://stackoverflow.com/questions/14245227/python-reset-stdout-to-normal-after-previously-redirecting-it-to-a-file) – gelonida Dec 09 '19 at 20:08

2 Answers2

1

You can assign it to variable and later assing it back

temp = sys.stdout 
print('console')

sys.stdout = open('output.txt', 'w')
print('file')

sys.stdout = temp
print('console')

You can also find examples how to use it with context manager so you can change it using with

import sys
from contextlib import contextmanager

@contextmanager
def custom_redirection(fileobj):
    old = sys.stdout
    sys.stdout = fileobj
    try:
        yield fileobj
    finally:
        sys.stdout = old

# ---

print('console')

with open('output.txt', 'w') as out:
     with custom_redirection(out):
          print('file')

print('console')

Code from: Python 101: Redirecting stdout

Currently you can even find redirect_stdout in contextlib

import sys
from contextlib import redirect_stdout

print('console')

with open('output.txt', 'w') as out:
    with redirect_stdout(out):
        print('file')

print('console')

BTW: if you want to redirect all text to file then you can use system/shell for this

$ python script.py > output.txt
furas
  • 134,197
  • 12
  • 106
  • 148
0

A better bet is to simply write to the file when you want.

with open('samplefile.txt', 'w') as sample:
    print('write to sample file', file=sample)

print('write to console')

reassigning the stdout would mean you need to track the previous file descriptor and assign it back whenever you want to send text to the console.

If you really must reassign you could do it like this.

holder = sys.stdout
sys.stdout = open(fpath, 'w')
print('write something to file')
sys.stdout = holder
print('write something to console')
JBirdVegas
  • 10,855
  • 2
  • 44
  • 50
  • This is often the prefered solution, but in some cases one really wants to redirect stdout and nothing else (for example because one wants to call existing code that uses print) – gelonida Dec 09 '19 at 20:07