Python argparse:有没有办法在 nargs 中指定范围?

发布于 2024-10-02 08:03:22 字数 327 浏览 0 评论 0原文

我有一个可选参数,它支持参数列表本身。

我的意思是,它应该支持:

  • -f 1 2
  • -f 1 2 3

但不支持:

  • -f 1
  • -f 1 2 3 4

有没有办法在 argparse 中强制执行此操作?现在我使用 nargs="*",然后检查列表长度。

编辑:根据要求,我需要的是能够定义一系列可接受的参数数量。我的意思是,(在示例中)2 或 3 个参数是正确的,但 1 或 4 或任何不在 2..3 范围内的参数是正确的

I have an optional argument that supports a list of arguments itself.

I mean, it should support:

  • -f 1 2
  • -f 1 2 3

but not:

  • -f 1
  • -f 1 2 3 4

Is there a way to force this within argparse ? Now I'm using nargs="*", and then checking the list length.

Edit: As requested, what I needed is being able to define a range of acceptable number of arguments. I mean, saying (in the example) 2 or 3 args is right, but not 1 or 4 or anything that's not inside the range 2..3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜司空 2024-10-09 08:03:22

您可以使用自定义操作来执行此操作:

import argparse

def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                    f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength

parser=argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', nargs='+', action=required_length(2,3))

args=parser.parse_args('-f 1 2 3'.split())
print(args.f)
# ['1', '2', '3']

try:
    args=parser.parse_args('-f 1 2 3 4'.split())
    print(args)
except argparse.ArgumentTypeError as err:
    print(err)
# argument "f" requires between 2 and 3 arguments

You could do this with a custom action:

import argparse

def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                    f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength

parser=argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', nargs='+', action=required_length(2,3))

args=parser.parse_args('-f 1 2 3'.split())
print(args.f)
# ['1', '2', '3']

try:
    args=parser.parse_args('-f 1 2 3 4'.split())
    print(args)
except argparse.ArgumentTypeError as err:
    print(err)
# argument "f" requires between 2 and 3 arguments
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文