Skip to main content
Basics

How to run a Python script

Quick answer

python script.py from the shell. Pass arguments after the script name — they land in sys.argv.

# save as hello.py:
import sys

name = sys.argv[1] if len(sys.argv) > 1 else "world"
print(f"Hello, {name}!")

# in the shell:
# python hello.py Alice
# → Hello, Alice!

`python script.py` launches the Python interpreter, loads the file, and runs the top-level code. sys.argv holds the command-line arguments as strings — sys.argv[0] is always the script name; sys.argv[1:] is everything the user passed.

For anything more complex than one or two positional args, use argparse (stdlib) — it handles help messages, --flags, type conversion, and default values with almost no boilerplate.

Make the script executable with a shebang (`#!/usr/bin/env python3` on the first line) + `chmod +x script.py`, then run it as `./script.py`. This is the standard for CLI tools.

Variations

argparse for real CLI args

import argparse
p = argparse.ArgumentParser()
p.add_argument("name")
p.add_argument("--times", type=int, default=1)
args = p.parse_args()
for _ in range(args.times):
    print(f"Hello, {args.name}!")

Free --help, type checking, and error messages.

Shebang for direct execution

#!/usr/bin/env python3
print("hi")
# Then: chmod +x hello.py && ./hello.py

Works on macOS/Linux. Windows ignores shebangs — use `py` launcher instead.

Run a module (-m)

# python -m http.server 8000
# python -m pip install requests
# python -m my_package.tool

Runs a module by name — respects sys.path and package structure.

Practise this in your browser

Every how-to has a live lesson. Free tier, no card.

Start free →

Unlock every lesson

Pro — $12/mo, unlimited AI, cancel any time.

See Pro plans →

Get one Python lesson + one career idea every Friday

No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.

Related how-tos