在 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 文件后,使用以下命令打包:
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, in <module> modulenotfounderror: no module named 'sample_test' [19324] failed to execute script calltest
解决方案是修改 pyinstaller 的 spec 文件(spec 文件在打包时自动生成):
a.datas = [('temp/sample_test.py', './sample_test.py')]
这行代码将 sample_test.py 文件复制到 exe 文件的同一目录中。
pyinstaller callTest.py --onefile --clean
现在,calltest.exe 可以正确导入 sample_test 模块并在未安装 python 的计算机上运行。
以上就是使用 Pyinstaller 打包后如何导入自定义模块?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号