管道输出时,Python子进程挂起为Popen

时间:2017-09-29 18:19:24

标签: multithreading python-2.7 popen

我已经浏览过几十篇“Python子流程挂起”文章,并认为我已经解决了下面代码中各篇文章中提出的所有问题。

我的代码间歇性地挂在Popen命令中。我使用multiprocessing.dummy.apply_async运行4个线程,每个线程启动一个子进程,然后逐行读取输出并将其修改后的版本打印到stdout。

def my_subproc():
   exec_command = ['stdbuf', '-i0', '-o0', '-e0',
                    sys.executable, '-u',
                    os.path.dirname(os.path.realpath(__file__)) + '/myscript.py']

   proc = subprocess.Popen(exec_command, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1)
   print "DEBUG1", device

   for line in iter(proc.stdout.readline, b''):
    with print_lock:
        for l in textwrap.wrap(line.rstrip(), LINE_WRAP_DEFAULT):

上面的代码是从apply_async:

运行的
pool = multiprocessing.dummy.Pool(4)
for i in range(0,4):
    pool.apply_async(my_subproc)

子进程将间歇性地挂起subprocess.Popen,不会打印语句“DEBUG1”。有时候所有线程都可以工作,有时只需要4个中的1个就可以工作。

我不知道这表明了Popen已知的任何僵局。我错了吗?

2 个答案:

答案 0 :(得分:1)

这似乎是与multiprocessing.dummy的不良交互。当我使用多处理(不是.dummy线程接口)时,我无法重现错误。

答案 1 :(得分:1)

subprocess.Popen()中有一个隐患,这是由stdout(可能是stderr)的io缓冲引起的。子进程io缓冲区中的限制大约为65536个字符。如果子进程写入足够的输出,则子进程将“挂起”,等待刷新缓冲区,这将导致死锁。 subprocess.py的作者似乎认为这是由孩子引起的问题,即使subprocess.flush受到欢迎。皮尔森·安德斯·皮尔森, https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/有一个简单的解决方案,但您必须注意。正如他所说,“ tempfile.TemporaryFile()是您的朋友。”就我而言,我正在循环运行一个应用程序以批处理一堆文件,该解决方案的代码为:

with tempfile.TemporaryFile() as fout:
     sp.run(['gmat', '-m', '-ns', '-x', '-r', str(gmat_args)], \
            timeout=cpto, check=True, stdout=fout, stderr=fout)

上面的修复程序在处理大约20个文件后仍然死锁。一种改进,但还不够好,因为我需要成批处理数百个文件。我想出了下面的“撬棍”方法。

                proc = sp.Popen(['gmat', '-m', '-ns', '-x', '-r', str(gmat_args)], stdout=sp.PIPE, stderr=sp.STDOUT)   
                """ Run GMAT for each file in batch.
                    Arguments:
                    -m: Start GMAT with a minimized interface.
                    -ns: Start GMAT without the splash screen showing.
                    -x: Exit GMAT after running the specified script.
                    -r: Automatically run the specified script after loading.
                Note: The buffer passed to Popen() defaults to io.DEFAULT_BUFFER_SIZE, usually 62526 bytes.
                If this is exceeded, the child process hangs with write pending for the buffer to be read.
                https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/
                """
                try:
                    (outs, errors) = proc.communicate(cpto)
                    """Timeout in cpto seconds if process does not complete."""

                except sp.TimeoutExpired as e:
                    logging.error('GMAT timed out in child process. Time allowed was %s secs, continuing', str(cpto))

                    logging.info("Process %s being terminated.", str(proc.pid))
                    proc.kill()
                    """ The child process is not killed by the system. """

                    (outs, errors) = proc.communicate()
                    """ And the stdout buffer must be flushed. """

基本思想是终止进程并在每次超时时刷新缓冲区。我将TimeoutExpired异常移至批处理循环中,以便在终止该进程后继续下一个进程。如果超时值足以使gmat完成(尽管速度较慢),则这是无害的。我发现该代码在超时之前将处理3至20个文件。

这似乎确实是子流程中的错误。