Python argparse:默认参数存储为字符串,而不是列表

Sch*_*mer 13 python command-line-arguments argparse

我无法从文档中找出argparse的这种行为:

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)
Run Code Online (Sandbox Code Playgroud)

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

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

>> python demo.py --host host
Namespace(host=['host'])
Run Code Online (Sandbox Code Playgroud)

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

Joo*_*wan 19

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