convert string to list

Jeff Shannon jeff at ccvcorp.com
Wed Oct 13 22:40:01 CEST 2004


Jochen Hub wrote:

> I tried with eval...simply using
>
> thelist=eval(argv[1])
>
> it didn't work :-(, I got the error message
>
>   File "./findCenter.py", line 64, in ?
>     print eval(sys.argv[1])
>   File "<string>", line 0, in ?
> NameError: name 'A' is not defined
>
>>
>> #!/bin/bash
>> myscript.py A B C
>

The problem here is with shell quoting more than anything else.  In 
order for eval() to work, the sys.argv[1] must look like a normal Python 
list literal once your script gets hold of it.  That means that firstly, 
you need to get bash to pass everything after your script name (or at 
least, everything that's part of the list) as a single argument, and 
secondly, you need to have quoting right so that the contents of the 
list will be interpreted as strings, not variable names.  Try something 
like:

myscript.py "['A', 'B', 'C']"

However, I'm not sure how much manipulation of those quotes bash will do 
before it passes the arguments on to Python -- read man bash for 
specifics, I think it's in there somewhere, but it might not be pretty.

Also be aware that there's some serious risks here; consider the 
following --

myscript.py "__import__('os'); os.system('rm -rf /*')"

... which will actually attempt to delete your entire filesystem, or as 
much of it as the current user has access to.  Be very careful about 
accepting data to feed to eval().

On the other hand, if you use the other suggestions of simply passing 
arguments in bare (as you're trying to do) and using sys.argv[1:] as 
your argument list, then you'll be fine... except that you'll have a 
hard time passing in two separate lists.  I'm not sure that trying to 
accept two lists is really the best idea, but you could perhaps use some 
sentinel value to indicate where you want lists broken...

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list