472,353 Members | 1,908 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,353 software developers and data experts.

convert string to list

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"]

Thanks you,
Jochen
Jul 18 '05 #1
10 17428
Jochen Hub wrote:

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"]


Why don't you give the args standalone

thescript.py "A" "B" "C"

and do this:

thelist = sys.argv[1:]

--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
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

--
Cliff Wells <cl************@comcast.net>

Jul 18 '05 #3
>>
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:


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 is that I want to pass one or two lists to the script, so it
should be able to distinguish between

thescript ["A","B"] ["C","D",E"]
thescript ["A","B","C"] ["D",E"]
thescript ["A","B","C","D",E"]
Jul 18 '05 #4
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"]

Thanks you,
Jochen

If you are sure that the list always looks that way:
l = '["A","B","C"] '
l[1:-2].replace('"','').split(',')

['A', 'B', 'C']
HTH,
Wolfram
Jul 18 '05 #5
Wolfram Kraus wrote:
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"]

Thanks you,
Jochen


If you are sure that the list always looks that way:
>>> l = '["A","B","C"] '
>>> l[1:-2].replace('"','').split(',') ['A', 'B', 'C']
HTH,
Wolfram

Damn, I knew there must be something wrong with the -2 (too much work
today??):
l = '["A","B","C"]'
l[1:-1].replace('"','').split(',')

['A', 'B', 'C']

Or try the other solution with multiple arguments (better way IMHO)

Wolfram
Jul 18 '05 #6
On Wed, 2004-10-13 at 16:49 +0200, Jochen Hub wrote:
#!/bin/bash
myscript.py A B C


The problem is that I want to pass one or two lists to the script, so it
should be able to distinguish between

thescript ["A","B"] ["C","D",E"]
thescript ["A","B","C"] ["D",E"]
thescript ["A","B","C","D",E"]


Okay, after considering several alternatives, it occurs to me that,
depending upon the scope of this script, eval might not be a bad way to
go. There are two main questions you have to ask yourself when deciding
if eval is safe:

1. Where will the arguments come from? If you are hardwiring them into
the bash script (and the script is properly secured) then I don't think
there's a problem. If they come from an untrusted source (network data,
etc), then you should by no means use eval.

2. Is there any chance this script will be run suid? I know Linux
doesn't allow suid scripts, but that doesn't prevent the script from
being run by a suid executable and thus gaining privileges.

If you feel secure about those two things, then I would say go ahead
with the eval-based solution, since it is clearly the simplest:

#!/bin/bash
script.py "['a', 'b', 'c']" "['d', 'e', 'f']"

#!/usr/bin/python
import sys

arglist = []
for arg in sys.argv[1:]:
arglist.append(eval(arg))

print arglist
Regards,
Cliff

--
Cliff Wells <cl************@comcast.net>

Jul 18 '05 #7
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

Jul 18 '05 #8
Jochen Hub <jh**@gwdg.here_simple_one_dot.de> wrote in message news:<ck**********@gwdu112.gwdg.de>...
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"]

Thanks you,
Jochen

Other posters have mentioned difficulties with what the shell will do
to your command line. If you can get it as a single string - I've
written a module that will turn a string like that back into a list. I
use it for reading lists from config files. It will properly handle
the quotes etc.....

It's called listwuote and you can find it at
http://www.voidspace.org.uk/atlantib...html#listquote

Regards,

Fuzzy
Jul 18 '05 #9
Hi,
#!/bin/bash
script.py "['a', 'b', 'c']" "['d', 'e', 'f']"

#!/usr/bin/python
import sys

arglist = []
for arg in sys.argv[1:]:
arglist.append(eval(arg))

print arglist

Why not just:

script.py "a, b, c" "d, e, f"

Then: arglist = []
for arg in sys.argv[1:]:
arglist.append(arg.split(','))


Better than eval.

Regards,
Josef
Jul 18 '05 #10
On Fri, 2004-10-15 at 10:15 +0200, Josef Meile wrote:

Why not just:

script.py "a, b, c" "d, e, f"

Then:
> arglist = []
> for arg in sys.argv[1:]:
> arglist.append(arg.split(','))


Better than eval.


A basic problem is that the OP gave no indication of what would really
be passed as the lists (well, I'm assuming that his examples of ['A',
'B', 'C'] were contrived for simplicity). Without knowing this, then
it's impossible to know if a character such as ',' might be contained in
the data. If it is then splitting on ',' is going to fail. A better
approach might be to pass the info as valid CSV data and use the csv
module to evaluate it:

#!/bin/bash
python bar.py '"a","b","c"' '"d","e","f"'
#!/usr/bin/python
import sys, csv
from StringIO import StringIO

for arg in sys.argv[1:]:
reader = csv.reader(StringIO(arg))
for row in reader:
print row
Regards,
Cliff

--
Cliff Wells <cl************@comcast.net>

Jul 18 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Klaus Neuner | last post by:
Hello, I need a function that converts a list into a set of regexes. Like so: string_list = print string_list2regexes(string_list) ...
5
by: Andrew V. Romero | last post by:
At work we have an excel file that contains the list of medications and their corresponding strengths. I would like to save the excel file as a...
4
by: aevans1108 | last post by:
expanding this message to microsoft.public.dotnet.xml Greetings Please direct me to the right group if this is an inappropriate place to post...
2
by: Steve | last post by:
I have a very simple datatable of 1 column which I retrieve from a database, call it 'data'. Dim data As Data.DataTable data =...
23
by: comp.lang.tcl | last post by:
I have a TCL proc that needs to convert what might be a list into a string to read consider this: ]; # OUTPUTS Hello World which is fine for...
5
by: Learner | last post by:
Hello, Here is the code snippet I got strucked at. I am unable to convert the below line of code to its equavalent vb.net code. could some one...
27
by: comp.lang.tcl | last post by:
My TCL proc, XML_GET_ALL_ELEMENT_ATTRS, is supposed to convert an XML file into a TCL list as follows: attr1 {val1} attr2 {val2} ... attrN {valN}...
2
by: CodeMonkey775 | last post by:
I'm having problems passing a variable to a method which is executed and compiled using CodeDom. The situation is I have a List<CellData> with cells,...
1
by: pnbaocuong | last post by:
Dear All When I try to use convert function of MS sql server like this: String sql = " (employee_id = '" + employee_id + "') and...
9
by: myotheraccount | last post by:
Hello, Is there a way to convert a DataRow to a StringArray, without looping through all of the items of the DataRow? Basically, I'm trying to...
1
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
0
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand....
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.