Python's subprocess.Popen object hangs gathering child output when child process does not exit

前端 未结 4 1956
既然无缘
既然无缘 2021-01-07 06:16

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.

The obvious solution to this

4条回答
  •  再見小時候
    2021-01-07 06:52

    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
    

    Outputs:

    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
    

提交回复
热议问题