473,372 Members | 1,191 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,372 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 17494
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) This should return something like:
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 text list and paste this list into a javascript...
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 this question. Thanks. I want to format a...
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 = myobject.mymethod(parameter) I want to now turn this 'data' into...
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 PHP ]; # OUTPUT {{-Hello}} World, which PHP...
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 please help me with this? static public...
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} This is the TCL code that does this: set...
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, each containing a formula (like Excel). I am...
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 ((convert(VARCHAR,w_date,103) = '" + w_date + "'))"; ...
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 get the results of a query and put them into a...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.