user2251503
user2251503

Reputation: 197

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

Upvotes: 0

Views: 843

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137577

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.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246807

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

Upvotes: 2

Related Questions