在程序内部实现无缓冲的stdout输出(类似python -u)
有没有什么方法可以在我的代码里实现运行 python -u
的效果?如果不行,我的程序能不能检查一下自己是不是在 -u
模式下运行,如果不是就显示一个错误信息并退出?这是在Linux(Ubuntu 8.10 Server)上。
4 个回答
9
假设你在使用Windows系统:
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
... 如果你在使用Unix系统的话:
fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
fl |= os.O_SYNC
fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl)
(Unix的内容是从评论中的解决方案复制过来的,而不是直接链接。)
40
你可以在脚本的开头加上一个参数 -u,这样就可以了:
#!/usr/bin/python -u
51
我能想到的最好办法是:
>>> 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之前,最好先把它关闭。