【问题标题】:No module named 'scipy' after creating exe with pyinstaller使用 pyinstaller 创建 exe 后没有名为“scipy”的模块
【发布时间】:2023-08-05 01:06:01
【问题描述】:

所以我有一个使用 PIL、numpy 和 scipy 打印图像主色的脚本:

from PIL import Image
import numpy as np
import scipy.cluster

def dominant_color(image):
    NUM_CLUSTERS = 5

    image = image.resize((150, 150))      # optional, to reduce time
    ar = np.asarray(image)
    shape = ar.shape
    ar = ar.reshape(np.product(shape[:2]), shape[2]).astype(float)

    codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)

    vecs, dist = scipy.cluster.vq.vq(ar, codes)         # assign codes
    counts, bins = np.histogram(vecs, len(codes))    # count occurrences

    index_max = np.argmax(counts)                    # find most frequent
    color = tuple([int(code) for code in codes[index_max]])
    return color

image = Image.open("image.jpg")
print(dominant_color(image))

我使用命令pyinstaller --onefile --hidden-import=scipy test.py 使用pyinstaller 创建了一个exe 但即使在运行exe 时使用隐藏导入,我也会得到ModuleNotFoundError: No module named 'scipy' 我也尝试将scipy.cluster 添加为隐藏导入,但我仍然得到相同的错误。我在这里错过了隐藏的导入吗?

【问题讨论】:

  • 也许你有多个 python 版本?您可能使用未安装模块的版本构建了您的解决方案
  • @CanciuCostin 我只安装了 python 3.8。

标签: python python-3.x scipy pyinstaller


【解决方案1】:

我尝试了您的代码并使用它生成了 exe,使用以下命令

pyinstaller --onefile --hidden-import=pkg_resources.py2_warn test.py

我没有收到任何错误。

我的建议是先试试上面的命令。 如果还是不行,那么你可能需要检查你的环境变量,以及是否有可能在系统中安装了多个python。

【讨论】:

    【解决方案2】:

    我是如何解决的:

    在目录中创建一个文件,代码如下:

    from PyInstaller.utils.hooks import collect_submodules
    from PyInstaller.utils.hooks import collect_data_files
    hiddenimports = collect_submodules('scipy')
    
    datas = collect_data_files('scipy')
    

    然后用--additional-hooks-dir=.newFileName.py运行命令

    【讨论】: