Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 149 ยท Beyond the Basics

Command-Line Programs with argparse

Build real command-line tools in Python. Read sys.argv, define arguments and options with argparse, add subcommands and help text, and return proper exit codes.

Many of the most useful Python programs have no windows or buttons. You run them from a terminal, give them a few words of instructions, and they do their job: python resize.py photo.jpg --width 800. Those extra words are command-line arguments, and handling them well is what turns a quick script into a tool that you (and your teammates) can use every day.

In this lesson you'll see how arguments reach your program through sys.argv, then switch to the standard library's argparse module, which handles types, defaults, help pages and error messages for you. You'll finish with subcommands (like git add and git commit) and the exit codes that let other programs know whether yours succeeded.

How arguments reach your program

When you type a command in a terminal, the shell splits the line into words and hands them to Python. Your code finds them in the list sys.argv. The first item is the script's name, and the rest are the arguments, always as strings:

TEXT
$ python greet.py Ada --shout
sys.argv == ["greet.py", "Ada", "--shout"]

The editors on this page don't have a terminal, so the first example fills in sys.argv by hand to pretend the program was started that way:

Python Reading sys.argv

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For a throwaway script, this is fine. But look at everything it doesn't do: no help text, no checking that numbers are numbers, no error when the user types --shuot by mistake, and options must appear in exactly the expected places. Writing all that by hand gets messy fast. That's the job of argparse.

Your first argparse parser

With argparse you describe the arguments your program accepts, and the parser does the rest. There are two kinds:

  • Positional arguments are required and identified by their position: greet.py Ada.
  • Optional arguments (options) start with - or -- and can appear in any order: --times 3, -s.

parse_args() normally reads sys.argv. You can also pass it a list of strings, which is perfect for experimenting and for testing:

Python Positional arguments and options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The result is a Namespace: a simple object with one attribute per argument. A few details worth noticing:

  • type=int converted "2" into the integer 2. Any function that takes a string works as a type: float, pathlib.Path, or one of your own.
  • The attribute names come from the long option: --times became args.times. Dashes turn into underscores, so --dry-run becomes args.dry_run.
  • action="store_true" makes a flag: False when absent, True when present. It takes no value.
  • choices restricts the value to a fixed set, and default is used when the option is missing.

Try changing the list passed to parse_args(): drop --shout, swap the order of the options, or use the short forms -n 3 -s.

Free help pages and error messages

argparse writes the help page for you from the help= texts, and adds a -h/--help option automatically. It also rejects bad input with a clear message.

Both cases end the program by raising SystemExit: code 0 after showing help, and code 2 after a usage error. Here we catch that exception so the editor can keep going and show several runs:

Python Help, mistakes and exit codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real script you don't catch SystemExit. Python prints the message, stops, and the shell receives the exit code.

More argument shapes

A handful of extra settings covers almost every real tool:

Setting Meaning Example on the command line
nargs="+" one or more values, collected in a list resize.py a.png b.png c.png
nargs="?" zero or one value (use with default) serve.py or serve.py 8000
nargs="*" zero or more values lint.py or lint.py src tests
action="count" count repetitions -v, -vv, -vvv
action="append" allow an option several times --tag web --tag urgent
required=True make an option mandatory --output report.csv
metavar="PX" the placeholder name shown in help --width PX

A mutually exclusive group allows at most one option from a set, and a custom type function can validate a value. Raise argparse.ArgumentTypeError from it to produce a normal usage error:

Python nargs, counters, groups and custom types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Subcommands

Bigger tools often group their features into subcommands: git add, git commit, pip install, pip list. Each subcommand has its own arguments. In argparse, call add_subparsers() and create one parser per command.

A neat pattern is set_defaults(handler=...): each subcommand stores the function that should handle it, and main() simply calls args.handler(args). Each handler returns an exit code.

Python A note keeper with subcommands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that remove 7 printed its error to standard error (sys.stderr) and returned 1. Keeping errors off standard output matters when someone pipes your output into a file or another program: the data stays clean, and the error still appears on screen.

Exit codes

Every program finishes with an exit code, a small integer for whoever started it. The convention is simple:

  • 0 means success.
  • Any other number means failure. 1 is the usual "something went wrong", and argparse uses 2 for "you called me incorrectly".

Shells, CI pipelines, cron jobs and subprocess.run() all check this number. A script that prints "error" but exits with 0 looks successful to all of them.

You set the code with sys.exit(code), which raises SystemExit. If you call it with a string, Python prints the string to standard error and uses code 1. A clean structure for any command-line program looks like this:

Python
import argparse
import sys

def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Count lines in text files.")
    parser.add_argument("files", nargs="+")
    args = parser.parse_args(argv)          # None means "use sys.argv"

    total = 0
    for name in args.files:
        try:
            with open(name, encoding="utf-8") as file:
                total += sum(1 for _ in file)
        except FileNotFoundError:
            print(f"error: {name} not found", file=sys.stderr)
            return 1
    print(total)
    return 0

if __name__ == "__main__":
    sys.exit(main())

Why this shape works well:

  • main() takes an optional argv list, so tests can call main(["a.txt"]) directly without touching sys.argv.
  • It returns an exit code instead of calling sys.exit() deep inside the logic, which keeps it easy to test.
  • The if __name__ == "__main__": guard runs it only when the file is executed as a program, not when another module imports it (see Modules and Imports).

Read from standard input too. Many good tools accept data piped in from another program: cat log.txt | python errors.py. Loop over sys.stdin to read it line by line, and consider treating the file name - as "read from standard input", a widespread convention.

Installing your tool as a command

Typing python path/to/notes.py add ... gets old. When your code lives in a package with a pyproject.toml (see Virtual Environments and Project Setup), you can declare a command name:

TOML
[project.scripts]
notes = "notes.cli:main"

After pip install -e . inside your virtual environment, a notes command appears that calls main() from notes/cli.py, and its return value becomes the exit code. You can also make a package runnable with python -m notes by adding a __main__.py file that calls main().

Beyond argparse

argparse is in the standard library, so it's always available and needs no installation. For larger tools, two popular third-party libraries are worth knowing:

  • Click builds commands from decorated functions and adds prompts, colors and progress bars.
  • Typer builds on Click and reads your type hints to define arguments: a parameter count: int = 1 becomes the option --count.

Both produce the same kind of program you built here: arguments in, exit code out. Recent Python versions also polish argparse itself; for example, Python 3.14 added suggest_on_error=True, which suggests the closest valid choice when a user mistypes a subcommand.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does sys.argv contain after running python tool.py 5 --fast?

    sys.argv is a list of strings, and its first item is the script name. Converting '5' into a number is your job, or argparse's.
  2. 2. Which add_argument call creates a flag that is True when present and False when absent?

    action="store_true" makes an option that takes no value. type=bool is a common trap, since bool("False") is True.
  3. 3. What happens when a user passes --times abc for an option declared with type=int?

    argparse catches the conversion failure, prints the usage line and an error message to standard error, and raises SystemExit(2).
  4. 4. Why is def main(argv: list[str] | None = None) -> int a good shape for a command-line program?

    Passing argv explicitly and returning an exit code keeps the logic testable. The script itself ends with sys.exit(main()).
  5. 5. A script reports an error but exits with code 0. What is the problem?

    Exit code 0 means success. Return or exit with a non-zero code, such as 1, whenever the program fails.

Summary

  • Command-line arguments arrive as a list of strings in sys.argv, starting with the script name.
  • argparse turns argument descriptions into parsing, type conversion, defaults, a --help page and clear error messages.
  • Positional arguments are required; options start with -/--; store_true, count, append, nargs, choices and custom type functions cover most needs.
  • parse_args(list) lets you parse any list of strings, which makes experiments and tests easy.
  • Subcommands use add_subparsers(), and set_defaults(handler=...) routes each one to its function.
  • Exit with 0 on success and a non-zero code on failure; print errors to sys.stderr; end scripts with sys.exit(main()).

Next: Desktop GUIs with tkinter.