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

Python脚本转.exe后无法识别不同目录模块的问题求助

解决PyInstaller打包exe后无法识别不同目录模块的问题

针对你当前的目录结构(main.py在根目录,sources、scripts为子目录),可以按以下步骤解决问题:

1. 将子目录转为Python可识别的包

在sources和scripts目录下各创建一个空的__init__.py文件,让Python把这两个目录识别为可导入的包,调整后的目录结构如下:

main.py
sources/
    __init__.py
    sources.py
    buttons.py
scripts/
    __init__.py
    scripts.py

2. 调整导入语句(确保IDE与打包后兼容)

在main.py中使用绝对导入格式,示例如下:

# main.py中的导入示例
from sources.sources import 你的函数或类名
from sources.buttons import 你的函数或类名
from scripts.scripts import 你的函数或类名

3. 打包时明确告知PyInstaller包含子模块

方法一:用命令行参数直接打包

执行打包命令时,通过--hidden-import指定需要额外包含的模块,或者用--collect-submodules批量导入整个包:

# 单个模块指定
pyinstaller --onefile --hidden-import sources.sources --hidden-import sources.buttons --hidden-import scripts.scripts main.py

# 批量导入整个包
pyinstaller --onefile --collect-submodules sources --collect-submodules scripts main.py

方法二:通过spec文件自定义配置

  1. 先生成基础spec文件:
pyinstaller main.py
  1. 打开生成的main.spec,在hiddenimports列表中添加需要的模块:
hiddenimports=['sources.sources', 'sources.buttons', 'scripts.scripts'],
  1. 用spec文件重新打包:
pyinstaller main.spec

4. 备选方案:临时添加路径到模块搜索列表

如果上述方法仍有问题,可在main.py最开头添加代码,将子目录路径加入Python的模块搜索路径:

import sys
import os

# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 把sources和scripts目录加入搜索路径
sys.path.append(os.path.join(current_dir, 'sources'))
sys.path.append(os.path.join(current_dir, 'scripts'))

# 之后再执行导入操作
from sources import xxx
from scripts import xxx

问题原因说明

IDE运行时会自动将项目根目录加入Python的模块搜索路径,但PyInstaller打包时默认只会识别main.py中直接显式导入的模块。如果子目录未被标记为可导入包,或者PyInstaller未检测到深层导入的模块,就会出现找不到模块的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:05:35