PyInstaller to package Python script
Recently I had a small project to create a reporting tool. This tool will be used only by a few non-technical people, so I decided just to create an executable that can be shared easily.
Get Muti’s stories in your inbox
Join Medium for free to get updates from this writer.
I did it before in Windows but now I’m using macOS, I stumbled upon a little path problem.
Basic Usage
Installing the library:
pip install pyinstallerPyInstaller read the script, analyze and discover modules/libraries needed to execute the script. It puts everything in a single folder or an executable file.
pyinstaller main.pyThis will create a folder. But for my case, I need an executable file.
pyinstaller --onefile main.pyIt will create an executable in “dist” folder: dist/main
PATH
My script reads a config file and an image in the report, it also create an output report file. After trying different approaches, I decided to use different functions to deal with paths (input and output) on the script.
Resource path
This is for files like a config file or image file that are used in the script.
def get_resource_basepath():
# running as compiled app
if getattr(sys, 'frozen', False):
base_path = sys._MEIPASS
# running as a script
else:
base_path = os.path.dirname(__file__)
return base_path
# Usage
config_path = os.path.join(get_resource_basepath(), "config.json")For the output path:
def get_output_basepath():
# running as compiled app
if getattr(sys, 'frozen', False):
base_path = os.path.dirname(sys.executable)
# running as a script
else:
base_path = os.path.dirname(__file__)
return base_path
# Usage
out_path = os.path.join(get_output_basepath(), "report.pdf")I used those functions because I need to run the original script as well for verification purpose. If you only need to run the executable file, the paths can be as simple as follow:
in_base_path = sys._MEIPASS
out_base_path = os.path.dirname(sys.executable)sys._MEIPASS is a special variable from PyInstaller to access the path for the executable file.
Packaging script with input files
To include files when creating the executable, it must be stated explicitly on the command.
pyinstaller --onefile --add-data "config.json:." --add-data "logo.png:." main.pyThis will create an executable file that can be used by user without installing anything.
Important
Running the command on macOS will create a Unix Executable File and running it on Windows will create the .exe file.
If there are errors, try to package as a folder first since it is easier to debug. Once the one-folder packaging is successful, then package it as a file.






