Python - 池映射从方法返回一些字典两次



我正在尝试使用Python的multiprocessing来加速从大型json文件中读取和处理数据的任务。处理完数据后,我需要将新数据写入新的 json 文件。但是,该方法返回某些字典两次或更多次,并完全忽略其他字典(不返回它们(。

此方法处理products中的每个product,并调用另一个称为func的函数,该函数将处理字典并将其返回给p_entry_attributes。如果我在返回之前打印p_entry_attributes,它将打印正确的字典,但在输出文件中import_file.json,有些词典重复,有些词典不存在。

def mainFunc(product):
import_entry_file["entries"] = copy.deepcopy(import_entry_file["entries"])
p_entry_attributes = copy.deepcopy(product_model)
try:
if (famille_produit == ""):
p_entry_attributes = func(product, product_model)
return p_entry_attributes
except Exception as e:
# Capture exception error log
print(e)
if __name__ == "__main__":
lock = mp.Lock()
pool = Pool(initializer=setup, initargs=[lock])
ent = pool.map(mainFunc, products)
pool.close()
pool.join()
pool.terminate()
import_entry_file["entries"] = []
for ele in ent:
import_entry_file["entries"].append(ele)
with open("data/import_file.json", 'w', encoding="utf-8") as outfile:
json.dump(import_entry_file, outfile, ensure_ascii=False)

这是修改字典并返回字典的方法 func。

def func(product, product_model):
p_entry_attributes = product_model
p_entry_attributes["fields"]["name"] = product["name"]
p_entry_attributes["fields"]["id"] = product["id"]
return p_entry_attributes

例如,如果我有两个这种格式的product

{ 'name' : 'one', 'id' : '1'}{ 'name' : 'two', 'id' : '2'}

我的输出文件将如下所示:

{ "entries" : [ {"fields" : { "name" : "two", "id" : "2" }, { "name" : "two", "id" : "2"}} ]}

而不是:

{ "entries" : [ {"fields" : { "name" : "one", "id" : "1" }, { "name" : "two", "id" : "2"}} ]}

尝试在函数中copy.deepcopy

p_entry_attributes = copy.deepcopy(product_model)

最新更新