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

使用PyInstaller打包含本地CompanyAPI包的exe时遇模块缺失问题

解决PyInstaller打包本地Python包时的ModuleNotFoundError问题

检查setup.py配置是否正确

确保setup.py正确声明包结构,示例配置如下:

from setuptools import setup, find_packages

setup(
    name="CompanyAPI",
    version="0.1",
    packages=find_packages(),  # 自动识别子目录下的包
    # 可添加author、description等可选配置
)

执行pip install -e .(无需额外--find-links参数),在Python交互环境测试from CompanyAPI import site1,确认包已正确安装到环境中。

基于虚拟环境执行打包操作

  1. 激活虚拟环境:
    • Windows:venv\Scripts\activate
    • Linux/macOS:source venv/bin/activate
  2. 在虚拟环境中重新安装本地包:pip install -e .
  3. 安装PyInstaller:pip install pyinstaller
  4. 执行打包命令(注意参数是--hidden-import而非--hidden-imports):
    pyinstaller --hidden-import CompanyAPI --hidden-import CompanyAPI.site1 --hidden-import CompanyAPI.site2 main.py
    

修改PyInstaller spec文件(更可靠方案)

  1. 生成spec文件:pyinstaller main.py
  2. 打开main.spec,在hiddenimports列表中添加包和子模块:
    a = Analysis(
        ['main.py'],
        pathex=['./'],  # 确保包含项目根目录
        binaries=[],
        datas=[],
        hiddenimports=['CompanyAPI', 'CompanyAPI.site1', 'CompanyAPI.site2'],
        hookspath=[],
        hooksconfig={},
        runtime_hooks=[],
        excludes=[],
        win_no_prefer_redirects=False,
        win_private_assemblies=False,
        cipher=block_cipher,
        noarchive=False,
    )
    
  3. 用spec文件重新打包:pyinstaller main.spec

确认sys.path添加时机正确

若在main.py手动添加路径,需在导入CompanyAPI前执行:

import sys
import os

# 将项目根目录添加到sys.path
sys.path.append(os.path.abspath(os.path.dirname(__file__)))

from CompanyAPI import site1

确保os.path.dirname(__file__)指向包含内层CompanyAPI文件夹的根目录。

让PyCharm识别本地包

打开File > Settings > Project: [你的项目名] > Python Interpreter,点击右上角齿轮图标选择Add,选中虚拟环境的Python解释器,PyCharm会自动识别已安装的CompanyAPI包并显示在列表中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 15:22:36