如何在Python中至少需要一个参数,并可以使用argparse接受所有参数? [英] How to make at least one argument required and have the possibility to take all arguments with argparse in Python?

查看:145
本文介绍了如何在Python中至少需要一个参数,并可以使用argparse接受所有参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序有2个要处理的参数:状态和键. 我需要提供以下选项作为输入:

The program has 2 arguments to deal with: state and key. I need to have a possibility to give as input the following options:

  • prog -state state_value
  • 程序-键key_value
  • prog -state state_value -key key_value

最近的事情是使用相互排斥的组,但是它无法给出 这两个参数都可以立即输入.

The closest thing is using mutually excluding groups, but it unables the possibility to give both arguments as input at once.

推荐答案

我认为这超出了argparse的能力.不过,您之后可以对返回的名称空间执行简单的验证.您应该在帮助中包括至少需要输入一次状态或密钥.

I think this is beyond the abilities of argparse. You could perform a simple validation on the returned namespace afterwards though. You should include in your help that at least once of state or key is required.

def validate(namespace, parser):
    if not any(arg in {"state", "key"} for arg in vars(namespace).keys()):
        parser.print_help()
        parser.exit(2)

namespace = parser.parse_args()
validate(namespace, parser)

这篇关于如何在Python中至少需要一个参数,并可以使用argparse接受所有参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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