16

Is there any way to compile python script into binary? I have one file python script which uses a lot of modules. What I would like is to have its copy on other machines (freebsd) but without installing all needed modules on every host.

What are possible solutions in such cases?

Cœur
  • 37,241
  • 25
  • 195
  • 267
andriyko
  • 277
  • 1
  • 4
  • 12

4 Answers4

20

Programs that can do what you ask for are:

But as mentioned you can also create a Package with Distribute and have the other packages as dependencies. You can then uses pip to install that package, and it will install all of the packages. You still need to install Python and pip, though.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
3

cx_freeze will append your python scripts to a standalone Python loader and produce a directory containing the program, and shared library dependencies. You can then copy the resulting distribution to other machines independent of Python or your modules.

$ cat hello.py 
print "Hello, World!"
$ ls dist/
datetime.so  _heapq.so  hello  libpython2.6.so.1.0  readline.so
$ cat hello.py 
print "Hello, World!"
$ cxfreeze hello.py 
... <snip> ...
$ ls dist/
datetime.so  _heapq.so  hello  libpython2.6.so.1.0  readline.so
$ ./dist/hello
Hello, World!

A better answer may be to create a PIP package that identifies these third modules as dependencies, so installation can be as simple as "pip install mypackage; ./package"

swdunlop
  • 124
  • 3
  • Does it actually compile to C? I thought that it works like py2exe: Put all the Python files into a .zip and fues it with a small executable that unzips and feeds it to the Python runtime. –  Dec 29 '10 at 18:25
  • Correct; got this tangled up with the original Python freeze. The cx-freeze utility concatenates zip-compressed modules to a stub loader. Not too terribly different from how I achieved the same with MOSREF's compiler. – swdunlop Dec 29 '10 at 18:53
  • 2
    // , Does this work if that version of Python isn't installed on the system, though? – Nathan Basanese Sep 08 '15 at 19:51
2

Python will also look for import modules in the current directory, so you don't have to install them into the python directory. Your distribution file structure might look like:

main.py
module1/
    __init__.py, ...
module2/
    __init__.py, ...

Where main.py has import module1, module2

Ian Wetherbee
  • 6,009
  • 1
  • 29
  • 30
2

You probably want to create a Python package from your script. In the end you will be able to do pip install mypackage on any host and all the required modules will be downloaded and installed automatically.

See this question on how to create such a package.

Community
  • 1
  • 1
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194