我有一堆 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 内置函数)被实现为 Python 函数。 if
, foreach
, set
, 等.. 是正常的 Tcl 结构。 post-configure
是一个 Python 函数,它接受一个 Tcl 代码块,稍后可以执行(这显然最终会调用上面提到的 Python“函数”)。
这可以用 Python 实现吗?如果是,怎么办?
from Tkinter import *; 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
关于python - 在 Tkinter.Tcl() 中使用 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2701909/