如何通过传递参数从TCL脚本调用python函数?

2024-09-28 20:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python文件sample.py,有两个函数。所以这里我想从tcl脚本调用特定的python函数,同时我还想将一个参数传递给那个python函数。你能谈谈你的想法吗。我不知道这是否可能。你的回答会对我们更有帮助。在

样品.py

def f1(a,b,c):
    x = a + b + c
    retun x

def f2(a,b):
    x = a + b
    return x

Tags: 文件sample函数py脚本returndef样品
2条回答

使用tclpython,可以执行进程内评估:

package require tclpython

set a 3
set b 5

# Make a Python system within this process
set py [python::interp new]

# Run some code that doesn't return anything
$py exec {import sample}

# Run some code that does return something; note that we substitute a and b
# *before* sending to Python
set result [$py eval "sample.f2($a,$b)"]
puts "result = $result"

# Dispose of the interpreter now that we're done
python::interp delete $py

在使用求值时,要注意的主要问题是引用传递到Python代码中的复杂值。对于数字来说这是微不足道的,并且需要小心引用字符串。在

看起来您需要启动一个python解释器,读取示例脚本,调用函数,然后打印结果。然后,Tcl可以捕获打印输出:

$ tclsh
% set a 3
3
% set b 5
5
% set result [exec python -c "import sample; print sample.f2($a,$b)"]
8

相关问题 更多 >