why does sys.stdout = None work?

穿精又带淫゛_ 提交于 2019-11-27 06:57:35

问题


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

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?

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.


回答1:


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;


来源:https://stackoverflow.com/questions/49757674/why-does-sys-stdout-none-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!