views:

43

answers:

2

I am calling a python script with the following command line:

myscript.py --myopt="[(5.,5.),(-5.,-5.)]"

The question is -- how to convert myopt to a list variable. My solution was to use optparse, treating myopt as a string, and using

(options, args) = parser.parse_args()    
myopt = eval(options.myopt)

Now, because I used eval() I feel a bit like Dobby the house elf, having knowingly transgressed the commandments of great (coding) wizards, and wanting to self-flagellate myself in punishment.

But are there better options for parsing lists or tuples or lists of tuples from the command line?.. I've seen solutions that use split(), but this won't work here since this isn't a simple list. Keep in mind, also, that this is being done in the context of mostly one-off scientific computing with no security concerns -- so perhaps eval() isn't as evil here?..

+1  A: 

Try JSON instead. The syntax is not exactly Python, but close enough.

>>> import json
>>> json.loads("[[5.0,5.0],[-5.0,-5.0]]")
[[5.0, 5.0], [-5.0, -5.0]]
>>> [tuple(p) for p in json.loads("[[5.0,5.0],[-5.0,-5.0]]")]
[(5.0, 5.0), (-5.0, -5.0)]
>>> 
gimel
+3  A: 

ast.literal_eval(node_or_string):

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

So you can do

import ast
(options, args) = parser.parse_args()    
myopt = ast.literal_eval(options.myopt)
brainjam