Example for accessing Tcl functions from Python
elmer enables one to run Python code from Tcl. What about the other way around? Could anyone give an example in开发者_StackOverflow Python?
Update: by this I mean, being able to access Tcl objects, invoke Tcl functions, etc. instead of simply running some Tcl code.
This is a rather old thread, but I recently stumbled on Tkinter.Tcl()
which gives you direct access to a Tcl interpreter in python without having to spawn a Tk GUI as Tkinter.Tk()
requires.
An example... suppose you have a Tcl file (foo.tcl
) with a proc called main
that requires an single filename as an argument... main
returns a string derived from reading foo.tcl
.
from Tkinter import Tcl
MYFILE = 'bar.txt'
tcl = Tcl()
# Execute proc main from foo.tcl with MYFILE as the arg
tcl.eval('source foo.tcl')
tcl_str = tcl.eval('main %s' % MYFILE)
# Access the contents of a Tcl variable, $tclVar from python
tcl.eval('set tclVar foobarme')
tclVar = tcl.eval('return $tclVar')
I haven't found another way to access Tcl objects from python besides through a return value, but this does give you a way to interface with Tcl procs. Furthermore, you can export python functions into Tcl as discussed in Using Python functions in Tkinter.Tcl()
You can take a look at python tkinter standard module, it is a binding to Tk UI, but that executes Tcl code in the background.
While it might be possible in theory by providing some custom Python object types that wrap C level Tcl_Obj*'s transparently, the general case is just exchanging strings back and forth as Tcl's EIAS semantics can shimmer away every other internal representation freely.
So yes, you could do better than strings, but its usually not worth it. Tkinter already has a few of the possible optimizations built in, so try to steal there...
This?
import subprocess
subprocess.Popen( "tclsh someFile.tcl", shell=True )
精彩评论