argparse — command-line parsing

ArgumentParser, explicit argv, Namespace, and catchable SystemExit on Python 3.13.12, without reading process arguments.

argparse builds a command-line parser and returns an argparse.Namespace. parse_args(args) reads the list you pass. If args is omitted, it would use sys.argv[1:]. Every example here passes an explicit list, so the page never reads the host process arguments.

Examples were checked on Python 3.13.12. With the default exit_on_error=True, usage errors and -h exit by raising SystemExit, which a caller can catch. This is not a click or typo package, and it is not a full rewrite of the official argparse tutorial.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

Explicit argv, types, and Namespace

ArgumentParser.add_argument registers a positional or optional argument. type=int converts the value, default is used when the option is omitted, and choices rejects other strings. The program name is set with prog so help text, if you print it, stays stable.

parse_args(["notes.txt", "--count", "3"]) returns a Namespace. Attributes and vars(namespace) both show path, count, and the default mode. The short option -n and the long option --count share the same dest.

ArgumentParser, add_argument, parse_args

class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)
ArgumentParser.add_argument(name_or_flags, ..., type=None, default=None, choices=None, required=False, dest=None, help=None, nargs=None)
ArgumentParser.parse_args(args=None, namespace=None)

Parse an explicit argument list into a Namespace, with type conversion, defaults, and choices.

ParameterDescription
progThe program name used in usage text. Set it in examples so the output does not depend on the script path.
name_or_flagsA positional dest, or one or more option strings such as -n and --count.
typeA callable used to convert the argument string, such as int.
argsThe list to parse. None would mean sys.argv[1:]; do not omit it when you want a closed example.

Returns: An argparse.Namespace whose attributes are the parsed values.

  • The example never calls parse_args() without a list.
python
import argparse

parser = argparse.ArgumentParser(prog="demo", description="Demo parser")
parser.add_argument("path")
parser.add_argument("-n", "--count", type=int, default=1)
parser.add_argument("--mode", choices=("fast", "slow"), default="fast")
namespace = parser.parse_args(["notes.txt", "--count", "3"])
print(type(namespace).__name__)
print(namespace.path, namespace.count, namespace.mode)
print(vars(namespace))

Expected output

Namespace
notes.txt 3 fast
{'path': 'notes.txt', 'count': 3, 'mode': 'fast'}

Official documentation →

SystemExit and exit_on_error

With the default exit_on_error=True, a bad value or a missing required option raises SystemExit with code 2, after usage text is written to standard error. -h raises SystemExit with code 0, and the help text goes to standard output. Catching SystemExit stops the process from ending, which is how this example stays runnable.

ArgumentParser(..., exit_on_error=False) raises argparse.ArgumentError instead of SystemExit for a usage error. That form is useful when a library wants to handle the error itself. The example still does not read sys.argv.

parse_args errors, SystemExit, exit_on_error

ArgumentParser.parse_args(args=None, namespace=None)
ArgumentParser(exit_on_error=True)

Catch SystemExit from a usage error or from -h, or raise ArgumentError when exit_on_error is False.

ParameterDescription
exit_on_errorIf True (the default), argparse exits through SystemExit on a usage error. If False, it raises ArgumentError instead.

Returns: A Namespace on success. On a handled error, the example prints the exception type and the exit code, not the full help text.

Raises

  • SystemExit — Usage errors used code 2, and -h used code 0, on Python 3.13.12 when exit_on_error is True.
  • argparse.ArgumentError — Raised for a usage error when exit_on_error is False. Measured for a missing required option.
  • The example redirects stdout and stderr while calling parse_args so the official usage text does not flood the recorded output. It only checks that the captured text contains a stable usage: demo line or the invalid int value phrase.
python
import argparse
import io
from contextlib import redirect_stderr, redirect_stdout

parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("--count", type=int, required=True)

out, err = io.StringIO(), io.StringIO()
try:
    with redirect_stdout(out), redirect_stderr(err):
        parser.parse_args(["--count", "x"])
except SystemExit as exc:
    print("bad-type", type(exc).__name__, exc.code)
    text = err.getvalue()
    print("has-usage", "usage: demo" in text)
    print("has-invalid", "invalid int value" in text)

out, err = io.StringIO(), io.StringIO()
try:
    with redirect_stdout(out), redirect_stderr(err):
        parser.parse_args(["-h"])
except SystemExit as exc:
    print("help", type(exc).__name__, exc.code)
    print("help-has-usage", "usage: demo" in out.getvalue())

out, err = io.StringIO(), io.StringIO()
try:
    with redirect_stdout(out), redirect_stderr(err):
        parser.parse_args([])
except SystemExit as exc:
    print("missing", type(exc).__name__, exc.code)

strict = argparse.ArgumentParser(prog="demo", exit_on_error=False)
strict.add_argument("--count", type=int, required=True)
try:
    strict.parse_args([])
except Exception as exc:
    print("no-exit", type(exc).__name__)

Expected output

bad-type SystemExit 2
has-usage True
has-invalid True
help SystemExit 0
help-has-usage True
missing SystemExit 2
no-exit ArgumentError

Official documentation →