所以我知道
Redirecting stdout to "nothing" in python
您可以抑制打印语句。但是是否有可能稍后撤消该命令,以便在特定点之后,打印语句确实会再次打印?
例如,假设我想打印“b”而不是“a”。
我会这样做:
import os
f = open(os.devnull, 'w')
sys.stdout = f
print("a")
# SOME COMMAND
print("b")
有人能告诉我什么是“某些命令”吗?
最佳答案
原始sys.stdout
总是保存在sys.__stdout__
中:
sys.stdout = sys.__stdout__
但是,文档确实指出,首选显式保存原始 sys.stdout
:
It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object.
关于Python-撤消标准输出重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336087/