如何在Python的argparse中的同一组参数上两次调用parse_args()? [英] How to call parse_args() twice on the same set of arguments in Python's argparse?

查看:262
本文介绍了如何在Python的argparse中的同一组参数上两次调用parse_args()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简化的测试用例: 我有一个带有两个参数的脚本.第一个是整数列表.第二个是单个整数,必须包含在第一个参数的整数集中.

Simplified test case: I have a script that takes two arguments. The first is a list of integers. The second is a single integer that must be contained in the first argument's set of integers.

例如:

$ python argtest.py --valid_nums 1 2 3 --num 2

应该可以,但是:

$ python argtest.py --valid_nums 1 2 3 --num 4

应该不起作用,因为num不是in valid_nums.但是,我在实现此功能时遇到了一些困难(阅读:我怀疑这是不值得的麻烦,但我真的希望它能起作用).

Should not work, since num is not in valid_nums. However, I have had some difficulty (read: I suspect it is more trouble than it's worth, but I really want it to work) implementing this functionality.

实施尝试:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--valid_nums',
                    type=int,
                    nargs='+')

args = parser.parse_args()
print "Numbers: ", args.valid_nums


parser.add_argument('--num',
                    type=int,
                    choices=args.valid_nums)

args = parser.parse_args()
print args

实际输出:

$ python argtesttest.py --valid_nums 1 2 3 --num 2
usage: argtesttest.py [-h] [--valid_nums VALID_NUMS [VALID_NUMS ...]]
argtesttest.py: error: unrecognized arguments: --num 2

所需的输出:

$ python argtesttest.py --valid_nums 1 2 3 --num 2
Namespace(num=2, valid_nums=[1, 2, 3])

现在,(我认为)这里的问题是,我调用parse_args()后无法在解析器中添加新的参数,这会产生关于无法识别的参数的错误,但我想不出解决方法它.有什么方法可以使参数的处理不被一次性处理吗?

Now, (I think) the issue here is that I cannot add a new argument to the parser after I have called parse_args(), which yields the error about an unrecognized argument, but I can't think of a way around it. Is there any way to break up the processing of arguments such that it isn't all at once?

很明显,如果我只调用一次parse_args()并自己处理容器成员身份检查,这将非常简单,但是我想使用argparse的内置错误使它本机"工作-检查.

Obviously this would be pretty trivial to do if I only called parse_args() once and handled the container membership checking myself, but I'd like to get it working 'natively' using argparse's built-in error-checking.

有什么想法吗?

推荐答案

您需要使用parser.parse_known_args()而不是parser.parse_args(),或者在调用parse_args()之前将所有参数添加到解析器中.

you need to use parser.parse_known_args() as opposed to parser.parse_args(), or add all the arguments to parser before calling parse_args().

parse_args()需要了解sys.argv中的所有当前参数,该参数在第一次解析时已经包含--num,因此是一个例外.

parse_args() needs to understand all the current arguments in sys.argv, which already contains --num at the time of first parsing, hence the exception.

这篇关于如何在Python的argparse中的同一组参数上两次调用parse_args()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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