[Tutor] command line list arguments
Peter Otten
__peter__ at web.de
Sat Nov 7 06:48:52 EST 2015
Garry Willgoose wrote:
> I want to input a python list as a command line argument as for example
>
> python weathering-sens.py -daughter ['p0-50-50','p0-0-0-100’]
>
> but what I get from sys.argv is [p0-50-50,p0-0-0-100] without the string
> delimiters on the list elements. I’m probably missing something really
> simple because sys.argv returns strings and probably strips the string
> delimiters in that conversion … but is there any way that I can keep the
> string delimiters so that inside the code I can just go (if arg is
> ['p0-50-50','p0-0-0-100’])
>
> a=eval(arg)
>
> or is there no alternative to doing this
>
> python weathering-sens.py -daughter 'p0-50-50’ 'p0-0-0-100’
>
> and doing the legwork of interpreting all the arguments individually (I’ve
> seen an example of this on the web).
With argparse it's really not that much legwork:
$ cat weathering-sens.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--daughter", nargs="+")
args = parser.parse_args()
print(args.daughter)
$ python weathering-sens.py -d foo bar
['foo', 'bar']
$ python weathering-sens.py --daughter p0-50-50 p0-0-0-100
['p0-50-50', 'p0-0-0-100']
Note that args.daughter is a list of strings -- no need for eval().
More information about the Tutor
mailing list