当我已经安装了父模块时,如何解决缺少的实用程序模块阻止我的可执行文件 运行?

How do I resolve a missing utility module preventing my executable from running when I already installed the parent module?

我已经编写了一些 Python 脚本来为机器学习算法过程创建一个 tkinter GUI。我最初在 PyCharm 中编写了所有内容,但我真的很想将所有内容放在一个独立的可执行文件中。我已将我的主脚本及其 .py 依赖项移动到它们自己的目录中,并使用命令提示符对其进行了测试,效果很好。但是,当我 运行 pyinstaller 时,可执行文件已创建但启动失败。

程序由三个文件组成,GUI.py是主脚本。如上所述,我将依赖文件移动到一个新目录并在命令提示符中测试 GUI.py ,并且效果很好。可执行文件已创建(尽管有很多关于丢失 'api-ms-win-crt' 文件的警告)但不能是 运行.

我使用以下命令创建了可执行文件:

pyinstaller --onefile GUI.py

当可执行文件在创建后从命令行 运行 时,我得到一个很长的回溯,结尾如下:

File "site-packages\sklearn\metrics\pairwise.py", line 32, in <module>
File "sklearn\metrics\pairwise_fast.pyx", line 1, in init 
    sklearn.metrics.pairwise_fast
ModuleNotFoundError: No module named 'sklearn.utils._cython_blas'
[3372] Failed to execute script GUI

我知道我已经通过命令提示符显式导入了 sklearn,但从回溯来看,我似乎在某处缺少实用程序模块。我试图专门导入缺少的模块,但出现没有分布式模块可用的错误。 我对 pyinstaller 没有太多经验,我不知道从这里去哪里。我正在使用 Windows 10 和 Python 3.7.3.

Pyinstaller 似乎无法解析 sklearn 导入。因此,一种简单的方法是将位于 <path_to_python>/Lib/site-packages/sklearn/ 中的整个模块目录与可执行输出一起使用。所以使用下面的规范文件来生成你的可执行文件:

# -*- mode: python -*-

block_cipher = None


a = Analysis(['test.py'],
             pathex=['<path to root of your project>'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
a.datas += Tree('<path_to_sklearn_in_python_dir>', prefix='sklearn')
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='test',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=False,
          runtime_tmpdir=None,
          console=True )

最后用

生成你的可执行文件
pyinstaller test.spec

这应该可以解决 sklearn 的导入错误,但如果您遇到其他 NotFound 导入,请像上面一样将它们添加到规范文件中。

的基础上,您可以直接在原始 pyinstaller 命令中包含 sklearn 的路径:

pyinstaller --onefile GUI.py --add-data "<path-to-python>\Lib\site-packages\sklearn;sklearn"

这会导致在自动生成的 GUI.spec 文件中的 a = Analysis() 中添加以下代码行:

datas=[('<path-to-python>\Lib\site-packages\sklearn', 'sklearn')]

请注意,--onefile 选项将导致可执行文件的启动速度比默认的单文件夹捆绑包慢(基于 pyinstaller documentation 和我自己捆绑的经验 sklearn):

pyinstaller GUI.py --add-data "<path-to-python>\Lib\site-packages\sklearn;sklearn"