Py2exe:在library.zip或exe文件中嵌入静态文件,并在运行时透明地访问它们
有没有办法让py2exe把静态文件(或者静态文件的子目录)嵌入到一个library.zip文件里,或者直接嵌入到exe文件中(这样zipfile就可以设为None),然后在运行时可以直接从代码中访问这些嵌入的静态文件呢?
谢谢,
Malcolm
3 个回答
0
很遗憾,py2exe已经改变了它的模块工作方式,所以这里提供的示例 已经不再有效。
我通过重写py2exe的一个功能,成功实现了这个功能,然后把它们放进py2exe创建的压缩文件里。
下面是一个示例:
import py2exe
import zipfile
myFiles = [
"C:/Users/Kade/Documents/ExampleFiles/example_1.doc",
"C:/Users/Kade/Documents/ExampleFiles/example_2.dll",
"C:/Users/Kade/Documents/ExampleFiles/example_3.obj",
"C:/Users/Kade/Documents/ExampleFiles/example_4.H",
]
def better_copy_files(self, destdir):
"""Overriden so that things can be included in the library.zip."""
#Run function as normal
original_copy_files(self, destdir)
#Get the zipfile's location
if self.options.libname is not None:
libpath = os.path.join(destdir, self.options.libname)
#Re-open the zip file
if self.options.compress:
compression = zipfile.ZIP_DEFLATED
else:
compression = zipfile.ZIP_STORED
arc = zipfile.ZipFile(libpath, "a", compression = compression)
#Add your items to the zipfile
for item in myFiles:
if self.options.verbose:
print("Copy File %s to %s" % (item, libpath))
arc.write(item, os.path.basename(item))
arc.close()
#Connect overrides
original_copy_files = py2exe.runtime.Runtime.copy_files
py2exe.runtime.Runtime.copy_files = better_copy_files
1
我想在这里分享一下这个内容,希望对那些还在寻找答案的人有帮助:
4
这听起来像是你需要的解决方案:扩展py2exe以将文件复制到zip文件中,pkg_resources可以从中加载它们
要有效使用这个方法,可能需要对pkg_resources有一些了解,它与setuptools有关,而setuptools就是“Python Eggs”的来源。