Paul McGuire wrote: > "Cameron Laird" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > In article <[EMAIL PROTECTED]>, > > <[EMAIL PROTECTED]> 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...) > > . > > . > > . > > 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. -- http://mail.python.org/mailman/listinfo/python-list