在python中控制用于调用外部命令的子进程数

Control the number of subprocesses using to call external commands in python(在python中控制用于调用外部命令的子进程数)
本文介绍了在python中控制用于调用外部命令的子进程数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我了解使用 subprocess 是调用外部命令的首选方式.

I understand using subprocess is the preferred way of calling external command.

但是,如果我想并行运行多个命令,但要限制生成的进程数怎么办?困扰我的是我无法阻止子进程.例如,如果我调用

But what if I want to run several commands in parall, but limit the number of processes being spawned? What bothers me is that I can't block the subprocesses. For example, if I call

subprocess.Popen(cmd, stderr=outputfile, stdout=outputfile)

然后该过程将继续,无需等待 cmd 完成.因此,我无法将其包装在 multiprocessing 库的工作人员中.

Then the process will continue, without waiting for cmd to finish. Therefore, I can't wrap it up in a worker of multiprocessing library.

例如,如果我这样做:

def worker(cmd): 
    subprocess.Popen(cmd, stderr=outputfile, stdout=outputfile);

pool = Pool( processes = 10 );
results =[pool.apply_async(worker, [cmd]) for cmd in cmd_list];
ans = [res.get() for res in results];

然后每个工作人员将在生成子进程后完成并返回.所以我不能通过使用Pool 来真正限制subprocess 生成的进程数.

then each worker will finish and return after spawning a subprocess. So I can't really limit the number of processes generated by subprocess by using Pool.

限制子进程数量的正确方法是什么?

What's the proper way of limiting the number of subprocesses?

推荐答案

如果要等待命令完成,可以使用subprocess.call.有关详细信息,请参阅 pydoc 子进程.

You can use subprocess.call if you want to wait for the command to complete. See pydoc subprocess for more information.

您也可以调用 Popen.wait 你的工人中的方法:

You could also call the Popen.wait method in your worker:

def worker(cmd): 
    p = subprocess.Popen(cmd, stderr=outputfile, stdout=outputfile);
    p.wait()

这篇关于在python中控制用于调用外部命令的子进程数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

build conda package from local python package(从本地 python 包构建 conda 包)
How can I see all packages that depend on a certain package with PIP?(如何使用 PIP 查看依赖于某个包的所有包?)
How to organize multiple python files into a single module without it behaving like a package?(如何将多个 python 文件组织到一个模块中而不像一个包一样?)
Check if requirements are up to date(检查要求是否是最新的)
How to upload new versions of project to PyPI with twine?(如何使用 twine 将新版本的项目上传到 PyPI?)
Why #egg=foo when pip-installing from git repo(为什么从 git repo 进行 pip 安装时 #egg=foo)