Setting default option in Python of two mutually e

2019-08-28 04:50发布

import argparse

parser = argparse.ArgumentParser(description="List or update! That is the question!")

group = parser.add_mutually_exclusive_group()
group.add_argument('-l', '--list', dest="update", action='store_false')
group.add_argument('-u', '--update', dest="update", action='store_true')

args = parser.parse_args()
print args

If the user does not specify any optional arguments I want update=False.

[Edit]: I changed my question to not be so general, it was confusing. Sorry.

3条回答
闹够了就滚
2楼-- · 2019-08-28 05:13

I think that you want add_mutually_exclusive_group(). The documentation is here.

查看更多
Luminary・发光体
3楼-- · 2019-08-28 05:14

Adding default=False for the --list option's parameters makes it do what you want. I am not exactly sure why, and note that adding it to the --update option's parameters instead does nothing.

查看更多
闹够了就滚
4楼-- · 2019-08-28 05:16

You should set different dest for the 2 options.

group.add_argument('-f', '--foo', dest="foo", action='store_false')
查看更多
登录 后发表回答