python - Nested options with argparse -
i'd have python script take variable number of arguments depending on particular choice. example:
python run.py foo
python run.py bar x y
where choosing option bar
requires 2 additional arguments, integer inputs, foo
requires no additional arguments.
import argparse argparser = argparse.argumentparser() # allow user choose test run argparser.add_argument("test", choices=['foo', 'bar'], help="you may choose foo or bar.") ...
but how can specify additional arguments required bar
? p.s. i'm working python 2.7, if solution requires python 3, won't in case.
you should use subparsers:
import argparse parser = argparse.argumentparser() subparsers = parser.add_subparsers(title='subcommands') parser_foo = subparsers.add_parser('foo') parser_foo.set_defaults(target='foo') parser_bar = subparsers.add_parser('bar') parser_bar.add_argument('more') parser_bar.set_defaults(target='bar')
usage:
>>> parser.parse_args(['foo']) namespace(target='foo') >>> parser.parse_args(['bar', '123']) namespace(target='bar', more='123')
note set target
e.g. function , call directly. here's sample code (extracted cactus' cli, that's rather common pattern):
parser = argparse.argumentparser() subparsers = parser.add_subparsers(title = 'subcommands') parser_create = subparsers.add_parser('create') parser_create.add_argument('path') parser_create.add_argument('-s', '--skeleton') parser_create.set_defaults(target=create) parser_build = subparsers.add_parser('build') parser_build.set_defaults(target = build) args = parser.parse_args() args.target(**{k: v k, v in vars(args).items() if k != 'target'})
Comments
Post a Comment