我过去曾多次使用 py2exe 为我的 python 程序创建 *.exe 文件。但是,这次我遇到了一个错误。我想我知道问题是什么,但我不知道如何解决。
我在一个子文件夹中有一些 wx.Panels,它的数量可能是可变的,所以我通过一个函数导入它们,该函数在文件夹中找到 *.py 文件并调用下面的函数来实际导入每个面板。
在普通的 python 中,这很有效。但是,py2exe 将这些文件排除在外。我假设因为它们没有明确导入,所以 py2exe 认为不需要它们。有针对这个的解决方法吗?我不知道 py2exe 中的某些选项?
谢谢!
# module = Module to be imported (string)
# folder = Folder containing the module (string)
def import_module(module, folder=None):
if folder is None:
return __import__(module)
return getattr(__import__('%s.%s' % (folder.replace(os.path.sep, '.'),
module)), module)
...within some other function...
modules = [import_module(os.path.basename(os.path.splitext(filename)[0]), 'Panels') for filename in glob.glob('Panels//*.py')]
编辑
我正在添加一个我使用过的示例 setup.py 脚本。但我已经使用了大概 20 种不同的变体和几个完全不同的脚本(我可以在 Internet 上找到的)。请注意,一个要求是它完全独立于一个可执行文件中。
from distutils.core import setup
import py2exe
import wxversion
wxversion.select("2.8.12.1")
import wx
import wx.lib.pubsub
includes = []
excludes = ['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger',
'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl',
'Tkconstants', 'Tkinter']
packages = ['wx.lib.pubsub']
dll_excludes = ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll',
'tk84.dll']
import glob
my_data_files = [('Panels', glob.glob('Panels/*.py'))]
setup(
options = {"py2exe": {"compressed": 2,
"optimize": 2,
"includes": includes,
"excludes": excludes,
"packages": packages,
"dll_excludes": dll_excludes,
"bundle_files": 2,
"dist_dir": "dist",
"xref": False,
"skip_archive": False,
"ascii": False,
"custom_boot_script": '',
}
},
zipfile = None,
#data_files = my_data_files,
windows=['Main.py']
)
最佳答案
我相信我已经找到了我的问题的解决方案。在我的 setup.py 文件中,我将“includes = []”行替换为:
includes = ['Panels.%s' % os.path.basename(os.path.splitext(filename)[0]) for
filename in glob.glob('Panels//*.py')]
在我使用“import_module”函数的代码中,它曾经使用该 glob 来导入 Panels 目录中的模块。相反,我对要包含的模块列表进行了硬编码。
这不是我想要的确切解决方案(我不想对该面板列表进行硬编码),但它似乎确实有效。除非我发现更好的东西,否则我将继续使用它。
关于Python 和 py2exe - 隐式导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8997490/