473,657 Members | 2,415 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6144

je*********@gma il.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*********@gm ail.comwrote in message
news:11******** *************@h 48g2000cwc.goog legroups.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,alp hanums+"_") | \
Combine(Word(nu ms) + "." + Optional(Word(n ums)) ) | Word(nums) | \
oneOf( list(r"(),.+=`~ !@#$%^&*-|\?/><;:") ) | Group( '{' + tcllist
+ '}' )
tcllist << OneOrMore( element )

import pprint
pprint.pprint( tcllist.parseSt ring(tcl).asLis t() )

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.wikis paces.com.

-- Paul
Sep 17 '06 #3
In article <CE************ *****@tornado.t exas.rr.com>,
Paul McGuire <pt***@austin.r r._bogus_.comwr ote:
><je*********@g mail.comwrote in message
news:11******* **************@ h48g2000cwc.goo glegroups.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,alp hanums+"_") | \
Combine(Word(nu ms) + "." + Optional(Word(n ums)) ) | Word(nums) | \
oneOf( list(r"(),.+=`~ !@#$%^&*-|\?/><;:") ) | Group( '{' + tcllist
+ '}' )
tcllist << OneOrMore( element )

import pprint
pprint.pprin t( tcllist.parseSt ring(tcl).asLis t() )

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.wikis paces.com.

-- Paul

Noooooooooooooo oooo!

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.t exas.rr.com>,
Paul McGuire <pt***@austin.r r._bogus_.comwr ote:
<yet another post showing a pyparsing stab at a parsing problem, this time
parsing Tcl lists>
>
Noooooooooooooo oooo!

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().ev al 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(Optiona l("$") + Word(alphas,alp hanums+"_"))
| \
Combine(Optiona l(oneOf(list("+-")))+ Word(nums) + "." +
Optional(Word(n ums)) ) | Word(nums+"+-",nums) | \
oneOf( list(r"(),.+=`~ !@#$%^&*-|\?/><;:") ) | Group( '{' + tcllist
+ '}' )
tcllist << ZeroOrMore( element )

import pprint
pprint.pprint( tcllist.parseSt ring(tcl).asLis t() )
=============== =======

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************ *********@h48g2 000cwc.googlegr oups.com>,
<je*********@gm ail.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.te xas.rr.com>,
Paul McGuire <pt***@austin.r r._bogus_.comwr ote:
Sep 18 '06 #7
"Cameron Laird" <cl****@lairds. uswrote in message
news:gv******** ****@lairds.us. ..
In article <11************ *********@h48g2 000cwc.googlegr oups.com>,
<je*********@gm ail.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(t k_instance("lin dex $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("se t tcl_list %s" % tcl_list)
numItems = int(tk_instance ("llength $tcl_list"))

# build Python list indexing by each item
result = [ tk_instance("li ndex $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************ *********@h48g2 000cwc.googlegr oups.com>,
<je*********@gm ail.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(t k_instance("lin dex $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("se t tcl_list %s" % tcl_list)
numItems = int(tk_instance ("llength $tcl_list"))

# build Python list indexing by each item
result = [ tk_instance("li ndex $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
2208
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 Usenet group). I tried unsubscribing and resubscribing to the list, but that turned out to be a mistake because once the list server sent me the email to confirm my subscription request, my reply email confirming it got ignored too!
1
1416
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 disabled due to too many bounced mails, even though (1) the mail server here hasn't suffered any network outages or downtime lately and (2) python-dev emails continued to arrive without problems. What's worse, when I looked at the list of...
3
1337
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 problem, or a general news to python-list problem?
0
1551
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, because my reply to "Partitions of an Integer" contained two little mistakes, which I wanted to correct in a followup...) I've never had this before mail.python.org switched to XS4ALL... If any of the mail admins happen to be reading this, it'd...
0
1589
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 this function available in Python. I use SWIG but I'm a complete newbie with it. I've only found an example to convert a Python list to C char** http://www.swig.org/Doc1.3/Python.html#Python_nn59
9
1728
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 presume is a 'machine' rather than a 'human' address. --------------------------- Your mail to 'Python-list' with the subject Re: how to join two Dictionary together?
7
1609
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 > obviously be a Py3k thing, though. Alex Martelli wrote: > I fully agree, but the BDFL has already (tentatively, I hope) > Pronounced that the form will stay in Py3K as syntax sugar for > list(...). I find that to be a truly hateful prospect, but...
1
1323
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 in whatever way is needed, if I know what the problem is. Is there FAQ somewhere that tells me what I should change? Thx, Tom
0
993
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
8413
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8324
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8617
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2742
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.