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:

  • Need to execute a file that reads input files and writes output files, like clean_data.py or resize_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 run or uvicorn, 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 cd and listing files:
    • ls on macOS/Linux
    • dir on Windows

Step-by-step instructions

1) Confirm Python is installed

First, check that your terminal can find Python.

macOS/Linux (try python3 first):

python3--version

Windows (try py first):

py--version

Option B (works on some systems):

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:

cd path/to/your/project
ls

Windows (PowerShell):

cdpath\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:

cd"My Projects/python-scripts"

3) Run the script

Use the Python command followed by the file name.

macOS/Linux:

python3 main.py

Windows (recommended):

pymain.py

Option B (if python points to Python 3 on your machine):

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:

python3 main.py input.csv output.csv

Inside the script, read arguments using sys.argv:

importsys

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:

importargparse

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:

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:

python3-m venv .venv

Windows:

py-mvenv .venv

Activate it

macOS/Linux:

source .venv/bin/activate

Windows (PowerShell):

.\.venv\Scripts\Activate.ps1

Install dependencies

python-m pip install requests

Run your script

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:

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:

name=input("What’s your name? ").strip()
print(f"Hi,{name}! You just ran a Python script.")

Run it:

python3 hello.py

Example 2: Rename files in a folder

Create rename_photos.py:

frompathlibimportPath

folder=Path("photos")
prefix="trip_"

fori,pathinenumerate(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/:

python3 rename_photos.py

Example 3: Read a CSV and write a cleaned CSV

Create clean_csv.py:

importcsv

withopen("input.csv",newline="",encoding="utf-8")asf:
reader=csv.DictReader(f)
rows= []
forrowinreader:
row["email"]=row["email"].strip().lower()
rows.append(row)

withopen("output.csv","w",newline="",encoding="utf-8")asf:
writer=csv.DictWriter(f,fieldnames=rows[0].keys())
writer.writeheader()
writer.writerows(rows)

print("Wrote output.csv")

Run it:

python3 clean_csv.py

Common mistakes and how to fix them

Mistake 1: Running the script from the wrong folder

You might run:

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:

cd path/to/the/folder/with/the-script
python3 main.py

Mistake 2: Installing packages, then getting ModuleNotFoundError

You might run:

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:

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:

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:

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:

which python3
python3--version

On Windows:

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:

python-m app.main

Quick recap

  • Check Python works with python3 --version on macOS/Linux or py --version on Windows.
  • cd into the folder that contains your .py file.
  • Run python3 your_script.py or py your_script.py.
  • Pass arguments with sys.argv or argparse.
  • Use a virtual environment when you install packages.
  • Use python -m package.module for scripts inside a package structure.