argparse list

Peter Otten __peter__ at web.de
Thu Sep 2 13:58:15 CEST 2010


Neal Becker wrote:

> I'm interested in using argparse to parse a string formatted as:
> 
> my_prog --option1=1,10,37
> 
> That is, a list of comma delimited values.  I guess nargs almost does it,
> but expects options to be space-delimited.
> 
> What would be the easiest approach?

>>> import argparse
>>> def csv(value):
...     return map(int, value.split(","))
...
>>> p = argparse.ArgumentParser()
>>> p.add_argument("--option1", type=csv) and None
>>> p.parse_args(["--option1=1,10,37"])
Namespace(option1=[1, 10, 37])
>>> _.option1[0]
1

Peter



More information about the Python-list mailing list