[英]How to get output in the subprocess in real time?
我試圖讓tail -f /var/log/syslog在變量data0中播放結果但沒有成功。
from subprocess import Popen,PIPE
def exit_data():
with Popen(['tail -f', '/var/log/syslog'],stdout=PIPE,stderr=PIPE) as b:
out,err = b.communicate()
data0 = out.decode('utf-8')
return data0
從文檔中,調用communicate()
方法將阻塞,直到子進程退出。 由於您正在調用tail -f
,直到tail
進程退出時才會返回,這只會在 EOF、錯誤等情況下發生。所以您什么都看不到。
看起來您想在 Python 中連續打印tail
子進程的 output。為此,您需要啟動該進程,並不斷(在循環中)從其標准輸出讀取並打印結果。 不要調用communicate()
,而只是從stdout
屬性讀取,這是一個標准文件,如 object。
例如,此腳本為reader.py
:
import subprocess as sp
# A dummy file to tail
filename = "/tmp/logfile"
proc = sp.Popen(
["tail", "-f", filename],
stdout=sp.PIPE,
stderr=sp.PIPE,
text=True, # I'm using text files, may not apply to your case
)
try:
while True:
print(proc.stdout.readline().rstrip("\n"))
except KeyboardInterrupt:
print("Received interrupt, exiting")
proc.terminate()
proc.wait()
print("Reaped child")
您可以通過在另一個 Python 腳本中運行以下代碼片段來測試這項工作,將其命名為writer.py
:
import time
N_LINES = 100
filename = "/tmp/logfile"
with open(filename, "wt") as f:
for _ in range(N_LINES):
time.sleep(1)
f.write("a new line of data\n")
f.flush()
運行它們:
$ python3 writer.py &
$ python3 reader.py
a new line of data
a new line of data
a new line of data
a new line of data
a new line of data
^CReceived interrupt, exiting
Reaped child
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.