Skip to main content

Running Python Scripts

Beginner Satellite

Running Python Scripts

Move beyond the REPL by running `.py` files, passing CLI arguments, and making scripts executable.

Basic execution

python hello.py
python3 hello.py # macOS/Linux when both versions installed

Use absolute or relative paths. Activate your virtual environment first (source .venv/bin/activate).

Passing arguments

python greet.py --name "Ada" --times 3

Inside your script, parse them with argparse:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--name', default='Developer')
args = parser.parse_args()

Shebang for executables

#!/usr/bin/env python3
print("Hello")
  1. Add shebang as the first line.
  2. Make file executable: chmod +x script.py
  3. Run ./script.py

Helpful flags

FlagPurpose
-m moduleRun a module as a script (python -m venv .venv)
-iDrop into interactive mode after running
-OOptimize bytecode (removes asserts)

Next up in your learning path