In this tutorial, we will learn how to compile a Python file in Windows. Compiling a Python file allows you to create an executable file from your code, which can be run on computers without Python installed. This is useful for distributing your programs to others or creating standalone applications.
Step 1: Install PyInstaller
First, you need to have PyInstaller installed on your computer. This package is responsible for converting your Python script into an executable file. You can install it using pip
. Open the command prompt (cmd) and enter the following command:
1 |
pip install pyinstaller |
If pip is not available on your Windows installation, follow the instructions here to install pip
.
Step 2: Create a Python Script
Next, you need to create a simple Python script and save it as a .py
file. In this tutorial, we will use a basic script that just prints “Hello, World!” when executed. Create a file named hello.py
with the following content:
1 2 3 4 5 |
def main(): print("Hello, World!") if __name__ == "__main__": main() |
Save this file in a convenient location on your computer.
Step 3: Compile the Script with PyInstaller
Open the command prompt (cmd) and change the working directory to the folder containing your hello.py
script. You can use the cd
(change directory) command for this, for example:
1 |
cd C:\Users\Username\Desktop\PythonScripts |
Now, use the following command to compile your Python script using PyInstaller:
1 |
pyinstaller --onefile hello.py |
This command tells PyInstaller to create a standalone executable (--onefile
) from your hello.py
script. PyInstaller will create a dist
folder in the directory where your script is located. Inside the dist
folder, you will find the compiled executable file with the same name as your script (hello.exe
).
Step 4: Run the Compiled Executable
Now that you have the compiled hello.exe
file, you can run it by double-clicking it. The output should be displayed in a new command prompt window.
Hello, World!
If you want to share your program with others, you need to distribute the executable file only (in this case, hello.exe
). The recipients don’t need to have Python installed on their computers to run the program.
Full Code
1 2 3 4 5 |
def main(): print("Hello, World!") if __name__ == "__main__": main() |
Conclusion
In this tutorial, you’ve learned how to compile a Python file in Windows using PyInstaller. This allows you to create standalone executable files from your Python scripts, which can be easily shared with others, regardless of whether they have Python installed on their computers.