【问题标题】:py2exe not including the modules from "includes"py2exe 不包括“包含”中的模块
【发布时间】:2026-02-21 23:30:02
【问题描述】:

我在 64 位 Windows 7 上使用最新版本的 Anaconda Python (3.4) 和最新版本的 py2exe(应该支持 Python 3.3 和 3.4)。

这是我正在使用的 py2exe 脚本:

from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {
                    'py2exe': {
                            'bundle_files': 2,
                            'optimize': 2,
                            'compressed': True,
                    }
               },
    windows = [{'script': "ImageSound GUI.py"}],
    data_files = [('images',['c:/Users/EvilDragon/Documents/GitHub/ImageSound/mario.png'])]
)

这里是 py2exe 返回的输出:

  84 missing Modules                 
  ------------------                 
? Cookie                              imported from requests.compat, tornado.httputil, tornado.web
? IPython.current_nbformat            imported from IPython.nbformat.validator
? Image                               imported from scipy.misc.pilutil
? ImageFilter                         imported from scipy.misc.pilutil
? OpenGL                              imported from IPython.lib.inputhook, IPython.lib.inputhookglut
? PIL._imagingagg                     imported from PIL.ImageDraw
? PyQt5                               imported from IPython.external.qt_loaders, PIL.ImageQt, matplotlib.pyplot
? PySide                              imported from IPython.external.qt_loaders, PIL.ImageQt
? Queue                               imported from IPython.kernel.blocking.channels, IPython.kernel.blocking.client, IPython.kernel.inprocess.blocking, IPython.kernel.inprocess.socket, IPython.kernel.manager, requests.packages.urllib3.connectionpool, zmq.eventloop.zmqstream
? SocketServer                        imported from zmq.ssh.forward
? UserDict                            imported from pytz.lazy
? _abcoll                             imported from requests.packages.urllib3.packages.ordered_dict
? _grabscreen                         imported from PIL.ImageGrab
? _imaging_gif                        imported from PIL.GifImagePlugin
? _subprocess                         imported from IPython.kernel.launcher, IPython.kernel.zmq.parentpoller
? _util                               imported from PIL.ImageCms
? appnope                             imported from IPython.external.appnope
? backports                           imported from requests.packages.urllib3.packages.ssl_match_hostname, setuptools.ssl_support, tornado.netutil
? cloud                               imported from IPython.utils.pickleutil
? cookielib                           imported from requests.compat
? coverage                            imported from IPython.testing.iptestcontroller
? dill                                imported from IPython.utils.pickleutil
? gi                                  imported from IPython.kernel.zmq.gui.gtk3embed, IPython.lib.inputhookgtk3
? glut_support                        imported from IPython.lib.inputhook
? gobject                             imported from IPython.kernel.zmq.gui.gtkembed, IPython.lib.inputhookgtk, matplotlib.pyplot
? gtk                                 imported from IPython.kernel.zmq.gui.gtkembed, IPython.lib.inputhook, IPython.lib.inputhookgtk
? isodate                             imported from jsonschema._format
? matplotlib.backends._macosx         imported from matplotlib.backends.backend_macosx
? mklfft                              imported from numpy.fft
? monotime                            imported from tornado.platform.auto, zmq.eventloop.minitornado.platform.auto
? mpl_toolkits.natgrid                imported from matplotlib.mlab
? multiprocessing.SimpleQueue         imported from concurrent.futures.process
? ndg                                 imported from requests.packages.urllib3.contrib.pyopenssl
? netifaces                           imported from IPython.utils.localinterfaces
? packaging                           imported from pkg_resources
? paramiko                            imported from zmq.ssh.tunnel
? path                                imported from IPython.external.path
? pexpect                             imported from IPython.external.pexpect, zmq.ssh.tunnel
? pyczmq                              imported from zmq.sugar.context
? pydb                                imported from IPython.core.debugger, IPython.core.interactiveshell
? pyglet                              imported from IPython.lib.inputhookpyglet
? pysqlite2                           imported from IPython.core.history
? pywintypes                          imported from -
? repr                                imported from IPython.core.debugger
? resource                            imported from IPython.external.pexpect._pexpect, IPython.utils.timing
? rfc3987                             imported from jsonschema._format
? scikits                             imported from scipy.sparse.linalg.dsolve.linsolve
? scipy.arange                        imported from scipy.sparse.linalg.isolve.minres
? scipy.ones                          imported from scipy.sparse.linalg.isolve.minres
? setuptools_svn                      imported from setuptools.command.egg_info
? simplegeneric                       imported from IPython.external.simplegeneric
? simplejson                          imported from requests.compat
? singledispatch                      imported from tornado.gen
? strict_rfc3339                      imported from jsonschema._format
? unittest._WritelnDecorator          imported from nose.plugins.multiprocess
? urllib.getproxies                   imported from requests.compat
? urllib.pathname2url                 imported from setuptools.compat
? urllib.proxy_bypass                 imported from requests.compat
? urllib.quote                        imported from matplotlib.textpath, requests.compat
? urllib.quote_plus                   imported from requests.compat
? urllib.splittag                     imported from setuptools.compat
? urllib.unquote                      imported from jsonschema.compat, requests.compat
? urllib.unquote_plus                 imported from requests.compat
? urllib.url2pathname                 imported from setuptools.compat
? urllib.urlencode                    imported from IPython.lib.display, requests.compat, requests.packages.urllib3.request, tornado.httputil, tornado.web
? urllib.urlopen                      imported from IPython.core.interactiveshell, IPython.utils.openpy
? urllib.urlretrieve                  imported from IPython.core.extensions, IPython.html.nbextensions
? webcolors                           imported from jsonschema._format
? win32api                            imported from IPython.utils._process_win32, distutils.msvccompiler, platform, win32evtlogutil
? win32com                            imported from setuptools.sandbox
? wincertstore                        imported from setuptools.ssl_support
? zmq.EAGAIN                          imported from zmq.error
? zmq.ETERM                           imported from zmq.devices.basedevice, zmq.error, zmq.eventloop.ioloop
? zmq.PUB                             imported from zmq.devices.monitoredqueuedevice
? zmq.QUEUE                           imported from zmq.devices.basedevice
? zmq.backend.Context                 imported from zmq.sugar.context
? zmq.backend.Frame                   imported from zmq.sugar.frame, zmq.sugar.tracker
? zmq.backend.Socket                  imported from zmq.sugar.socket
? zmq.backend.constants               imported from zmq.sugar.constants
? zmq.backend.strerror                imported from zmq.error
? zmq.backend.zmq_errno               imported from zmq.error
? zmq.backend.zmq_poll                imported from zmq.sugar.poll
? zmq.backend.zmq_version_info        imported from zmq.sugar.version
? zmq.device                          imported from zmq.devices, zmq.devices.basedevice

  5 submodules that appear to be missing, but could also be global names in the parent package
  ---------------------------------------------------------------------------------------------
? numpy.conj                          imported from scipy.io.mmio, scipy.linalg.decomp
? numpy.log2                          imported from scipy.sparse.linalg.matfuncs
? scipy.spatial.cKDTree               imported from scipy.spatial
? scipy.special.ellipeinc             imported from scipy.special
? scipy.special.ellipkinc             imported from scipy.special
Building 'dist\ImageSound GUI.exe'.
Building shared code archive 'dist\library.zip'.
Copy c:\program files\anaconda\python34.dll to dist
Copy DLL C:\Program Files\Anaconda\DLLs\tcl86t.dll to dist
Copy DLL C:\Program Files\Anaconda\DLLs\tk86t.dll to dist
Copy DLL C:\Program Files\Anaconda\lib\site-packages\numpy\core\libiomp5md.dll to dist
Copy DLL C:\Program Files\Anaconda\DLLs\sqlite3.dll to dist
Copy DLL C:\Program Files\Anaconda\lib\site-packages\PyQt4\QtCore4.dll to dist
Copy DLL C:\Program Files\Anaconda\lib\site-packages\portaudio_x64.dll to dist
Copy DLL C:\Program Files\Anaconda\lib\site-packages\PyQt4\QtSvg4.dll to dist
Copy DLL C:\Program Files\Anaconda\lib\site-packages\PyQt4\QtGui4.dll to dist

然后,当我尝试运行我的 EXE 时,我得到了这个回溯:

Traceback (most recent call last):
  File "ImageSound.py", line 5, in <module>
  File "C:\Program Files\Anaconda\lib\site-packages\zipextimporter.py", line 116, in load_module
    raise zipimport.ZipImportError("can't find module %s" % fullname)
zipimport.ZipImportError: can't find module skimage.draw

即使我将 skimage.draw 添加到包含中,这也不会改变...如果我将 bundle_files 设置为 3,那么回溯也会改变:

Traceback (most recent call last):
  File "ImageSound.py", line 5, in <module>
  File "C:\Program Files\Anaconda\lib\site-packages\skimage\draw\__init__.py", line 1, in <module>
    from .draw import circle, ellipse, set_color
  File "C:\Program Files\Anaconda\lib\site-packages\skimage\draw\draw.py", line 3, in <module>
    from ._draw import _coords_inside_image
  File "<loader>", line 10, in <module>
  File "<loader>", line 8, in __load
ImportError: (No module named 'skimage._shared') 'C:\\Users\\EvilDragon\\Documents\\GitHub\\ImageSound\\dist\\skimage.draw._draw.pyd'

这完全超出了我的范围,因为它指向字节码,但是我在 skimage.draw 中使用的唯一函数是 Line,仅此而已!在这一点上我完全感到困惑。

编辑:我尝试使用各种包含和排除运行 py2exe,以便它尝试递归查找所需的内容,但无济于事。它总是会报告缺少 skimage.draw 或没有名为 skimage._shared 的模块。毫无意义,它们就在我的 lib/site-packages/ 文件夹中!

任何有兴趣尝试使用 py2exe 的人都可以在此处查看该程序的代码:https://github.com/mkruselj/ImageSound。必要的库:numpy、scipy、skimage、PIL、pyaudio。

这是我正在使用的两个 .py 文件中的所有包含(一个 .py 文件被导入另一个)。

ImageSound.py:

from tkinter import *
from tkinter import filedialog, ttk, messagebox
from PIL import Image, ImageTk
from numpy import array
from skimage.draw import line as skline
import time
import DSP  # this is the second .py file

DSP.py:

from numpy import linspace, sin, pi, int16, array, append, multiply
from scipy.io.wavfile import write as writewav
from scipy.interpolate import UnivariateSpline as interpolate
from math import sqrt
import pyaudio

感谢您的任何见解!

编辑#2:cx_freeze 和 PyInstaller 也不想合作。我曾尝试使用 nuitka 直接编译东西,但这更糟糕,因为它需要同时安装 py2 和 py3 以及 C++ 编译器。我惨败了。

【问题讨论】:

  • 对于 scipy 包含错误,请尝试将以下行添加到您的包含中:scipy.sparse.csgraph._validation 这似乎是一个常见错误。
  • 将尝试并报告!谢谢,弗兰! :)
  • 不幸的是,这不起作用,仍然报告了相同的缺失模块:(
  • 我不认为 skimage 可以捆绑到 zip 中。使用bundle_files=3,然后连续(反复试验)将缺少的模块附加到'includes' 列表中。这对我有用:'includes': ['pyaudio', 'scipy', 'numpy', 'skimage', 'PIL', 'difflib', 'locale', 'inspect', 'skimage._shared', 'skimage._shared.geometry', 'scipy.special._ufuncs_cxx', 'scipy.linalg.cython_blas', 'scipy.linalg.cython_lapack', 'scipy.integrate', 'scipy.sparse.csgraph._validation']
  • 我刚才尝试了包含,我得到了这个:pastebin.com/raw.php?i=JVAi3cJF。还有一种方法可以将 skimage 与 zip 一起添加到 dist 中吗?我不想在文件夹中有大量文件,这样人们就很难找到 exe(除非我去隐藏所有这些文件,但这不是解决方案)......这是给我的 M. Sc。论文,所以它将与源代码等一起放在CD上。

标签: python py2exe


【解决方案1】:

好吧,既然 cgohlke 没有发布他的建议作为答案,让我这样做。

这个 setup.py 使用 py2exe 为我生成了一个工作可执行文件:

from distutils.core import setup
import py2exe, sys, os, skimage, PIL, numpy, scipy, pyaudio

sys.argv.append('py2exe')

setup(
    options = {
                    'py2exe': {
                            'bundle_files': 3,
                            'optimize': 2,
                            'includes': ['pyaudio', 'scipy', 'numpy', 'skimage', 'PIL', 'difflib', 'locale', 'inspect', 'skimage._shared', 'skimage._shared.geometry', 'scipy.special._ufuncs_cxx', 'scipy.linalg.cython_blas', 'scipy.linalg.cython_lapack', 'scipy.integrate', 'scipy.sparse.csgraph._validation'],
                            'excludes': ['pkg_resources','doctest', 'pdb', 'calendar', 'optparse', 'jsonschema', 'tornado', 'setuptools', 'distutils', 'matplotlib']
                    }
               },
    windows = [{'script': 'ImageSound.py'}],
    data_files = [('images',['images/author.png'])]
)

诀窍在于在 setup.py 中包含所有使用的库,而不是使用捆绑文件选项(对我来说很不幸)!

【讨论】:

    【解决方案2】:

    我建议不要使用“包含”,而是对您遇到问题的包使用“包”。

    看看“http://wiki.wxpython.org/py2exe-python26”有点过时,但大多数(如果不是全部)仍然适用于最新的 py2exe,尤其是查看“zipfile = r'lib\library.zip'”,以便更好地组织你的 dist 文件夹.

    【讨论】:

    • 我尝试使用“包”,但并没有真正起到任何作用。无论如何,根据最初问题帖子的最后评论,我让我的 EXE 正常工作。 :)
    【解决方案3】:

    我前段时间曾涉足 pyexe,但也遇到了问题(尽管那是 Python2.7 和 qt4)。我发现pyinstaller 是一个更好的可执行程序包。正如该网站所说,pyinstaller 几乎已经为 Python 3 做好了准备,可能值得一试。

    【讨论】:

    • 我想我可以尝试一下,但“几乎准备好了”听起来并不令人信服,我必须说...
    • 不,遗憾的是,即使 PyInstaller 也不想合作。 ://