argparse parser stores lists instead of strings

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 28 10:25:56 CEST 2011


En Thu, 28 Apr 2011 04:24:46 -0300, Andrew Berg  
<bahamutzero8825 at gmail.com> escribió:

> 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.

That's because of nargs=1. From the argparse documentation: [1]

	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 remove nargs=1 from add_argument()

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

-- 
Gabriel Genellina




More information about the Python-list mailing list