C.W.K.
Stream
Lesson 01 of 04 · published

sys.argv and argparse — The Stdlib Way

~20 min · sys.argv, argparse, cli

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

sys.argv — the raw list

The simplest way to read command-line arguments: sys.argv is a list. sys.argv[0] is the script name. sys.argv[1:] are the arguments. For tiny scripts that take a positional arg or two, this is fine. For anything with flags, options, or help text, use argparse.

argparse — the stdlib's CLI parser

argparse handles parsing, validation, type conversion, default values, help text generation. parser = argparse.ArgumentParser(); parser.add_argument("--input"); args = parser.parse_args(). The result is a namespace object with attributes for each defined argument. Auto-generated --help output is one of argparse's biggest wins.

Positional vs optional

add_argument("input") declares a positional argument. add_argument("--input") declares an optional flag (note the leading --). add_argument("-i", "--input") declares both short and long forms. Positionals are required by default; optionals are not unless required=True.

Type conversion and choices

type=int on an argument tells argparse to convert the string to int and validate. choices=["a", "b"] restricts to a fixed set. action="store_true" makes --verbose a flag (no value, just present-or-not). These cover most CLI patterns.

Principle: argparse is built into Python and handles 90% of CLI needs. Reach for click or typer when you have many subcommands, want richer features, or prefer the decorator style. argparse vs typer is style preference more than capability.

Code

sys.argv — the bare basics·python
# script.py
import sys

print("script:", sys.argv[0])
print("args:", sys.argv[1:])

# python script.py hello world
# script: script.py
# args: ['hello', 'world']
argparse — minimal·python
import argparse

parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument("integers", type=int, nargs="+", help="integers to sum")
parser.add_argument("--verbose", action="store_true", help="verbose output")

args = parser.parse_args()

if args.verbose:
    print("summing:", args.integers)
print("total:", sum(args.integers))

# python script.py 1 2 3 4 --verbose
# summing: [1, 2, 3, 4]
# total: 10

# python script.py --help    auto-generates help
Positional, optional, type, choices·python
import argparse

parser = argparse.ArgumentParser()

# Positional — required
parser.add_argument("input")

# Optional — short and long forms
parser.add_argument("-o", "--output", default="result.txt")

# Type conversion + range
parser.add_argument("--port", type=int, default=8000)

# Restricted choices
parser.add_argument("--mode", choices=["dev", "prod"], default="dev")

# Boolean flag
parser.add_argument("--verbose", action="store_true")

# Counting flag — -vvv → 3
parser.add_argument("-v", action="count", default=0)

args = parser.parse_args()
print(args)
Subcommands — argparse style·python
import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command", required=True)

# 'add' subcommand
add_parser = subparsers.add_parser("add", help="add two numbers")
add_parser.add_argument("a", type=int)
add_parser.add_argument("b", type=int)

# 'multiply' subcommand
mul_parser = subparsers.add_parser("multiply", help="multiply two numbers")
mul_parser.add_argument("a", type=int)
mul_parser.add_argument("b", type=int)

args = parser.parse_args()

if args.command == "add":
    print(args.a + args.b)
elif args.command == "multiply":
    print(args.a * args.b)

# python script.py add 3 4         → 7
# python script.py multiply 3 4    → 12
# python script.py --help          shows subcommands

External links

Exercise

Build a small CLI tool with argparse: python tool.py [--verbose] [--count N] input output. The required positional args are input/output paths. --count is an optional int defaulting to 1. --verbose is a flag. The script just prints the parsed arguments. Add help text. Run with --help and confirm it auto-generates the help. Test with various combinations.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.