How to build a single python file from multiple scripts?

Question:

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:

[foomodule.py]
def example():
    print "Hello"

[barprogram.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.

Asked By: xorsyst

||

Answers:

You should create an egg file. This is an archive of python files.

See this question for guidance: How to create Python egg file

Update: Consider wheels in 2019

Answered By: Marcin

Have you taken into considerations Automatic script creation of distribute the official packaging solution.

What you do is create a setup.py for you program and provide entry points that will be turned into executables that you will be able run. This way you don’t have to change your source layout while still having the possibility to easily distribute and run you program.

You will find an example on a real app of this system in gunicorn’s setup.py

Answered By: amirouche

The only way to send a single .py is if the code from all of the various modules were moved into the single script and they your’d have to redo everything to reference the new locations.

A better way of doing it would be to move the modules in question into subdirectories under the same directory as your command. You can then make sure that the subdirectory containing the module has a __init__.py that imports the primary module file. At that point you can then reference things through it.

For example:

App Directory: /test

Module Directory: /test/hello

/test/hello/__init__.py contents:

import sayhello

/test/hello/sayhello.py contents:

def print_hello():
    print 'hello!'

/test/test.py contents:

#!/usr/bin/python2.7

import hello

hello.sayhello.print_hello()

If you run /test/test.py you will see that it runs the print_hello function from the module directory under the existing directory, no changes to your PYTHONPATH required.

Answered By: Drahkar

If you want to package your script with all its dependencies into a single file (it won’t be a .py file) you should look into virtualenv. This is a tool that lets you build a sandbox environment to install Python packages into, and manages all the PATH, PYTHONPATH, and LD_LIBRARY_PATH issues to make sure that the sandbox is completely self-contained.

If you start with a virgin Python with no additional libraries installed, then easy_install your dependencies into the virtual environment, you will end up with a built project in the virtualenv that requires only Python to run.

The sandbox is a directory tree, not a single file, but for distribution you can tar/zip it. I have never tried distributing the env so there may be path dependencies, I’m not sure.

You may need to, instead, distribute a build script that builds out a virtual environment on the target machine. zc.buildout is a tool that helps automate that process, sort of like a “make install” that is tightly integrated with the Python package system and PyPI.

Answered By: Bill Gribble

I’ve come up with a solution involving modulefinder, the compiler, and the zip function that works well. Unfortunately I can’t paste a working program here as it’s intermingled with other irrelevant code, but here are some snippets:

zipfile = ZipFile(os.path.join(dest_dir, zip_name), 'w', ZIP_DEFLATED)
sys.path.insert(0, '.')
finder = ModuleFinder()
finder.run_script(source_name)

for name, mod in finder.modules.iteritems():
    filename = mod.__file__
    if filename is None:
        continue
    if "python" in filename.lower():
        continue

    subprocess.call('"%s" -OO -m py_compile "%s"' % (python_exe, filename))

    zipfile.write(filename, dest_path)
Answered By: xorsyst

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
Answered By: Gringo Suave

Use stickytape module

stickytape scripts/blah --add-python-path . > /tmp/blah-standalone

This will result with a functioning script, but not necessarily human-readable.

Answered By: Marek

You can try converting the script into an executable file.
First, use:

pip install pyinstaller

After installation type ( Be sure you are in your file of interest directory):

pyinstaller --onefile --windowed filename.py

This will create an executable version of your script containing all the necessary modules. You can then transfer (copy and paste) this executable to the PC or machine you want to run your script.

I hope this helps.

Answered By: Daachi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.