Python 即使在超时的情况下,Subprocess.Popen也会获得输出
我正在使用Python 即使在超时的情况下,Subprocess.Popen也会获得输出,python,subprocess,python-3.5,Python,Subprocess,Python 3.5,我正在使用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(
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
异常,我如何获得进程的输出(直到它被终止的输出)?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
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
不幸的是,这不会杀死进程组,因此python脚本被阻塞。如果我手动终止进程,输出变量将保持为空。不幸的是,这不会终止进程组,因此python脚本被阻塞。如果手动终止进程,输出变量将保持为空。