How to use the subcommand using argparse module of python

I am writing a application_backup.py and would like to have two sub commands as 'backup' and 'restore'. with associated option. e.g.

application_backup.py backup -e prod -r east
application_backup.py restore -e prod -m 1.txt -d 2.txt

Open in new window


Appreciate if someone can help with how to get the above done using the argparse module ( https://docs.python.org/2/library/argparse.html#sub-commands ). Any sample code is very much appreciated
beer9Asked:
Who is Participating?
 
Walter RitzelSenior Software EngineerCommented:
Here it goes.
import argparse
parser = argparse.ArgumentParser(prog='PROG')
subparsers = parser.add_subparsers(help='sub-command help')
parser_a = subparsers.add_parser('backup', help='backup help')
parser_a.add_argument('-e', help='e help')
parser_a.add_argument('-r', help='r help')

parser_b = subparsers.add_parser('restore', help='restore help')
parser_b.add_argument('-e', help='e help')
parser_b.add_argument('-m', help='m help')
parser_b.add_argument('-d', help='d help')

# parse some argument lists
print parser.parse_args(['restore', '-e','prod'])

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.