As a python developer you might want to ship your code to other platforms where python interpreter is not installed. In such event you would need to rely on the binary execution. You can use pyinstaller
to achieve your aim; where you can convert your python code to executable binary.
Steps to Generate Binary with PyInstaller
-
Create virtual environment and Install
pyinstaller
withpip
$ virtualenv -p python3 venv $ . venv/bin/activate (venv) $ pip install pyinstaller --upgrade
-
Finalise and Save your python script :
hello.py
#!/usr/bin/env python3 print("Hello World")
-
Test your python code before generating actual binary
virtualenv -p python3 venv (venv) $ python hello.py Hello World
-
Convert Python Script to Binary with Pyinstaller
(venv) $ pyinstaller hello.py --onefile
-
After successful conversion you will be able to Locate and Execute binary file inside
./dist
with the namehello
$ ls ./dist/hello hello $ ./dist/hello Hello World
Known Issues with Pyinstaller
During the prcess of generating binary file, you might receive following error with upx.
---------------------------------------- Error running 'upx -V': [Errno 13] Permission denied: 'upx' ---------------------------------------- Error: Executing command failed!
(venv) $ pyinstaller hello.py --onefile
67 INFO: PyInstaller: 4.3
67 INFO: Python: 3.6.8
69 INFO: Platform: Linux-3.10.0-1160.21.1.el7.x86_64-x86_64-with-redhat-7.9-Maipo
70 INFO: wrote /code/hello.spec
----------------------------------------
Error running 'upx -V':
[Errno 13] Permission denied: 'upx'
----------------------------------------
Error: Executing command failed!
To resolve this issue, you can use following command
pyinstaller hello.py --upx-dir=..\upx391w -y --onefile
Conclusion
We learned how to convert python script into distributable binary file with pyinstaller.