python subprocess.Popen挂起

问题描述 投票:7回答:2
            child = subprocess.Popen(command,
                         shell=True,
                         env=environment,
                         close_fds=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT,
                         bufsize=1,
                                     )

            subout = ""
            with child.stdout:
                for line in iter(child.stdout.readline, b''):
                    subout += line
            logging.info(subout)
            rc = child.wait()

有些时候(间歇性地)这种情况永远存在。不确定它是否挂在iter(child.stdout.readline)child.wait()

ps -ef的Popens过程和该过程不再存在

我的猜测是它与bufsize有关,所以child.stdout.readline永远存在,但我不知道如何测试它,因为这种情况间歇性地发生

我可以实现警报,但我不确定这是否合适,因为我无法确定popen'd进程是缓慢还是悬挂

让我们假设child.stdout.readline或wait()永远挂起,除了闹钟之外我还可以采取什么行动?

python subprocess
2个回答
8
投票

你可能会遇到explained in the documentation的僵局:

Popen.wait()

等待子进程终止。设置并返回returncode属性。

警告:当使用stdout=PIPE和/或stderr=PIPE时,这将导致死锁,并且子进程会为管道生成足够的输出,以便阻止等待OS管道缓冲区接受更多数据。使用communicate()来避免这种情况。

解决方案是使用Popen.communicate()


1
投票

close_fds=True所述,将subprocess.Popen()添加到here的调用中。

© www.soinside.com 2019 - 2024. All rights reserved.