Python argparse 类型和选择限制与 nargs >1 [英] Python argparse type and choice restrictions with nargs > 1

查看:18
本文介绍了Python argparse 类型和选择限制与 nargs >1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎说明了一切.如果我的 nargs 大于 1,有什么方法可以对解析的单个 args 设置限制(例如选择/类型)?

The title pretty much says it all. If I have nargs greater than 1, is there any way I can set restrictions (such as choice/type) on the individual args parsed?

这是一些示例代码:

parser = argparse.ArgumentParser()
parser.add_argument('-c', '--credits', nargs=2,
    help='number of credits required for a subject')

对于 -c 参数,我需要指定一个主题以及需要多少学分.科目应限制在预定义的科目列表中,所需学分应为浮点数.

For the -c argument I need to specify a subject and how many credits are required. The subject should be limited to a predefined list of subjects, and the number of credits required should be a float.

我可能可以使用子解析器来做到这一点,但由于它已经是子命令的一部分,所以我真的不希望事情变得更复杂.

I could probably do this with a subparser, but as it is this is already part of a sub-command so I don't really want things to get any more complicated.

推荐答案

您可以使用 自定义操作:

import argparse
import collections


class ValidateCredits(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
        # print '{n} {v} {o}'.format(n=args, v=values, o=option_string)
        valid_subjects = ('foo', 'bar')
        subject, credits = values
        if subject not in valid_subjects:
            raise ValueError('invalid subject {s!r}'.format(s=subject))
        credits = float(credits)
        Credits = collections.namedtuple('Credits', 'subject required')
        setattr(args, self.dest, Credits(subject, credits))

parser = argparse.ArgumentParser()
parser.add_argument('-c', '--credits', nargs=2, action=ValidateCredits,
                    help='subject followed by number of credits required',
                    metavar=('SUBJECT', 'CREDITS')
                    )
args = parser.parse_args()
print(args)
print(args.credits.subject)
print(args.credits.required)

<小时>

例如

% test.py -c foo 2
Namespace(credits=Credits(subject='foo', required=2.0))
foo
2.0
% test.py -c baz 2
ValueError: invalid subject 'baz'
% test.py -c foo bar
ValueError: could not convert string to float: bar

这篇关于Python argparse 类型和选择限制与 nargs &gt;1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆