本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

使用Pyinstaller打包后如何导入自定义模块?

网络教程 app 1℃

使用Pyinstaller打包后如何导入自定义模块

在 pyinstaller 打包 exe 文件时引入自定义模块

使用 pyinstaller 打包 python 脚本后,在未安装 python 的计算机上运行时,导入自定义模块可能遇到问题。以下是如何解决此问题:

对于给定的示例,文件结构如下:

test1├ temp│ └ sample_test.py└ calltest.py

其中包含以下代码:

calltest.py:

import syssys.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 –onefilepyinstaller 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 文件在打包时自动生成):

    找到生成的 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 的计算机上运行。

以上就是使用 Pyinstaller 打包后如何导入自定义模块?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » 使用Pyinstaller打包后如何导入自定义模块?

喜欢 (0)