簡體   English   中英

如何在python中運行並行程序

[英]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()

你可以逃避這一點(而不是使用multiprocessingthreading模塊),因為你並不真正對這些互操作感興趣 - 你只是希望操作系統並行運行它們並確保它們在你去的時候都完成了結合結果......

並行運行也可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM