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:
-c (compare) takes 2 parameter.
-v (verify) takes 1 parameter.
Either of these two must be present, but not both.
- -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()