我想利用子进程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
答案 0 :(得分:1)
这是一个简短的示例:
请注意:
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)