python:可执行zip文件可以包含数据文件吗? [英] python: can executable zip files include data files?

查看:153
本文介绍了python:可执行zip文件可以包含数据文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对python来说还很陌生,直到最近我才发现可以通过在文件顶部放置__main__.py文件来直接执行.zip文件的功能.这对于python代码非常有用,但是我可以捆绑其他类型的文件并通过脚本访问它们吗?如果可以,怎么办?

Being fairly new to python I only recently discovered the ability to directly execute a .zip file by placing a __main__.py file at the top of the file. This works great for python code, but can I bundle other types of files and access them with my scripts? If so, how?

我的最终目标是将一些图像文件和python代码捆绑在一个.zip文件中,然后能够在应用程序内使用这些图像,而不必将其提取到磁盘中.我还希望捆绑版权声明,发行说明等,以便整个应用程序及其数据文件位于一个单独的zip中,无需将其提取到某个地方即可执行.

My ultimate goal would be to bundle some image files along with the python code in a single .zip file, then be able to use those images within the app without having to extract them to disk. I also would like to bundle a copyright notice, release notes, etc so that the entire app and its data files is in a single zip that can be executed without having to extract it somewhere.

推荐答案

您可以使用

You could use pkg_resources functions to access files:

# __main__.py
import pkg_resources
from PIL import Image

print pkg_resources.resource_string(__name__, 'README.txt')

im = Image.open(pkg_resources.resource_stream('app', 'im.png'))
im.rotate(45).show()

zip文件包含以下内容:

Where zipfile contains:

.
|-- app
|   |-- im.png
|   `-- __init__.py
|-- README.txt
`-- __main__.py

要使zipfile可执行,请运行:

To make zipfile executable, run:

$ echo '#!/usr/bin/env python' | cat - zipfile > program-name
$ chmod +x program-name

要测试:

$ cp program-name /another-dir/
$ cd /another-dir && ./program-name

这篇关于python:可执行zip文件可以包含数据文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆