Skip to content

Instantly share code, notes, and snippets.

@brccabral
Last active January 22, 2023 07:26
Show Gist options
  • Save brccabral/a47829b9ff5562d0e4ad6b8246261d7e to your computer and use it in GitHub Desktop.
Save brccabral/a47829b9ff5562d0e4ad6b8246261d7e to your computer and use it in GitHub Desktop.
Compile Python

How to build python code into executable

Install pyinstaller

pip install pyinstaller

Create a build folder

mkdir ~/my_build

Enter the new folder

cd ~/my_build

Build the code into one file

If Windows or Mac need to add -w if the code runs in a window

pyinstaller --onefile -w /path/to/the/code/mycode.py

Inside the ~/my_build folder will be created

~/my_build/build
~/my_build/dist
~/my_build/mycode.spec

Run it

The executable is inside dist and you can run it

~/my_build/dist/mycode

Compile with assets

If your code needs to access assets (or resources) files like fonts, images, sounds, you need to add another option

pyinstaller --onefile -w --add-data /path/to/the/code/datafiles/myfile.png:datafiles /path/to/the/code/mycode.py

If you have multiple assets, add more "--add-data" options for each file

pyinstaller --onefile -w --add-data /path/to/the/code/datafiles/myfile.png:datafiles --add-data /path/to/the/code/datafiles/more/secondfile.png:datafiles/more /path/to/the/code/mycode.py

Edit your code to get assets relative paths

For any file access in your code, replace any 'filepath/myimage.png' or even os.path.join('filepath','myimage.png') for the funtion below

bundle_dir = getattr(sys, "_MEIPASS", os.path.abspath(os.path.dirname(__file__)))
def resource_path(relative):
    return os.path.abspath(os.path.join(bundle_dir, relative))

resource_path('filepath/myimage.png')  

Recompile with .spec file

This new option "--add-data" will be saved inside the .spec file.
To add more files, you can edit the .spec file directly and rebuild the project by just calling the .spec file

cd ~/my_build
pyinstaller --onefile -w mycode.spec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment