Python argparse tutorial

Python argparse tutorial shows how to use the argparse module to parse command-line arguments in Python.

Python’s argparse

The argparse module makes it easy to write user-friendly command-line interfaces. It parses the arguments defined in sys.argv.

argparse also automatically generates help and usage messages and issues errors when the user provides invalid arguments to the program.

argparse is a standard module; we don’t need to install it.

Create a parser using ArgumentParser and add a new argument using add_argument(). Arguments can be optional, required, or positional.

Python argparse Optional Arguments

The following example creates a simple argument parser.

optional_arg.py

#!/usr/bin/env python

import argparse

# help flag provides flag help
# store_true actions stores argument as True

parser = argparse.ArgumentParser()

parser.add_argument('-o', '--output', action='store_true',
help="shows output")

args = parser.parse_args()

if args.output:
print("This is some output")

This example adds an argument with two options: the short -o and the long --ouput. These are optional arguments.

import argparse

The module has been imported.

parser.add_argument('-o', '--output', action='store_true',
help="shows output")

The argument is added by add_argument(). If set to store_true, the action will store the argument as True. The help option provides argument help.

args = parser.parse_args()

The arguments are parsed by parse_args(). The parsed arguments are stored as object attributes. In our example, there will be an args.output attribute.

if args.output:
print("This is some output")

If the argument exists, we will display some output.

$ optional_arg.py -o
This is some output
$ optional_arg.py --output
This is some output

We run the program using -o and --output.

$ optional_arg.py --help
usage: optional_arg.py [-h] [-o]

optional arguments:
-h, --help show this help message and exit
-o, --output shows output

We can display help for the program.

Python argparse Required Arguments

Using the required option requires an argument.

required_arg.py

#!/usr/bin/env python

import argparse

# required arg

parser = argparse.ArgumentParser()

parser.add_argument('--name', required=True)

args = parser.parse_args()

print(f'Hello {args.name}')

This example requires the name option; otherwise, it fails.

$ required_arg.py --name Peter
Hello Peter

$ required_arg.py
usage: required_arg.py [-h] --name NAME
required_arg.py: error: the following arguments are required: --name

Python argparse Positional Arguments

The following examples apply to positional arguments. They are created using add_argument().

positional_arg.py

#!/usr/bin/env python

import argparse

# positional args

parser = argparse.ArgumentParser()

parser.add_argument('name')
parser.add_argument('age')

args = parser.parse_args()

print(f'{args.name} is {args.age} years old')

This example requires two positional arguments: name and age.

parser.add_argument('name')
parser.add_argument('age')

Positional arguments are created without the dash prefix character.

$ positional_arg.py Peter 23
Peter is 23 years old

This is example output.

Python argparse Destination

add_argument()‘s dest option specifies a name for the argument. If not given, it is inferred from the options.

dest.py

#!/usr/bin/env python

import argparse
import datetime

# dest gives a different name to a flag

parser = argparse.ArgumentParser()

parser.add_argument('-n', dest='now', action='store_true', help="shows now")

args = parser.parse_args()

# we can refer to the flag
# by a new name
if args.now:

    now = datetime.datetime.now()
    print(f"Now: {now}")

The program assigns the now name to the -n parameter.

$ dest.py -n
Now: 2019-03-22 17:37:40.406571

Python argparse Types

type parameter determines the argument type.

rand_int.py

#!/usr/bin/env python

import argparse
import random

# type determines the type of the argument

parser = argparse.ArgumentParser()

parser.add_argument('-n', type=int, required=True,
    help="define the number of random integers")
args = parser.parse_args()

n = args.n

for i in range(n):
    print(random.randint(-100, 100))

The program displays n random integers from -100 to 100.

parser.add_argument('-n', type=int, required=True,
help="define the number of random integers")

-n option requires an integer value and is required.

$ rand_int.py -n 3
92
-61
-61

Python argparse Defaults

Specifies a default value if the default option is not specified.

power.py

#!/usr/bin/env python

import argparse

# required defines a mandatory argument
# default defines a default value if not specified

parser = argparse.ArgumentParser()

parser.add_argument('-b', type=int, required=True, help="defines the base value")
parser.add_argument('-e', type=int, default=2, help="defines the exponent value")
args = parser.parse_args()

val = 1

base = args.b
exp = args.e

for i in range(exp):
val *= base

print(val)

This example calculates the exponent. An exponent value is not required; if not given, it defaults to 2.

$ power.py -b 3
9
$ power.py -b 3 -e 3
27

Python argparse metavar

metavar option names the expected value of an error and provides help output.

metavar.py

#!/usr/bin/env python

import argparse

# metavar gives name to the expected value
# in error and help outputs

parser = argparse.ArgumentParser()

parser.add_argument('-v', type=int, required=True, metavar='value',
    help="computes cube for the given value")
args = parser.parse_args()

print(args)

val = args.v

print(val * val * val)

This example names the expected value value. The default name is V.

$ metavar.py -h
usage: metavar.py [-h] -v value

optional arguments:
-h, --help show this help message and exit
-v value computes cube for the given value

The given name is displayed in the help output.

Python argparse Append Operation

append operation allows grouping of repeated options.

appending.py

#!/usr/bin/env python

import argparse

# append action allows for group repeating
# options

parser = argparse.ArgumentParser()

parser.add_argument('-n', '--name', dest='names', action='append',
help="provides names to greet")

args = parser.parse_args()

names = args.names

for name in names:
print(f'Hello {name}!')

This example generates a greeting and specifies all names using the n or name options. These can be repeated multiple times.

$ appending.py -n Peter -n Lucy --name Jane
Hello Peter!
Hello Lucy!
Hello Jane!

Python’s argparse nargs

nargs specifies the number of command-line arguments to use.

charseq.py

#!/usr/bin/env python

import argparse
importsys

# nargs sets the required number of argument values
# metavar gives name to argument values in error and help output

parser = argparse.ArgumentParser()
parser.add_argument('chars', type=str, nargs=2, metavar='c',
                    help='starting and ending character')

args = parser.parse_args()

try:
    v1 = ord(args.chars[0])
    v2 = ord(args.chars[1])

except TypeError as e:

    print('Error: arguments must be characters')
    parser.print_help()
    sys.exit(1)

if v1 > v2: print('first letter must precede the second in alphabet')
parser.print_help()
sys.exit(1)

This example displays the sequence of characters from character one to character two. It requires two arguments.

parser.add_argument('chars', type=str, nargs=2, metavar='c',
help='starting and ending character')

Using nargs=2, we specify that two arguments are expected.

$ charseq.py e k
e f g h i j k

The program displays the sequence of characters from e to k.

A variable number of arguments can be specified using the * character.

var_args.py

#!/usr/bin/env python

import argparse

# * nargs expects 0 or more arguments

parser = argparse.ArgumentParser()
parser.add_argument('num', type=int, nargs='*')
args = parser.parse_args()

print(f"The sum of values is {sum(args.num)}")

This example calculates the sum of values. We can specify a variable number of arguments to a program.

$ var_args.py 1 2 3 4 5
The sum of values is 15

Python argparse Choices

choices option restricts the arguments to a given list.

mytime.py

#!/usr/bin/env python

import argparse
import datetime
import time

# choices limits argument values to the
# given list

parser = argparse.ArgumentParser()

parser.add_argument('--now', dest='format', choices=['std', 'iso', 'unix', 'tz'],
                    help="shows datetime in given format")

args = parser.parse_args()
fmt = args.format

if fmt == 'std':
    print(datetime.date.today())
elif fmt == 'iso':
    print(datetime.datetime.now().isoformat())
elif fmt == 'unix': print(time.time())
elif fmt == 'tz':
print(datetime.datetime.now(datetime.timezone.utc))

In the example, the now option can accept the following values: std, iso, unix, or tz.

$ mytime.py --now iso
2019-03-27T11:34:54.106643

$ mytime.py --now unix
1553682898.422863

Header Example

The following example mimics the Linux head command. It displays n lines of text at the beginning of a file.

words.txt

sky
top
forest
wood
lake
wood

For our example, we have this small test file.

head.py

#!/usr/bin/env python

import argparse
from pathlib import Path

# head command
# Working with positional arguments

parser = argparse.ArgumentParser()

parser.add_argument('f', type=str, help='file name')
parser.add_argument('n', type=int, help='show n lines from the top')

args = parser.parse_args()

filename = args.f

lines = Path(filename).read_text().splitlines()

for line in lines[:args.n]:
print(line)

This example has two options: f for the file name and -n for the number of lines to display.

$ head.py words.txt 3
sky
top
forest

This is a Python argparse tutorial. You may also be interested in the Python pathlib tutorial and the Python tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *