Multiprocessing.pool - 在可并行函数中传递另一个变量

Multiprocessing.pool - Pass another variable in the parallelisable function

假设我有以下代码:

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) 

应该这样写才能正常工作?

还有更好的选择吗?

您有两个选择:

一般选项是传递一个可迭代的序列(例如,一个元组)

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']