grep的蟒输出流(试图打印和stdout)

问题描述 投票:2回答:3

这个回答说,这是简单的:

pipe python logging stdout stream output to 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"

python grep stdout
3个回答
2
投票

您需要使用newline,更好地flushstdout

import sys
from time import sleep

while True:
    sys.stdout.write("this is a thing\n")
    sys.stdout.flush()
    sleep(1)

1
投票
while True:
    sleep(1)
    print("this is a thing", flush=True)

也能发挥作用,没有必要与标准输出直接喧嚣。

默认情况下,print使用缓冲区输出,只需冲洗它的每一个打电话给你将有半实时流。


0
投票

作为加法:如果输出会去到stderr,什么不是这里的情况下,你仍然会看到它的终端,因为管道|只有将stdout重定向如果不指定,否则其余部分则未过滤到终端

© www.soinside.com 2019 - 2024. All rights reserved.