[英]Prevent subprocess PIPE from blocking
我想利用子Popen
Popen在Linux上調用strace。 我還想實時捕獲strace輸出的每一行。
為此,我提出了以下代碼,但是由於某種原因,我無法使其正常運行。 我只有在終止程序后才能得到輸出。
from threading import Thread
from queue import Queue, Empty
pid = 1
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
p = Popen(["strace", "-p", pid], stdout=subprocess.PIPE, bufsize=1)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()
try:
line = q.get_nowait()
print("Got it! "+line)
except Empty:
pass
這是一個簡短的工作示例:
請注意:
strace
寫入stderr
(除非給出-o filename
) import subprocess
PID = 1
p = subprocess.Popen(
["strace", "-p", str(PID)],
stdin=subprocess.DEVNULL, stderr=subprocess.PIPE,
universal_newlines=True, bufsize=1)
for line in p.stderr:
line = line.rstrip()
print(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.