繁花如伊
您不需要线程并行运行子进程:from subprocess import Popencommands = [
'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 parallelprocesses = [Popen(cmd, shell=True) for cmd in commands]# do other things here..# wait for completionfor p in processes: p.wait()限制您可以使用的并发命令的数量multiprocessing.dummy.Pool,它使用线程并提供与multiprocessing.Pool所使用的程序:from functools import partialfrom multiprocessing.dummy import Poolfrom subprocess import call
pool = Pool(2) # two concurrent commands at a timefor i, returncode in enumerate(pool.imap(partial(call, shell=True), commands)):
if returncode != 0:
print("%d command failed: %d" % (i, returncode))这个答案演示了限制并发子进程数量的各种技术。它展示了多进程、池、并发、期货、线程+基于队列的解决方案。您可以在不使用线程/进程池的情况下限制并发子进程的数量:from subprocess import Popenfrom itertools import islice
max_workers = 2 # no more than 2 concurrent processesprocesses = (Popen(cmd, shell=True) for cmd in commands)running_processes = list(islice(processes, max_workers)) # start new processeswhile 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上,您可以避免繁忙的循环和封锁os.waitpid(-1, 0),等待任何子进程退出。.