在Python中并行执行一个函数

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

下面是并行代码。当我运行时,我得到了错误------。UnboundLocalError: 本地变量'df_project'在赋值前被引用。 我不知道我做错了什么。当我把同样的代码作为一个普通函数运行时,它可以正常工作。

任何输入将是巨大的帮助

from multiprocessing import Pool

def square(x):
    # calculate the square of the value of x
    v=x['content'][0]['template']['module']
    if isinstance(v, list):
        for i, v2 in enumerate(v): 
            df_project,df_module,df_module_header,df_module_paragraph,df_module_image,df_module_chart,df_module_chart_row,df_module_list = normalizeJSON(x,i,v2['id'])
    else:
        print('module is not a list')

    return df_project,df_module,df_module_header,df_module_paragraph,df_module_image,df_module_chart,df_module_chart_row,df_module_list

if __name__ == '__main__':

    # Define the dataset
    dataset = result_list

    # Run this with a pool of 5 agents having a chunksize of 3 until finished
    agents = 5
    chunksize = 3
    project=pd.DataFrame()
    module=pd.DataFrame()
    content_module_columns=["module_id","module_text", "project_id", "project_revision","index"]  
    dim_content_module=pd.DataFrame(columns = content_module_columns)

    with Pool(processes=agents) as pool:
         project,module, module_header,module_paragraph,module_image,module_chart,module_chart_row,module_list=pool.map(square,dataset,chunksize)


Below is the normal (serial) version of the code that Im trying to parallelize 

    for index in range(len(result_list)):
        print('processing file number:', index)
        d=result_list[index]
        v=d['content'][0]['template']['module']
        if isinstance(v, list):
           for i, v2 in enumerate(v): 
               df_project,df_module = normalizeJSON(d,i,v2['id'])
               dim_content_module=dim_content_module.append(df_module, 
                                  ignore_index=True,sort=False)
        else:
            print('module is not a list')

I dont get any error in the serial version with the same input. 

*result_list* is a list of dictionaries
python python-multithreading
1个回答
0
投票

在没有看到完整的堆栈跟踪的情况下,很难猜测,但很可能你的问题出在这个函数上。


def square(x):
    # calculate the square of the value of x
    v=x['content'][0]['template']['module']
    if isinstance(v, list):
        for i, v2 in enumerate(v): 
            df_project,df_module,df_module_header,df_module_paragraph,df_module_image,df_module_chart,df_module_chart_row,df_module_list = normalizeJSON(x,i,v2['id'])
    else:
        print('module is not a list')

    return df_project,df_module,df_module_header,df_module_paragraph,df_module_image,df_module_chart,df_module_chart_row,df_module_list

最有可能的是 isinstance 退货 False 在其中一次运行中,当在 return 你想使用所有这些对象,它就会抛出 UnboundLocalError 因为事实上你引用的变量从来没有被分配过。

© www.soinside.com 2019 - 2024. All rights reserved.