Python Using List/Multiple Arguments in Pool Map

前端 未结 3 1631
清酒与你
清酒与你 2021-02-20 14:13

I am trying to pass a list as a parameter to the pool.map(co_refresh, input_list). However, pool.map didn\'t trigger the function co_refresh

3条回答
  •  旧时难觅i
    2021-02-20 14:41

    Consider the below code

    from multiprocessing.pool import Pool
    
    data = [["a1", "b1", "c1", "d1"],
            ["a2", "b2", "c2", "d2"],
            ["a3", "b3", "c3", "d3"], ]
    
    
    def someaction(a, b=1, c=2, d=3):
        print(a, b, c, d)
    

    When you call this in your script using a pool

    pool = Pool(4)
    pool.map(someaction, data)
    

    The output is

    ['a1', 'b1', 'c1', 'd1'] 1 2 3
    ['a2', 'b2', 'c2', 'd2'] 1 2 3
    ['a3', 'b3', 'c3', 'd3'] 1 2 3
    

    So a gets the array and rest all parameters are not passed. Pool.map expects a function to only have one argument. So for your case to work you need to create a wrapper function

    def someaction_wrapper(data):
        someaction(*data)
    

    And then call this wrapper function in pool. Now you use

    pool = Pool(4)
    pool.map(someaction_wrapper, data)
    

    And the output is

    a1 b1 c1 d1
    a2 b2 c2 d2
    a3 b3 c3 d3
    

    Which is what you wanted I believe

提交回复
热议问题