【发布时间】:2012-08-31 11:28:18
【问题描述】:
我意识到这很像Setting default option in Python of two mutually exclusive options using the argparse module,尽管从不同的角度来看(那里给出的答案似乎没有帮助)。
代码块(解析器是argparse.ArgumentParser的一个实例):
mutex_group = parser.add_mutually_exclusive_group()
mutex_group.add_argument("--show", action="store_true",
dest="show", default=True)
mutex_group.add_argument("--insert", action="store_true",
dest="insert")
opts = parser.parse_args()
如果没有指定--show 或--insert,我想默认为--show(因此default=True)但如果使用--insert,那么opts.show 仍然设置为true(因为默认),尽管是互斥块的一部分。
当前代码在测试opt.show是否为True时检查是否没有设置其他选项,即:
if opts.show and not opts.insert:
do_something()
elif opts.insert:
do_something_else()
但这不会扩展(当您将--delete 添加到互斥组时会发生什么,等等)所以我正在寻找一种更好的方法来使所有其他变量都使opts.show false 同时仍然有它是默认值。
阅读 argparse 文档,我认为自定义操作是可行的方法,但看不到如何从其中访问互斥组的其他成员(理论是我可以迭代它们,然后翻转如果设置了其余任何一个,则为默认值)。 另一种选择是反转 if 条件,但这似乎不干净(如果默认更改,if 语句的顺序也必须更改)。
【问题讨论】:
标签: python arguments command-line-arguments argparse