Wednesday, March 29, 2017

Using PyInstaller

The other day, I wrote about using Cython to create an executable file. Well, as expected, it does create a smaller executable file, but it depends on the user having the required DLLs already installed on the system.

Which may not be an option for end-users who are not that computer savvy.

In my search for a good way to package software for distribution to end-users, I came across PyInstaller. It is actually one of the easiest ways to package Python code for distribution.

Simply install PyInstaller using pip.
pip install pyinstaller

Then, use PyInstaller to package the Python script into a Windows executable file. I prefer to make this a single standalone exe file for easy distribution, which is easily done with the -F option. And you can even embed an icon for your exe file, using the -i option.
pyinstaller -F -i my_icon.ico my_script.py

This creates my_script.exe which contains the required DLLs together with your Python code, and end-users can easily run the file by typing:
my_script

Oh, and if it is a non-console program, just add the -w option to get rid of the console window.
pyinstaller -F -w -i my_icon.ico my_script.py

To make use of the embedded icon, add
        if sys.platform == 'win32':
            exeName = sys.executable
            icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
            self.SetIcon(icon)

to the __init__() method of your wx.Frame class.

Easy, single line way to package Python code for distribution to end-users. But of course, the exe file can be quite big since it contains the DLLs (including python.dll to run your Python code). And it doesn't protect your code, people can still reverse the process to get to your code. Still, it is a simple and fast way to get code out to people who just want to use them.

No comments: