Python argparse type and choice restrictions with nargs > 1

狂风中的少年 提交于 2019-11-29 11:39:57

问题


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?

This is some example code:

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

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.


回答1:


You can validate it with a custom action:

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)

For example,

% 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



回答2:


i suppose you could try this - in add_argument(), you can specify a limited set of inputs with choice='xyz' or choice=[this, that] as described here: http://docs.python.org/library/argparse.html#choices

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


来源:https://stackoverflow.com/questions/8624034/python-argparse-type-and-choice-restrictions-with-nargs-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!