Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse: default argument stored as string, not list

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?

like image 365
Schemer Avatar asked Aug 16 '14 20:08

Schemer


1 Answers

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)

like image 131
Joohwan Avatar answered Sep 19 '22 16:09

Joohwan