I have a program which can be used in the following way:
program install -a arg -b arg
program list
program update
There can only ever be one of the positional arguments specified (install, list or update). And there can only be other arguments in the install scenario.
The argparse documentation is a little dense and I'm having a hard time figuring out how to do this correctly. What should my add_arguments look like?
asked May 20, 2013 at 1:55
user623990
1 Answer 1
This seems like you want to use subparsers.
from argparse import ArgumentParser
parser = ArgumentParser()
subparsers = parser.add_subparsers()
install = subparsers.add_parser('install')
install.add_argument('-b')
install.add_argument('-a')
install.set_defaults(subparser='install')
lst = subparsers.add_parser('list')
lst.set_defaults(subparser='list')
update = subparsers.add_parser('update')
update.set_defaults(subparser='update')
print parser.parse_args()
As stated in the docs, I have combined with set_defaults so that you can know which subparser was invoked.
answered May 20, 2013 at 2:00
mgilson
312k70 gold badges656 silver badges722 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
mgilson
@MaxMackie -- That's there the
set_default comes in.Good Person
@n0pe [and mgilson] use subparsers = parser.add_subparsers(dest="cmd") instead of set_default.
|
lang-py
argparsedocumentation is something I struggle with nearly every time I go to do something non-trivial with it.argparsedoc is very good, and if you want to master the commandline in python. I think you need to read it. Recently I write some nagios plugins in python, and the argparse is very important. So I have read the doc some times, it was really very good.