Command-Line Arguments

Pass information to a script when you run it

Beginner 10 min

In this lesson

When you launch a program from the terminal — python report.py sales.csv — anything you type after the script name is handed straight to your program as a command-line argument. Reading those arguments is what lets one script work on any file or value instead of a hard-coded one. It's the difference between a one-off and a reusable tool.

Explain it like I’m 5

It's like ordering at a counter. The program is the order — ‘make a coffee’ — and the command-line arguments are the choices you add: ‘…large, oat milk’. Same program, different details each time you run it.

What command-line arguments are

The sys module hands you the arguments in sys.argv — a list of strings. The first item, sys.argv[0], is always the script's own name; everything you typed after it follows from index 1 onward.

Example
import sys

print(sys.argv)
Output
$ python args.py hello 42
['args.py', 'hello', '42']
Whatever you type after the script name lands in sys.argv. (Run locally.)

Reading an argument safely

If the user runs your script with no arguments, sys.argv holds only the script name — so reaching for sys.argv[1] would raise an IndexError. Check how many arguments arrived with len(sys.argv) first, and fall back to a sensible default when one is missing.

Example
import sys

name = sys.argv[1] if len(sys.argv) > 1 else "World"
print(f"Hello, {name}!")
Output
$ python greet.py Ada
Hello, Ada!
$ python greet.py
Hello, World!
Read the first argument, or fall back to a default. (Run locally.)

Arguments are always strings

Every value in sys.argv is a string, even when it looks like a number. To do arithmetic you must convert first with int() or float() — otherwise + joins the text instead of adding.

Example
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])
print(a + b)
Output
$ python add.py 2 3
5
Convert the text arguments before doing maths. (Run locally.)

Checking the count and showing usage

A polished tool tells people how to use it. Compare len(sys.argv) against what you expect, print a short usage line when it's wrong, and stop with sys.exit(1) — the 1 signals ‘something went wrong’ to the terminal.

Example
import sys

if len(sys.argv) != 2:
    print("Usage: python greet.py <name>")
    sys.exit(1)

print(f"Hello, {sys.argv[1]}!")
Output
$ python greet.py
Usage: python greet.py <name>
One guard handles both too-few and too-many arguments. (Run locally.)

When you outgrow sys.argv: argparse

Reading sys.argv by hand is perfect for one or two simple arguments. Once a script grows real options — a flag here, an optional output name there — the standard-library argparse module takes over the tedious parts. You declare the arguments you want; it parses them, converts types, generates a --help screen, and prints a friendly error when someone gets it wrong.

You don't need it yet, but it's worth knowing where the road leads — it's exactly the upgrade suggested in the CSV Cleaner project.

Example
import argparse

parser = argparse.ArgumentParser(description="Greet someone.")
parser.add_argument("name")
parser.add_argument("--shout", action="store_true")
args = parser.parse_args()

greeting = f"Hello, {args.name}!"
print(greeting.upper() if args.shout else greeting)
Output
$ python tool.py Ada --shout
HELLO, ADA!
argparse turns a wishlist of arguments into a polished tool. (Run locally.)

Common mistake: Reading sys.argv[1] when no argument was given

Why it happens:

With no arguments, sys.argv contains only the script name, so index 1 doesn't exist and Python raises IndexError.

How to fix it:

Check len(sys.argv) before indexing, or supply a default with a conditional expression such as sys.argv[1] if len(sys.argv) > 1 else "default".

Common mistake: Doing maths on arguments without converting them

Why it happens:

Everything in sys.argv is a string, so sys.argv[1] + sys.argv[2] joins the text ('2' + '3''23') instead of adding.

How to fix it:

Convert each value with int() or float() — ideally inside try/except — before calculating.

import sys

# "2" + "3" would give "23", not 5
total = int(sys.argv[1]) + int(sys.argv[2])
print(total)

What does sys.argv[0] contain?

What type are the values in sys.argv?

Mini exercise (medium)

Write area.py that takes a width and a height on the command line and prints their product. Running python area.py 5 4 should print 20.

There’s no command line in the browser, so we simulate the arguments as a list — exactly what sys.argv[1:] would give you. Read the width and height and print their product.

args = ["5", "4"]    # like running:  python area.py 5 4
width = 0     # TODO: convert args[0]
height = 0    # TODO: convert args[1]
area = width * height
print(area)

What to learn next

You learned to read command-line arguments with sys.argv, why argv[0] is the script name, how to guard against missing arguments, how to convert argument strings to numbers, and how to print a usage message. You read a width and height from a simulated argv and printed their product.

Your programs are growing past a single file, so the last foundation is keeping them tidy. Organizing a Python Project covers splitting code into modules, a sensible folder layout, the __main__ guard, and README and requirements files. When you’re ready, continue to the next lesson.