tcl list to python list?

Cameron Laird claird at lairds.us
Sun Sep 17 20:31:12 EDT 2006


In article <1158459542.693284.98090 at h48g2000cwc.googlegroups.com>,
 <jerry.levan at 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...)
			.
			.
			.
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) "]



More information about the Python-list mailing list