由pyinstaller创建的exe文件,在运行时找不到自定义模块

Dar*_*gic 9 python python-2.6 pyinstaller python-2.7 python-3.x

我创建了两个python文件,目录/文件关系如下:

mytest---
     |---mycommon.py
     |---myMainDir---
                     |----myMain.py
Run Code Online (Sandbox Code Playgroud)

在mycommon.py中:

def myFunc(a):
    ...
Run Code Online (Sandbox Code Playgroud)

在myMain.py中:

import sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath('__file__')), '..'))
import mycommon.py
mycommon.myFunc("abc")
Run Code Online (Sandbox Code Playgroud)

然后我使用pyinstaller创建了exe:

pyinstall.py -F mytest\myMainDir\myMain.py
Run Code Online (Sandbox Code Playgroud)

MyMain.exe已创建,但运行时会告诉无法找到mycommon模块.

Yoe*_*oel 17

PyInstaller的官方手册描述了这个问题:

一些Python脚本以PyInstaller无法检测的方式导入模块:例如,通过将__import__()函数与变量数据一起使用,或sys.path在运行时操作值.如果您的脚本需要PyInstaller不知道的文件,您必须提供帮助.

它还建议在这种情况下应该做些什么:

如果Analysis认识到需要一个模块,但找不到该模块,那通常是因为脚本正在操作sys.path.在这种情况下最简单的方法是使用该--paths=选项列出脚本可能正在搜索导入的所有其他位置:

pyi-makespec --paths=/path/to/thisdir --paths=/path/to/otherdir myscript.py

这些路径将sys.path在分析期间添加到当前路径中.

因此,请--paths在构建应用程序时指定参数.手册指出指定-p参数是等效的:

-p dir_list, --paths=dir_list

设置导入模块的搜索路径(如使用PYTHONPATH).使用此选项可帮助PyInstaller在代码修改sys.path导入时在正确的位置进行搜索.将一个或多个路径分隔;(在Windows下)或:(所有其他平台),或者多次提供该选项以提供多个搜索路径.