Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.
6 Answers
After looking for a solution to the same problem, I ended up writing a simple tool which combines multiple .py files into one: PyBreeder
It will only work with pure-Python modules and may require some trial-and-error to get the order of modules right, but it is quite handy whenever you want to deploy a script with some dependencies as a single .py. Comments/patches/critique are very welcome!

- 101
- 1
- 2
-
I did [something similar](https://github.com/thomasballinger/pyconcat) because it seemed cool, but PyBreeder looks less ridiculous and hacky. – Thomas Sep 15 '13 at 16:32
Take a look at Python Eggs: http://peak.telecommunity.com/DevCenter/PythonEggs
Or, you can use regular zips: http://docs.python.org/library/zipimport.html

- 26,247
- 4
- 39
- 46
-
Thank you! I had seen the term 'egg' used, but I had no clue what it was. – c4757p Jul 09 '09 at 14:04
The simplest approach is to just use zip
. A jar
file in Java is a zipfile containing some metadata such as a manifest; but you don't necessarily need the metatada -- Python can import from inside a zipfile as long as you place that zipfile on sys.path, just as you would do for any directory. In the zipfile you can have the sources (.py files), but then Python will have to compile them on the fly each time a process first imports them; or you can have the bytecode files (.pyc or .pyo) but then you're limited to a specific release of Python and to either absence (for .pyc) or presence (for .pyo) of flag -O (or -OO).
As other answers indicated, there are formats such as .egg
that enrich the zipfile with metatada in Python as well, like Java .jar
, but whether in a particular use case that gives you extra value wrt a plain zipfile is a decision for you to make

- 854,459
- 170
- 1,222
- 1,395
You can create zip files containing Python code and import from zip files using zipimport. A system such as PyInstaller (cross-platform) or py2exe (Windows) will do all this for you.

- 95,872
- 14
- 179
- 191
stickytape (mentioned before) worked for me.
stickytape importingSomeModules.py > resultWithEmbeddedImports.py
Sometimes you just want to redistribute just a single .py
file, so neither PyInstaller, zipimport nor Python Eggs cut the deal then.
PyBreeder is (currently) throwing exceptions.

- 117
- 1
- 6