How to Run a Python Script
What you’ll build or solve
You’ll take a Python file like main.py and run it from your terminal so it executes and prints results, writes files, or does whatever the script is meant to do.
When this approach works best
Running a script from the terminal is the right choice when you:
Learn Python on Mimo
- Need to execute a file that reads input files and writes output files, like
clean_data.pyorresize_images.py. - Want to automate a repetitive task, like renaming folders, checking URLs, or generating reports.
- Need a repeatable way to run the same code locally and later in CI, Docker, or on a server.
Skip this approach when:
- You’re building a web app or API and should run a framework command, for example
flask runoruvicorn, instead of a random file. - You’re in a notebook-first workflow like Jupyter and the script depends on notebook state.
Prerequisites
- Python installed, any modern version, usually 3.10+ is fine.
- A terminal:
- macOS/Linux: Terminal
- Windows: PowerShell or Windows Terminal
- Basic comfort with
cdand listing files:lson macOS/Linuxdiron Windows
Step-by-step instructions
1) Confirm Python is installed
First, check that your terminal can find Python.
macOS/Linux (try python3 first):
Bash
python3 --version
Windows (try py first):
Bash
py --version
Option B (works on some systems):
Bash
python --version
What to look for
You should see a version like:
Python 3.12.2
If you see “command not found” or a Microsoft Store prompt on Windows, jump to the Troubleshooting section.
2) Go to the folder that contains your script
Navigate to the directory where your .py file lives.
macOS/Linux:
Bash
cd path/to/your/project
ls
Windows (PowerShell):
cd path\to\your\project
dir
You should see your script in the listing, for example main.py.
Tip: If your folder path contains spaces, wrap it in quotes:
Bash
cd "My Projects/python-scripts"
3) Run the script
Use the Python command followed by the file name.
macOS/Linux:
Bash
python3 main.py
Windows (recommended):
Bash
py main.py
Option B (if python points to Python 3 on your machine):
Bash
python main.py
If the script prints output, you’ll see it right away. If it writes files, check your folder for new files after the command finishes.
4) Pass command-line arguments (when your script expects them)
Many scripts take inputs like file paths, flags, or options.
Example call:
Bash
python3 main.py input.csv output.csv
Inside the script, read arguments using sys.argv:
Python
import sys
input_path = sys.argv[1]
output_path = sys.argv[2]
print("Input:", input_path)
print("Output:", output_path)
What to look for
sys.argv[0]is the script name.- If you get
IndexError: list index out of range, you likely forgot an argument.
Option B (more beginner-friendly): use argparse for named arguments:
Python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
print("Input:", args.input)
print("Output:", args.output)
Run it like this:
Bash
python3 main.py --input input.csv --output output.csv
5) Use a virtual environment (when your script has dependencies)
If your script imports packages you installed with pip, like requests, use a virtual environment so your project stays isolated.
Create a venv
macOS/Linux:
Bash
python3 -m venv .venv
Windows:
Bash
py -m venv .venv
Activate it
macOS/Linux:
Bash
source .venv/bin/activate
Windows (PowerShell):
.\.venv\Scripts\Activate.ps1
Install dependencies
Bash
python -m pip install requests
Run your script
Bash
python main.py
What to look for
Your prompt often changes to show the environment name, for example:
(.venv)
If pip installs packages but your script still can’t import them, you might be using a different interpreter. Activating the virtual environment usually fixes this.
6) Run a file as a module (when you’re inside a package)
Projects often look like this:
my_project/
app/
__init__.py
main.py
tests/
pyproject.toml
If app/main.py imports other modules from app, running it directly can break imports. Running as a module keeps Python’s import paths consistent.
From the project root:
Bash
python -m app.main
What to look for
If your file is app/main.py, the module path becomes app.main.
This avoids “attempted relative import” issues in many project layouts.
Examples you can copy
Example 1: A script that prints a quick summary
Create hello.py:
Python
name = input("What’s your name? ").strip()
print(f"Hi, {name}! You just ran a Python script.")
Run it:
Bash
python3 hello.py
Example 2: Rename files in a folder
Create rename_photos.py:
Python
from pathlib import Path
folder = Path("photos")
prefix = "trip_"
for i, path in enumerate(sorted(folder.glob("*.jpg")), start=1):
new_name = folder / f"{prefix}{i:03d}.jpg"
path.rename(new_name)
print("Done renaming .jpg files.")
Run it from the folder that contains photos/:
Bash
python3 rename_photos.py
Example 3: Read a CSV and write a cleaned CSV
Create clean_csv.py:
Python
import csv
with open("input.csv", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
rows = []
for row in reader:
row["email"] = row["email"].strip().lower()
rows.append(row)
with open("output.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=rows[0].keys())
writer.writeheader()
writer.writerows(rows)
print("Wrote output.csv")
Run it:
Bash
python3 clean_csv.py
Common mistakes and how to fix them
Mistake 1: Running the script from the wrong folder
You might run:
Bash
python3 main.py
…and get:
python3: can't open file 'main.py': [Errno 2] No such file or directory
Why it breaks
Your terminal is not in the directory that contains main.py.
Fix
Navigate to the right folder, then run it:
Bash
cd path/to/the/folder/with/the-script
python3 main.py
Mistake 2: Installing packages, then getting ModuleNotFoundError
You might run:
Bash
pip install requests
python3 main.py
…and see:
ModuleNotFoundError: No module named 'requests'
Why it breaks
pip installed into a different Python environment than the one running your script.
Fix
Install using the same interpreter you use to run the script:
Bash
python3 -m pip install requests
python3 main.py
Or activate your virtual environment first, then install and run.
Troubleshooting
If you see: python3: command not found
Install Python 3, or on some systems try:
Bash
python --version
to see what’s available.
If you see (Windows): py is not recognized as the name of a cmdlet
Reinstall Python and check the option to add Python to PATH, or try:
Bash
python --version
If you see: PermissionError: [Errno 13] Permission denied
Write output to a folder you own, like your user folder. Avoid protected system directories.
If you see: IndentationError: unexpected indent
Replace mixed tabs and spaces with 4 spaces per indent level, then run again.
If your script runs but uses the wrong version, for example, 3.8 instead of 3.12
Check which interpreter runs:
Bash
which python3
python3 --version
On Windows:
Bash
py -0
Then run with the interpreter you want, or use a virtual environment.
If you see: ModuleNotFoundError only when running a file inside a package
Run it as a module from the project root:
Bash
python -m app.main
Quick recap
- Check Python works with
python3 --versionon macOS/Linux orpy --versionon Windows. cdinto the folder that contains your.pyfile.- Run
python3 your_script.pyorpy your_script.py. - Pass arguments with
sys.argvorargparse. - Use a virtual environment when you install packages.
- Use
python -m package.modulefor scripts inside a package structure.
Join 40M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot