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

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

问题描述

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

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
  • prog -key 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 的能力.不过,您之后可以对返回的命名空间执行简单的验证.您应该在帮助中包含至少需要一次 state 或 key.

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天全站免登陆