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

查看:23
本文介绍了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天全站免登陆