Python Subprocess等待子进程列表[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我正在使用python3子进程模块来处理bash脚本调用。我想在调用脚本时控制并发子进程的数量。

Popen.wait(timeout = None)等待子进程终止。设置并返回returncode属性。

我知道我可以调用subprocess.Popen.wait(timeout = None)来等待子进程终止。但我想知道我是否可以等待subprocess.Popen列表完成,有了它,我可以控制并发进程的数量。

示例代码段如下:

example.朋友

import subprocess
from itertools import zip_longest

seed = [1, 2, 4, 1, 3, 5, 4, 1]
basepath="/path/to/file/hello.sh"

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def bash_handler(num):
    return subprocess.Popen('bash {0} {1}'.format(basepath, num), shell=True)

for bulk in grouper(seed, 2):
    [bash_handler(item).wait() for item in bulk if item is not None]
# This will executed one by one 

hello.是

# Validation goes here.
echo $1
sleep $1
echo "Finish Executed"
python bash concurrency subprocess
1个回答
0
投票

当您使用communic()时,您不需要指定等待子进程退出。更多信息可以在这里找到https://docs.python.org/2/library/subprocess.html其他链接Understanding Popen.communicate

以下更改应该适合您

from subprocess import Popen,PIPE
def bash_handler(num):
    return subprocess.Popen('bash {0} {1}'.format(basepath, num), shell=True,stdout=PIPE)


for bulk in grouper(seed, 2):
    [bash_handler(item).communicate() for item in bulk if item is not None]
© www.soinside.com 2019 - 2024. All rights reserved.