Back to Explore
GuideVibeFix editorialUpdated Nov 25, 2026

Stop Hand-Rolling sys.argv: Give Your CLI Arguments with argparse

Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.

Real photo: an old CRT monitor on a wooden desk showing green terminal text, with a keyboard beside it

The most common flaw in an AI-written command-line tool is not wrong behavior — it is hand-rolled argument parsing: take one item from sys.argv by index, compare one string, guess the types, and when the user types something wrong, all they get is an error they cannot read, with no --help at all. This guide covers argparse from the standard library, which the official tutorial names the recommended command-line parsing module in the standard library: it does exactly this job. You declare which arguments the program accepts; parsing, type conversion, help generation and error exits are its work. The demo uses a fictional bookshop CLI called bookcli, with two subcommands, add for adding a book and list for listing books. The example and the numbers are for teaching, but every step really ran: the demo script is demo250_g2.py, the local environment is Python 3.12.3, standard library only, and the Chinese and English runs execute the same logic with identical numbers — each transcript is stored in this directory.

The conclusion first: add "Python Basics" --price 59.9 --count 3 parses to price=59.9, count=3, with a total of 59.9 x 3 = 179.7; list --sort price --limit 2 -v parses to sort='price', limit=2, verbose=True; giving only the title and price leaves count at its default of 1, tag at None, and format at its default of text; two --tag flags collect into ['new', 'signed']; four errors — a missing required item, an option outside choices, a number that does not convert, and one undefined option — all exit with code 2; the abbreviation --pri works; running with no subcommand at all does not error by default and leaves command as None, and switching to required=True makes it an error. Keep these numbers in mind; every detail below is their expansion.

From hand-rolled sys.argv to argparse: what is different

To see clearly what argparse saves you, look first at the hand-rolled way. Suppose the add command parses sys.argv by hand; the code looks roughly like this:

import sys
title = sys.argv[2]
price = float(sys.argv[4])  # assuming --price is always in position 4

That code has four flaws, each one a real pitfall from real projects. First, the positions are hard-coded: if the user writes --count 3 before --price, every index shifts, the price reads 3, the count reads 59.9, and the program does not error — it just quietly computes the wrong bill. Second, a missing argument reports IndexError: list index out of range, which tells the user nothing about which argument is missing or what the correct call looks like. Third, type conversion is your own work, and float("three") raises ValueError: could not convert string to float: 'three', with no usage line and no argument name — the user has to read the code. Fourth, --help has to be written by hand, and every new argument means another place to update the help text; miss one and the help disagrees with the program, which is worse than having none.

argparse takes all four jobs: order does not matter, since the result is the same either way; a missing argument reports the following arguments are required: --price plus the usage line; a failed conversion reports invalid int value: 'three' with the argument name; help is generated from the declarations, so adding an argument never means editing the help. Hand-rolled parsing can run — for a three-argument bookcli it is only a dozen lines — but as arguments and subcommands grow, the hand-written indexes and checks get longer and more brittle, while argparse declarations only get longer and clearer. The rule for when to switch is simple: more than two arguments, or any user other than yourself, means stop hand-rolling.

The smallest parse: positional plus options

Here is what bookcli looks like. The main parser fixes the program name with prog="bookcli", so the name in errors and help is always bookcli and never follows the script filename; then add_subparsers(dest="command") hangs two subcommands, add and list, each with its own arguments. The add command is declared like this:

add.add_argument("title", help="Book title.")
add.add_argument("--price", type=float, required=True,
                 help="Price in yuan (required).")
add.add_argument("--count", type=int, default=1,
                 help="How many copies (default 1).")
add.add_argument("--tag", action="append", default=None,
                 help="Tag; repeatable.")
add.add_argument("--format", choices=["text", "json"], default="text",
                 help="Output format.")

Running add "Python Basics" --price 59.9 --count 3, parse_args() returns a Namespace that prints as Namespace(command='add', title='Python Basics', price=59.9, count=3, tag=None, format='text'). The positional title is recognized by where it appears; options are recognized by their -- names, and the order can change — --count 3 "Python Basics" --price 59.9 parses to the same result. The official tutorial has the matching example: prog.py 4 --verbose and prog.py --verbose 4 print exactly the same thing, because options and positionals are recognized separately and order does not matter.

A Namespace is just a plain object holding the results, with attribute names matching the argument names one to one: args.price, args.count, args.title. It works much like a dict you wrote yourself, except you never count indexes into sys.argv. Internally argparse does read its arguments from sys.argv — the difference is that you never touch that list yourself.

type= is conversion, and also validation

Everything on a command line starts as a string, and type= tells argparse what to convert it into. In the demo, --price is type=float and --count is type=int, so the total can be computed right away: 59.9 x 3 = 179.7, with no hand-written float() or int() call. Without type=, whatever comes in stays a string; the tutorial spells out this trap plainly: with a positional square and no type=int, running prog.py 4 to compute a square gives TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'; adding type=int makes the same command print 16.

The other side of type= is validation. In the demo, --count three passes a word where a number belongs, and argparse stops it at the parsing step: bookcli add: error: argument --count: invalid int value: 'three', exit code 2, and the program never reaches the business code. The tutorial's matching example is prog.py four, with prog.py: error: argument square: invalid int value: 'four' — the same pattern. Catching the error at the entrance beats crashing halfway through the business logic: the message says which argument, what value, and why it failed, and the user can fix it from that alone.

Defaults: what an omitted option looks like

Not every option has to be given every time. In the demo, add "Three-Body" --price 69.0 gives only the title and price, and parses to Namespace(command='add', title='Three-Body', price=69.0, count=1, tag=None, format='text'): count falls back to its default of 1, tag is None, and format falls back to its default of text. Defaults come in two forms: an explicit default= in the declaration, such as 1 for count and text for format; or None when no default is written, such as tag, meaning "the user did not give this one".

Defaults and required are opposites. --price is declared with required=True, and leaving it out is an error: bookcli add: error: the following arguments are required: --price, exit code 2. The tutorial's positional version is prog.py: error: the following arguments are required: echo, the same sentence shape. The test for whether an option should be required is simple: if the program cannot do its job without it, write required=True, as with the price; if it can run without it and only runs differently, give it a default, as with a count of 1 book or a format of text. Getting this backwards hurts: a required value given a default lets the program silently run with the wrong value when the user forgets an argument; a defaultable value made required forces extra typing on every call for no reason.

choices: stop the mistake at the parsing step

--format has only two legal values, text and json, and the demo pins that range down with choices=["text", "json"]. Passing --format xml gives bookcli add: error: argument --format: invalid choice: 'xml' (choose from 'text', 'json'), exit code 2, and helpfully lists the two legal values too. The list command's --sort works the same way with choices=["title", "price"]; the demo passes price and gets sort='price'.

This is the same idea as type=: a mistake that can be stopped at the parsing step should not be left for the business code to catch. Writing if format not in ("text", "json") in the business code can stop it too, but it has to be written everywhere and is easy to miss; declared once, the check and the error come from argparse, and the help text automatically shows the allowed values, so a user running --help sees them at a glance. choices fits options whose value range is small and fixed, such as a format, a sort key or an output level; for wide or dynamic ranges, such as book titles or tags, do not squeeze them into choices.

Flags and repeats: store_true and append

Not every option takes a value. The list command's -v/--verbose uses action="store_true", meaning it takes no value: present means True, absent means False. In the demo, list --sort price --limit 2 -v parses to verbose=True, and without -v it is False. The tutorial's matching example is --verbose on its own printing verbosity turned on, while --verbose 1 errors, because a flag should not be followed by a value and the extra 1 is treated as an undefined argument: prog.py: error: unrecognized arguments: 1. The short form -v and the long form --verbose are two spellings of one argument, declared together with add_argument("-v", "--verbose", ...); either works.

--tag takes the other path: action="append". In the demo, add "To Live" --price 39.0 --tag new --tag signed parses to tag=['new', 'signed'] — each occurrence is collected, and the result is a list. When absent it is None, the default. append fits options that may repeat with one value each, such as tags, exclusions or multiple input files; written as an ordinary option, a second occurrence would silently overwrite the first, so a user passing two tags keeps only the last one — a mistake that is hard to spot, because the program does not error, it just quietly drops data.

--help comes free, one for the main command and one per subcommand

The best deal in argparse is that help text costs nothing to write. The first 6 lines of the main command's --help look like this:

usage: bookcli [-h] {add,list} ...
A tiny bookshop stock manager (demo CLI).
positional arguments:
  {add,list}

Subcommands have their own copy too; the first 8 lines of add --help:

usage: bookcli add [-h] --price PRICE [--count COUNT] [--tag TAG]
                   [--format {text,json}]
                   title
positional arguments:
  title                 Book title.
options:

The usage line is assembled from the declarations: square brackets hold the optional parts, --price PRICE has no brackets because it is required, {text,json} is the choices range, and title is the positional. The description sits under the usage line, and each argument's help sits on its own line. What makes help genuinely useful is writing the help text clearly when the argument is declared — Price in yuan (required) helps far more than price — and writing the description as one plain sentence about what the program does. The tutorial also notes that help text is re-wrapped to the terminal width by default; the demo pins COLUMNS to 80 at the top of the script so the output is byte-identical across the two runs, but a real project does not need that — it wraps to whatever width the terminal has.

Count defaults to 1, given 3; limit defaults to 10, given 2; total 59.9 x 3 = 179.7; all 4 errors exit with code 2

Four errors, all exiting with code 2

Section 5 of the demo runs the four most common errors, and all of them exit with code 2 — argparse's fixed exit code for errors. First, a missing required item: add "Python Basics" without --price gives bookcli add: error: the following arguments are required: --price. Second, an option outside choices: --format xml gives bookcli add: error: argument --format: invalid choice: 'xml' (choose from 'text', 'json'). Third, a number that does not convert: --count three gives bookcli add: error: argument --count: invalid int value: 'three'. Fourth, an undefined option: list --nope gives bookcli: error: unrecognized arguments: --nope.

The four errors share two traits. First, each prints the usage line before the specific problem, so the user knows how to fix it without opening the docs. Second, each goes to standard error with exit code 2, never mixed into normal output, so a script can tell success from failure by the exit code alone. When writing a CLI, do not reinvent either of these: hand-written error messages easily drop the usage line, and hand-picked exit codes easily collide with other codes — argparse's defaults are the safest choice.

Two easy traps: abbreviations and a missing subcommand

The first trap is abbreviations. argparse enables allow_abbrev by default, so a long option can be shortened whenever it is unambiguous: in the demo, --pri 59.9 stands in for --price 59.9 and parses to price=59.9, count=1, with everything else at defaults. Convenient, but with two costs: the abbreviation rule depends on the current set of arguments, so adding a --print option later suddenly makes the old --pri ambiguous and parsing fails; and a user may write an abbreviation by accident and find it stops working in another version. For a tool others will use, always write the full name in docs and examples, and treat abbreviations as a shortcut for your own debugging only — never put them in any formal call.

The second trap is running with no subcommand. In the demo, running bare bookcli with no subcommand does not error by default; it parses to Namespace(command=None), and business code that dispatches on command will then fail somewhere else with a confusing error. The fix is required=True when building the subparsers: add_subparsers(dest="command", required=True). With that, the same bare call reports bookcli: error: the following arguments are required: command, exit code 2 — the mistake is caught at the entrance, where it is easy to find. Whether to use the default or required=True depends on whether the program has anything sensible to do without a subcommand: a tool like ls, which has a default behavior with no arguments, uses the default; a tool like bookcli, which does not know what to do without a subcommand, must write required=True.

Putting the parsed result to work: a smallest runnable main

Parsing is only the first step — it has to connect to the business code. bookcli's smallest main dispatches on command: add puts the book in the list, list sorts and prints as requested. The demo stock holds 3 books: Python Basics at 59.9, Three-Body at 69.0, and To Live at 39.0, totaling 167.9. Sorted by price the order is To Live, Python Basics, Three-Body; sorted by title it is Python Basics, Three-Body, To Live; the demo's list --sort price --limit 2 takes the first 2, which are To Live and Python Basics. These numbers are computed straight from the demo's 3 books, not invented: 59.9 + 69.0 + 39.0 = 167.9, and the sort orders match sorted output one to one.

The dispatch code is fixed in shape — check args.command for add or list, then read each one's arguments:

stock = [{"title": "Python Basics", "price": 59.9},
         {"title": "Three-Body", "price": 69.0},
         {"title": "To Live", "price": 39.0}]

if args.command == "add":
    total = args.price * args.count
    print(f"Added {args.count} x {args.title}: {total}")
elif args.command == "list":
    books = sorted(stock, key=lambda b: b["price"] if args.sort == "price" else b["title"])
    for book in books[:args.limit]:
        print(book["title"], book["price"])

This shows another benefit of type=: args.price * args.count computes directly, because the values were already converted to float and int at parse time — the business code never converts them again. In the other direction, if args.command is None — the user wrote no subcommand — neither branch runs, and the program exits quietly having done nothing, with exit code 0, looking successful while nothing happened. That is the same trap from the previous section as it appears in business code: a None at the parse layer becomes a silent no-op at the business layer, so required=True must be written at the parser level and not left for the business code to cover.

One more exit-code detail is worth remembering: a successful parse and a completed run exit with 0; --help prints the help and exits with 0 too, because the user asked for the help itself and that is not an error; only a parse error exits with 2. To judge whether one call succeeded, the exit code is enough: 0 means success or help viewed, 2 means the arguments were wrong, and any other number is most likely the business code's own problem, not argparse's.

What this guide does not cover, and what comes next

argparse can do more than this guide shows; the rest can wait until it is needed. Two options that must not appear together — for example --json and --text, pick one — go in a mutually exclusive group built with add_mutually_exclusive_group(), which itself can take required=True to mean at least one must be chosen; the official docs carry full examples of this method. Several subcommands sharing one set of arguments, such as every subcommand wanting --verbose, use parents= with a pre-built parent parser — but the parent parser needs add_help=False, or the two -h options conflict, and the docs flag that point explicitly. Reading arguments from a file, for example putting common arguments in a file and passing @file, uses fromfile_prefix_chars, which the docs describe, and fits calls with very long argument lists. Taking over error handling instead of letting argparse exit is done by setting exit_on_error to False, so a parse error raises an exception instead of exiting — that fits embedding a CLI inside another program, and the parameter was added in Python 3.9.

One more habit is easy to overlook: treat the output of --help as a test to run. When a CLI's arguments change, its help changes with them, but callers, docs and scripts with hard-coded calls do not change on their own — the most common failure is adding a required argument while an old script still uses the old call, and the next run reports the following arguments are required. The demo pins COLUMNS to 80 precisely so the help output is byte-identical across two runs; the same trick works in tests: save the --help output, compare it once whenever the arguments change, and any place where the help moved but the call did not will show up at once. Arguments are the program's public face; when the face changes, everything written against the old face has to change with it — that step cannot be skipped.

The docs carry one sentence worth repeating: argparse is the default recommended command-line parsing module in the standard library, but authors with more exacting requirements for exactly how their programs behave may find it does not provide the necessary control, and the docs have a whole section on choosing another parsing library. The implication is that for most command-line tools, positional arguments, options, types, defaults, choices and subcommands are already enough — use them properly first, and only switch libraries when you hit something argparse genuinely cannot do, instead of installing a third-party package up front for the sake of "more power". The config guide covers config files and environment variables, the other side of the same coin as this guide's command-line arguments: command-line arguments fit things that change on every run, such as which book to add or how many to list; config files and environment variables fit things that change when the environment changes, such as ports and secrets — do not mix the two up.

Back to the original flaw: hand-rolled sys.argv parsing mixes "declaring" with "parsing" — every new argument means another stretch of indexes and checks, with no unified error when something goes wrong. argparse separates the two: declare once, and parsing, type conversion, help generation and error exits are its work — 6 successful parses, 4 errors, 2 traps, and every number in the demo is the result of that division of labor. The next time you add command-line arguments to your own small tool, write add_argument first and the business code second. Do not reverse that order.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles