繁体   English   中英

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

[英]How to call the python function from TCL script by passing an argument?

我有一个带两个功能的python文件sample.py 所以在这里我想从tcl脚本调用特定的python函数,也想将参数传递给该python函数。 您能否分享您的想法。 不知道有没有可能 您的答案将对我们更有帮助。

sample.py

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

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

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

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

使用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代码。 对于数字而言,这是微不足道的,并且在引用字符串时需要格外小心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM