Python Reference ยท Standard Library: Concurrency, Network and Tools
The argparse module
Reference for Python's argparse module: ArgumentParser, add_argument, positional and optional arguments, types, choices, actions, subparsers and error handling.
argparse turns the words typed after your script's name into Python values. You describe the arguments you accept, and the module parses sys.argv, converts types, fills in defaults, writes --help output for you and prints a clear error for bad input.
The pattern is always the same: create an ArgumentParser, call add_argument() for each option, call parse_args() and read attributes from the result. Passing an explicit list to parse_args() (as the examples do) is also the easiest way to test a parser.
import argparse parser = argparse.ArgumentParser(description="Greet someone") parser.add_argument("name") args = parser.parse_args() print(f"Hello, {args.name}!")
Try it
In a script, parse_args() reads sys.argv automatically. Here we hand it lists, which also works in the browser.
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.
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.
Syntax
parser = argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, add_help=True, exit_on_error=True) parser.add_argument(name_or_flags, ..., action=None, nargs=None, const=None, default=None, type=None, choices=None, required=None, help=None, metavar=None, dest=None) namespace = parser.parse_args(args=None, namespace=None)
| Name | Description |
|---|---|
name_or_flags |
"name" for a positional argument, or "-n", "--name" for an optional one. |
action |
store (default), store_true, store_false, store_const, append, count, BooleanOptionalAction (adds --x and --no-x), version. |
nargs |
How many values: an integer, ? (zero or one), * (any), + (at least one). |
type |
A callable that converts the text, such as int, float or pathlib.Path. Raising ValueError or TypeError produces a usage error. |
choices |
Allowed values. |
default |
Value when the argument is missing. For store_true the default is False. |
required |
Makes an optional argument mandatory. |
dest |
Attribute name on the result. Derived from the first long flag, with - turned into _. |
help, metavar |
Text shown in --help, and the placeholder name for the value. |
Return value: parse_args() returns a Namespace object; use vars(ns) for a dictionary. parse_known_args() returns (namespace, leftovers) instead of failing on unknown arguments.
Raises: on bad input the parser prints usage to standard error and calls sys.exit(2), which raises SystemExit. With exit_on_error=False it raises argparse.ArgumentError for many errors instead. --help also exits, with status 0.
Usage notes
- Positional versus optional: positional arguments are required unless
nargs="?"or"*"; optional arguments (starting with-) are optional unlessrequired=True. type=boolis a trap. Any non-empty text, including"False", converts toTrue. Usestore_true/BooleanOptionalActionfor switches.-in names:--dry-runbecomesargs.dry_run.- Short flags combine:
-vvvworks withaction="count", and-n5is the same as-n 5. - Mutual exclusion:
parser.add_mutually_exclusive_group()lets the user pass at most one of several options. - Subcommands (
git commit,git pushstyle) come fromadd_subparsers(). Give itdest="command"so you can see which one ran. - Files:
type=argparse.FileType("r")opens files for you, butpathlib.Pathpluswith open(...)is usually cleaner. - Negative numbers like
-5may be read as options if the parser has options that look like numbers; use--to mark the end of options. - Report errors yourself:
parser.error("message")prints usage and exits with status 2, the right way to reject a combination argparse cannot check. - Third-party alternatives such as
clickandtyperoffer decorator-based interfaces;argparseneeds no installation.
Related
sys,os,pathliblogging- Lessons: Command-line programs, Running Python