Is there a way to compile python application into static binary?
<p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>

<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have to manually copy a bunch of libraries into your virtualenv, since <code>--always-copy</code> doesn't work as expected) and generally slow.</p>

<p>There's (in theory) <a href="https://wiki.python.org/moin/BuildStatically">a way</a> to build python itself statically.</p>

<p>I wonder if I could pack interpreter with my code into one binary and run my application as module. Something like that: <code>./mypython -m myapp run</code> or <code>./mypython -m gunicorn -c ./gunicorn.conf myapp.wsgi:application</code>.</p>

<p>There are two ways you could go about to solve your problem</p>

<ol>
<li>Use a static builder, like freeze, or pyinstaller, or py2exe</li>
<li>Compile using cython</li>
</ol>

<p>I will explain how you can go about doing it using the second, since the first method is not cross platform and version, and has been explained in other answers. Also, using programs like pyinstaller typically results in huge file sizes, where as using cython will result in a file that's KBs in size</p>

<p>First, install cython. Then, rename your python file (say test.py) into a pyx file </p>

<pre><code>$ sudo pip install cython
$ mv test.py test.pyx
</code></pre>

<p>Then, you can use cython along with GCC to compile it (Cython generates a C file out of a Python .pyx file, and then GCC compiles the C file)
(in reference to <a href="http://stackoverflow.com/a/22040484/5714445">http://stackoverflow.com/a/22040484/5714445</a>)</p>

<pre><code>$ cython test.pyx --embed
$ gcc -Os -I /usr/include/python3.5m -o test test.c -lpython3.5m -lpthread -lm -lutil -ldl
</code></pre>

<p>NOTE: Depending on your version of python, you might have to change the last command. To know which version of python you are using, simply use</p>

<pre><code>$ python -V
</code></pre>

<p>You will now have a binary file 'test', which is what you are looking for</p>

<p>NOTE: Cython is used to use C-Type Variable definitions for static memory allocation to speed up Python programs. In your case however, you will still be using traditional Python definitions.</p>

<p>NOTE2: If you are using additional libraries (like opencv, for example), you might have to provide the directory to them using -L and then specify the name of the library using -l in the GCC Flags. For more information on this, please refer to GCC flags</p>

python build