2012-08-14 27 views
8

我有一个python脚本来使用os.subprocess模块​​运行一些外部命令。但其中一个步骤需要很长时间,所以我想单独运行。我需要启动它们,检查它们是否完成,然后执行下一个不平行的命令。 我的代码是这样的:如何在python中运行并行程序

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) 

回答

0

你可以使用线程来做到这一点。这是很短,(未测试)例如有非常难看的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... 
+0

这实际上并没有做任何事情,因为'join()'阻塞(阻止其他线程开始),直到线程完成。看到我的答案如何解决这个问题。 – pR0Ps 2012-08-14 14:32:15

6

对于您的示例,您只需要并行地执行shell命令 - 您不需要线程。

使用Popen构造的subprocess模块: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() 

你可以用这个脱身(如反对使用multiprocessingthreading模块),因为你并不是真的对这些互操作感兴趣 - 你只是希望os能够并行运行它们,并确保它们在完成时完成你去结合的结果...

+0

+1由于某种原因,我在阅读问题时错过了细节。这绝对是运行外部命令的方法。 – pR0Ps 2012-08-14 14:56:59

+0

这是完美的。正是我在找什么,比其他答案简单得多。线程示例对其他内容非常有用,尽管如此谢谢 – user1598231 2012-08-14 16:47:29

+0

@Daren Thomas:如果我想要获得每个进程的结果,那么该怎么办? – hguser 2014-01-09 00:22:08