且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 Python 运行 TCL 代码(在现有的 TCL shell 上)

更新时间:1970-01-01 07:57:42

首先:如果你只是想要一个基于类的 OO 系统来编写你的代码,你不需要 python,Tcl 可以很好地做 OO.(内置于 8.6,但在旧版本中也有很多选项可以获取 OO 功能、类等,例如 Tcllibs SNITSTOOOP

First: If you just want a class based OO system to write your code in, you don't need python, Tcl can do OO just fine. (built in with 8.6, but there are quite a few options to get OO features, classes etc. in older versions too, e.g. Tcllibs SNIT or STOOOP

如果您仍然觉得 Python 是手头任务的高级工具(例如,由于对某些任务有更好的库支持),您可以使用 Tcllib comm 包远程控制"Tcl 解释器.这需要您想要控制的 Tcl shell 中的工作事件循环,否则它很容易做到.

If you still feel Python is the superior tool for the task at hand (e.g. due to better library support for some tasks), you can 'remote control' the Tcl interpreter using the Tcllib comm package. This needs a working event loop in the Tcl shell you want to control, but otherwise it is pretty simple to do.

在你的 Tcl shell 中,安装 Tcllib comm 包.(如果您需要帮助,请再次询问)

In your Tcl shell, install the Tcllib comm package. (ask again if you need help with that)

完成后,在 Tcl shell 中启动通信服务器.

Once you have that, start the comm server in your Tcl shell.

package require comm
set id [::comm::comm self]
# write ID to a file
set fd [open idfile.txt w]
puts $fd $id
close $fd
proc stop_server {} {set ::forever 1 }
# enter the event loop
vwait forever

在 python 方面,你几乎可以做同样的事情,只是在 Tkinter 代码中.

On the python side, you do nearly the same, just in Tkinter code.

基本上是这样的:

import Tkinter
interp = Tkinter.Tcl()
interp.eval('package require comm')

# load the id
with open('idfile.txt') as fd:
    comm_id = fd.read().strip()

result = interp.eval(
    'comm::comm send {0!s} {1!s}'.format(comm_id, '{puts "Hello World"}')

使用 python 代码和你的 shell,你应该看到 Hello World 打印在你的 shell 中.

Using that python code and your shell, you should see Hello World printed in your shell.

阅读通信手册了解更多细节,如何保护事物,获取回调等.comm

Read the comm manual for more details, how to secure things, get callbacks etc. comm

如果您不喜欢 tkinter 的负担,您也可以为 comm 实现有线协议,在 Twisted 或 Python 3.x 中新的异步支持中应该不会太难.在线协议记录在:通信线路协议

If you don't like the tkinter burden, you can implement the wire procotol for comm too, should not be too hard in Twisted or with the new async support in Python 3.x. The on the wire protocol is documented in: comm wire protocol