Python argparse:默认参数存储为字符串,而不是列表 [英] Python argparse: default argument stored as string, not list

查看:79
本文介绍了Python argparse:默认参数存储为字符串,而不是列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从文档中了解argparse的这种行为:

I cannot figure out this behaviour of argparse from the documentation:

import argparse

parser.add_argument("--host", metavar="", dest="host", nargs=1, default="localhost", help="Name of host for database.  Default is 'localhost'.")
args = parser.parse_args()
print(args)

以下是带有和不带有"--host"参数的输出:

Here is the output with and without an argument for "--host":

>> python demo.py
Namespace(host='localhost')

>> python demo.py --host host
Namespace(host=['host'])

特别是:为什么"--host"的参数在指定时为什么存储在列表中,而在使用默认值时却不存储在列表中?

In particular: why does the argument to "--host" get stored in a list when it is specified but not when the default is used?

推荐答案

删除"nargs"关键字参数.定义完该参数后,argparse会假设您的参数是一个列表(nargs = 1表示一个包含1个元素的列表)

Remove the "nargs" keyword argument. Once that argument is defined argparse assumes your argument is a list (nargs=1 meaning a list with 1 element)

这篇关于Python argparse:默认参数存储为字符串,而不是列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆