我有一个Python脚本,必须调用某个应用3次。这些调用应该是并行的,因为它们需要几个小时才能完成,并且彼此之间不相干。但是它们的脚本应该停止运行,直到它们全部完成,然后再进行一些清理工作。
这是一些代码:
#do some stuff
for work in worklist: # these should run in parralel
output=open('test.txt','w')
subprocess.call(work,stdout=output,stderr=output)
output.close()
# wait for subprocesses to finish
# cleanup
Run Code Online (Sandbox Code Playgroud)
所以我基本上想在捕获其输出到文件中的同时运行此命令。完成所有实例后,我要继续执行脚本
subprocess.call()正在阻止。这意味着,每个调用必须等待子进程完成才能继续。
您想要的是将参数传递给subprocess.Popen构造函数。这样,您的子进程将不会受到阻塞地启动。
稍后,您可以通过调用Popen.communicate()或将这些子进程连接在一起Popen.wait()。
child_processes = []
for work, filename in worklist:
with io.open(filename, mode='wb') as out:
p = subprocess.Popen(work, stdout=out, stderr=out)
child_processes.append(p) # start this one, and immediately return to start another
# now you can join them together
for cp in child_processes:
cp.wait() # this will block on each child process until it exits
Run Code Online (Sandbox Code Playgroud)
PS您是否研究了subprocess模块上的Python文档?
| 归档时间: |
|
| 查看次数: |
6619 次 |
| 最近记录: |