[Tutor] command line list arguments

Chris Warrick kwpolska at gmail.com
Sat Nov 7 06:07:50 EST 2015


On 7 November 2015 at 02:56, Garry Willgoose
<garry.willgoose at newcastle.edu.au> 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).

1. NEVER use eval().
2. Trying to pass Python code as arguments looks bad.  Don’t do that.
3. Your issues with '' are caused by your shell. You would need to
wrap your entire thing in quotes first, or use escaping. But instead,
4. Use argparse or another argument parsing solution, and implement it
with two arguments.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16


More information about the Tutor mailing list