Python:将 sys.stdout 恢复为默认值

Python: Revert sys.stdout to default

我想将输出写入文件,因此我做到了

sys.stdout = open(outfile, 'w+')

但是我想在写入文件后打印回控制台

sys.stdout.close()
sys.stdout = None

我得到了

AttributeError: 'NoneType' object has no attribute 'write'

显然默认输出流不能是None,所以我怎么说Python:

sys.stdout = use_the_default_one()

根据回答 here,您不需要保存对旧标准输出的引用。只需使用 sys.__stdout__.

此外,您可以考虑使用 with open('filename.txt', 'w+') as f 并改用 f.write

您可以通过重新分配给 sys.__stdout__ 来恢复到原始流。

来自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.

可以使用 redirect_stdout 上下文管理器而不是手动重新分配:

import contextlib

with contextlib.redirect_stdout(myoutputfile):
    print(output) 

(有个类似的redirect_stderr)

更改 sys.stdout 具有全局效果。例如,这在多线程环境中可能是不受欢迎的。它也可能被视为简单脚本中的过度工程。一种本地化的替代方法是通过其 file 关键字参数将输出流传递给 print

print(output, file=myoutputfile) 

在Python3中使用redirect_stdout;以类似案例为例:

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)