防止子进程 PIPE 阻塞

Prevent subprocess PIPE from blocking

我想利用子进程 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
  • 所有参数必须是字符串(或字节),即 pid 必须为“1”
  • 行缓冲仅适用于通用换行符
  • 您必须是 root 才能跟踪进程 1

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)