繁体   English   中英

Grep python输出流(尝试打印和stdout)

[英]Grep python output stream (tried print and stdout)

这个答案说起来很简单:

管道python记录stdout流输出到grep

python main.py 2>&1 | grep INFO

我有以下文件,我已尝试使用print()sys.stdout.write()

import sys
from time import sleep

while True:
    sleep(1)
    sys.stdout.write("this is a thing")
    # Also tried print()

我正在尝试通过以下方式收集"thing"

python output.py 2>&1 | grep "thing"

您需要使用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)

也将正常工作,无需直接与stdout争吵。

默认情况下, print使用缓冲区进行输出,只需将每个调用都刷新为半实时流即可。

另外:如果输出将发送到stderr,在这里不是这种情况,您仍然会在终端中看到它,因为管道| 仅在未指定的情况下重定向stdout,否则其余部分将不过滤到终端

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM