Skip to content

Python - Argparse

Description

The argparse module makes it easier to manage the arguments of a python script.

Module is native to python.

Use

See an example of basic usage:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo', help='foo help')
args = parser.parse_args()
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help      show this help message and exit
 -f, --foo FOO   foo help

By default the option -h/--help is added and allows to list the available options for the script.

Examples

# reclaim_vmax.py

parser = argparse.ArgumentParser()

parser.add_argument('-d', '--debug', action="store_true", help='Debug Mode')
parser.add_argument('-b', '--bay', help='Symmetrix Array', required=True)

dev_group = parser.add_mutually_exclusive_group(required=True)
dev_group.add_argument('-l', '--lun', help='Lun List')
dev_group.add_argument('-s', '--sgroup', help='S.Group List')

args = parser.parse_args()

sid = args.bay
debug_mode = args.debug
# ./reclaim_vmax.py
usage: reclaim_vmax.py [-h] [-d] -b BAY (-l LUN | -s SGROUP)
reclaim_vmax.py: error: argument -b/--bay is required

# ./reclaim_vmax.py -h
usage: reclaim_vmax.py [-h] [-d] -b BAY (-l LUN | -s SGROUP)

optional arguments:
  -h, --help            show this help message and exit
  -d, --debug           Debug Mode
  -b BAY, --bay BAY     Symmetrix Array
  -l LUN, --lun LUN     Lun List
  -s SGROUP, --sgroup SGROUP
                        S.Group List
Back to top