You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyInstaller打包含pandas的Python脚本时遇导入与语法错误

问题描述
  • 无模块依赖的简单Python脚本可通过PyInstaller正常打包为.exe,但包含pandas的脚本打包失败
  • 待打包脚本内容:
import pandas as pd
pd.DataFrame()
name = input(" Enter your Name  ")
print(" Your name is ", name)
  • 在Anaconda Prompt执行打包命令:
pyinstaller --onefile untitled2.py
  • 出现报错:

    ImportError: cannot import name 'Sequence' from 'collections' (C:\ProgramData\anaconda3\lib\collections_init_.py)
    Traceback (most recent call last)
    SyntaxError: invalid syntax

  • 在Windows PowerShell中执行pyinstaller命令时,提示:
C:\Users\INTELIGENCIA>pyinstaller
pyinstaller' is not recognized as an internal or external command operable program or batch file
  • 补充背景:近期在公司电脑安装了Anaconda,此前修改过pip安装路径,不确定是否与报错相关
解决方案

一、解决PowerShell中PyInstaller命令未识别问题

PyInstaller默认安装在Anaconda的Scripts目录下,PowerShell未将该路径加入环境变量,可通过以下方式解决:

  • 直接调用绝对路径执行打包:
    C:\ProgramData\anaconda3\Scripts\pyinstaller --onefile untitled2.py
    
  • 先激活Anaconda的base环境再执行命令:
    conda activate base
    pyinstaller --onefile untitled2.py
    
  • 永久解决:将C:\ProgramData\anaconda3\Scripts添加到系统环境变量的PATH中,重启PowerShell后即可直接使用pyinstaller命令

二、解决打包时的ImportError和SyntaxError问题

核心原因

Python 3.10及以上版本中,Sequence等集合抽象类型从collections模块迁移到了collections.abc,旧版本的pandas或PyInstaller仍使用旧导入逻辑,导致兼容报错;SyntaxError多为依赖版本不连锁匹配引发的语法冲突。

具体解决步骤

  1. 升级依赖到兼容版本
    在Anaconda Prompt中执行:

    conda update pandas pyinstaller
    

    若使用pip管理依赖:

    pip install --upgrade pandas pyinstaller
    
  2. 添加PyInstaller钩子文件(升级后仍报错时使用)
    创建名为hook-pandas.py的文件,内容如下:

    from PyInstaller.utils.hooks import collect_submodules
    hiddenimports = collect_submodules('pandas')
    

    打包时指定钩子文件所在目录:

    pyinstaller --onefile --additional-hooks-dir=. untitled2.py
    
  3. 临时修改库文件导入逻辑(仅作应急方案)
    找到报错的from collections import Sequence代码行,替换为from collections.abc import Sequence。此方法需修改第三方库文件,不推荐长期使用,仅作为临时应急手段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:42:41