Python argparse: default argument stored as string, not list

若如初见. 提交于 2021-02-04 14:32:11

问题


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)

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

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


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




回答2:


As an alternative and handy module: Docopt can be used for parsing command line arguments. Docopt transform a commandline into a dictionnary by defining values inside doc.




回答3:


The question title and the question body ask two different questions. This is potentially a sign of the confusion I shared with the OP.

The title: why is the default a string not a list? The body: why is the given value a list not a string?

The selected answer provides the solution to the question in the body. The answer to the question in the title is:

The entry default="localhost" sets default to "localhost", which is a sting. To set it as a list, you could use: default=["localhost"].



来源:https://stackoverflow.com/questions/25343868/python-argparse-default-argument-stored-as-string-not-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!