我已经浏览了几十篇“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已知的任何僵局。我错了吗?
subprocess.Popen()中存在一个阴险的错误,它由缓冲stdout(可能是stderr)引起。子进程io缓冲区中有大约65536个字符的限制。如果子进程写入足够的输出,子进程将“挂起”等待刷新缓冲区 - 死锁情况。 subprocess.py的作者似乎认为这是由孩子引起的问题,即使subprocess.flush是受欢迎的。 Pearson Anders pearson,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个文件。
这看起来像是子进程中的一个错误。
这似乎是与multiprocessing.dummy的不良交互。当我使用多处理(不是.dummy线程接口)时,我无法重现错误。