user2251503
user2251503

Reputation: 197

Call Python functions from TCL script with arguments

I have a Python script, say, sample.py with 2 functions func1() and func2():

def func1():
    print("Called Function 1")

def func2():
    print("Called Function 2")

How do I call this function func2() from the Tcl script and also how to pass the arguments to that function?

Upvotes: 2

Views: 3142

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137777

The best method is probably to see if tclpython will work for you. (Download links on http://jfontain.free.fr/; pick the one(s) you need.) That should let you write code like this:

# Set up a python interpreter
package require tclpython
set py [python::interp new]

# Load a file in with your definitions
$py exec {
    # This is Python code, embedded directly in Tcl
    evalfile("sample.py")
}

# Evaluate a python expression (in this case, call an argument-less function)
set result [$py eval func2()]

# Dispose of the python interpreter
python::interp delete $py

Upvotes: 1

Ron Norris
Ron Norris

Reputation: 2690

python code needs this (I called it junk.py and put it in the same folder with tcl script).

import sys

def func1():
    print("Called Function 1")

def func2():
    print("Called Function 2")

if __name__ == '__main__':
    eval(sys.argv[1] + '()')

Tcl file called test_tcl.tcl:

set out [exec python junk.py [lindex $argv 0]]
puts $out

Execute from command line:

tclsh test_tcl.tcl func1

Output is:

Called Function 1

Upvotes: 3

Related Questions