通过 subprocess.Popen 限制同时 运行 的进程数

Limiting the number of processes being run at once by subprocess.Popen

我有一个计算密集型文件列表,我正在使用 Python 的子进程模块 运行ning。这个想法是使用 Popen 而不是像 check_call 这样的东西来更快地浏览列表。但是,当列表大于计算机的 4 或 5 个元素时,程序会耗尽所有计算机资源,使其在完成之前无法使用。我的问题是:有没有方便的方法来限制我的程序一次打开的进程数?

我使用的代码很简单,但是是一个更大程序的一部分,因此无法将所有需要的代码粘贴到 运行。

def run_fast(self):
    '''
    self.cps_dct is a nested dictionary dct[index1][index2]=filename
    CopasiSE is a program for simulating mathematical models using the terminal/cmd

    '''
    for i in self.cps_dct.keys():
        for j in self.cps_dct[i]:
            subprocess.Popen('CopasiSE {}'.format(self.cps_dct[i][j]))
    return self.cps_dct

谢谢

添加 Klaus 的建议: 类似的东西可以工作:

from multiprocessing import Pool
import subprocess


class Cps:
    def __init__(self):
        self.cps_dct = {
            'a': {
                '1': 'file1',
                '2': 'file2',
                '3': 'file3',
                '4': 'file4'
            },
            'b': {
                '1': 'file1',
                '2': 'file2',
                '3': 'file3',
                '4': 'file4'
            }
        }


def open_proc(file_name):
    subprocess.Popen('CopasiSE {}'.format(file_name))

if __name__ == '__main__':

    process_cap = 4
    p = Pool(process_cap)
    # Initialize the object.
    item = Cps()
    for i in item.cps_dct.keys():
        iterable = item.cps_dct[i].values()
        p.map(open_proc, iterable)
        p.close()
        p.join()