Python argparser for multiple arguments for partial selection

I create argparser as follows:

parser = argparse.ArgumentParser(description='someDesc') parser.add_argument(-a,required=true,choices=[x,y,z]) parser.add_argument( ... ) 

However, only to select "x", and not to select "y, z", I want to have the additional REQUIRED argument. For instance,

 python test -ax // not fine...needs additional MANDATORY argument b python test -ay // fine...will run python test -az // fine...will run python test -ax -b "ccc" // fine...will run 

How can I do this using ArgumentParser? I know this is possible with bash optparser

+4
source share
2 answers

To clarify the approach of the subparameter:

 sp = parser.add_subparsers(dest='a') x = sp.add_parser('x') y=sp.add_parser('y') z=sp.add_parser('z') x.add_argument('-b', required=True) 
  • this differs from your specification in that -a is not required. Argument
  • dest='a' ensures that the attribute 'a' is in the namespace.
  • usually the optional parameter '-b' is not required. Subparser 'x' can also take the required position.

If you must use the -a optional option, two-step parsing may work

 p1 = argparse.ArgumentParser() p1.add_argument('-a',choices=['x','y','z']) p2 = argparse.ArgumentParser() p2.add_argument('-b',required=True) ns, rest = p1.parse_known_args() if ns.a == 'x': p2.parse_args(rest, ns) 

The third approach is to do your own test after the fact. You can still use argparse error mechanism

 parser.error('-b required with -a x') 
+3
source

ArgumentParser supports the creation of such subcommands using add_subparsers (). Typically, the add_subparsers () method is called without arguments and returns a special action object. This object has a single method, add_parser (), which takes the command name and any arguments of the ArgumentParser constructor, and returns an ArgumentParser object, which can be changed as usual.

 ArgumentParser.add_subparsers() 
+1
source

Source: https://habr.com/ru/post/1494017/


All Articles