How to Convert Python Scripts to EXE: A Step-by-Step Guide with PyInstaller

July 1, 2025

βœ… 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 and logo.png into the .exe.
  • Inside the executable, they are copied to the current working directory (.).

Β© Copyright 2025 β€” CATStudio

Terms of Service / Privacy Policy