Subcommands with Argument Parsing in Python

An example how subcommands can be used with argparse module:

import argparse
import sys

parser = argparse.ArgumentParser()
# Global options
parser.add_argument(
    "-c", "--config-file",
    help="specify the configuration file to read (default: argtest.cfg)",
    default="argtest.cfg",
)
subparsers = parser.add_subparsers(dest="command")
# Command: update-device
parser_update_device = subparsers.add_parser(
    "update-device",
    help="update device data",
)
parser_update_device.add_argument(
    "-I", "--ip",
    help="device IP address",
    required=True,
)
parser_update_device.add_argument(
    "-S", "--site-name",
    help="new site name",
)
# Command: add-vlan
parser_add_vlan = subparsers.add_parser(
    "add-vlan",
    help="add a VLAN",
)
parser_add_vlan.add_argument(
    "--vlan-id",
    help="new VLAN ID",
    required=True,
)
args = parser.parse_args()
if not args.command:
    parser.parse_args(["--help"])
    sys.exit(0)

# Do the stuff here
print(args)

Sample output:

markku@btest:~/temp$ python3 argtest.py
usage: argtest.py [-h] [-c CONFIG_FILE] {update-device,add-vlan} ...

positional arguments:
  {update-device,add-vlan}
    update-device       update device data
    add-vlan            add a VLAN

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG_FILE, --config-file CONFIG_FILE
                        specify the configuration file to read (default:
                        argtest.cfg)
markku@btest:~/temp$ python3 argtest.py invalid-command
usage: argtest.py [-h] [-c CONFIG_FILE] {update-device,add-vlan} ...
argtest.py: error: argument command: invalid choice: 'invalid-command' (choose from 'update-device', 'add-vlan')
markku@btest:~/temp$ python3 argtest.py update-device
usage: argtest.py update-device [-h] -I IP [-S SITE_NAME]
argtest.py update-device: error: the following arguments are required: -I/--ip
markku@btest:~/temp$ python3 argtest.py update-device -h
usage: argtest.py update-device [-h] -I IP [-S SITE_NAME]

optional arguments:
  -h, --help            show this help message and exit
  -I IP, --ip IP        device IP address
  -S SITE_NAME, --site-name SITE_NAME
                        new site name
markku@btest:~/temp$ python3 argtest.py update-device -I x.x.x.x
Namespace(command='update-device', config_file='argtest.cfg', ip='x.x.x.x', site_name=None)
markku@btest:~/temp$

Reference: https://docs.python.org/3/library/argparse.html

Updated: May 22, 2020 — 15:32

Leave a Reply