Python argparse: default argument stored as string, not list

I cannot understand this argparse behavior 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 result with and without the -host argument:

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

In particular: why is the "-host" argument stored in the list when it is specified, but not when the default value is used?

+7
python command-line-arguments argparse
source share
2 answers

Remove the nargs keyword argument. Once this argument is defined, argparse assumes your argument will be a list (nargs = 1 means a list with 1 element)

+12
source share

As an alternative and convenient module: Docopt can be used to parse command line arguments. Docopt converts the command line to dictionnary by defining the values ​​inside the doc .

0
source share

All Articles