[英]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__
来恢复到原始流。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.