使用 tee 从 python 获取实时打印语句 [英] Using tee to get realtime print statements from python
问题描述
我有一个看起来像这样的 python 脚本:
I have a python script that looks something like this:
for item in collection:
print "what up"
#do complicated stuff that takes a long time.
在 bash 中,我通过执行以下操作来运行此脚本:
In bash, I run this script by doing the following:
$ python my.py | tee my_file.txt
然而,我在 bash 中看到的只是一个空行,直到程序完成.然后,所有的打印语句都集中在一起.
However, all I see in bash is a blank line until the program finishes. Then, all of the print statements come all at one.
这是tee的预期操作吗?我可以使用 tee 实时查看输出吗?
Is this the expected operation of tee? Can I use tee to see the output in real-time?
推荐答案
Python 与许多程序一样,试图尽量减少它调用 write
系统调用的次数.它通过在将多个 print
语句的输出实际写入其标准输出文件之前收集它们来实现这一点.这个过程称为缓冲输出.
Python, like many programs, tries to minimize the number of times it calls the write
system call. It does this by collecting the output of several print
statements before it actually writes them to its standard output file. This process is called buffering the output.
当 Python 连接到终端时,它不会缓冲其输出.这是有道理的,因为终端的人希望立即看到输出.
When Python is connected to a terminal, it doesn't buffer its output. This makes sense, because the human at the terminal wants to see the output right away.
当 Python 写入文件(或管道)时,它会缓冲其输出.这也是有道理的,因为在过程完成之前没有人会看到输出
When Python is writing to a file (or a pipe), it does buffer its output. This also makes sense, because no one will see the output until the process is complete
每当您想强制 Python 将其缓冲输出写入其标准输出文件时,您都可以通过调用 sys.stdout.flush()
来破坏此优化.
You can defeat this optimization by calling sys.stdout.flush()
whenever you want to force Python to write its buffered output to its standard output file.
在你的情况下,试试这个:
In your case, try this:
import sys
...
for item in collection:
print "what up"
sys.stdout.flush()
#do complicated stuff that takes a long time.
这篇关于使用 tee 从 python 获取实时打印语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!