多进程调用函数时,如何获取返回的DataFrame变量?
多进程中获取pd.read_pickle返回的DataFrame的解决方案
原代码无法获取子进程返回值的核心原因是:每个进程拥有独立的内存空间,直接用multiprocessing.Process创建的子进程,其返回值不会自动传递到主进程,主进程中未定义df1等变量,自然会报错。以下是两种可行的解决方法:
方法一:使用multiprocessing.Pool(简洁高效)
将读取pickle文件的逻辑封装为通用函数,通过进程池批量处理任务,自动收集返回值:
import pandas as pd import multiprocessing def read_pickle_file(file_path): return pd.read_pickle(file_path) if __name__ == '__main__': # 整理所有要读取的文件路径 file_paths = [ r"C:\xampp\htdocs\bi\cache\ventas.pkl", r"C:\xampp\htdocs\bi\cache\altas.pkl", r"C:\xampp\htdocs\bi\cache\vali.pkl", r"C:\xampp\htdocs\bi\cache\cuotas.pkl" ] # 创建进程池,进程数与文件数匹配 with multiprocessing.Pool(processes=4) as pool: # 批量执行任务,获取所有DataFrame df_list = pool.map(read_pickle_file, file_paths) # 拆分结果到对应变量 df1, df2, df3, df4 = df_list # 验证结果 print(df1.head())
方法二:使用multiprocessing.Queue手动传递结果
如果需要保留原有的四个独立函数,可以通过队列实现进程间的数据传递:
import pandas as pd import multiprocessing def a(queue): df1 = pd.read_pickle(r"C:\xampp\htdocs\bi\cache\ventas.pkl") queue.put(df1) def b(queue): df2 = pd.read_pickle(r"C:\xampp\htdocs\bi\cache\altas.pkl") queue.put(df2) def c(queue): df3 = pd.read_pickle(r"C:\xampp\htdocs\bi\cache\vali.pkl") queue.put(df3) def d(queue): df4 = pd.read_pickle(r"C:\xampp\htdocs\bi\cache\cuotas.pkl") queue.put(df4) if __name__ == '__main__': # 创建进程间通信队列 result_queue = multiprocessing.Queue() # 启动子进程,将队列作为参数传入 p1 = multiprocessing.Process(target=a, args=(result_queue,)) p2 = multiprocessing.Process(target=b, args=(result_queue,)) p3 = multiprocessing.Process(target=c, args=(result_queue,)) p4 = multiprocessing.Process(target=d, args=(result_queue,)) p1.start() p2.start() p3.start() p4.start() # 等待所有子进程执行完毕 p1.join() p2.join() p3.join() p4.join() # 从队列中取出结果(顺序与进程启动顺序一致) df1 = result_queue.get() df2 = result_queue.get() df3 = result_queue.get() df4 = result_queue.get() print(df1)
注意事项
- Windows系统下必须将进程启动代码放在
if __name__ == '__main__':块内,否则会触发重复创建进程的错误。 - 进程间传递DataFrame会涉及序列化/反序列化操作,pandas已自动处理相关逻辑,但数据量过大时会有一定性能开销。
- 优先推荐使用
Pool方案,代码更简洁且易于维护,尤其适合批量同类任务。
内容的提问来源于stack exchange,提问作者Juan Carlos Figueroa
相关产品推荐
相关产品推荐

