convert string to list
Jeremy Jones
zanesdad at bellsouth.net
Wed Oct 13 08:34:19 EDT 2004
Cliff Wells wrote:
>On Wed, 2004-10-13 at 14:03 +0200, Jochen Hub wrote:
>
>
>>Hi,
>>
>>I am a real beginner in Python and I was wondering if there is a way to
>>convert a string (which contains a list) to a "real" list.
>>
>>I need this since I would like to give a list as an argument to my
>>Python script from the bash:
>>
>>#!/usr/bin/python
>>import sys
>>argument1 = sys.argv[1]
>>thelist = ???(argument1)
>>
>>and then call the script from the bash like this
>>
>>thescript.py ["A","B","C"]
>>
>>
>
>You can use eval for this. Better, you could simply pass your list as a
>series of arguments from bash:
>
>#!/bin/bash
>myscript.py A B C
>
>
>#!/usr/bin/python
>import sys
>thelist = sys.argv[1:]
>
>Regards,
>Cliff
>
>
>
As Cliff and Diez stated, you're better off passing your list as
elements broken up and using sys.argv to get at them. But, here is a
sample of how to use eval:
#!/usr/bin/env python
import sys
import string
print "sys.argv>>", sys.argv
if len(sys.argv) > 1:
s = "".join(sys.argv[1:])
l = eval(s)
for i, e in enumerate(l):
print i, e
A problem with this approach is, you need to make sure you put your list
string in quotes like this:
./test_list.py "['a', 'b', 'c']"
so that the list is treated by the shell as a single argument rather
than a series of strings. And, actually, the "[" character is actually
an executable (on *NIX operatins systems) that performs all kinds of
"tests" So, I don't think the shell will substitute it for anything,
but......you may not want to just leave it out unquoted..... Plus, if
you don't quote the whole thing, your shell may gobble up your quote
marks and you won't get exactly what you're looking for. Look at your
sys.argv. The quotes around the letters are gone, gobbled up by the shell:
[jmjones at qatestrunner python]$ ./test_list.py ['a','b','c']
sys.argv>> ['./test_list.py', '[a,b,c]']
Traceback (most recent call last):
File "./test_list.py", line 12, in ?
l = eval(s)
File "<string>", line 0, in ?
NameError: name 'a' is not defined
So, again, you're probably best to go with the solution proposed by
Cliff and Diez.
Jeremy Jones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20041013/5ccd0f7b/attachment.html>
More information about the Python-list
mailing list