You need to enable JavaScript to run this app. PyInstaller打包含Multiprocessing、Pandas的脚本运行报文件缺失错误
优惠活动
大模型
产品
解决方案
定价
更多

PyInstaller打包含Multiprocessing、Pandas的脚本运行报文件缺失错误

PyInstaller打包多进程程序运行异常说明

核心异常表现

在PyCharm原生Python环境下运行脚本完全正常,打包为独立exe后出现两类无法解释的问题:

  • 本应仅输出一次的Start DateTime...启动提示日志,随第一个子进程启动后重复输出一次
  • 首次读取1200万行CSV文件、切分完成13个数据块的流程全部正常完成,启动第一个并行子进程时直接崩溃,抛出FileNotFoundError,报错提示找不到名为parent_pid=22208的文件

附完整运行日志:

Start DateTime=2020-11-18 11:29:22
Pandas reading large CSV file
Number of rows in CSV loaded into memory: 12,632,654
group_size= 1,052,721
remainder_size= 2
Number of split_dataframes= 12
Revised Number of split_dataframes= 13
split_df: 0  size= 1052721
split_df: 1  size= 1052721
split_df: 2  size= 1052721
split_df: 3  size= 1052721
split_df: 4  size= 1052721
split_df: 5  size= 1052721
split_df: 6  size= 1052721
split_df: 7  size= 1052721
split_df: 8  size= 1052721
split_df: 9  size= 1052721
split_df: 10  size= 1052721
split_df: 11  size= 1052721
split_df: 12  size= 2
Number of Concurrent Process= 12
Defining Process: 0
Starting Process: 0
Start DateTime=2020-11-18 11:29:41
Pandas reading large CSV file
Traceback (most recent call last):
  File "UploadIP2LocationsToMongoDBMultiProc.py", line 243, in <module>
  File "pandas\io\parsers.py", line 688, in read_csv
  File "pandas\io\parsers.py", line 454, in _read
  File "pandas\io\parsers.py", line 948, in __init__
  File "pandas\io\parsers.py", line 1180, in _make_engine
  File "pandas\io\parsers.py", line 2010, in __init__
  File "pandas\_libs\parsers.pyx", line 382, in pandas._libs.parsers.TextReader.__cinit__
  File "pandas\_libs\parsers.pyx", line 674, in pandas._libs.parsers.TextReader._setup_parser_source
FileNotFoundError: [Errno 2] No such file or directory: 'parent_pid=22208'
[22956] Failed to execute script UploadIP2LocationsToMongoDBMultiProc

根因解释

这类问题是Windows环境下使用multiprocessing配合PyInstaller打包的经典兼容问题:

  • Windows系统没有类Unix系统的fork进程创建机制,多进程库默认使用spawn模式启动子进程,子进程初始化时会从头重新导入主程序模块的所有顶层代码
  • PyInstaller打包后的exe在spawn子进程时,会通过命令行传入父进程PID等特殊参数作为进程标识
  • 如果主程序没有加主模块入口保护,子进程导入模块时会从上到下执行所有顶层业务代码:重复打印启动日志、重复执行读CSV操作,且pandas会把传给子进程的特殊参数parent_pid=xxx错误识别为待读取的CSV文件路径,直接抛出文件不存在的错误

修复步骤

  • 所有业务逻辑代码全部包裹在if __name__ == "__main__":入口判断块中:避免子进程重新导入模块时错误执行业务流程
  • 在主入口块的最开头调用multiprocessing.freeze_support():这是PyInstaller官方提供的打包兼容函数,会拦截子进程启动时的特殊命令行参数,跳过子进程的业务代码执行

修复后的核心代码结构参考:

import multiprocessing as mp
import pandas as pd

# 子进程的执行函数保留在模块顶层,不需要放入主入口块
def load_dataframe_to_mongodb(process_index, df_chunk, mongodb_collection):
    # 原有数据上传逻辑
    pass

if __name__ == "__main__":
    # 兼容PyInstaller打包多进程的必须调用
    mp.freeze_support()

    # 原有所有顶层业务代码全部挪入这个块中
    print("Start DateTime=" + str(startDateNowFmt))
    print("Pandas reading large CSV file")
    df = pd.read_csv(input_csv_filename, dtype=dataTypes)
    print(f"Number of rows in CSV loaded into memory: {len(df.index):,}")

    processes = []
    for index, split_df in enumerate(df_split_list):
        print("Defining Process:", index)
        process = mp.Process(
            target=load_dataframe_to_mongodb,
            args=(index, split_df, arg_mongodb_collection_name)
        )
        processes.append(process)
        print("Starting Process:", index)
        process.start()

    for indx, process in enumerate(processes):
        process.join()

重新打包运行后,即可消除日志重复输出、子进程错误识别文件路径的异常。

内容的提问来源于stack exchange,提问作者NealWalters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.16 15:54:08