如何验证传递的参数总数?(How do I validate the total number of passed arguments?)

编程入门 行业动态 更新时间:2024-10-14 20:18:26
如何验证传递的参数总数?(How do I validate the total number of passed arguments?)

使用argparse ,我需要确保用户输入两个字符串。 但是,它们有两种可能的选项来输入字符串,例如选项-a和-b 。 他们应该能够做以下任何事情:

python runscript.py -a str1 str2 python runscript.py -a str1 -b str2 python runscript.py -b str1 str2

关键是必须只有两个输入,但它们可以用于任何可用的选项。

我的尝试基本上设置了这样的论点

parser.add_argument('-a', nargs='*') parser.add_argument('-b', nargs='*')

然后我必须这样做:

if (args.a): num_a = len(args.a) # I need to check if the -a option was even used else: num_a = 0 if (args.b): num_b = len(args.b) # same as above but for -b option else: num_b = 0 # Check that number of arguments is correct if (num_a + num_b) != 2: <error code>

这似乎有点无关紧要。 有更多的Pythonic方式吗?

While using argparse, I need to make sure the user inputs two strings. However, there are two possible options for them to input the strings in, e.g. options -a and -b. They should be able to do any of the following:

python runscript.py -a str1 str2 python runscript.py -a str1 -b str2 python runscript.py -b str1 str2

The key is there must be only two inputs but that they can be for any of the options available.

My attempt basically sets the arguments like this

parser.add_argument('-a', nargs='*') parser.add_argument('-b', nargs='*')

Then I have to do this:

if (args.a): num_a = len(args.a) # I need to check if the -a option was even used else: num_a = 0 if (args.b): num_b = len(args.b) # same as above but for -b option else: num_b = 0 # Check that number of arguments is correct if (num_a + num_b) != 2: <error code>

This seems a little extraneous. Is there a more Pythonic way of doing this?

最满意答案

为两个参数提供默认的列表值:

parser.add_argument('-a', nargs='*', default=[]) parser.add_argument('-b', nargs='*', default=[])

现在,值始终是一个列表,简化了错误检查:

if len(args.a) + len(args.b) != 2: parser.error('....')

Give both arguments a default empty list value:

parser.add_argument('-a', nargs='*', default=[]) parser.add_argument('-b', nargs='*', default=[])

Now the value is always going to be a list, simplifying your error check:

if len(args.a) + len(args.b) != 2: parser.error('....')

更多推荐

本文发布于:2023-08-07 16:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465377.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总数   参数   validate   total   passed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!