a Python package for Tcl

上一篇 / 下一篇  2009-07-06 22:02:37 / 个人分类:TCL

This package allows the execution of Python code from a Tcl interpreter, as in:
package require tclpython 4
set interpreter [python::interp new]
$interpreter exec {print("Hello World")}
puts [$interpreter eval 3/2.0]
python::interp delete $interpreter
which outputs:
Hello World
1.5

and, starting with version 4.0, execution of Tcl code from Python interpreters, as in:

package require tclpython 4
set interpreter [python::interp new]
puts [$interpreter eval {tcl.eval('clock format [clock seconds]')}]
python::interp delete $interpreter

It works by creating one or more embedded Python interpreters and sending them strings to evaluate or execute. Modules can be loaded in the Python interpreter as if it were the real Python program.

The commands created by the package are very simple:

  • python::interp new
  • python::interp deleteinterpreter
  • interpreterevalscript.
  • interpreterexecscript.

As expected,evalreturns the Python interpreter result or reports an error at the Tcl level when the Python interpreter itself fails in executing the code string, whileexecsimply lets the Python interpreter execute the code and returns nothing or eventually report an error.

You can create several Python interpreters, if the tclpython package was linked against a Python library compiled with threads support, otherwise only 1 Python interpreter can exist at a time.

Notes:

  • for Python 2.2 and above, the automaticimport siteon a new thread is suppressed because it otherwise makes the program hang (you can still useimport sitein your code, as described at the top of theLib/site.pyfile).
  • on aRedhatsystem, use the tclpythonrpmon my homepage.
  • tclpython is used by themoodsssystem monitoring software (information on my homepage) to allow its modules to be written in Python as well as Tcl and Perl.

Upgrading from tclpython version 2

In tclpython version 2, only theevalcommand was available to an interpreter. Some such invocations, generally that return nothing, need to be converted to theexeccommand, as the following examples show:

  • $interpreter eval {print("Hello World")} ;# version 2
    $interpreter exec {print("Hello World")} ;# version 3 or 4
  • $interpreter eval {def initialize(): pass} ;# version 2
    $interpreter exec {def initialize(): pass} ;# version 3 or 4
  • # version 2:
    set exists [$interpreter eval "try: type(initialize) == FunctionType\nexcept: 0"]
    # version 3 or 4:
    $interpreter exec "try: result = (type(initialize) == FunctionType)\nexcept: result = 0"
    set exists [$interpreter eval result]

Send your comments, complaints, ... tojfontain@free.fr.
My homepage is athttp://jfontain.free.fr/.


TAG:

 

评分:0

我来说两句

日历

« 2024-04-26  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 30737
  • 日志数: 37
  • 建立时间: 2008-07-09
  • 更新时间: 2009-07-23

RSS订阅

Open Toolbar