我如何告诉 argparse 只允许一个参数一次? [英] How do I tell argparse to allow an argument only once?

查看:37
本文介绍了我如何告诉 argparse 只允许一个参数一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何告诉 argparse 我只想允许一个命令行参数一次?

How do I tell argparse that I want to allow a command line argument only once?

import sys
import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    "--out",
    required=True,
)

parsed = parser.parse_args(sys.argv[1:])
print(f"out: {parsed.out}")

如果我这样调用这段代码:

If I call this code like this:

python3 argparsetest.py --out 1 --out 2 --out 3

打印

输出:3

但我宁愿错误地告诉用户 --out 参数只能使用一次.

But I would rather have it error out telling the user that the --out argument can only be used once.

我查看了 nargs 选项,但它表示应该为 --out 考虑多少以下参数,而不是我可以传递 - 的频率-out.

I looked at the nargs option, but that says how many following arguments should be considered for --out, not how often I can pass the --out.

required 选项强制用户提供参数(至少一次),但我正在寻找限制参数使用频率的上限,而不是较低.

There is the required option which forces the user to supply the argument (at least once), but I'm looking for limiting the upper number of how often the argument can be used, not the lower.

我见过 只有一个命令行参数与 argparse但这是从 2013 年开始的,我希望现在有更简单的方法来做到这一点.

I've seen Only one command line argument with argparse but this is from 2013 and I am hoping that there is an easier way to do this now.

如何限制命令行标志的使用次数?

How can I limit the number of uses of a command line flag?

推荐答案

跟进我的评论:

import sys
import argparse

# args = sys.argv[1:]

args = "--out 1 --out 2 --out 3".split()

print(f"Input args: {args}")


parser = argparse.ArgumentParser()
parser.add_argument(
    "--out",
    action="append",
    required=True,
)

parsed = vars(parser.parse_args(args))

for key, val in parsed.items():
    if isinstance(val, list):
        print(f"{key} specified {len(val)} times!")
        parsed[key] = val[0]  # or val[-1]

print(parsed)

这篇关于我如何告诉 argparse 只允许一个参数一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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