Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code argparse combinational options in python

Tags:

I have been troubled with this small piece of activity to be completed. I did do some experiment, but was not able to achieve the result.

Requirement:

   test2.py [-c/-v] -f 

Usage or Rules:

  1. -c (compare) takes 2 parameter.

    -v (verify) takes 1 parameter.

    Either of these two must be present, but not both.

  2. -f is a mandatory parameter (output file name).

Output:

I am able to get the desired output as shown below

kp@kp:~/Study/scripts$ ./test.py -c P1 P2 -f p kp@kp:~/Study/scripts$ ./test.py -v P1 -f p kp@kp:~/Study/scripts$ ./test.py -v P1  usage: test.py <functional argument> <ouput target argument> test.py: error: argument -f/--file is required kp@kp:~/Study/scripts$ ./test.py -c P1 P2  usage: test.py <functional argument> <ouput target argument> test.py: error: argument -f/--file is required kp@kp:~/Study/scripts$  

Problem is:

When you use, test.py -h,
1. The output will not indicate that -c/-v either of them is mandatory but not both . It indicates all the arguments are optional.
2. The output will indicate -f option under optional arguments which is incorrect. -f is mandatory argument, and I want to display outside - optional arguments.

How to change the script so that -h option output will be more user friendly (without any external validation)

usage: test.py <functional argument> <ouput target argument>  Package Compare/Verifier tool.  optional arguments:   -h, --help            show this help message and exit   -f outFileName, --file outFileName                         File Name where result is stored.   -c Package1 Package2, --compare Package1 Package2                         Compare two packages.   -v Package, --verify Package                         Verify Content of package. kiran@kiran-laptop:~/Study/scripts$  

Code:

I am using the below code to achieve the output,

#!/usr/bin/python  import sys import argparse  def main():     usage='%(prog)s <functional argument> <ouput target argument>'     description='Package Compare/Verifier tool.'     parser = argparse.ArgumentParser(usage=usage,description=description)      parser.add_argument('-f','--file',action='store',nargs=1,dest='outFileName',help='File Name where result is stored.',metavar="outFileName",required=True)       group = parser.add_mutually_exclusive_group(required=True)     group.add_argument('-c','--compare',action='store',nargs=2,dest='packageInfo',help='Compare two packages.',metavar=("Package1","Package2"))     group.add_argument('-v','--verify',action='store',nargs=1,dest='packageName',help='Verify Content of package.',metavar='Package')     args = parser.parse_args()  if __name__ == "__main__":     main() 
like image 856
kumar_m_kiran Avatar asked Apr 09 '11 06:04

kumar_m_kiran


People also ask

How do you make Argparse optional?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How does Argparse work in Python?

Python argparse It parses the defined arguments from the sys. argv . The argparse module also automatically generates help and usage messages, and issues errors when users give the program invalid arguments. The argparse is a standard module; we do not need to install it.


1 Answers

Set the filename to be a positional argument, and let argparse set its own usage message:

$ python so.py --help usage: so.py [-h] [-c Package1 Package2 | -v Package] outFileName 

The filename should be positional, and you should let argparse write its own usage message.

Code

#!/usr/bin/python  import sys import argparse  def main():     description='Package Compare/Verifier tool.'     parser = argparse.ArgumentParser(description=description,                                      epilog='--compare and --verify are mutually exclusive')      parser.add_argument('f',action='store',nargs=1,                         help='File Name where result is stored.',                         metavar="outFileName")      group = parser.add_mutually_exclusive_group(required=False)     group.add_argument('-c','--compare',action='store',nargs=2,dest='packageInfo',help='Compare two packages.',metavar=("Package1","Package2"))     group.add_argument('-v','--verify',action='store',nargs=1,dest='packageName',help='Verify Content of package.',metavar='Package')      args = parser.parse_args()  if __name__ == "__main__":     main() 

Help message

$ python so.py --help usage: so.py [-h] [-c Package1 Package2 | -v Package] outFileName  Package Compare/Verifier tool.  positional arguments:   outFileName           File Name where result is stored.  optional arguments:   -h, --help            show this help message and exit   -c Package1 Package2, --compare Package1 Package2                         Compare two packages.   -v Package, --verify Package                         Verify Content of package.  --compare and --verify are mutually exclusive 
like image 157
Adam Matan Avatar answered Oct 04 '22 12:10

Adam Matan