Grep python 输出流(尝试打印和标准输出)
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,这里不是这种情况,您仍然会在终端中看到它,因为管道 |如果您没有另外指定,则仅重定向标准输出
其余的未过滤到终端
这个答案说它很简单:
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,这里不是这种情况,您仍然会在终端中看到它,因为管道 |如果您没有另外指定,则仅重定向标准输出 其余的未过滤到终端