arguments - Use Python Argparse with several subparsers -


hi trying configure argparse several subparsers accepting specific long arguments. here below code

import argparse  parser = argparse.argumentparser(prog='program', description='prog description') subparsers = parser.add_subparsers(help='choices') parser.add_argument('--choice', '-c', choices=['a', 'apple', 'b', 'banana', 'l', 'lemmon', 'p', 'papaya'], type=str, help='menu choices', required=true) a_parser = subparsers.add_parser("a") b_parser = subparsers.add_parser("b") l_parser = subparsers.add_parser("l") p_parser = subparsers.add_parser("p")  a_parser.add_argument("--peel") b_parser.add_argument("--peel") l_parser.add_argument("--lamount") p_parser.add_argument("--pamount",required=true,type=str) 

but failing @ following points.

  • subparsers should accept both short form , long forms. ex. prog -c a , prog -c apple both legal , same
  • argumens subparsers not required except --pamount. code seem expecting them getting following error when running valid mode python prog -c a

    usage: program [-h] --choice {a,apple,b,banana,l,lemmon,p,papaya} {a,p,b,l} ... program: error: few arguments

i glad if provide me guidelines resolve problems. thank you!

by using subparsers don't need --choice optional.

subparsers = parser.add_subparsers(dest='choice', help='choices') # parser.add_argument('--choice', '-c', choices=['a', 'apple', 'b', 'b ... 

specify dest define slot in args subparser name (see docs).

when use 'python prog -c a', parses a argument -c; still expects string a argument subparsers (which in effect positional argument). hence error. (in other words, it's not expecting --peel argument; hasn't gotten far in parsing.)

python prog python prog --peel 3 

should work.

python prog p --pamount 1 

should work (the --pamount required).

to accept both 'a' , 'apple' subparser names use aliases parameter (see docs add_parser).

a_parser = subparsers.add_parser("a", aliases=['apple','apples','manzana']) 

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -