ZetCode

Python argparse

last modified November 29, 2026 Python 3.15

In this article we show how to parse command line arguments in Python with the argparse module.

The argparse module is part of the standard library. We describe the arguments a program accepts and the module parses sys.argv, converts the values to the right types, generates help and usage messages, and reports errors when the user gives invalid arguments. The raw argument list is covered in the sys module article.

A parser is created with ArgumentParser, arguments are added with add_argument, and the command line is parsed with parse_args. There are two kinds of arguments: positional arguments, identified by their position, and options, which start with a dash, such as -n or --name.

The first parser

The first program accepts a single positional argument.

greet.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('name')
args = parser.parse_args()

print(f'Hello there, {args.name}!')

A name without a dash prefix creates a positional argument. The parse_args method returns an object whose attributes hold the parsed values, so the name is available as args.name. When the argument is missing, argparse prints a usage line and an error message to the standard error output and exits with status 2.

$ python greet.py Peter
Hello there, Peter!
$ python greet.py
usage: greet.py [-h] name
greet.py: error: the following arguments are required: name
$ echo $?
2

Help messages

Every parser has a -h/--help option. The help text is built from the program description, the arguments, and their help strings.

greeting.py
import argparse

parser = argparse.ArgumentParser(
    description='Greets a person by name.',
    epilog='Example: python greeting.py Lucia')
parser.add_argument('name', help='the name of the person to greet')
args = parser.parse_args()

print(f'Hello there, {args.name}!')

The description is printed after the usage line and the epilog at the end of the help. The help argument of add_argument describes a single argument. The program name in the usage line is taken from the script name. Since Python 3.14, help and error messages are coloured when printed to a terminal; the color parameter of ArgumentParser turns this off.

$ python greeting.py -h
usage: greeting.py [-h] name

Greets a person by name.

positional arguments:
  name        the name of the person to greet

options:
  -h, --help  show this help message and exit

Example: python greeting.py Lucia

The Namespace object

The parse_args method takes an optional list of strings. Without it, the arguments are read from sys.argv. Passing a list is handy for experiments and tests.

namespace.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('name')
parser.add_argument('city')

args = parser.parse_args(['Lucia', 'Bratislava'])

print(args)
print(args.name)
print(args.city)
print(vars(args))

The result is an argparse.Namespace object. Its attributes are named after the arguments. The vars function turns the namespace into a dictionary.

$ python namespace.py
Namespace(name='Lucia', city='Bratislava')
Lucia
Bratislava
{'name': 'Lucia', 'city': 'Bratislava'}

Optional arguments

Options are created with names that start with a dash. An option usually has a short form with one dash and a long form with two dashes.

options.py
import argparse

parser = argparse.ArgumentParser(description='Greets a person by name.')
parser.add_argument('name', help='the name of the person to greet')
parser.add_argument('-g', '--greeting', default='Hello',
                    help='the greeting word (default: %(default)s)')
parser.add_argument('-s', '--shout', action='store_true',
                    help='print the message in uppercase')
args = parser.parse_args()

message = f'{args.greeting} there, {args.name}!'

if args.shout:
    message = message.upper()

print(message)

The attribute is named after the long form, so the options are available as args.greeting and args.shout. An option that is not given gets its default value; without a default, it is None. The %(default)s placeholder in the help text is replaced with the default value.

The store_true action creates a flag: an option without a value that sets the attribute to True when present and False otherwise. Option values can follow the option as a separate argument or after an equals sign, and options may appear before or after positional arguments.

$ python options.py Peter
Hello there, Peter!
$ python options.py -g Hi Peter
Hi there, Peter!
$ python options.py Peter --shout --greeting=Ahoy
AHOY THERE, PETER!
$ python options.py -h
usage: options.py [-h] [-g GREETING] [-s] name

Greets a person by name.

positional arguments:
  name                  the name of the person to greet

options:
  -h, --help            show this help message and exit
  -g, --greeting GREETING
                        the greeting word (default: Hello)
  -s, --shout           print the message in uppercase

Argument types

Arguments are strings by default. The type option names a function that converts the string to another type.

power.py
import argparse

parser = argparse.ArgumentParser(description='Computes a power of a number.')
parser.add_argument('base', type=float)
parser.add_argument('-e', '--exponent', type=int, default=2)
args = parser.parse_args()

result = args.base ** args.exponent
print(f'{args.base} ** {args.exponent} = {result}')

The base is converted with float and the exponent with int. The default value of the exponent is already an integer, so no conversion is needed. If the conversion fails, argparse reports an error instead of a traceback.

$ python power.py 3
3.0 ** 2 = 9.0
$ python power.py 1.5 -e 3
1.5 ** 3 = 3.375
$ python power.py three
usage: power.py [-h] [-e EXPONENT] base
power.py: error: argument base: invalid float value: 'three'

Required options

Options are optional by default. The required option makes the user give it.

connect.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--host', required=True)
parser.add_argument('--port', type=int, default=8080)
args = parser.parse_args()

print(f'Connecting to {args.host}:{args.port}')

The program cannot run without a host, but the port has a sensible default. Users usually expect options to be optional, so positional arguments are often a better choice for values that must be given.

$ python connect.py --host example.com
Connecting to example.com:8080
$ python connect.py --port 443
usage: connect.py [-h] --host HOST [--port PORT]
connect.py: error: the following arguments are required: --host

Choices

The choices option limits an argument to a set of values. It accepts any container: a list, a tuple, a set, or a dictionary.

convert.py
import argparse

factors = {'km': 1.0, 'mi': 1.609344, 'nmi': 1.852}

parser = argparse.ArgumentParser(description='Converts kilometres.')
parser.add_argument('km', type=float)
parser.add_argument('-t', '--to', choices=factors, default='km')
args = parser.parse_args()

value = args.km / factors[args.to]
print(f'{args.km} km = {value:.3f} {args.to}')

The program converts kilometres to miles or nautical miles. The keys of the factors dictionary are the allowed units. The choices appear in the usage line, and a value outside of them is an error.

When a value is not allowed, argparse suggests the closest choice. The suggest_on_error parameter of ArgumentParser was added in Python 3.14 and is enabled by default since Python 3.15. The last command shows the same error in Python 3.14.

$ python convert.py 42.195 --to mi
42.195 km = 26.219 mi
$ python convert.py 42.195 -t nmi
42.195 km = 22.783 nmi
$ python convert.py 42.195 --to mile
usage: convert.py [-h] [-t {km,mi,nmi}] km
convert.py: error: argument -t/--to: invalid choice: 'mile', maybe you meant 'mi'? (choose from 'km', 'mi', 'nmi')
$ python3.14 convert.py 42.195 --to mile
usage: convert.py [-h] [-t {km,mi,nmi}] km
convert.py: error: argument -t/--to: invalid choice: 'mile' (choose from km, mi, nmi)

Repeated options

The append action collects every occurrence of an option into a list, and the count action counts how many times an option was given.

note.py
import argparse

parser = argparse.ArgumentParser(description='Saves a note.')
parser.add_argument('text')
parser.add_argument('-t', '--tag', dest='tags', action='append', default=[])
parser.add_argument('-v', '--verbose', action='count', default=0)
args = parser.parse_args()

print(f'Note: {args.text}')

if args.verbose >= 1:
    print(f'Tags: {", ".join(args.tags) or "none"}')

if args.verbose >= 2:
    print(f'Length: {len(args.text)} characters')

The dest option sets the attribute name: the tags are stored in args.tags instead of args.tag. Each -v raises the verbosity by one, and short flags can be combined, so -vv counts twice. Both options need a default, otherwise the attributes are None when the options are not given.

$ python note.py "Buy milk"
Note: Buy milk
$ python note.py "Buy milk" -t home -t shop -v
Note: Buy milk
Tags: home, shop
$ python note.py "Buy milk" -t home -vv
Note: Buy milk
Tags: home
Length: 8 characters

Number of values

The nargs option sets how many command line arguments an argument consumes. An integer means exactly that many, '?' zero or one, '*' any number, and '+' one or more. The values are collected into a list.

summary.py
import argparse
import statistics

parser = argparse.ArgumentParser(description='Summarizes numbers.')
parser.add_argument('values', type=float, nargs='+')
parser.add_argument('-b', '--between', type=float, nargs=2,
                    metavar=('LOW', 'HIGH'),
                    help='use only values in the range')
args = parser.parse_args()

values = args.values

if args.between:
    low, high = args.between
    values = [v for v in values if low <= v <= high]

print(f'count: {len(values)}')
print(f'sum: {sum(values)}')
print(f'mean: {statistics.mean(values):.2f}')

The values argument takes one or more numbers. The --between option takes exactly two values; a tuple of names in metavar labels them in the usage and help messages.

$ python summary.py 4 8 15 16 23 42
count: 6
sum: 108.0
mean: 18.00
$ python summary.py 4 8 15 16 23 42 -b 10 20
count: 2
sum: 31.0
mean: 15.50
$ python summary.py -h
usage: summary.py [-h] [-b LOW HIGH] values [values ...]

Summarizes numbers.

positional arguments:
  values

options:
  -h, --help            show this help message and exit
  -b, --between LOW HIGH
                        use only values in the range

Boolean options

The BooleanOptionalAction creates a pair of options that switch a setting on and off.

table.py
import argparse

rows = [('Bratislava', 475503), ('Kosice', 229040), ('Presov', 84824)]

parser = argparse.ArgumentParser(description='Prints a table of cities.')
parser.add_argument('--header', action=argparse.BooleanOptionalAction,
                    default=True, help='print the header line')
parser.add_argument('--limit', type=int, metavar='N', dest='max_rows',
                    help='print at most N rows')
args = parser.parse_args()

if args.header:
    print(f'{"City":<12}{"Population":>12}')

for city, population in rows[:args.max_rows]:
    print(f'{city:<12}{population:>12}')

The --header option sets args.header to True and --no-header sets it to False; the default is True. The --limit option shows two more settings: metavar names the value in the help text and dest sets the attribute name. When the limit is not given, args.max_rows is None and the slice returns all rows.

$ python table.py --limit 2
City          Population
Bratislava        475503
Kosice            229040
$ python table.py --no-header
Bratislava        475503
Kosice            229040
Presov             84824
$ python table.py -h
usage: table.py [-h] [--header | --no-header] [--limit N]

Prints a table of cities.

options:
  -h, --help            show this help message and exit
  --header, --no-header
                        print the header line
  --limit N             print at most N rows

Mutually exclusive options

Some options make no sense together. A mutually exclusive group allows at most one of its options on the command line.

copier.py
import argparse

parser = argparse.ArgumentParser(description='Copies files.')
parser.add_argument('files', nargs='*')

group = parser.add_mutually_exclusive_group()
group.add_argument('-q', '--quiet', action='store_true')
group.add_argument('-v', '--verbose', action='store_true')

args = parser.parse_args()

if args.verbose:
    for name in args.files:
        print(f'copying {name}')

if not args.quiet:
    print(f'{len(args.files)} files copied')

The group is created with add_mutually_exclusive_group and the options are added to the group instead of the parser. The usage line shows them separated by a vertical bar. Passing required=True to the group would require exactly one of them.

$ python copier.py a.txt b.txt
2 files copied
$ python copier.py -v a.txt b.txt
copying a.txt
copying b.txt
2 files copied
$ python copier.py -q -v a.txt
usage: copier.py [-h] [-q | -v] [files ...]
copier.py: error: argument -v/--verbose: not allowed with argument -q/--quiet

Custom types

The type option accepts any function that takes a string. To reject a value with our own message, the function raises ArgumentTypeError.

plan.py
import argparse
from datetime import date, timedelta


def positive(text):
    value = int(text)
    if value <= 0:
        raise argparse.ArgumentTypeError(f'{value} is not a positive number')
    return value


parser = argparse.ArgumentParser(description='Plans regular meetings.')
parser.add_argument('start', type=date.fromisoformat, help='YYYY-MM-DD')
parser.add_argument('-e', '--every', type=positive, default=7, metavar='DAYS')
parser.add_argument('-c', '--count', type=positive, default=4)
args = parser.parse_args()

for i in range(args.count):
    day = args.start + timedelta(days=i * args.every)
    print(day.strftime('%a %d %b %Y'))

The program prints the dates of regular meetings. The start date is converted with the date.fromisoformat method. A ValueError raised by a type function produces a generic message with the function name, while the message of an ArgumentTypeError is printed as it is.

$ python plan.py 2026-12-01
Tue 01 Dec 2026
Tue 08 Dec 2026
Tue 15 Dec 2026
Tue 22 Dec 2026
$ python plan.py 2026-12-01 --every 14 -c 3
Tue 01 Dec 2026
Tue 15 Dec 2026
Tue 29 Dec 2026
$ python plan.py 2026-02-30
usage: plan.py [-h] [-e DAYS] [-c COUNT] start
plan.py: error: argument start: invalid fromisoformat value: '2026-02-30'
$ python plan.py 2026-12-01 -e 0
usage: plan.py [-h] [-e DAYS] [-c COUNT] start
plan.py: error: argument -e/--every: 0 is not a positive number

Files

File names are best converted to pathlib.Path objects. The argparse.FileType type, which opened files during parsing, is deprecated since Python 3.14.

head.py
import argparse
from pathlib import Path

parser = argparse.ArgumentParser(description='Prints the first lines of files.')
parser.add_argument('files', type=Path, nargs='+', metavar='FILE')
parser.add_argument('-n', '--lines', type=int, default=3)
args = parser.parse_args()

for path in args.files:
    if not path.is_file():
        parser.error(f'{path}: no such file')

for path in args.files:
    print(f'==> {path} <==')
    with path.open() as f:
        for i, line in enumerate(f):
            if i == args.lines:
                break
            print(line, end='')

The program prints the first lines of the given files, like the Unix head command. The parser.error method reports a problem found after parsing in the same way as argparse's own errors: it prints the usage and the message and exits with status 2. The files are checked first so that nothing is printed when one of them is missing.

$ python head.py cities.txt rivers.txt -n 2
==> cities.txt <==
Bratislava
Kosice
==> rivers.txt <==
Danube
Vah
$ python head.py cities.txt lakes.txt
usage: head.py [-h] [-n LINES] FILE [FILE ...]
head.py: error: lakes.txt: no such file

Subcommands

Programs such as git or pip have subcommands, each with its own arguments. The add_subparsers method creates them.

temperature.py
import argparse


def to_fahrenheit(args):
    print(f'{args.degrees} °C = {args.degrees * 9 / 5 + 32:.1f} °F')


def to_celsius(args):
    print(f'{args.degrees} °F = {(args.degrees - 32) * 5 / 9:.1f} °C')


parser = argparse.ArgumentParser(description='Converts temperatures.')
commands = parser.add_subparsers(title='commands', required=True)

c2f = commands.add_parser('c2f', help='Celsius to Fahrenheit')
c2f.add_argument('degrees', type=float)
c2f.set_defaults(func=to_fahrenheit)

f2c = commands.add_parser('f2c', help='Fahrenheit to Celsius')
f2c.add_argument('degrees', type=float)
f2c.set_defaults(func=to_celsius)

args = parser.parse_args()
args.func(args)

Each add_parser call returns a new parser for one subcommand. The set_defaults method stores the function that handles the subcommand in the namespace, so the main code just calls args.func. With required=True, a missing subcommand is an error. A misspelled subcommand gets a suggestion, just like a wrong choice.

$ python temperature.py c2f 36.6
36.6 °C = 97.9 °F
$ python temperature.py f2c 451
451.0 °F = 232.8 °C
$ python temperature.py c2g 100
usage: temperature.py [-h] {c2f,f2c} ...
temperature.py: error: argument {c2f,f2c}: invalid choice: 'c2g', maybe you meant 'c2f'? (choose from 'c2f', 'f2c')
$ python temperature.py -h
usage: temperature.py [-h] {c2f,f2c} ...

Converts temperatures.

options:
  -h, --help  show this help message and exit

commands:
  {c2f,f2c}
    c2f       Celsius to Fahrenheit
    f2c       Fahrenheit to Celsius

Source

Python argparse documentation

Argparse tutorial

In this article we have parsed command line arguments with argparse: positional arguments and options, help messages, types, choices, the number of values, actions, mutually exclusive groups, custom types, files, and subcommands. See also Python sys module, Python click tutorial, and Python Fire.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.