我试图将一个列表作为参数传递给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,这是list
of list
[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
。如何将列表用作要传递给我的函数的参数?
发布于 2017-11-27 08:44:57
您应该在声明Pool
之前定义您的work函数,当您声明Pool
、子工人进程分叉时,工作流程不会执行超出该行的代码,因此看不到您的工作函数。
此外,您最好用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()
发布于 2017-11-27 08:49:58
考虑下面的代码
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
获取数组,rest所有参数都不会被传递。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
这就是你想要的我相信
发布于 2017-12-17 20:48:44
georgexsh的答案在Python3中非常有效;关键是starmap
允许将多个参数传递到函数中。
但是,如果您使用Python2,您将需要使用ython古典解压,在这里问题下艾哈迈德在评论中提到了这一点。
在我的例子中,我只需要在函数中首先“加入”参数。
def func(args)
(a, b, c, d) = args
# You can then use a, b, c, d in your function
return;
https://stackoverflow.com/questions/47424315
复制相似问题