我想利用子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)