python argparse选择与默认选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40324356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:23:34  来源:igfitidea点击:

python argparse choices with a default choice

pythonpython-3.xargparse

提问by MVanOrder

I'm trying to use argparse in a Python 3 application where there's an explicit list of choices, but a default if none are specified.

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

The code I have is:

我的代码是:

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))

However, when I run this I get the following with an option:

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

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

Or without an option:

或者没有选择:

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

Am I missing something here? Or can I not have a default with choices specified?

我在这里错过了什么吗?或者我可以没有指定选项的默认值吗?

采纳答案by MVanOrder

Thanks @ShadowRanger. Subcommandsis exactly what I need, combined with nargsand const. The following works:

谢谢@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

list option alone:

单独列出选项:

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

List option with a parameter:

带参数的列表选项:

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

回答by Francisco Couzo

Pass the nargsand constarguments to add_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)')

If you want to know if --listwas passed without an argument, remove the constargument, and check if args.listis None.

如果你想知道 if--list是不带参数传递的,删除const参数,然后检查是否args.listNone