我希望找到一种Pythonic的方式,在需要从其他参数解析出值时逻辑地验证参数。
这里有一个简单的例子:
parser.add_argument(
'--animal',
choices=['raccoon', 'giraffe', 'snake'],
default='raccoon',
)
parser.add_argument(
'--with-shoes',
action='store_true',
)
在这种情况下,解析此命令应该会导致错误:
my_script.py --animal snake --with-shoes
似乎添加一个互斥组在这里并没有帮助,因为其他组合是可以的:
my_script.py --animal raccoon --with-shoes
my_script.py --animal raccoon
my_script.py --animal snake
my_script.py --animal giraffe --with-shoes
my_script.py --animal giraffe
最好不要将验证错误与--animal
参数或--with-shoes
参数绑定在一起,因为界面无法告诉您更改哪个值。每个值都是有效的,但不能组合使用。
我们可以通过对args
名称空间进行后处理来做到这一点,但我正在寻找一种解决方案,可以导致parser.parse_args()
调用失败,即我们实际上在参数解析期间失败,而不是之后。