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

查看:19
本文介绍了如何在 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天全站免登陆