If you’ve ever wanted to take your scripts to the next level and convert them into Windows executables, then this is the guide for you!
Converting your python scripts into Exe has a number of advantages.
First, it means that you can run your script on any computer, regardless of whether they have the required interpreter installed.
Second, it can make your script more secure by hiding the source code.
And finally, it can make your script more portable, since the process bundles all the required dependencies into the executable.
The first obvious step is just installing python into your Windows machine!
To do that, click on this link, select the last version and finally download the Windows installer like the image shows:
Now launch the installer, with default values, keeping attention to check “Add Python VERSION to PATH”
PyInstaller is a program that converts (packages) Python scripts into stand-alone executables, under Windows, Linux, and Mac OS X.
So seems to be the right choice for our python to Exe conversion.
In order to install that, let’s open a command prompt and write this command:
pip install pyinstaller
That should output a Success message.
Test Pyinstaller: Python to Exe
Now we want to test if everything is ok, so let’s write that simple script that will just create a file (test.txt) with a success message.
with open("test.txt", "w") as f: f.write("It works!")
That’s almost done, let’s compile that with Pyinstaller (remembering that the script is inside a file called “main.py”).
To do that we need to open a prompt inside the same directory of the script and write that:
pyinstaller --onefile main.py
Now our Exe file is saved into the “dist” folder and you can run it with a double click.
During the execution, you may have noticed that a console appears just for a fraction of a second, if it annoys you, the right compilation command is:
pyinstaller --onefile --noconsole main.py
If some error occurs, maybe you need to install Microsoft Visual C++ Redistributable.
At this point, we have a good strategy to convert our python tools into Exe, and it also works for different OS’ executables!
If you want to know deeper Pyinstaller, and all its options you can read the manual.
Just as an exercise, try to convert into Exe what we have created in those articles: