[英]How to run parallel programs in python
我有一个python脚本使用os.subprocess模块运行一些外部命令。 但其中一个步骤需要很长时间,所以我想分开运行它。 我需要启动它们,检查它们是否已完成,然后执行下一个不平行的命令。 我的代码是这样的:
nproc = 24
for i in xrange(nproc):
#Run program in parallel
#Combine files generated by the parallel step
for i in xrange(nproc):
handle = open('Niben_%s_structures' % (zfile_name), 'w')
for i in xrange(nproc):
for zline in open('Niben_%s_file%d_structures' % (zfile_name,i)):handle.write(zline)
handle.close()
#Run next step
cmd = 'bowtie-build -f Niben_%s_precursors.fa bowtie-index/Niben_%s_precursors' % (zfile_name,zfile_name)
对于您的示例,您只想并行shell - 您不需要线程。
在subprocess
模块中使用Popen
构造函数: http : //docs.python.org/library/subprocess.htm
为您生成的每个进程收集Popen
实例,然后wait()
让它们完成:
procs = []
for i in xrange(nproc):
procs.append(subprocess.Popen(ARGS_GO_HERE)) #Run program in parallel
for p in procs:
p.wait()
你可以逃避这一点(而不是使用multiprocessing
或threading
模块),因为你并不真正对这些互操作感兴趣 - 你只是希望操作系统并行运行它们并确保它们在你去的时候都完成了结合结果......
并行运行也可以使用Python中的多个进程来实现。 我刚刚写了一篇关于这个主题的博客文章,你可以在这里找到它
http://multicodecjukebox.blogspot.de/2010/11/parallelizing-multiprocessing-commands.html
基本上,我们的想法是使用“工作进程”,它独立地从队列中检索作业,然后完成这些作业。
在我的经验中运作得很好。
你可以使用线程来做到这一点。 这是非常简短的(未经测试)示例,非常丑陋的if-else就是你在线程中实际做的事情,但你可以编写自己的工人类..
import threading
class Worker(threading.Thread):
def __init__(self, i):
self._i = i
super(threading.Thread,self).__init__()
def run(self):
if self._i == 1:
self.result = do_this()
elif self._i == 2:
self.result = do_that()
threads = []
nproc = 24
for i in xrange(nproc):
#Run program in parallel
w = Worker(i)
threads.append(w)
w.start()
w.join()
# ...now all threads are done
#Combine files generated by the parallel step
for i in xrange(nproc):
handle = open('Niben_%s_structures' % (zfile_name), 'w')
...etc...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.