【问题标题】:Python - using multiprocessing with multiple args doesn't workPython - 使用具有多个参数的多处理不起作用
【发布时间】:2019-10-16 12:12:01
【问题描述】:

我正在尝试使用具有多个参数的多处理来打印虚拟值,但这似乎不起作用。我收到错误

"f() missing 2 required positional arguments:..."

以下代码:

from multiprocessing import Pool

class tryProcessing:
    def f(self, arr, arg1, arg2):
        print(arr + " " + arg1 + " " + arg2)

    def func(self, arr, arg1, arg2):
        arg1 = "hi"
        arg2 = "hello"
        arr_a = ['1','2']
        arr_b = ['3','4','5']
        p = Pool(Processes=2)
        p.map(self.f, [[a, arg1, arg2], [b, arg1, arg2]])
        p.close

我做错了什么?

附: in this answer,他做了类似的事情,我不明白为什么他的作品,而我的没有。

【问题讨论】:

  • 参数是否需要在元组中? [(a, arg1, arg2), (b, arg1, arg2)]

标签: python python-3.x python-multiprocessing


【解决方案1】:

您正在寻找starmap,它期望迭代包含要扩展为函数参数的嵌套迭代参数。它使用星号(splat)符号来扩展,因此得名。

附:你从来没有在函数结束时真正调用p.close

【讨论】:

    【解决方案2】:

    你传递一个参数,它是一个完整的列表。

    
    test = map(lambda x : x, [[a, arg1, arg2], [b, arg1, arg2]]) 
    print(next(test)) 
    

    你可以像这样更新你的 f func。

    
    def f(self, *args):
        arr, arg1, arg2 = args
        print(f"{arr} {arg1} {arg2}")
    

    【讨论】:

      【解决方案3】:

      与您在此处发布链接的解决方案相比,您的方法存在一些差异。

      • 注意位置参数def someaction(a, b=1, c=2, d=3)
      • 你没有位置参数def f(self, arr, arg1, arg2)

      这可能解释了您遇到的错误。 调整你的代码这工作

      from multiprocessing import Pool
      
      class tryProcessing:
          def f(self, arr):
              print(arr)
      
          def func(self, arr, arg1, arg2):
              arg1 = "hi"
              arg2 = "hello"
              arr_a = ['1','2']
              arr_b = ['3','4','5']
              p = Pool(2)
      
              data = [["a1", "b1", "c1", "d1"],
              ["a2", "b2", "c2", "d2"],
              ["a3", "b3", "c3", "d3"], ]
      
              p.map( self.f, data)
              p.close
      
      t = tryProcessing()
      t.func("adfasf", "dfaf", "daf")
      

      【讨论】:

        猜你喜欢
        • 2017-03-24
        • 2018-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-17
        • 2019-04-05
        相关资源
        最近更新 更多