スレッド化モジュールとサブプロセス モジュールを使用して並列 bash プロセスを生成するにはどうすればよいですか? スレッドを開始すると、最初の答えがここにあります: How to use threading in Python? 、bash プロセスは並列ではなく順次実行されます。
2 に答える
サブプロセスを並行して実行するためにスレッドは必要ありません。
from subprocess import Popen
commands = [
'date; ls -l; sleep 1; date',
'date; sleep 5; date',
'date; df -h; sleep 3; date',
'date; hostname; sleep 2; date',
'date; uname -a; date',
]
# run in parallel
processes = [Popen(cmd, shell=True) for cmd in commands]
# do other things here..
# wait for completion
for p in processes: p.wait()
スレッドを使用し、プロセスを使用するmultiprocessing.dummy.Pool
ものと同じインターフェイスを提供する、使用できる同時コマンドの数を制限するには:multiprocessing.Pool
from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call
pool = Pool(2) # two concurrent commands at a time
for i, returncode in enumerate(pool.imap(partial(call, shell=True), commands)):
if returncode != 0:
print("%d command failed: %d" % (i, returncode))
この回答は、同時サブプロセスの数を制限するさまざまな手法を示しています。これは、 multiprocessing.Pool、concurrent.futures、threading + Queue ベースのソリューションを示しています。
スレッド/プロセス プールを使用せずに、同時の子プロセスの数を制限できます。
from subprocess import Popen
from itertools import islice
max_workers = 2 # no more than 2 concurrent processes
processes = (Popen(cmd, shell=True) for cmd in commands)
running_processes = list(islice(processes, max_workers)) # start new processes
while running_processes:
for i, process in enumerate(running_processes):
if process.poll() is not None: # the process has finished
running_processes[i] = next(processes, None) # start new process
if running_processes[i] is None: # no new processes
del running_processes[i]
break
Unix では、ビジー ループを回避してon をブロックしos.waitpid(-1, 0)
、子プロセスが終了するのを待つことができます。
簡単なスレッドの例:
import threading
import Queue
import commands
import time
# thread class to run a command
class ExampleThread(threading.Thread):
def __init__(self, cmd, queue):
threading.Thread.__init__(self)
self.cmd = cmd
self.queue = queue
def run(self):
# execute the command, queue the result
(status, output) = commands.getstatusoutput(self.cmd)
self.queue.put((self.cmd, output, status))
# queue where results are placed
result_queue = Queue.Queue()
# define the commands to be run in parallel, run them
cmds = ['date; ls -l; sleep 1; date',
'date; sleep 5; date',
'date; df -h; sleep 3; date',
'date; hostname; sleep 2; date',
'date; uname -a; date',
]
for cmd in cmds:
thread = ExampleThread(cmd, result_queue)
thread.start()
# print results as we get them
while threading.active_count() > 1 or not result_queue.empty():
while not result_queue.empty():
(cmd, output, status) = result_queue.get()
print('%s:' % cmd)
print(output)
print('='*60)
time.sleep(1)
これを行うためのより良い方法がいくつかあることに注意してください。ただし、これはそれほど複雑ではありません。この例では、コマンドごとに 1 つのスレッドを使用しています。限られた数のスレッドを使用して不明な数のコマンドを処理するようなことをしたい場合、複雑さが忍び寄り始めます。スレッド化の基本を理解すれば、これらのより高度な手法はそれほど複雑ではないように思えます。そして、これらのテクニックを扱えるようになると、マルチプロセッシングはより簡単になります。