Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a single python file from multiple scripts?

Tags:

python

I have a simple python script, which imports various other modules I've written (and so on). Due to my environment, my PYTHONPATH is quite long. I'm also using Python 2.4.

What I need to do is somehow package up my script and all the dependencies that aren't part of the standard python, so that I can email a single file to another system where I want to execute it. I know the target version of python is the same, but it's on linux where I'm on Windows. Otherwise I'd just use py2exe.

Ideally I'd like to send a .py file that somehow embeds all the required modules, but I'd settle for automatically building a zip I can just unzip, with the required modules all in a single directory.

I've had a look at various packaging solutions, but I can't seem to find a suitable way of doing this. Have I missed something?

[edit] I appear to be quite unclear in what I'm after. I'm basically looking for something like py2exe that will produce a single file (or 2 files) from a given python script, automatically including all the imported modules.

For example, if I have the following two files:

[\foo\module.py] def example():     print "Hello"  [\bar\program.py] import module module.example() 

And I run:

cd \bar set PYTHONPATH=\foo program.py 

Then it will work. What I want is to be able to say:

magic program.py 

and end up with a single file, or possibly a file and a zip, that I can then copy to linux and run. I don't want to be installing my modules on the target linux system.

like image 608
xorsyst Avatar asked Jan 25 '12 11:01

xorsyst


People also ask

Can two python scripts import each other?

As explained in my answer, it is possible for modules to import each other, but if you need to do that, you may want to reconsider your design.


1 Answers

I found this useful:

http://blog.ablepear.com/2012/10/bundling-python-files-into-stand-alone.html

In short, you can .zip your modules and include a __main__.py file inside, which will enable you to run it like so:

python3 app.zip 

Since my app is small I made a link from my main script to __main__.py.

Addendum:

You can also make the zip self-executable on UNIX-like systems by adding a single line at the top of the file. This may be important for scripts using Python3.

echo '#!/usr/bin/env python3' | cat - app.zip > app chmod a+x app 

Which can now be executed without specifying python

./app 
like image 99
Gringo Suave Avatar answered Sep 19 '22 21:09

Gringo Suave