Py2exe:在 exe 文件本身中嵌入静态文件并访问它们 [英] Py2exe: Embed static files in exe file itself and access them
问题描述
我找到了通过以下方式在 library.zip 中添加文件的解决方案:将 py2exe 扩展到将文件复制到 pkg_resources 可以加载它们的压缩文件.
I found a solution to add files in library.zip via: Extend py2exe to copy files to the zipfile where pkg_resources can load them.
当 library.zip 不包含 exe 时,我可以访问我的文件.
I can access to my file when library.zip is not include the exe.
我在目录中添加了一个文件:text.txt:在 library.zip 中的 foo/media.我使用这个代码:
I add a file : text.txt in directory: foo/media in library.zip. And I use this code:
import pkg_resources
import zipfile
from cStringIO import StringIO
my_data = pkg_resources.resource_string(__name__,"library.zip")
filezip = StringIO(my_data)
zip = zipfile.ZipFile(filezip)
data = zip.read("foo/media/text.txt")
我尝试使用 pkg_resources,但我认为我不明白某些东西,因为我可以直接打开library.zip".
I try to use pkg_resources but I think that I don't understand something because I could open directly "library.zip".
我的问题是当library.zip 嵌入到exe 中时我该怎么做?
My question is how can I do this when library.zip is embed in exe?
最好的问候
让-米歇尔
推荐答案
我拼凑了一个相当简洁的解决方案,但它不使用 pkg_resources.
I cobbled together a reasonably neat solution to this, but it doesn't use pkg_resources.
我需要将生产力工具作为独立的 EXE 分发,也就是说,所有工具都捆绑到一个 .exe 文件中.我还需要在使用这些工具时发出通知,我通过 Logging API 使用基于文件的配置来发送通知.我嵌入了 logging.cfg 文件,以便更难有效地关闭这些通知,即删除松散的文件......无论如何这可能会破坏应用程序.
I need to distribute productivity tools as standalone EXEs, that is, all bundled into the one .exe file. I also need to send out notifications when these tools are used, which I do via the Logging API, using file-based configuration. I emded the logging.cfg fileto make it harder to effectively switch-off these notifications i.e. by deleting the loose file... which would probably break the app anyway.
以下是我的 setup.py 中有趣的部分:
So the following is the interesting bits from my setup.py:
LOGGING_CFG = open('main/resources/logging.cfg').read()
setup(
name='productivity-tool',
...
# py2exe extras
console=[{'script': productivity_tool.__file__.replace('.pyc', '.py'),
'other_resources': [(u'LOGGINGCFG', 1, LOGGING_CFG)]}],
zipfile=None,
options={'py2exe': {'bundle_files': 1, 'dll_excludes': ['w9xpopen.exe']}},
)
然后在productivity_tool.py的启动代码中:
Then in the startup code for productivity_tool.py:
from win32api import LoadResource
from StringIO import StringIO
from logging.config import fileConfig
...
if __name__ == '__main__':
if is_exe():
logging_cfg = StringIO(LoadResource(0, u'LOGGINGCFG', 1))
else:
logging_cfg = 'main/resources/logging.cfg'
fileConfig(logging_cfg)
...
效果很好!!!
这篇关于Py2exe:在 exe 文件本身中嵌入静态文件并访问它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!