On this page
argparse
Prev: antigravity | Up: stdlib_module | Next: array
Rel: os, io, time, getopt, optparse
Ref: docs.python.org — argparse
Tags: #public #python3 #stdlib
Import
import argparse
Overview
Standard-library command-line argument parser that handles positional arguments, optional flags, type conversion, subcommands (git commit-style), and auto-generated --help text. Reach for argparse whenever a script takes more than one positional argument or needs proper flags and usage help.
Quick Start
import argparse
parser = argparse.ArgumentParser(description="Greet a user.")
parser.add_argument("name", help="Person to greet")
parser.add_argument("-n", "--count", type=int, default=1, help="Repeat count")
parser.add_argument("--loud", action="store_true", help="Uppercase output")
args = parser.parse_args(["Ada", "--count", "2", "--loud"])
assert (args.name, args.count, args.loud) == ("Ada", 2, True)
Implementation Walkthrough
1. Subcommands (add_subparsers) & Clean Dispatch
Bind each subcommand to a handler function with set_defaults(func=...) so main() stays flat and testable:
import argparse
def cmd_add(args: argparse.Namespace) -> int:
print(f"Adding {args.item}")
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True)
p_add = sub.add_parser("add", help="Add a task")
p_add.add_argument("item")
p_add.set_defaults(func=cmd_add)
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
return args.func(args)
2. Validating Choices, Paths & Mutually Exclusive Flags
import argparse
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("--config", type=Path, default=Path("config.toml"))
parser.add_argument("--format", choices=("text", "json"), default="text")
group = parser.add_mutually_exclusive_group()
group.add_argument("-q", "--quiet", action="store_true")
group.add_argument("-v", "--verbose", action="store_true")
Gotchas & Boundaries
- Accept
argv: list[str] | None = Noneinmain(): Passingargvtoparse_args(argv)lets unit tests invoke your CLI directly without monkeypatchingsys.argv. - Never use
type=bool:bool("false")isTrue! Useaction="store_true"orargparse.BooleanOptionalAction(gives--flag/--no-flag). parse_args()callssys.exit(2)on invalid input: CatchSystemExitin tests or inspectparse_known_args()if forwarding unknown flags.
Classes & Objects
- argparse.Action — Information about how to convert command line strings to Python objects. (Methods:
.format_usage()) - argparse.ArgumentDefaultsHelpFormatter — Help message formatter which adds default values to argument help. (Methods:
.add_argument(),.add_arguments(),.add_text(),.add_usage(),.end_section(),.format_help()) - argparse.ArgumentError — An error from creating or using an argument (optional or positional). (Methods:
.add_note(),.with_traceback()) - argparse.ArgumentParser — Object for parsing command line strings into Python objects. (Methods:
.add_argument(),.add_argument_group(),.add_mutually_exclusive_group(),.add_subparsers(),.convert_arg_line_to_args(),.error()) - argparse.ArgumentTypeError — An error from trying to convert a command line string to a type. (Methods:
.add_note(),.with_traceback()) - argparse.BooleanOptionalAction —
argparse.BooleanOptionalActionclass. (Methods:.format_usage()) - argparse.FileType — Deprecated factory for creating file object types Instances of FileType are typically passed as type= arguments to the ArgumentParser add_argument() method.
- argparse.HelpFormatter — Formatter for generating usage messages and argument help strings. (Methods:
.add_argument(),.add_arguments(),.add_text(),.add_usage(),.end_section(),.format_help()) - argparse.MetavarTypeHelpFormatter — Help message formatter which uses the argument 'type' as the default metavar value (instead of the argument 'dest') Only the name of this class is considered a public API. All the methods (Methods:
.add_argument(),.add_arguments(),.add_text(),.add_usage(),.end_section(),.format_help()) - argparse.Namespace — Simple object for storing attributes.
- argparse.RawDescriptionHelpFormatter — Help message formatter which retains any formatting in descriptions. (Methods:
.add_argument(),.add_arguments(),.add_text(),.add_usage(),.end_section(),.format_help()) - argparse.RawTextHelpFormatter — Help message formatter which retains formatting of all help text. (Methods:
.add_argument(),.add_arguments(),.add_text(),.add_usage(),.end_section(),.format_help())
Constants & Attributes
argparse.ONE_OR_MORE(str) ='+'argparse.OPTIONAL(str) ='?'argparse.PARSER(str) ='A...'argparse.REMAINDER(str) ='...'argparse.SUPPRESS(str) ='==SUPPRESS=='argparse.ZERO_OR_MORE(str) ='*'
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/antigravity
- tuts/python3/stdlib_module/argparse/Action
- tuts/python3/stdlib_module/argparse/ArgumentDefaultsHelpFormatter
- tuts/python3/stdlib_module/argparse/ArgumentError
- tuts/python3/stdlib_module/argparse/ArgumentParser
- tuts/python3/stdlib_module/argparse/ArgumentTypeError
- tuts/python3/stdlib_module/argparse/BooleanOptionalAction
- tuts/python3/stdlib_module/argparse/FileType
- tuts/python3/stdlib_module/argparse/HelpFormatter
- tuts/python3/stdlib_module/argparse/MetavarTypeHelpFormatter
- tuts/python3/stdlib_module/argparse/Namespace
- tuts/python3/stdlib_module/argparse/RawDescriptionHelpFormatter
- tuts/python3/stdlib_module/argparse/RawTextHelpFormatter
- tuts/python3/stdlib_module/array
- tuts/python3/stdlib_module/asyncio
- tuts/python3/stdlib_module/concurrent
- tuts/python3/stdlib_module/contextvars
- tuts/python3/stdlib_module/ctypes
- tuts/python3/stdlib_module/curses
- tuts/python3/stdlib_module/errno
- tuts/python3/stdlib_module/fcntl
- tuts/python3/stdlib_module/fileinput
- tuts/python3/stdlib_module/getopt
- tuts/python3/stdlib_module/getopt/getopt
- tuts/python3/stdlib_module/getpass
- tuts/python3/stdlib_module/grp
- tuts/python3/stdlib_module/logging
- tuts/python3/stdlib_module/mmap
- tuts/python3/stdlib_module/msvcrt
- tuts/python3/stdlib_module/multiprocessing
- tuts/python3/stdlib_module/nt
- tuts/python3/stdlib_module/optparse
- tuts/python3/stdlib_module/optparse/BadOptionError
- tuts/python3/stdlib_module/platform
- tuts/python3/stdlib_module/posix
- tuts/python3/stdlib_module/pty
- tuts/python3/stdlib_module/pwd
- tuts/python3/stdlib_module/queue
- tuts/python3/stdlib_module/resource
- tuts/python3/stdlib_module/sched
- tuts/python3/stdlib_module/select
- tuts/python3/stdlib_module/selectors
- tuts/python3/stdlib_module/signal
- tuts/python3/stdlib_module/socket
- tuts/python3/stdlib_module/ssl
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/subprocess
- tuts/python3/stdlib_module/sys
- tuts/python3/stdlib_module/syslog
- tuts/python3/stdlib_module/termios
- tuts/python3/stdlib_module/threading
- tuts/python3/stdlib_module/tty
- tuts/python3/stdlib_module/winreg
- tuts/python3/stdlib_module/winsound
- tuts/python3/tutorials/popular_application_domains/automation_devops_and_web_scraping
Related notes
- tuts/python3/stdlib_module/antigravity Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/Action Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/ArgumentDefaultsHelpFormatter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/ArgumentError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/ArgumentParser Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/ArgumentTypeError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/BooleanOptionalAction Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/FileType Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/HelpFormatter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/MetavarTypeHelpFormatter Linked here; links to this page; shared tags: #stdlib