subprocess32.Popen崩溃(cpu 100%)

时间:2016-09-30 08:28:17

标签: bash python-2.7 subprocess

我一直在尝试使用subprocess32.Popen,但这会导致我的系统崩溃(CPU 100%)。所以,我有以下代码:

import subprocess32 as subprocess

for i in some_iterable:
    output = subprocess.Popen(['/path/to/sh/file/script.sh',i[0],i[1],i[2],i[3],i[4],i[5]],shell=False,stdin=None,stdout=None,stderr=None,close_fds=True)

在此之前,我有以下内容:

import subprocess32 as subprocess
for i in some_iterable:
    output subprocess.check_output(['/path/to/sh/file/script.sh',i[0],i[1],i[2],i[3],i[4],i[5]])

..我对此没有任何问题 - 除了它已经死了。

使用Popen我发现这很快 - 但是我的CPU在几秒内过于100%且系统崩溃 - 迫使硬重启。

我想知道我正在做什么让Popen崩溃?

在Linux上,Python2.7,如果这有帮助的话。

感谢。

1 个答案:

答案 0 :(得分:0)

问题是你试图一次启动2个进程,这会阻塞你的系统。

解决方案是使用池来限制一次可以运行的最大进程数,并等待每个进程完成。对于您正在启动子进程并等待它们(IO绑定)的情况,来自multiprocessing.dummy模块的线程池将执行:

import multiprocessing.dummy as mp
import subprocess32 as subprocess

def run_script(args):
    args = ['/path/to/sh/file/script.sh'] + args
    process = subprocess.Popen(args, close_fds=True)
    # wait for exit and return exit code
    # or use check_output() instead of Popen() if you need to process the output.
    return process.wait()

# use a pool of 10 to allow at most 10 processes to be alive at a time
threadpool = mp.Pool(10)

# pool.imap or pool.imap_unordered should be used to avoid creating a list
# of all 2M return values in memory
results = threadpool.imap_unordered(run_script, some_iterable)
for result in results:
    ... # process result if needed

我遗漏了Popen的大部分参数,因为您仍在使用默认值。如果你的脚本正在进行计算工作,那么池的大小应该在你可用的CPU核心范围内,如果它主要是IO(网络访问,写文件......),那么可能更多。