3 Things to know when using PyInstaller to Avoid Hard Knocks
> pyinstaller main.py
The above command is said to be enough for you to bundle your newly written python app to face the world. It’s too simplistic. To use pyinstaller, you need to tinker with it. My aim is to share 3 tips so that you don’t have to take hard knocks.
1. Option Command: — name
> pyinstaller --name Pomodoro main.py
Using the long option of name above, you can avoid having your distribution directory and executable name following the python script name. Your client/users of your app likely won’t understand why the executable is named “main”.
2. Option Command: — add-data
> pyinstaller --name Pomodoro --add-data "./tomato.png:." main.py
You could have a picture file or any sort of resource files that your script would tap on during run-time. Unfortunately, pyinstaller, while able to trace dependency libraries, cannot do the same to detect your user-defined resource files. You would need to tell pyinstaller what they are and where they are. This is where the “ — add-data” option comes in handy. In the above example, “tomato.png” image file is located at the same directory level as the “main.py” script. So in the option value “./tomato.png:.”, we tell pyinstaller the location of the image file to bundle using the left of the semi-colon. To the right of the semi-colon, we specify, the destination to copy to the image file in the distribution bundle.
The above only takes care of the bundling of file. You have to ensure your code is able to work with the mappings during the bundle. For example, in the script, the code below to find the tomato file assume that it will be located within the same directory as the script, even after the bundling.
TOMATO_IMG_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "tomato.png"))
3. Creating a Desktop shortcut for your Executable in Linux
I am rocking a Raspberry Pi 400. So the way to create a desktop shortcut or a menu shortcut is more involved unlike on Windows, where you can use the windows infrastructure to make a shortcut.
On Raspberry Pi OS, you have to create a text file with “.desktop” extension in the desktop folder.
The Exec path needs to point to the executable created by pyinstaller. One common error is not to specify the Current Working Directory (“CWD”). CWD ensures the executable file can find the bundled resource files and libraries. We do this with the “Path =”. So in the example below, we point it to the bundle directory encapsulating the executable. Then our tomato image can be found.
[Desktop Entry]Type=ApplicationEncoding=UTF-8Name=PomodoroComment=Pomodoro Concentration appIcon=/home/pi/Documents/Pomodoro/dist/Pomodoro/tomato.pngExec=/home/pi/Documents/Pomodoro/dist/Pomodoro/PomodoroTerminal=falseCategories=Accessories;Path=/home/pi/Documents/Pomodoro/dist/Pomodoro/