Calling Python from an expression

Written by Ben Dickson on .

You can easily call Python methods from within expressions, similar to calling Tcl expressions from Python via nuke.tcl()

To do this, you use the "python" Tcl method, for example:

[python nuke.thisNode().metadata().keys()]

While this is mostly straight-forward, there are a few things to be aware of..

Square brackets in the Python expression clash with Tcl's syntax, or should either be escaped:

[python nuke.thisNode().metadata()\['input/filename'\]]

 

..or enclose the Python code in { } (this is what the "Py" button in the edit-expression dialog does):

[python {nuke.thisNode().metadata['input/filename']}]

 

Note that if the expression errors, it returns a string containing the exception's message. The following will evaluate to a string containing "name 'fakefunction' is not defined":

[python fakefunction()]

In other words, if the Python function fails, it will not cause the Tcl expression to error. This can cause problems in some (admittedly obscure) situtations, for example, say you use a [python ...] expression to calculate the autosave filename. If the method fails for some reason (error in the script, missing import etc) - you end up with autosave files called "name 'myautosavepath' is not defined".

One last thing - it is usually far more succinct to use a standard Tcl expression, instead of calling Python. I.e my first example is far shorter when written as a Tcl expression:

1
[metadata]

While calling Python from Tcl does not seem to be noticeably slower, the Python equivalents can quickly get long and hard to read (especially if characters like [ ] need to be escaped), so try to only use this where necessary (i.e when you have existing Python code/modules you wish to use)

You have no rights to post comments

We have 3905 guests and 38 members online