>我有一堆Python函数.我们称他们为foo,bar和baz.它们接受可变数量的字符串参数,并执行其他复杂的操作(如访问网络).
>我希望“用户”(让我们假设他只熟悉Tcl)使用这些函数在Tcl中编写脚本.
以下是用户可以提出的示例(取自Macports):
post-configure {
if {[variant_isset universal]} {
set conflags ""
foreach arch ${configure.universal_archs} {
if {${arch} == "i386"} {append conflags "x86 "} else {
if {${arch} == "ppc64"} {append conflags "ppc_64 "} else {
append conflags ${arch} " "
}
}
}
set profiles [exec find ${worksrcpath} -name "*.pro"]
foreach profile ${profiles} {
reinplace -E "s|^(CONFIG\[ \\t].*)|\\1 ${conflags}|" ${profile}
# Cures an isolated case
system "cd ${worksrcpath}/designer && \
${qt_dir}/bin/qmake -spec ${qt_dir}/mkspecs/macx-g++ -macx \
-o Makefile python.pro"
}
}
}
这里,variant_issset,reinplace等(除了Tcl builtins)实现为Python函数. if,foreach,set等等是正常的Tcl结构. post-configure是一个Python函数,它接受一个Tcl代码块,以后可以执行(反过来显然最终会调用上面提到的Python“函数”).
这可以用Python做吗?如果是这样,怎么样?
来自Tkinter进口*; root = Tk(); root.tk.eval(‘puts [array get tcl_platform]’)是我所知道的唯一集成,显然非常有限(更不用说它在mac上启动X11服务器的事实).
解决方法:
通过一些实验,我发现你可以做这样的事情来创建一个tcl解释器,注册一个python命令,并从Tcl调用它:
import Tkinter
# create the tcl interpreter
tcl = Tkinter.Tcl()
# define a python function
def pycommand(*args):
print "pycommand args:", ", ".join(args)
# register it as a tcl command:
tcl_command_name = "pycommand"
python_function = pycommand
cmd = tcl.createcommand(tcl_command_name, python_function)
# call it, and print the results:
result = tcl.eval("pycommand one two three")
print "tcl result:", result
当我运行上面的代码时,我得到:
$python2.5 /tmp/example.py
pycommand args: one, two, three
tcl result: None