用>缓冲的Python打印语句输出重定向 [英] Python print statements being buffered with > output redirection
问题描述
我正在用python做打印语句.我正在像这样执行我的脚本:
I'm doing print statements in python. I'm executing my script like so:
python script.py > out.log nohup &
打印语句不是全部显示在out.log
中,但是程序运行正常.
The print statements are not all showing up in out.log
but the program is finishing ok.
该行代码在.sh
文件中
我通过执行./script.sh
That line of code is in an .sh
file
I execute by doing ./script.sh
更新:该日志确实会获取所有数据,但要等到打印出特定的行数之后才能获取.它似乎正在缓冲输出.
Update: The log does get all the data but not until a certain # of lines are printed. It would appear to be buffering the output.
推荐答案
将stdout发送到tty时,它将被行缓冲并刷新每一行,但是当重定向到文件或管道时,它将被完全缓冲并且只会在溢出缓冲区时定期刷新.
When stdout is sent to a tty it will be line buffered and will be flushed every line, but when redirected to a file or pipe it'll be fully buffered and will only be flushed periodically when you overrun the buffer.
如果要立即显示输出,则必须在每行之后添加sys.stdout.flush()
调用,或者完全禁用缓冲.有关执行后者的方法,请参见禁用输出缓冲:
You'll have to add sys.stdout.flush()
calls after each line if you want the output to be immediately visible, or disable buffering entirely. See Disable output buffering for ways to do the latter:
- 使用
-u
命令行开关 - 在每次写入后刷新的对象中包装
sys.stdout
- 设置
PYTHONUNBUFFERED
env var -
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
- Use the
-u
command line switch - Wrap
sys.stdout
in an object that flushes after every write - Set
PYTHONUNBUFFERED
env var sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
这篇关于用>缓冲的Python打印语句输出重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!