Multiprocessing.pool-在parallelisable函数中传递另一个变量

问题描述 投票:0回答:1

假设我有以下代码:

path = "/my_path/"
filename_ending = '.json'


json_files = [file for file in os.listdir(f"{path}") if file.endswith(filename_ending)]


def read_extracted(name):
    with open(f"/my_path/{name}", 'r') as f:
        return json.load(f)


with mp.Pool(processes=os.cpu_count()-1) as pool:       
    json_list = pool.map(read_extracted, json_files) 

但是我想在read_extracted函数中传递另一个变量,该变量将确定路径。

所以我想像那样起作用(以便它也可以用于其他路径):

def read_extracted(name, path):
    with open(f"{path}{name}", 'r') as f:
        return json.load(f)

但是此行如何:

json_list = pool.map(read_extracted, json_files) 

应该写成能正常工作吗?

还有更好的选择吗?

python pool
1个回答
0
投票

您有两个选择:

常规选项是传递可迭代的序列(例如,元组)

json_files_and_path = [(f1, path), (f2, path)]
json_list = pool.map(read_extracted, json_files_and_path)

并将功能签名更改为

def read_extracted(*args):
  name, path = args

针对您的情况的第二种选择只是传递完整路径列表。

json_files = ['path/to/f1', 'path/to/f2']
© www.soinside.com 2019 - 2024. All rights reserved.