There are two ways you could go about to solve your problem
- Use a static builder, like freeze, or
pyinstaller
, orpy2exe
- Compile using
cython
This answer explains how you can go about doing it using the second approach, 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, while using cython will result in a file that’s much smaller
-
First, install
cython
.sudo -H pip3 install cython
-
Then, you can use
cython
to generate a C file out of the Python.py
file
(in reference to https://stackoverflow.com/a/22040484/5714445)cython example_file.py --embed
-
Use GCC to compile it after getting your current python version (Note: The below assumes you are trying to compile it to Python3)
PYTHONLIBVER=python$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')$(python3-config --abiflags) gcc -Os $(python3-config --includes) example_file.c -o output_bin_file $(python3-config --ldflags) -l$PYTHONLIBVER
You will now have a binary file output_bin_file
, which is what you are looking for
Other things to note:
- Change
example_file.py
to whatever file you are actually trying to compile. - 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.
- 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 - The above method might not work for anaconda python, as you will likely have to install a version of gcc that is compatible with your conda-python.