2017-12-20 6 views
0

私は、bashスクリプトコールに対処するためにpython3サブプロセスモジュールを使用しています。私はスクリプトを呼び出すときに同時にサブプロセスの数を制御したい。Pythonサブプロセスはサブプロセスのリストを待ちます

Popen.wait(timeout =なし) 子プロセスが終了するまで待ちます。 returncode属性を設定して返します。

子プロセスが終了するのを待つために、subprocess.Popen.wait(timeout = None)を呼び出すことができます。しかし、私はサブプロセスのリストを待つことができるかどうか疑問に思っていました。完了するために、完了すると、同時にプロセスの数を制御できます。

Example.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 

hello.sh

# Validation goes here. 
echo $1 
sleep $1 
echo "Finish Executed" 
+0

のために働く必要がありますが、 '通信()' –

+0

@MaheshKaria私はそれを使用することができますどのようにないアイデアを使用することはできません。助けや役に立つスレッド? – shady

+0

おっと、私は実際には重複して閉じることを意味しませんでした(これはタグ付けされたことを認識しませんでした[タグ:bash])。私は、現在の複製があなたの問題を解決しない場合、または少なくとも異なる複製を探す場合は、再度開くことができます。 – tripleee

答えて

0

あなたが通信する()を使用する場合、あなたは待機を指定する必要はありません。次のように

サンプルコードスニペットサブプロセスを終了します。より多くの情報が変更以下 Understanding Popen.communicate

ここhttps://docs.python.org/2/library/subprocess.html 他のリンクを見つけることができます

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] 
+0

'bash'を' shell = True'で動かすのはうんざりです。 https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess – tripleee

+0

@pankaj mishra「bulk」内のサブプロセスを同時に実行したいことに注目してください。これを達成する方法はありますか?または、マルチプロセッシングモジュールに切り替えるだけでいいですか? – shady

+0

@tripleeeはこれに答える正しい人になる可能性があります。 –

関連する問題