在程序中使用python(如python -u)中的无缓冲stdout [重复]
问题内容:
这个问题已经在这里有了答案 :
8年前关闭。
可能重复:
Python输出缓冲
有什么办法可以在我的代码中获得运行python -u的效果?如果失败,我的程序可以检查它是否在-
u模式下运行,如果没有退出并显示错误消息?这是在Linux(Ubuntu 8.10服务器)上
问题答案:
我能想到的最好的方法是:
>>> import os
>>> import sys
>>> unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)
>>> unbuffered.write('test')
test>>>
>>> sys.stdout = unbuffered
>>> print 'test'
test
在GNU / Linux上测试。似乎它也应该在Windows上工作。如果我知道如何重新打开sys.stdout,它将容易得多:
sys.stdout = open('???', 'w', 0)
参考:
http :
//docs.python.org/library/stdtypes.html#file-objects
http://docs.python.org/library/functions.html#open
http://docs.python.org/library/ os.html#file-object-
creation
[编辑]
请注意,覆盖sys.stdout可能会更好。