python 带有默认选择的 argparse 选择

python argparse choices with a default choice

我正在尝试在 Python 3 应用程序中使用 argparse,其中有一个明确的选择列表,但如果指定 none 则为默认值。

我的代码是:

parser.add_argument('--list', default='all', choices=['servers', 'storage', 'all'], help='list servers, storage, or both (default: %(default)s)') 
args = parser.parse_args()
print(vars(args))

但是,当我 运行 这个时,我得到以下选项:

$ python3 ./myapp.py --list all
{'list': 'all'}

或没有选项:

$ python3 ./myapp.py --list
usage: myapp.py [-h] [--list {servers,storage,all}]
myapp.py: error: argument --list: expected one argument

我是不是漏掉了什么?或者我可以不指定选项的默认值吗?

nargsconst 参数传递给 add_argument:

parser.add_argument('--list',
                    default='all',
                    const='all',
                    nargs='?',
                    choices=['servers', 'storage', 'all'],
                    help='list servers, storage, or both (default: %(default)s)')

如果您想知道 --list 是否在没有参数的情况下传递,请删除 const 参数,并检查 args.list 是否为 None.


文档:

nargs'?'

One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced.

const

When add_argument() is called with option strings (like -f or --foo) and nargs='?'. This creates an optional argument that can be followed by zero or one command-line arguments. When parsing the command line, if the option string is encountered with no command-line argument following it, the value of const will be assumed instead. See the nargs description for examples.

谢谢@ShadowRanger。 Subcommands 正是我需要的,结合 nargsconst。以下作品:

parser = argparse.ArgumentParser()
subparser = parser.add_subparsers()
parser_list = subparser.add_parser('list')
parser_list.add_argument('list_type', default='all', const='all', nargs='?', choices=['all', 'servers', 'storage'])

parser_create = subparser.add_parser('create')
parser_create.add_argument('create_type', default='server', const='server', nargs='?', choices=['server', 'storage'])

args = parser.parse_args()
pprint(vars(args))

$ python3 ./myapp.py -h
usage: dotool.py [-h] {list,create} ...

Digital Ocean tool

positional arguments:
  {list,create}

optional arguments:
  -h, --help     show this help message and exit

单独列出选项:

$ python3 ./myapp.py list
{'list_type': 'all'}

列出带有参数的选项:

$ python3 ./myapp.py list servers
{'list_type': 'servers'}