【问题标题】:How to run parallel programs in python如何在python中运行并行程序
【发布时间】:2012-08-14 14:04:25
【问题描述】:

我有一个 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)

【问题讨论】:

    标签: python


    【解决方案1】:

    对于您的示例,您只想并行处理 - 您不需要线程。

    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 模块),因为你对让这些互操作并不真正感兴趣 - 你只希望操作系统并行运行它们并确保当你去合并结果时,它们都完成了......

    【讨论】:

    • +1 出于某种原因,我在阅读问题时错过了这个细节。这绝对是运行外部命令的方式。
    • 这是完美的。正是我正在寻找的东西,并且比其他答案简单得多。线程示例对其他事情非常有用,所以还是谢谢你
    • @Daren Thomas:如果我想得到每个过程的结果呢?
    • @hguser,阅读模块 subprocess - 你可以重定向 STDOUT 和朋友 :-)
    • @DarenThomas,如果你能看看这个,我将不胜感激,感谢你的时间。 stackoverflow.com/questions/45643375/…
    【解决方案2】:

    并行运行也可以使用 Python 中的多个进程来实现。我前段时间写了一篇关于这个主题的博客文章,你可以在这里找到它

    http://multicodecjukebox.blogspot.de/2010/11/parallelizing-multiprocessing-commands.html

    基本上,这个想法是使用“工作进程”从队列中独立检索作业,然后完成这些作业。

    根据我的经验,效果很好。

    【讨论】:

      【解决方案3】:

      您可以使用线程来完成。这是一个非常简短且(未经测试)的示例,如果您在线程中实际执行的操作非常丑陋,但您可以编写自己的工作类..

      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...
      

      【讨论】:

      • 由于join() 阻塞(阻止其他线程启动)直到线程完成,这实际上不会并行执行任何操作。请参阅我的答案以了解如何解决此问题。
      猜你喜欢
      • 2012-09-14
      • 2023-03-04
      • 2010-12-04
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      相关资源
      最近更新 更多