为什么 sys.stdout = None 工作? [英] why does sys.stdout = None work?
本文介绍了为什么 sys.stdout = None 工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过这种方式静音和恢复sys.stdout
:
i can silence and restore sys.stdout
this way:
import sys
sys.stdout = None
print('hello') # does not write to stdout
sys.stdout = sys.__stdout__
print('hello') # writes to stdout
我知道我最好使用 contextlib.redirect_stdout
可能做了类似的事情,但我的问题是:为什么上面的代码有效?
i know i'd better be using contextlib.redirect_stdout
which probably does something similar but my question is: why does the above code work?
我假设 python 会调用诸如 sys.stdout.write()
之类的东西,所以无论我用什么替换 sys.stdout
都应该有一个 write
方法(例如 io.StringIO
) 至少.
i'd have assumed python would call things like sys.stdout.write()
so whatever i replace sys.stdout
with should have a write
method (like e.g. io.StringIO
) at least.
推荐答案
print
has an explicit check for None
.
/* sys.stdout may be None when FILE* stdout isn't connected */
if (file == Py_None)
Py_RETURN_NONE;
这篇关于为什么 sys.stdout = None 工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文