
在 pyinstaller 打包 exe 文件时引入自定义模块
使用 pyinstaller 打包 python 脚本后,在未安装 python 的计算机上运行时,导入自定义模块可能遇到问题。以下是如何解决此问题:
对于给定的示例,文件结构如下:
test1 ├ temp │ └ sample_test.py └ calltest.py
其中包含以下代码:
calltest.py:
import sys
sys.path.append('./temp')
from sample_test import *
stdresult = eval("dispatch_character('input_test')")
print(stdresult)sample_test.py:
def dispatch_character(argv):
return argv + '_ok'原本未打包前可以正常运行,但打包成 exe 文件后,使用以下命令打包:
易学易用:友好的系统操作界面,无须具备专业知识,即可熟练的使用系统。功能完善:具备新建、修改、明细、审批、导入、导出、删除、批量、打印等功能。模型开发:自定义表单字段选项零代码二次开发,可无限扩展后台功能模块。 维护方便:基于互联网技术B/S体系结构,实施快速,极大的减少系统升级维护工作。售后保证:专业的技术研发团队,可提供可靠的产品迭代、版本升级和技术支持服务。超低成本:一次投入终身使用、用户不
pyinstaller calltest.py --onefile pyinstaller sample_test.py --onefile
打包后的文件结构如下:
test2 ├ temp │ └ sample_test.exe └ calltest.exe
运行 calltest.exe 会报错:
traceback (most recent call last): file "calltest.py", line 3, inmodulenotfounderror: no module named 'sample_test' [19324] failed to execute script calltest
解决方案是修改 pyinstaller 的 spec 文件(spec 文件在打包时自动生成):
- 找到生成的 spec 文件,通常在 build 目录下,如 build/calltest/calltest.spec。
- 编辑 spec 文件,增加以下行:
a.datas = [('temp/sample_test.py', './sample_test.py')]这行代码将 sample_test.py 文件复制到 exe 文件的同一目录中。
- 重新打包 calltest.py:
pyinstaller callTest.py --onefile --clean
现在,calltest.exe 可以正确导入 sample_test 模块并在未安装 python 的计算机上运行。









