当子进程未退出时,Python的subprocess.Popen对象挂起收集子输出 [英] Python's subprocess.Popen object hangs gathering child output when child process does not exit

查看:95
本文介绍了当子进程未退出时,Python的subprocess.Popen对象挂起收集子输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当某个进程异常退出或根本没有退出时,我仍然希望能够收集到该时刻为止它可能已经生成的输出.

When a process exits abnormally or not at all, I still want to be able to gather what output it may have generated up until that point.

此示例代码的明显解决方案是使用os.kill杀死子进程,但是在我的真实代码中,该子进程挂起以等待NFS,并且不响应SIGKILL.

The obvious solution to this example code is to kill the child process with an os.kill, but in my real code, the child is hung waiting for NFS and does not respond to a SIGKILL.

#!/usr/bin/python
import subprocess
import os
import time
import signal
import sys
child_script = """
#!/bin/bash
i=0
while [ 1 ]; do
    echo "output line $i"
    i=$(expr $i \+ 1)
    sleep 1
done
"""
childFile = open("/tmp/childProc.sh", 'w')
childFile.write(child_script)
childFile.close()

cmd = ["bash", "/tmp/childProc.sh"]
finish = time.time() + 3
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
while p.poll() is None:
    time.sleep(0.05)
    if finish < time.time():
        print "timed out and killed child, collecting what output exists so far"
        out, err = p.communicate()
        print "got it"
        sys.exit(0)

在这种情况下,将出现有关超时的打印语句,并且python脚本永远不会退出或继续.有人知道我该怎么做才能仍然从我的子进程获得输出

In this case, the print statement about timing out appears and the python script never exits or progresses. Does anybody know how I can do this differently and still get output from my child processe

推荐答案

问题是,当不与终端连接时,bash无法响应CTRL-C. 切换到SIGHUP或SIGTERM似乎可以解决问题:

Problem is that bash doesn't answer to CTRL-C when not connected with a terminal. Switching to SIGHUP or SIGTERM seems to do the trick:

cmd = ["bash", 'childProc.sh']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                          stderr=subprocess.STDOUT, 
                          close_fds=True)
time.sleep(3)
print 'killing pid', p.pid
os.kill(p.pid, signal.SIGTERM)
print "timed out and killed child, collecting what output exists so far"
out  = p.communicate()[0]
print "got it", out

输出:

killing pid 5844
timed out and killed child, collecting what output exists so far
got it output line 0
output line 1
output line 2

这篇关于当子进程未退出时,Python的subprocess.Popen对象挂起收集子输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆