argparse parser stores lists instead of strings

Peter Otten __peter__ at web.de
Thu Apr 28 04:08:22 EDT 2011


Andrew Berg wrote:

> I've set up groups of arguments for a script I'm writing, and any time I
> give an argument a value, it gets stored as a list instead of a string,
> even if I explicitly tell it to store a string. Arguments declared with
> other types (e.g. float, int) and default values are stored as expected.
> For example:
> 
> vidin_args=parser.add_argument_group('Video Input Options', 'Various
> options that control how the video file is demuxed/decoded.')
> vidin_args.add_argument('-m', dest='vmode', nargs=1, type=str,
> metavar='video_mode', choices=['ntsc', 'pal', 'film', 'ivtc'],
> default='ntsc', help='Valid values are "ntsc", "pal", "film" and "ivtc".')
> ...more arguments...
> opts=parser.parse_args()
> 
> If I assign a value on the command line (e.g. -m pal), opts.vmode is a
> list, otherwise it's a string. This is pretty bad since I can't know
> whether to get opts.vmode or opts.vmode[0] later in the script. I could
> loop through all the options and convert each option to a string, but
> that's not really something I want to do, especially if I start adding
> more options.
> 
> I'm pretty new to Python, and I might have missed something, but I have
> been looking!

http://docs.python.org/py3k/library/argparse.html#nargs

"""
Note that nargs=1 produces a list of one item. This is different from the 
default, in which the item is produced by itself.
"""

So just omit 'nargs=1' from the add_argument() call.

> In case it matters, I'm learning Python 3.2 and have no intention of
> using older code (once I have one version of Python covered, then I'll
> look into making code that's compatible with 2.x if I have to).




More information about the Python-list mailing list