如何在文件和终端之间切换 sys.stdout?

How to toggle sys.stdout between a file and terminal?

我知道如果你想将 stdout 重定向到一个文件,你可以简单地这样做。

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

但是如何切换回 stdout 以在终端上写入?

更好的选择是在需要时直接写入文件。

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

print('write to console')

重新分配 stdout 意味着您需要跟踪之前的文件描述符,并在您想将文本发送到控制台时重新分配它。

如果你真的必须重新分配,你可以这样做。

holder = sys.stdout
sys.stdout = open(fpath, 'w')
print('write something to file')
sys.stdout = holder
print('write something to console')

您可以将它赋值给变量,然后再赋值给它

temp = sys.stdout 
print('console')

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

sys.stdout = temp
print('console')

您还可以找到如何将它与上下文管理器一起使用的示例,以便您可以使用 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')

代码来自:Python 101: Redirecting stdout

目前您甚至可以在 contextlib

中找到 redirect_stdout
import sys
from contextlib import redirect_stdout

print('console')

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

print('console')

顺便说一句: 如果你想将所有文本重定向到文件,那么你可以使用 system/shell

$ python script.py > output.txt