簡體   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