简体   繁体   English

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

[英]Python: Revert sys.stdout to default

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 :显然默认输出流不能是None那么我该怎么说 Python

sys.stdout = use_the_default_one()

You can revert to the original stream by reassigning to sys.__stdout__ .您可以通过重新分配给sys.__stdout__来恢复到原始流。

From the docs文档

contain[s] the original values of stdin, stderr and stdout at the start of the program.在程序开始时包含 [s] 标准输入、标准错误和标准输出的原始值。 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.它们在完成期间使用,无论 sys.std* 对象是否已重定向,都可以用于打印到实际的标准流。

The redirect_stdout context manager may be used instead of manually reassigning:可以使用redirect_stdout上下文管理器代替手动重新分配:

import contextlib

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

(there is a similar redirect_stderr ) (有一个类似的redirect_stderr

Changing sys.stdout has a global effect.更改sys.stdout具有全局影响。 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:一种本地化的替代方法是通过其file关键字参数传递输出流以进行打印

print(output, file=myoutputfile) 

In Python3 use redirect_stdout ;在 Python3 中使用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:要将 help() 的输出发送到磁盘上的文件,请将输出重定向到常规文件:

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)

As per the answer here you don't need to save a reference to the old stdout.根据此处的答案您无需保存对旧标准输出的引用。 Just use sys.__stdout__.只需使用 sys.__stdout__。

Also, you might consider using with open('filename.txt', 'w+') as f and using f.write instead.此外,您可以考虑使用with open('filename.txt', 'w+') as f并使用f.write代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM