简体   繁体   中英

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

I have a python file sample.py with two functions. So here I want to call the specific python function from tcl script, also I want to passing an argument to that python function. Could you please share your ideas. I don't know whether it is possible. Your answers will be more helpful for us.

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. Tcl can then capture the printed output:

$ 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:

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. It's trivial for numbers, and requires care with quoting for strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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