有没有办法在我的代码中获得运行python -u
的效果?如果无法做到这一点,那么我的程序是否可以检查是否在-u
模式下运行,并在没有时退出并显示错误消息?这是在Linux(Ubuntu 8.10 Server)上的情况。
有没有办法在我的代码中获得运行python -u
的效果?如果无法做到这一点,那么我的程序是否可以检查是否在-u
模式下运行,并在没有时退出并显示错误消息?这是在Linux(Ubuntu 8.10 Server)上的情况。
我能想到的最好方案是:
>>> 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,那将会更容易:
在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。
stdout
still lives in sys.__stdout__
- Thomas AhleValueError: can't have unbuffered text I/O
。 - vbo你可以在shebang行中传递-u参数:
#!/usr/bin/python -u
#!/usr/bin/env python -u
。我得到以下错误/usr/bin/env: python -u: No such file or directory
。如果我去掉-u
,它就能正常工作。 - Aaron McDaid-S
选项传递给env
命令,像这样:#!/usr/bin/env -S python3 -u
- Nico Villanuevamsvcrt.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)
编辑 (2020年10月)。如在此回答的注释中指出的那样,在Python3中,stderr也是被缓冲的。
您可以利用stderr从不缓冲的特性,尝试将stdout重定向到stderr:
import sys
#buffered output is here
doStuff()
oldStdout = sys.stdout
sys.stdout = sys.stderr
#unbuffered output from here on
doMoreStuff()
sys.stdout = oldStdout
#the output is buffered again
doEvenMoreStuff()
PYTHONUNBUFFERED
环境变量为任何非空字符串。这不在你的代码中 - 必须在Python解释器启动之前设置 - 但比修改启动脚本以添加 "-u" 更容易。 - Beni Cherniavsky-Paskin