【发布时间】:2017-12-20 05:40:27
【问题描述】:
我正在使用 python3 子进程模块来处理 bash 脚本调用。我想在调用脚本时控制并发子进程的数量。
Popen.wait(超时=无) 等待子进程终止。设置并返回返回码属性。
我知道我可以调用 subprocess.Popen.wait(timeout=None) 来等待子进程终止。但是我想知道是否可以等待 subprocess.Popen 列表完成,这样我就可以控制并发进程的数量。
示例代码sn-ps如下:
例子.py
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
你好.sh
# Validation goes here.
echo $1
sleep $1
echo "Finish Executed"
【问题讨论】:
-
你可以使用
communicate() -
@MaheshKaria 不知道如何使用它。任何帮助或有用的线程?
-
糟糕,我并不是真的要关闭为重复项(没有意识到这也被标记为bash)。如果当前的副本不能解决您的问题,或者至少寻找不同的副本,我会很乐意重新打开。
标签: python bash concurrency subprocess