[英]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
function 中传递另一个变量,它将确定路径。
所以我想 function 是这样的(这样它也可以用于其他路径):
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)
并将 function 签名更改为
def read_extracted(*args):
name, path = args
针对您的情况的第二个选项只是传递完整路径列表。
json_files = ['path/to/f1', 'path/to/f2']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.