简体   繁体   English

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

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

I have a python file sample.py with two functions. 我有一个带两个功能的python文件sample.py So here I want to call the specific python function from tcl script, also I want to passing an argument to that python function. 所以在这里我想从tcl脚本调用特定的python函数,也想将参数传递给该python函数。 Could you please share your ideas. 您能否分享您的想法。 I don't know whether it is possible. 不知道有没有可能 Your answers will be more helpful for us. 您的答案将对我们更有帮助。

sample.py sample.py

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

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

Looks like you need to launch a python interpreter, read the sample script, invoke the function, and print the result. 看来您需要启动python解释器,阅读示例脚本,调用函数并打印结果。 Tcl can then capture the printed output: Tcl然后可以捕获打印的输出:

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

With tclpython , you can do an in-process evaluation: 使用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

The main thing to watch out for is the quoting of complex values being passed into the Python code, as you're using evaluation. 需要注意的主要事情是在使用评估时,将复杂值的引用传递给Python代码。 It's trivial for numbers, and requires care with quoting for strings. 对于数字而言,这是微不足道的,并且在引用字符串时需要格外小心。

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

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