阻塞防止子PIPE

问题描述 投票:0回答:1

我想利用子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
python multithreading subprocess pipe strace
1个回答
1
投票

这里是一个简短的工作示例:

请注意:

  • strace写入stderr(除非-o filename给出)
  • 所有参数必须是字符串(或字节),即PID必须被给定为“1”
  • 行缓冲只适用于通用换行符
  • 你必须是根追查过程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)
© www.soinside.com 2019 - 2024. All rights reserved.