Python线程处理多个bash子进程?如何使用线程和子处理模块生成并行bash进程?当我启动线程时,首先回答如下:如何在Python中使用线程?,bash进程按顺序运行,而不是并行运行。
3 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
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
os.waitpid(-1, 0)
添加回答
举报
0/150
提交
取消