gpt4 book ai didi

带有默认选项的python argparse选项

转载 作者:IT老高 更新时间:2023-10-28 20:25:41 27 4
gpt4 key购买 nike

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

我的代码是:

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


文档:

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.

关于带有默认选项的python argparse选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40324356/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com