我想使用argparse并使用它,所以提供的参数数量决定了哪个子例程被执行。
例如,在下面的脚本中,我希望argparse能够执行以下操作:
dmsconvert.py 12.5
>>> (12, 30, 0)
dmsconvert.py 12 30 0.0
>>> 12.5
相反,我能用argparse执行此操作的唯一方法是有一个明确的选项,即:
dmsconvert.py 12.5
>>> (12, 30, 0)
dmsconvert.py -a 12 30 0.0
>>> 12.5
有人能建议一种方法来使用argparse来实现我的首选方法吗? 注意:我希望自动生成的argparse帮助文本看起来很合理。
完整代码示例:
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'])
答案 0 :(得分:1)
可以使用自定义操作完成:
import argparse
class OneOrThree(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if len(values) == 1:
setattr(namespace, self.dest, values)
setattr(namespace, 'result', decimal_to_dms(*values))
elif len(values) == 3:
setattr(namespace, self.dest, values)
setattr(namespace, 'result', dms_to_decimal(*values))
else:
raise parser.error('Expected 1 or 3 arguments')
def dms_to_decimal(deg,minute,sec):
assert float(minute) < 60.0, 'Mintue value: %s must be less than 60' % float(minute)
assert float(sec) < 60.0, 'Second value: %s must be less than 60' % float(sec)
return float(deg)+float(minute)/60.0+float(sec)/(60.0*60.0)
def decimal_to_dms(deg):
minute = 60.0*(deg-int(deg))
sec = 60.0*(minute-int(minute))
return int(deg),int(minute),sec
parser = argparse.ArgumentParser(
usage='%(prog)s deg [minute, sec]',)
parser.add_argument('dms_args', nargs='+',
type=float,
action=OneOrThree,
metavar='deg [minute, sec]',
help='Given one arg, returns dms. Given three args, returns deg')
args = parser.parse_args()
print(args.result)
运行上述操作会产生如下行为:
% test.py 12.5
(12, 30, 0.0)
% test.py 12 30 0.0
12.5
如果提供的参数数量不正确,则会引发错误:
% test.py 12 30
usage: test.py [-h] dms_args [dms_args ...]
test.py: error: Expected 1 or 3 arguments
帮助信息如下所示:
% test.py -h
usage: test.py deg [minute, sec]
positional arguments:
deg [minute, sec] Given one arg, returns dms. Given three args, returns deg
optional arguments:
-h, --help show this help message and exit