I want to use argparse and have it so the number of arguments supplied determines which subroutine is executed.
For example, in the script below, I would like argparse to be able to execute the following:
dmsconvert.py 12.5
>>> (12, 30, 0)
dmsconvert.py 12 30 0.0
>>> 12.5
Instead, the only way I have been able to do this with argparse is to have an explicit option, i.e:
dmsconvert.py 12.5
>>> (12, 30, 0)
dmsconvert.py -a 12 30 0.0
>>> 12.5
Can anyone suggest a way to achieve my preferred approach using argparse? Note: I want the auto-generated argparse help text to look sensible.
Full code example:
import argparse
import sys
def dms_to_decimal(deg,min,sec):
assert float(min) < 60.0, 'Mintue value: %s must be less than 60' % float(min)
assert float(sec) < 60.0, 'Second value: %s must be less than 60' % float(sec)
return float(deg)+float(min)/60.0+float(sec)/(60.0*60.0)
def decimal_to_dms(deg):
min = 60.0*(deg-int(deg))
sec = 60.0*(min-int(min))
return int(deg),int(min),sec
parser = argparse.ArgumentParser(description = 'Convert decimal degrees to dms and visa versa')
parser.add_argument('-a',dest='dms_args',nargs=3)
parser.add_argument(dest='dec_arg',type=float,nargs='?')
args = vars(parser.parse_args(sys.argv[1:]))
if args['dms_args'] is not None:
print dms_to_decimal(*args['dms_args'])
if args['dec_arg'] is not None:
print decimal_to_dms(args['dec_arg'])