[英]Grep python output stream (tried print and stdout)
這個答案說起來很簡單:
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.