用>缓冲的Python打印语句输出重定向 [英] Python print statements being buffered with > output redirection

查看:67
本文介绍了用>缓冲的Python打印语句输出重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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:

  1. 使用-u命令行开关
  2. 在每次写入后刷新的对象中包装sys.stdout
  3. 设置PYTHONUNBUFFERED env var
  4. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
  1. Use the -u command line switch
  2. Wrap sys.stdout in an object that flushes after every write
  3. Set PYTHONUNBUFFERED env var
  4. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

这篇关于用>缓冲的Python打印语句输出重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆