all Python 3argparseterm
argparse.ArgumentParser
parser
A command-line argument parser: you declare arguments with add_argument(), and parse_args() turns a list of strings into a Namespace of ready values.
Syntax
parser = argparse.ArgumentParser(prog=None, description=None, formatter_class=..., allow_abbrev=True, exit_on_error=True)
On bad input parse_args() does not raise an ordinary exception: it prints the usage to stderr and calls sys.exit(2), i.e. SystemExit, which except Exception does not catch. To get an ArgumentError instead, pass exit_on_error=False. Long options are matched by prefix by default, so '--verb' works as '--verbose' unless allow_abbrev=False. Called with no argument, parse_args() reads sys.argv[1:], so pass a list explicitly in tests.
Examples
import argparse
parser = argparse.ArgumentParser(prog='app')
parser.add_argument('--n', type=int, default=1)
parser.add_argument('--verbose', action='store_true')
print(parser.parse_args(['--n', '3'])) # → Namespace(n=3, verbose=False)
print(parser.parse_args(['--verb'])) # → Namespace(n=1, verbose=True) — префикс опции
# Python 3.9+
import argparse
parser = argparse.ArgumentParser(prog='app', exit_on_error=False)
parser.add_argument('--n', type=int)
try:
parser.parse_args(['--n', 'x'])
except argparse.ArgumentError as e:
print(e) # → argument --n: invalid int value: 'x'
import argparse
parser = argparse.ArgumentParser(prog='app')
try:
parser.parse_args(['--oops'])
except SystemExit as e:
print('код выхода', e.code) # → код выхода 2
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy