2012-08-14 26 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