Below is an example code that uses argparse
import os
import numpy
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-C','--Chk',type=str, help='Choose arg')
parser.add_argument('-R','--ReC',type=str, help='Choose arg')
args = vars(parser.parse_args())
if args['Chk'] == 'compo1':
print('This is comp1')
elif args['Chk'] == 'compo2':
print('This is comp2')
else:
print('The specified comp does not exist')
if args['ReC'] == 'recompo':
print('This is second test')
else:
print('The specified second_T does not exist')
if __name__=='__main__':
main()
The above code works fine. Since both are optional arguments, I would like to have two features:
- If invalid arguments are given, for
-Cor-RI would like to print/raise a message. I tried usingraise argparse.ArgumentTypeError, see below.
if len(args) > 8 or len(args) < 3:
raise argparse.ArgumentTypeError('Print this error message')
return
- Secondly, I would like to have situations where the code should not do anything if either of
-Cor-Rare not given. In the above code, if no arguments are given in either case, it printsThe specified comp does not existwhich is not ideal.
Any better way to do the above tasks ? Thanks
argsis adictwith 2 items. What's with thelentest?len(str)length as a criterion. It should belen(args['Chk'])choices. Thetypefunction can also be used to test for allowable values.