Python 防止子流程管道堵塞
我想利用subprocessPython 防止子流程管道堵塞,python,multithreading,subprocess,pipe,strace,Python,Multithreading,Subprocess,Pipe,Strace,我想利用subprocessPopen在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''):
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文件名
- 所有参数必须为字符串(或字节),即pid必须为“1”
- 行缓冲仅适用于通用换行符
- 您必须是root才能跟踪进程1
安装信号不是更好吗?嗨!我不想跟踪Python程序,所以安装信号没有用,不是吗?队列的预期用途是什么?您可以直接从子进程输出中读取。队列是用来作为缓冲区从单独的线程读取输出的。我也在没有排队的情况下试过了,但也没用。效果很好!非常感谢你!
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)