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.
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.