[英]Grep python output stream (tried print and stdout)
This answer says it's as simple as: 这个答案说起来很简单:
pipe python logging stdout stream output to grep 管道python记录stdout流输出到grep
python main.py 2>&1 | grep INFO
I have the following file, which I've tried with print()
and sys.stdout.write()
. 我有以下文件,我已尝试使用print()
和sys.stdout.write()
。
import sys
from time import sleep
while True:
sleep(1)
sys.stdout.write("this is a thing")
# Also tried print()
I'm trying to collect "thing"
with: 我正在尝试通过以下方式收集"thing"
:
python output.py 2>&1 | grep "thing"
You need to use the newline
and better to flush
the stdout
. 您需要使用newline
并且更好地flush
stdout
。
import sys
from time import sleep
while True:
sys.stdout.write("this is a thing\n")
sys.stdout.flush()
sleep(1)
while True:
sleep(1)
print("this is a thing", flush=True)
Will work as well, no need to hustle with stdout directly. 也将正常工作,无需直接与stdout争吵。
By default print
uses buffer for output, just by flushing it every call you'll have semi-realtime streaming. 默认情况下, print
使用缓冲区进行输出,只需将每个调用都刷新为半实时流即可。
as an addition: if the output would have gone to stderr, whats not the case here, you would still see it in the terminal, because the pipe | 另外:如果输出将发送到stderr,在这里不是这种情况,您仍然会在终端中看到它,因为管道| only redirects stdout if you don't specify otherwise the rest goes unfiltered to the terminal 仅在未指定的情况下重定向stdout,否则其余部分将不过滤到终端
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.