[英]Unable to pipe python output to program
I want to pipe stdout from python to another program, but I am faceing a problem where my stdout is not piped.我想将标准输出从 python 管道传输到另一个程序,但我面临一个问题,我的标准输出没有通过管道传输。
I have it shortened down to a simple sample:我将它缩短为一个简单的示例:
import time
while True:
print("Hello!")
time.sleep(1)
I check it with cat like so:我像这样用猫检查它:
./my_python_script.py | cat
And then I get nothing at all.然后我什么也得不到。
Strange thing is that it works just fine if i remove the sleep command.奇怪的是,如果我删除 sleep 命令,它就可以正常工作。 However, I do not want to pipe the output that fast, so I would really like to sleep for a second.
但是,我不想那么快地通过管道传输输出,所以我真的很想睡一会儿。
I checked with the corresponding bash script:我检查了相应的bash脚本:
while true; do
echo "Hello!"
sleep 1
done
And that works like a charm too.这也很有魅力。 So any idea as to why the python script does not pipe the output as expected?
那么关于为什么python脚本没有按预期管道输出的任何想法? Thanks!
谢谢!
You'll need to flush the stdout:您需要刷新标准输出:
import time
import sys
while True:
print("Hello!")
sys.stdout.flush()
time.sleep(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.