Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: can executable zip files include data files?

Tags:

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?

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.

like image 337
Bryan Oakley Avatar asked Mar 18 '11 17:03

Bryan Oakley


People also ask

Are ZIP files executable?

A self-extracting Zip file is a Windows executable file (.exe). It will contain a Zip file and a small program to extract (unzip) the files in the Zip file. A user can run (execute) a self-extracting Zip file just as they run any other program: just double click on the .exe file.

Can Python access zipped files?

Python can work directly with data in ZIP files. You can look at the list of items in the directory and work with the data files themselves. This recipe is a snippet that lists all of the names and content lengths of the files included in the ZIP archive zipfile.

Which module can help extract all of the files from a ZIP file in Python?

To work on zip files using Python, we will use an inbuilt python module called zipfile. In Python's zipfile module, the ZipFile class provides a member function to extract all the ZIP archive contents.


1 Answers

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() 

Where zipfile contains:

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

To make zipfile executable, run:

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

To test it:

$ cp program-name /another-dir/ $ cd /another-dir && ./program-name 
like image 96
jfs Avatar answered Oct 20 '22 20:10

jfs