Python argparse, positional arguments and subparsers -
this question has answer here:
i have following snippet using argparse multiple subparsers
parser = argparse.argumentparser(description = "setup db", add_help=false) parser.add_argument('action', type = str, choices=['drop','populate','print','create','print-metadata'], = "specify action", default = none) subparsers = parser.add_subparsers() drop_parser = subparsers.add_parser('drop',parents=[parser]) drop_parser.add_argument('-dataset-name', required=true, type = str, = "dataset name", default = none) ..... args = parser.parse_args() .....
when go run following:
python .\populatedb.py drop -dataset-name foo populatedb.py: error: invalid choice: 'foo' (choose 'drop', 'populate', 'print', 'create', 'print-metadata')
i wondering code above going wrong. note "action" argument positional argument.
thank in advance. first use of subparsers making obvious mistake.
thank in advance.
regards,
ranga
the accepted thing here not have argument subparser -- it's own argument provided argparse
:
parser = argparse.argumentparser(description = "setup db", add_help=false) subparsers = parser.add_subparsers() drop_parser = subparsers.add_parser('drop',parents=[parser]) drop_parser.add_argument('-dataset-name', required=true, type = str, = "dataset name", default = none) ..... args = parser.parse_args()
now don't know parser selected don't worry, there's built-in mechanism well. 1 common use-case having 1 function should invoked each subparser...
parser = argparse.argumentparser(description = "setup db", add_help=false) subparsers = parser.add_subparsers() def drop_parser_handler(args): ... drop_parser = subparsers.add_parser('drop',parents=[parser]) drop_parser.add_argument('-dataset-name', required=true, type = str, = "dataset name", default = none) drop_parser.set_defaults(func=drop_parser_handler) ..... args = parser.parse_args() args.func(args)
of course don't need complex -- set constant value:
drop_parser.set_defaults(subparser_name='drop')
Comments
Post a Comment