Pyinstaller | Converting python scripts into executables

Image for post
Image for post

Reference: pyinstaller home

Question: How do you go from python myscript.py -verbose to just myscrpt -verbose? Follow along to find out!

  1. Install the required packages
$ pip install --upgrade pyinstaller

2. Add the python scripts folder to the system path if you have not done so already

The basics

  1. Basic usage
$ pyinstaller <your-script>.py# output(s):
# <your-script>.spec - Default settings used to generate exe
# build/ - Build artifacts e.g. build logs
# dist/ - contains <your-script>.exe + python dependencies

2. Useful options

  • — name | Specify the name of the generated executable
  • — onefile | Bundle all binary artifacts into one executable file
  • — distpath | Customize the output directory of the generated executable
  • -y or — no-confirm | Replace dist_path contents without asking for confirmation
  • — exclude-module | Ignore modules not required to make the executable
# example:
$ pyinstaller --exclude-module pytest ex.py
  • — paths | Specify additional import folders
  • — add-data | Include any additional data file e.g. config.xml
  • — add-binary | Include additional binary data files
  • More info.

3. Using the spec file to specify build options

  • As an alternative to specifying multiple command line options, you can use a spec file to generated your executable
# Example:$ pyinstaller <your_script>.spec
  • Here is an example of a spec file you might use:
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None


a = Analysis(['src1.py', 'src2.py'],
pathex=['root_path\', 'extra_pythonpath\'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='pybuildselector',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=True )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='pybuildselector')

Written by

Former Glorified Electrician(aka Electrical Engineer). Now a Software Developer working on complex Enterprise Software. Lets connect on twitter @NdamuleloNemakh

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store