PyInstaller 运行正常,但 exe 文件错误:没有命名模块,无法执行脚本

Zan*_*nam 6 pyinstaller python-2.7

我正在运行以下代码:

pyinstaller --onefile main.py
Run Code Online (Sandbox Code Playgroud)

main.py好像:

import sys
import os
sys.path.append(r'C:\Model\Utilities')
from import_pythonpkg import *

......
Run Code Online (Sandbox Code Playgroud)

import_pythonpkg.py好像:

from astroML.density_estimation import EmpiricalDistribution
import calendar
import collections
from collections import Counter, OrderedDict, defaultdict
import csv

....
Run Code Online (Sandbox Code Playgroud)

通过运行pyinstalleron main.pymain.exe文件已成功创建。

但是当我运行时main.exe它给出了错误astroML。如果我转到astroMLfrom main.pyimport_pythonpkg.py则 不会出现错误astroML。现在我收到错误csv

即如果我将其更改main.py为:

import sys
from astroML.density_estimation import EmpiricalDistribution
import os
sys.path.append(r'C:\Model\Utilities')
from import_pythonpkg import *

......
Run Code Online (Sandbox Code Playgroud)

当我运行时,错误astroML不再存在main.exe

import calendarline inimport_pythonpkg.py完全没有错误。

我不确定在运行main.exe后运行时如何处理包的随机错误pyinstaller

import_pythonpkg位于r'C:\Model\Utilities'

编辑:

main.exe尽管原始版本运行良好,但错误看起来如下main.py。Pyinstaller 甚至能够让我main.exe毫无错误地创建。

    Traceback (most recent call last):
  File "main.py", line 8, in <module>
  File "C:\Model\Utilities\import_pythonpkg.py", line 1, in <module>
    from astroML.density_estimation import EmpiricalDistribution
ImportError: No module named astroML.density_estimation
[29180] Failed to execute script main
Run Code Online (Sandbox Code Playgroud)

The*_*man 1

我相信 PyInstaller 没有看到import_pythonpkg. 根据我的经验,当添加到路径或处理外部模块和 dll 时,PyInstaller 不会去搜索它,你必须明确告诉它这样做。它会正确编译为 .exe,因为它只是忽略它,但随后不会运行。检查运行 PyInstaller 命令时是否有任何有关缺少包或模块的警告。

但如何解决它...如果确实是这个问题(我不确定是不是),你可以尝试 3 件事:

1)将该包移动到您的工作目录中并避免使用sys.path.append. 然后用 PyInstaller 进行编译,看看这是否有效,那么你就知道问题是 pyinstaller 无法找到import_pythonpkg. 如果这有效的话你可以停在那里。

2) 明确告诉 PyInstaller 去那里查看。您可以在使用 PyInstaller 编译时使用该hidden-import标签来让它知道(给它完整的路径名)。

--hidden-import=modulename
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看此处:如何正确创建 pyinstaller 挂钩,或者隐藏导入?

3)如果您使用 PyInstaller 创建的规范文件,您可以尝试添加一个变量调用pathex来告诉 PyInstaller 在那里搜索内容:

block_cipher = None
a = Analysis(['minimal.py'],
    pathex=['C:\\Program Files (x86)\\Windows Kits\\10\\example_directory'],
    binaries=None,
    datas=None,
    hiddenimports=['path_to_import', 'path_to_second_import'],
    hookspath=None,
    runtime_hooks=None,
    excludes=None,
    cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
    cipher=block_cipher)
exe = EXE(pyz,... )
coll = COLLECT(...)
Run Code Online (Sandbox Code Playgroud)

有关规范文件的更多信息:https://pyinstaller.readthedocs.io/en/stable/spec-files.html

(请注意,您还可以在此处添加隐藏导入)

这个答案也可能会有所帮助:PyInstaller - 没有名为的模块