Python 在池映射中使用 List/Multiple 个参数

Python Using List/Multiple Arguments in Pool Map

我正在尝试将列表作为参数传递给 pool.map(co_refresh, input_list)。但是,pool.map 并没有触发函数 co_refresh。也没有返回错误。看起来进程挂在那里了。

原码:

from multiprocessing import Pool
import pandas as pd
import os

account='xxx'
password='xxx'
threads=5
co_links='file.csv'

input_list=[]

pool = Pool(processes=threads)
def co_refresh(url, account, password, outputfile):

    print(url + ' : ' + account + ' : ' + password + ' : ' + outputfile)

    return;

link_pool = pd.read_csv(co_links, skipinitialspace = True)

for i, row in link_pool.iterrows():

    ln = (row.URL, account, password, os.path.join('e:/', row.File_Name.split('.')[0] + '.csv'))

    input_list.append(ln)

pool.map(co_refresh, input_list)

pool.close()

然而,它从未触发函数co_refresh。如何使用列表作为参数传递给我的函数?

老问题(简体):

我下面有 input_list,这是 listlist

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

我有如下功能:

def func(a, b, c, d)
   ###
    return;

我想为此功能使用多进程func:

from multiprocessing import Pool
pool = Pool(processes=5)
pool.map(func, input_list)
pool.close()

然而,它从未触发函数func。如何使用列表作为参数传递给我的函数?

你应该在之前定义你的工作函数声明Pool,当你声明Poolsub worker processes forked时,工作进程不要执行超出该行的代码,因此看不到您的工作功能。

此外,您最好将 pool.map 替换为 pool.starmap 以适合您的输入。

一个简化的例子:

from multiprocessing import Pool

def co_refresh(a, b, c, d):
    print(a, b, c, d)

input_list = [f'a{i} b{i} c{i} d{i}'.split() for i in range(4)]
# [['a0', 'b0', 'c0', 'd0'], ['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3']]

pool = Pool(processes=3)
pool.starmap(co_refresh, input_list)
pool.close()

考虑下面的代码

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)

当您使用池在脚本中调用它时

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

输出为

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

所以a获取数组,其余所有参数均未传递。 Pool.map 期望一个函数只有一个参数。所以为了你的案例工作,你需要创建一个包装函数

def someaction_wrapper(data):
    someaction(*data)

然后在池中调用这个包装函数。现在你用

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

输出为

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

我相信这是你想要的

georgexsh 的答案在 Python 3 中完美运行;关键是 starmap 允许将多个参数传递给函数。

但是,如果您使用 Python 2,则需要使用 Ahmed 在问题 here.

下评论中提到的 python 经典解包

在我的例子中,我只需要 "enlist" 函数中的第一个参数。

def func(args)
   (a, b, c, d) = args
   # You can then use a, b, c, d in your function
    return;