Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to export python and its necessary libraries into a environment independent file?

I have a python script that uses keras and tensorflow libraries, which are incredibly time consuming to set up on every machines. Is it possible to export my python script and the keras and tensorflow libraries into a file like java projects --> .jar so that I don't need to set up the libraries every time I moved to a new machine?

like image 852
Bing Gan Avatar asked Jan 24 '17 01:01

Bing Gan


1 Answers

Python 3 includes a tool called zipapp that allows you to build single archives out of Python projects, bundling in all (or some) dependencies. The tool is only bundled with Python 3, but the generated archive will work with any version of Python >= 2.6 you are targeting.

Supposing you have all your source files in src/, including the mentioned Tensor Flow library:

$ python3 -m zipapp -o yourapp.pyz -m "your.entry.point.module:main_function" src/

The -m flag allows you to specify a module and a function inside it, separed with a :, that will be executed when you run the .pyz file. About running it, it's just a matter of:

$ python ./yourapp.pyz

Again, you will need Python >= 2.6 in order for this to work.

If you are targeting unix platforms, you might also add a shebang:

$ echo "#! /usr/bin/python" > yourapp2.pyz
$ cat yourapp.pyz >> yourapp2.pyz
$ chmod +x yourapp2.pyz

so that you can run the file as:

$ ./yourapp2.pyz

As a side note, a .pyz is nothing more than a .zip file. You might create one yourself without zipapp, just include a __main__.py file at top level. That will be the entry point of your bundle.

like image 89
Stefano Sanfilippo Avatar answered Oct 27 '22 00:10

Stefano Sanfilippo