473,386 Members | 1,702 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,386 software developers and data experts.

tcl list to python list?

Hi,

I have a file that contains a "tcl" list stored as a string. The list
members are
sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }

I would like to parse the tcl list into a python list...

Any suggestions ( I am running Tkinter...)

Jerry

Sep 17 '06 #1
8 6101

je*********@gmail.com wrote:
Hi,

I have a file that contains a "tcl" list stored as a string. The list
members are
sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }

I would like to parse the tcl list into a python list...

Any suggestions ( I am running Tkinter...)

Jerry
Well, if you know TCL then read the bit about how to write a python
list:
(http://docs.python.org/tut/node5.htm...00000000000000)
Then write a TCL function to traverse your TCL list and write it out in
the python format.

Another suggestion might be to use CSV as an intermediary:
http://tcllib.sourceforge.net/doc/csv.html
http://docs.python.org/dev/lib/module-csv.html

Now if you know Python and not TCL ... :-)

- Paddy.

Sep 17 '06 #2
<je*********@gmail.comwrote in message
news:11*********************@h48g2000cwc.googlegro ups.com...
Hi,

I have a file that contains a "tcl" list stored as a string. The list
members are
sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }

I would like to parse the tcl list into a python list...

Any suggestions ( I am running Tkinter...)

Jerry
This is very similar to the Python list parser that comes with pyparsing.
Adapted to your syntax, this looks something like:

tcl = """sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }"""

from pyparsing import *

tcllist = Forward()
element = quotedString | Word(alphas,alphanums+"_") | \
Combine(Word(nums) + "." + Optional(Word(nums)) ) | Word(nums) | \
oneOf( list(r"(),.+=`~!@#$%^&*-|\?/><;:") ) | Group( '{' + tcllist
+ '}' )
tcllist << OneOrMore( element )

import pprint
pprint.pprint( tcllist.parseString(tcl).asList() )

Giving:

['sql',
'commands',
'ex',
':',
['{',
'begin',
['{', 'select', '*', 'from', 'foo', 'where', 'baz', '=', "'whatever'",
'}'],
['{', 'select', '*', 'from', 'gooble', '}'],
'end',
['{', 'insert', 'into', 'bar', 'values', '(', "'Tom'", ',', '25', ')',
'}'],
'}']]

The pyparsing home page is at pyparsing.wikispaces.com.

-- Paul
Sep 17 '06 #3
In article <CE*****************@tornado.texas.rr.com>,
Paul McGuire <pt***@austin.rr._bogus_.comwrote:
><je*********@gmail.comwrote in message
news:11*********************@h48g2000cwc.googlegr oups.com...
>Hi,

I have a file that contains a "tcl" list stored as a string. The list
members are
sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }

I would like to parse the tcl list into a python list...

Any suggestions ( I am running Tkinter...)

Jerry

This is very similar to the Python list parser that comes with pyparsing.
Adapted to your syntax, this looks something like:

tcl = """sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }"""

from pyparsing import *

tcllist = Forward()
element = quotedString | Word(alphas,alphanums+"_") | \
Combine(Word(nums) + "." + Optional(Word(nums)) ) | Word(nums) | \
oneOf( list(r"(),.+=`~!@#$%^&*-|\?/><;:") ) | Group( '{' + tcllist
+ '}' )
tcllist << OneOrMore( element )

import pprint
pprint.pprint( tcllist.parseString(tcl).asList() )

Giving:

['sql',
'commands',
'ex',
':',
['{',
'begin',
['{', 'select', '*', 'from', 'foo', 'where', 'baz', '=', "'whatever'",
'}'],
['{', 'select', '*', 'from', 'gooble', '}'],
'end',
['{', 'insert', 'into', 'bar', 'values', '(', "'Tom'", ',', '25', ')',
'}'],
'}']]

The pyparsing home page is at pyparsing.wikispaces.com.

-- Paul

Noooooooooooooooooo!

I'll be more precise: pyparsing is quite wonderful, and I'm
all in favor of clever demonstrations of its capabilities. I
don't think this is one, though; in fact, although I haven't
yet paid enough attention to the original question to provide
an example, I'm reasonably certain that the code offered above
mishandles at least some data (Tcl syntax is different from
what outsiders expect).

Paddy's advice elsewhere in this thread is almost entirely
correct. Anyone who has imported Tkinter has all of Tcl avail-
able immediately, so much the easiest, most reliable, most
maintainable, and most lucid solution is simply to iterate in
Tcl over the list, and construct thus the corresponding Python
list.

I'm willing to write either a correct implementation, or a
counterexample with problematic data, if these sufficiently
interest readers. It'll be a day or two before I can make the
time to be careful, though.
Sep 17 '06 #4
"Cameron Laird" <cl****@lairds.uswrote in message
news:3k************@lairds.us...
In article <CE*****************@tornado.texas.rr.com>,
Paul McGuire <pt***@austin.rr._bogus_.comwrote:
<yet another post showing a pyparsing stab at a parsing problem, this time
parsing Tcl lists>
>
Noooooooooooooooooo!

I'll be more precise: pyparsing is quite wonderful, and I'm
all in favor of clever demonstrations of its capabilities. I
don't think this is one, though; in fact, although I haven't
yet paid enough attention to the original question to provide
an example, I'm reasonably certain that the code offered above
mishandles at least some data (Tcl syntax is different from
what outsiders expect).

Paddy's advice elsewhere in this thread is almost entirely
correct. Anyone who has imported Tkinter has all of Tcl avail-
able immediately, so much the easiest, most reliable, most
maintainable, and most lucid solution is simply to iterate in
Tcl over the list, and construct thus the corresponding Python
list.

I'm willing to write either a correct implementation, or a
counterexample with problematic data, if these sufficiently
interest readers. It'll be a day or two before I can make the
time to be careful, though.
Cameron -

Er? Thanks for the nice comments re: pyparsing, sometimes I feel a little
self-conscious always posting these pyparsing snippets. So I'm glad you
clarified your intent with your "I'll be more precise" paragraph. But I'm
not sure I see the reason for an 18-O "No!"

"Outsider"? I'm no stranger to Tcl (although I *am* a bit rusty). In the
90's I worked for several years with a script-based process control system
for semiconductor manufacturing, in which we used Tcl for customer-defined
control logic. Tcl led me to appreciate the value of a scripting language,
despite its clunky assignment syntax ("set x 1"), and "$"-happiness. When I
looked into Python a few years later, I remember thinking "Man, I wish we
could have used Python instead."

I took a look at how accessible Tcl is using Tkinter. It looks to me like
one would need to:
- write a Tcl proc to recursively traverse a list, returning a stringified
list in Python-like syntax (enclosing non-list items in ''s, separating with
commas, nesting sublists with []'s, etc.)
- construct a string passing the OP's Tcl list string "sql commands ex:
...." to this method
- invoke Tkinter.Tk().eval on this string to perform the Tcl traversal
- invoke Python's eval function on the returned string to get an actual
list.

Did I get that right? Or is there another, simpler back door into Tcl from
Tkinter?

I'll confess, I wrote my sample code based on the sample text posted by the
OP, without much extra syntax (such as negative integers or floating-point
values). So here is a version with a bit broader coverage:
======================
tcl = """sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from $gooble } { } end
{ insert into bar values('Tom', 25) } }"""

from pyparsing import *

tcllist = Forward()
element = quotedString | Combine(Optional("$") + Word(alphas,alphanums+"_"))
| \
Combine(Optional(oneOf(list("+-")))+ Word(nums) + "." +
Optional(Word(nums)) ) | Word(nums+"+-",nums) | \
oneOf( list(r"(),.+=`~!@#$%^&*-|\?/><;:") ) | Group( '{' + tcllist
+ '}' )
tcllist << ZeroOrMore( element )

import pprint
pprint.pprint( tcllist.parseString(tcl).asList() )
======================

This should handle empty lists, signed integers and reals, and variables
with leading '$' signs.

Before putting too much effort into problematic counter-example data, it
might be a good idea to check with the OP, to see what types of values are
likely to come up in practice. Given that c.l.py posting is only a
spare-time activity (probably so for you, too), I wouldn't want to waste
time on the be-all-and-end-all Tcl list parser that handles cases the OP
wont run into.

-- Paul
Sep 17 '06 #5
In article <11*********************@h48g2000cwc.googlegroups. com>,
<je*********@gmail.comwrote:
>Hi,

I have a file that contains a "tcl" list stored as a string. The list
members are
sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }

I would like to parse the tcl list into a python list...

Any suggestions ( I am running Tkinter...)
Sep 18 '06 #6
In article <Ac****************@tornado.texas.rr.com>,
Paul McGuire <pt***@austin.rr._bogus_.comwrote:
Sep 18 '06 #7
"Cameron Laird" <cl****@lairds.uswrote in message
news:gv************@lairds.us...
In article <11*********************@h48g2000cwc.googlegroups. com>,
<je*********@gmail.comwrote:
>>Hi,

I have a file that contains a "tcl" list stored as a string. The list
members are
sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }

I would like to parse the tcl list into a python list...

Any suggestions ( I am running Tkinter...)
.
.
.
No correct solution's going to be as elegant as I suspect you imagine.
Here's an example of what's required:

# If you try anything you suspect is simpler, you're going to have to
# teach Python about Tcl treatment of whitespace, or teach Tcl how
# Python quotes, or ...

import Tkinter
tcl_list = """{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }"""

# Collect the Python list here.
result = []
# Create a single Tcl interpretive context for all the work.
tk_instance = Tkinter.Tk().tk.eval
# Everything Tcl returns is a string; make this value an integer.
tcl_list_length = int(tk_instance(
"set tcl_list %s; llength $tcl_list" % tcl_list))

# With all the set-up done, simply loop over the elements.
for counter in range(tcl_list_length):
# Ask Tcl for each successive list item.
result.append(tk_instance("lindex $tcl_list %d" % counter))

print result

The output is
['begin', " select * from foo\n where baz='whatever'",
'select * from gooble ', 'end', " insert into bar values('Tom', 25) "]
Elegant-shmelegant, looks like it gets the job done, and neatly too. I had
no idea that you can invoke Tcl so easily from Python.

Why is your indentation so weird though? The comments actually make your
solution harder to read. If I may be so forward as to edit for readability
(I think a list comprehension to build the actual list is easier to follow
than the for loop with the strangely-indented comments):

# Create a single Tcl interpretive context for all the work.
tk_instance = Tkinter.Tk().tk.eval

# define list in Tcl context, and extract number of elements
tk_instance("set tcl_list %s" % tcl_list)
numItems = int(tk_instance("llength $tcl_list"))

# build Python list indexing by each item
result = [ tk_instance("lindex $tcl_list %d" % i)
for i in range(numItems)]
-- Paul
Sep 18 '06 #8

Paul McGuire wrote:
"Cameron Laird" <cl****@lairds.uswrote in message
news:gv************@lairds.us...
In article <11*********************@h48g2000cwc.googlegroups. com>,
<je*********@gmail.comwrote:
>Hi,

I have a file that contains a "tcl" list stored as a string. The list
members are
sql commands ex:
{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }

I would like to parse the tcl list into a python list...

Any suggestions ( I am running Tkinter...)
.
.
.
No correct solution's going to be as elegant as I suspect you imagine.
Here's an example of what's required:

# If you try anything you suspect is simpler, you're going to have to
# teach Python about Tcl treatment of whitespace, or teach Tcl how
# Python quotes, or ...

import Tkinter
tcl_list = """{ begin { select * from foo
where baz='whatever'}
{select * from gooble } end
{ insert into bar values('Tom', 25) } }"""

# Collect the Python list here.
result = []
# Create a single Tcl interpretive context for all the work.
tk_instance = Tkinter.Tk().tk.eval
# Everything Tcl returns is a string; make this value an integer.
tcl_list_length = int(tk_instance(
"set tcl_list %s; llength $tcl_list" % tcl_list))

# With all the set-up done, simply loop over the elements.
for counter in range(tcl_list_length):
# Ask Tcl for each successive list item.
result.append(tk_instance("lindex $tcl_list %d" % counter))

print result

The output is
['begin', " select * from foo\n where baz='whatever'",
'select * from gooble ', 'end', " insert into bar values('Tom', 25) "]

Elegant-shmelegant, looks like it gets the job done, and neatly too. I had
no idea that you can invoke Tcl so easily from Python.

Why is your indentation so weird though? The comments actually make your
solution harder to read. If I may be so forward as to edit for readability
(I think a list comprehension to build the actual list is easier to follow
than the for loop with the strangely-indented comments):

# Create a single Tcl interpretive context for all the work.
tk_instance = Tkinter.Tk().tk.eval

# define list in Tcl context, and extract number of elements
tk_instance("set tcl_list %s" % tcl_list)
numItems = int(tk_instance("llength $tcl_list"))

# build Python list indexing by each item
result = [ tk_instance("lindex $tcl_list %d" % i)
for i in range(numItems)]
-- Paul
Thanks, Cameron, Paul;
I'm still in the Electronics business, where TCL is everywhere. I too
did not know how easy it is to invoke TCL from inside Python. Yet more
ammunition in my quest to be allowed to write more Python at work.

- Cheers, Paddy.

Sep 18 '06 #9

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

Similar topics

5
by: Dave Brueck | last post by:
Is anybody else having problems sending email to python-list@python.org? About 48 hours ago or so my posts stopped making it to the list (I usually post via the mailing list rather than to the...
1
by: Dave Brueck | last post by:
The other day I stopped receiving emails from python-list (although python-dev kept going just fine). This morning I decided to investigate and the Mailman page for python-list had my address...
3
by: Brad Clements | last post by:
I have not seen any new posts in gmane.comp.python.general since 6/18/2004. However when I post to gmane, that post seems to make it out to the python list. Does anyone know if its a gmane...
0
by: Heiko Wundram | last post by:
Hi all, esp. list admins! Why is it that I always get bounces saying my mails have suspicious headers lately when I post to python-list? This only happens when I reply to myself (as I just did,...
0
by: Chris | last post by:
Hi I have a C function that builds a list of null terminated strings: void buildStringList(char **asStrings, int n); The number of elements in the list is given in input. I'd like to have...
9
by: Terry Reedy | last post by:
For a couple of years, I have been reading and posting and posting to python-list and c.l.p via gmane.news.orgs gmane.comp.python.general group. Today I got this from 'python-list-bounces', which I...
7
by: Steven Bethard | last post by:
Tom Anderson <twic@urchin.earth.li> wrote: > Sounds good. More generally, i'd be more than happy to get rid of list > comprehensions, letting people use list(genexp) instead. That would >...
1
by: Tom Stambaugh | last post by:
I continue to receive emails, addressed to python-list-bounces@python.org, with subject: "Re: Your message to Python-list awaits moderator approval", which read: I'm happy to adjust my headers...
0
by: Gareth Owen | last post by:
On Monday 12 May 2008 14:55:06 python-list-request@python.org wrote: If timing is critical, try using a semaphore technique.
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: 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...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.