在实时读取标准输出时超时子进程

时间:2017-09-27 14:50:20

标签: python python-3.x

from subprocess import Popen, PIPE, STDOUT, TimeoutExpired

cmd = 'for x in $(seq 1 3); do echo stage $x; sleep 1; done'

proc = Popen(cmd, shell=True, close_fds=True,
             stdout=PIPE, stderr=STDOUT,
             universal_newlines=True, start_new_session=True)              

for line in proc.stdout:
     print(line.strip())

communicate的默认行为是在proc之后吐出所有stdout。被终止。但是我需要在proc时访问stdout。如果它运行的时间太长,它仍在运行,但会终止它。

修改

以下似乎按照我想要的方式工作,不确定这是否正确?

from os import killpg
from signal import SIGKILL
from concurrent import futures
from subprocess import Popen, PIPE, STDOUT, TimeoutExpired

cmd = 'for x in $(seq 1 3); do echo stage $x; sleep 1; done'

proc = Popen(cmd, shell=True, close_fds=True,
             stdout=PIPE, stderr=STDOUT,
             universal_newlines=True, start_new_session=True)

def handler(proc, timeout=None):
    try:
        proc.wait(timeout)
    except TimeoutExpired as err:
        print(err)
        killpg(proc.pid, SIGKILL)

exe = futures.ThreadPoolExecutor(max_workers=1)  
exe.submit(handler, proc, 2)

for line in proc.stdout:
     print(line.strip())

0 个答案:

没有答案