【问题标题】:Multiprocessing in python compatible from 3 to 2.7python中的多处理兼容从3到2.7
【发布时间】:2019-04-10 03:26:11
【问题描述】:

以下代码在 Python 3 中运行顺畅,但无法将其转换为 Python 2.7。

from multiprocessing import *

def func(path, filename, path_2):
    #Things to do

for i in range(0,len(chr_names)): #len(chr_names) = 24
    tuple_var.append((path, chr_names[i][0], chrom_sizes[i][0]))

cores = 4
with Pool(cores) as p:
    p.starmap(func, tuple_var)

我收到以下错误。

python AttributeError: __exit__

我知道 Python 2.7 不支持星图。

我应该在 Python 2.7 中使用什么代码?

【问题讨论】:

标签: python multiprocessing pool starmap


【解决方案1】:

一种简单的方法,使用包装函数:

def star_wrapper(args):
    return func(*args)

....

with Pool(cores) as p:
    p.map(star_wrapper, tuple_var)

【讨论】:

  • 感谢使用 wrapper 和 @blhsing 回答将 'with Pool(cores) as p:' 替换为 'p = Pool(cores)'
【解决方案2】:

除非我误解你,你似乎可以在 Python 2.6+ 中使用Pool 的 map 函数。您所需要的只是一个可以将元组参数应用于原始函数的函数。比如:

def pool_starmap(pool, fn, items):
    def map_fn(args):
        fn(*args)
    return pool.map(map_fn, items)

cores = 4
with Pool(cores) as p:
    pool_starmap(p, func, tuple_var)

【讨论】:

    【解决方案3】:

    其他答案已经涵盖了如何移植starmap,但至于AttributeError: __exit__ 错误,它来自于multiprocessing.Pool 在Python 2.7 中不能用作上下文管理器,因此您只需必须改为:

    p = Pool(cores)
    

    【讨论】:

      【解决方案4】:

      第一:

      在 Python 2.x 和 3.0、3.1 和 3.2 中,multiprocessing.Pool() 对象不是上下文管理器

      查看这篇文章了解更多信息: Python Multiprocessing Lib Error (AttributeError: __exit__)

      第二:

      使用辅助函数

      或选择此处提供的其他选项之一: Multiprocessing with multiple arguments to function in Python 2.7

      示例代码:

      from contextlib import contextmanager
      from multiprocessing import *
      
      @contextmanager
      def terminating(thing):
          try:
              yield thing
          finally:
              thing.terminate()
      
      def func(path, filename, path_2):
          # Things to do
          print(path)
          print(filename)
          print(path_2)
          print('-----------------------------\n')
      
      def helper(args):
          return func(args[0], args[1], args[2])
      
      def task():
          tuple_var = []
          for i in range(0, 10):
              tuple_var.append(('hi_' + str(i), i, i))
      
          with terminating(Pool(processes=2)) as p:
              p.map(helper, tuple_var)
      
      if __name__ == '__main__':
          task()
      

      【讨论】:

        猜你喜欢
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-15
        • 2015-04-07
        • 2018-09-16
        • 2011-04-08
        • 2019-05-12
        相关资源
        最近更新 更多