How to use the subcommand using argparse module of python

I am writing a and would like to have two sub commands as 'backup' and 'restore'. with associated option. e.g. backup -e prod -r east 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 ( ). Any sample code is very much appreciated
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.