我使用subprocess.Popen
和Popen.communicate
来运行超时的进程,类似于给出的建议是这个问题:
因此我使用以下代码:
with Popen(["strace","/usr/bin/wireshark"], stdout=subprocess.PIPE,stderr=subprocess.PIPE, preexec_fn=os.setsid) as process:
try:
output = process.communicate(timeout=2)[0]
print("Output try", output)
except TimeoutExpired:
os.killpg(process.pid, signal.SIGINT) # send signal to the process group
output = process.communicate()[0]
print("Output except",output)
return output
我得到以下输出:
Output except b''
和b''
作为返回值。
即使引发TimeoutExpired
异常,如何获取进程的输出(输出直到被杀死)?
答案 0 :(得分:0)
Popen
个对象有一个kill
方法,为什么不使用它呢?一个进程被杀死后,你可以只读它的标准输出。这有用吗?
with Popen(["strace","/usr/bin/wireshark"], stdout=subprocess.PIPE,stderr=subprocess.PIPE, preexec_fn=os.setsid) as process:
try:
output = process.communicate(timeout=2)[0]
print("Output try", output)
except TimeoutExpired:
process.kill()
output = process.stdout.read().decode()
print("Output except",output)
return output