How to Convert Python Scripts to EXE: A Step-by-Step Guide with PyInstaller
β Project Structure:
Letβs say you have a simple Python script like this:
πΉ hello.py
def greet():
print("Hello from EXE!")
if __name__ == "__main__":
greet()
βοΈ Step-by-Step Instructions to Build .exe
β 1. Install PyInstaller
Make sure it's installed in your environment:
pip install pyinstaller
β
2. Use This Command to Generate a Single .exe
From the terminal (inside the folder where hello.py
is located, run:
pyinstaller --onefile hello.py
β 3. Output Directory Structure:
After running the above command, youβll get:
your-folder/
β
βββ hello.py
βββ build/ β intermediate build files
βββ dist/
β βββ hello.exe β β
Your final `.exe` file
βββ hello.spec β config file (optional to edit later)
β Optional: Hide Console (for GUI apps)
If you're building a GUI app (e.g., Tkinter or PyQt), use:
pyinstaller --onefile --noconsole hello.py
This hides the black terminal window that usually appears when you run .exe
.
β Optional: Add a Custom Icon
Place your .ico
file in the same folder (e.g., myicon.ico
) and run:
pyinstaller --onefile --icon=myicon.ico hello.py
π§ͺ Testing the .exe
Go to the dist/
folder:
cd dist
./hello.exe
You should see:
Hello from EXE!
π§ Bonus: Tips for Bigger Projects
If your script uses:
- External files (like images,
.csv
, etc.) - A GUI library like
tkinter
...you might need to:
- Use a
.spec
file to include assets - Add a
--add-data
flag (ask me if needed!)
π§Ύ Why This Matters?
When you run a .py
script normally:
- Files like
"data.csv"
or"image.png"
are read from the file system.
But when PyInstaller builds a .exe
, it bundles everything β and the paths change.
So you need explicitly tell PyInstaller:
"Hey, Iβm using these extra files. Include them too!"
β
1: --add-data
Flag (Recommended for Simple Use)
Syntax:
bashCopyEditpyinstaller --onefile --add-data "source_path;destination_folder" script.py
Note: Use
;
on Windows, but:
on Mac/Linux.
π§ͺ Example
Suppose this is your project:
kotlinCopyEditmyapp/
βββ app.py
βββ data.csv
βββ logo.png
You read files like this:
pythonCopyEditimport pandas as pd
from tkinter import PhotoImage
df = pd.read_csv("data.csv") # CSV read
logo = PhotoImage(file="logo.png") # Tkinter GUI image
Now, build .exe
with:
bashCopyEditpyinstaller --onefile --add-data "data.csv;." --add-data "logo.png;." app.py
β What this does:
- It bundles
data.csv
andlogo.png
into the.exe
. - Inside the executable, they are copied to the current working directory (
.
).