我有一个 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
所以我基本上想并行运行这个命令,同时将其输出捕获到文件中。一旦所有实例完成,我想继续该脚本
subprocess.call()
正在阻塞。这意味着,每个调用都必须等待子进程完成才能继续。
你想要的是将你的论点传递给subprocess.Popen
构造函数,而不是。这样,您的子进程将在不阻塞的情况下启动。
稍后,您可以通过调用将这些子进程连接在一起Popen.communicate()
or 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
附:你有没有看过Python的文档subprocess module https://docs.python.org/2/library/subprocess.html?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)