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

2024-04-26 01:26:46 发布

您现在位置: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"}} ]}

Tags: 文件nameimportidjsonfieldsmodel字典