如何在python中并行运行多个进程

如何在python中并行运行多个进程,python,process,Python,Process,标题非常通用,但问题可能不是这样 我有一个脚本,它使用从文件(xls文件)传递的参数编译一些代码。根据xls上的配置数量,我必须编译某些文件。 我想将每个编译的结果(stdout和stderr)存储在文本文件中,这些文件的名称来自配置 我已经能够完成所有这些,但为了加快速度,我希望并行运行所有编译。有办法做到这一点吗 示例文件 for n in num_rows: # num_rows store all the rows read using xlrd object parameter

标题非常通用,但问题可能不是这样

我有一个脚本,它使用从文件(xls文件)传递的参数编译一些代码。根据xls上的配置数量,我必须编译某些文件。 我想将每个编译的结果(stdout和stderr)存储在文本文件中,这些文件的名称来自配置

我已经能够完成所有这些,但为了加快速度,我希望并行运行所有编译。有办法做到这一点吗

示例文件

for n in num_rows: # num_rows store all the rows read using xlrd object
    parameters_list = [...] # has all the parameters read from xls
    .
    .
    .
    logfile = ...txt #name is based on name read from xls

    p = subprocess.Popen(parameters_list, stderr=logfile)
    p.wait()
    logfile.close()
在关闭文件之前,我必须等待每个进程结束


我的问题可能太长,但欢迎提供任何帮助或线索。

假设您的流程都将写入不同的日志文件,答案很简单:
子流程
模块将已经并行运行了。只需为每个对象创建不同的
Popen
对象,并将它们存储在列表中:

processes = []
logfiles = []
for n in num_rows: # num_rows store all the rows read using xlrd object
    parameters_list = [...] # has all the parameters read from xls
    .
    .
    .
    logfile = ...txt #name is based on name read from xls
    logfiles.append(logfile)

    p = subprocess.Popen(parameters_list, stderr=logfile)
    logfiles.append(logfile)
    processes.append(p)

# Now, outside the for loop, the processes are all running in parallel.
# Now we can just wait for each of them to finish, and close its corresponding logfile

for p, logfile in zip(processes, logfiles):
    p.wait() # This will return instantly if that process was already finished
    logfile.close()

可以使用多处理池执行此操作。池:

def parse_row(n):
    parameters_list = [...] # has all the parameters read from xls
    .
    .
    .
    logfile = ...txt #name is based on name read from xls
    p = subprocess.Popen(parameters_list, stderr=logfile)
    p.wait()
    logfile.close()
pool = multiprocessing.Pool()
pool.map_async(parse_row, num_rows)
pool.close()
pool.join()

虽然子进程非常有用,但对于并行处理,
多处理
包工作得更好…@xtofl-绝对如此。我对你的答案投了赞成票,因为它比我的好。这很有同情心:)不过,我是一个客观的出类拔萃者:功劳归佩里。