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

标签 python process

标题非常通用,但问题可能并非如此。

我有一个脚本,它使用从文件(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()

我必须等待每个进程结束才能关闭文件。

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

最佳答案

您可以使用 multiprocessing.Pool 来完成此操作:

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()

关于python - 如何在Python中并行运行多个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33081233/

相关文章:

.net - 如何获取当前的ProcessID?

c - pipe() 从 1 个父进程到单独的 c 文件中的多个子进程

python - 当某些项目相互依赖时,如何运行异步进程列表?

java - 使用 processBuilder 执行 shell 命令并与之交互

Python 比较两个 3 维 numpy 数组

当使用 staticmethod 或 classmethod 装饰器装饰时,类中的 Python LRU 缓存忽略 maxsize 限制

c# - Process.StartInfo.Username 为空

python - 从 python 中的 feedparser 解析不同的日期格式?

使用 MediaInfo plus wrapper 的 Python 错误

python - 蝗虫 : How to invoke the test through an API