gpt4 book ai didi

python - 为什么 sys.stdout = None 有效?

转载 作者:太空狗 更新时间:2023-10-29 20:48:53 33 4
gpt4 key购买 nike

我可以通过这种方式静音和恢复 sys.stdout:

import sys
sys.stdout = None
print('hello') # does not write to stdout
sys.stdout = sys.__stdout__
print('hello') # writes to stdout

我知道我最好使用 contextlib.redirect_stdout这可能会做类似的事情,但我的问题是:为什么上面的代码有效?

我假设 python 会调用像 sys.stdout.write() 这样的东西,所以无论我用什么替换 sys.stdout 都应该有一个 write 方法(例如 io.StringIO )至少。

最佳答案

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;

关于python - 为什么 sys.stdout = None 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49757674/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com