Python argparse Module
Example
Define a simple CLI that accepts a name argument:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args(["Tobias"])
print(args.name)
Try it Yourself »
Definition and Usage
The argparse module makes it easy to build user-friendly command-line interfaces.
It parses arguments and options, generates help and usage messages automatically, and provides errors when users give the program invalid arguments.
Members
| Member | Description |
|---|---|
| Action | Base class for how an argument should be handled (store, append, count, etc.). |
| add_argument() | ArgumentParser method: Define a new positional or optional argument. |
| add_subparsers() | ArgumentParser method: Create sub-commands (e.g. git commit, git push). |
| ArgumentDefaultsHelpFormatter | Help formatter that shows default values next to options. |
| ArgumentError | Error raised for invalid arguments or combinations. |
| ArgumentParser() | Create a parser; add options/arguments and parse the command line. |
| ArgumentTypeError | Error raised when converting a value to the required type fails. |
| BooleanOptionalAction | Action that creates --foo / --no-foo style boolean flags. |
| error() | ArgumentParser method: Raise an error message and exit. |
| exit() | ArgumentParser method: Exit the program with a status code. |
| FileType() | Helper for opening files from argument values (e.g. "-" for stdin). |
| format_help() | ArgumentParser method: Return the full help text as a string. |
| format_usage() | ArgumentParser method: Return the short usage message as a string. |
| HelpFormatter | Base class for help text formatting. |
| MetavarTypeHelpFormatter | Formatter that adds information about argument types. |
| Namespace | Simple object used to store parsed values (dot-attribute access). |
| ONE_OR_MORE | Marker used in help/usage to indicate one or more values are expected. |
| OPTIONAL | Marker used in help/usage to indicate an optional argument. |
| PARSER | Marker used internally for sub-parsers in usage strings. |
| parse_args() | ArgumentParser method: Parse the command line and return a Namespace. |
| parse_known_args() | ArgumentParser method: Parse known options and return (namespace, remaining). |
| PARSER | Marker used internally for sub-parsers in usage strings. |
| print_help() | ArgumentParser method: Print the full help text to stdout. |
| print_usage() | ArgumentParser method: Print the short usage message to stdout. |
| RawDescriptionHelpFormatter | Formatter that preserves whitespace in the description. |
| RawTextHelpFormatter | Formatter that preserves whitespace in both description and epilog. |
| REMAINDER | Collect all remaining command-line parts into a list. |
| SUPPRESS | Special value to hide a value from the help/usage output. |
| ZERO_OR_MORE | Marker used in help/usage to indicate zero or more values are accepted. |