Convert Python 3 Script to Windows Executable [.py to .exe]
Python is one of the most used language in today’s web applications. At times, you may write a script to run only on a Windows machine. To run on a Windows machine, it will be good if you can provide your Python script as a Windows Executable (.exe) format (convert .py to ,exe). One other way to provide your Python script to end user to ease them to execute the script is by writing a Windows Batch (.bat) file but still you may have to share your .py file in order to run the file.
Python 2.7 and below used a Py2Exe, a third-party library to convert .py to .exe. The method to create a Windows Executable file of Python 2 script was tedious as you need to prepare another Python file to include all your packages.
Python 3 and above has a package with which you will be able to convert .py to .exe. You can use pip, a Python Package Index to install pyinstaller – a Python package that converts .py file to .exe.
To do this, install pyinstaller using pip
pip install pyinstaller
Once pyinstaller is installed, you will be able to convert .py to .exe using the following command: (considering your Python 3 script file is hello_world.py)
This will also include your packages that you have mentioned in your Python 3 script, so you do not have to worry about the packages.
On running pyinstaller will create two directories, namely, build and dist. The dist folder will contain a folder with your Python script name. And your dependencies and hello_world.exe will be available in this folder.
If your Python 3 script is depended on any text files where you may read data from or write to, you need to copy this file manually under the newly created folder of dist folder. For best practice, always check for existence of the file and throw error message, in case of unavailability of the file.
You cannot simply delete .dll files and other folders in your dist, as the exe makes use of all the files. For instance, if you have built a script that uses selenium, pyinstaller will recognize and will create a folder “selenium” where browser drivers will be found.
Were you able to convert your Python 3 script to Windows Executable? Share your experiences below.