python - 使用多处理在python3.7中并行运行不同的函数
问题描述
我想在 python 中并行运行两个不同的函数,我使用了以下代码:
def remove_special_char(data):
data['Description'] = data['Description'].apply(lambda val: re.sub(r'^=', "'=", str(val))) # Change cell values which start with '=' sign leading to Excel formula issues
return(data)
file_path1 = '.\file1.xlsx'
file_path2 = '.\file2.xlsx'
def method1(file_path1):
data = pd.read_excel(file_path1)
data= remove_special_char(data)
return data
def method2(file_path2):
data = pd.read_excel(file_path2)
data= remove_special_char(data)
return data
我正在使用以下Pool
过程,但它不起作用。
from multiprocessing import Pool
p = Pool(3)
result1 = p.map(method1(file_path1), args=file_path1)
result2 = p.map(method2(file_path1), args=file_path2)
我想并行运行这两种方法以节省执行时间,同时也获得返回值。
解决方案
我不知道你为什么用不同的参数名称定义相同的方法两次,但无论如何 s 的map
方法Pool
将一个函数作为它的第一个参数,而第二个参数是一个可迭代的。什么map
是在可迭代的每个项目上调用函数,并返回一个包含所有结果的列表。所以你想要做的更像是:
from multiprocessing import Pool
file_paths = ('.\file1.xlsx', '.\file2.xlsx')
def method(file_path):
data = pd.read_excel(file_path)
data= remove_special_char(data)
return data
with Pool(3) as p:
result = p.map(method, file_paths)