In this tutorial, we will learn how to convert a Python script (.py) into a standalone executable (.exe) file. By converting your script to an executable, you can easily distribute your programs without requiring users to install Python or any dependencies. We will be using the popular Python library, PyInstaller, to achieve this conversion.
Prerequisites
Before we start converting our Python script, ensure you have the following installed:
- Python: Download and install the latest version of Python (3.x).
- pip: Python package manager, usually comes pre-installed with Python. If not, you can follow the link for installation instructions.
Step 1: Install PyInstaller
With Python and pip installed, you can now install the PyInstaller package using the following command in your terminal (Linux/macOS) or Command Prompt (Windows):
1 |
pip install pyinstaller |
After the installation is complete, you should see a message similar to the following, indicating that PyInstaller has been successfully installed:
Successfully installed pyinstaller-...
Step 2: Create a Python script
For this tutorial, we will create a simple Python script named hello_world.py to demonstrate the conversion process. You can replace the script with your own Python program.
1 |
print("Hello, World!") |
To prevent the console window from closing immediately and allowing you to see the output, you can add a line at the end of your script to wait for user input before exiting. You can use the input()
function for this purpose.
1 2 |
print("Hello, World!") input("Press Enter to close the program...") |
Step 3: Convert Python script to .exe
Navigate to the folder containing your Python script using the terminal or Command Prompt. Then, run the following command to convert the script to a .exe file:
1 |
pyinstaller --onefile hello_world.py |
The --onefile
flag is used to generate a single executable file. After the conversion is complete, you will find the .exe file in the dist folder created in the same directory as your Python script.
For additional options and customizations, you can check the PyInstaller documentation.
Step 4: Test the .exe file
Now you can execute the .exe file by double-clicking it (Windows) or running it from the terminal (Linux/macOS). The output should be the same as when running the original Python script:
Hello, World!
Full Code
The Python script (hello_world.py) used in this tutorial contains the following code:
1 |
print("Hello, World!") |
Conclusion
In this tutorial, you’ve learned how to convert a Python script to a standalone .exe file using PyInstaller. This process will help you package and distribute your Python applications easily without the need for your users to install Python or any dependencies.