PYTHON STARTER KIT

If you are new to Python in Nuke I put together a following list of snippets that can help you remember the basics and to have a toolset for more common tasks for compositors. 

Using python in a script editor is a powerful tool with many possible use.

Python itself is an interpreted, high-level, general-purpose programming language.

For more visit Wikipedia.

 

If you feel like you are in need of a proper guidance into the world of Python in Nuke the Foundry has a Python Developers Guide.

To make it more efficient for artists to use python in Nuke the Foundry developed `Nuke Python API` (API = Application Programming Interface) which is basically a bunch of specified commands (functions and modules) that Nuke can interpret and execute. You can find HERE.

To make sure your code stays in the script editor I recommend

a following setup for your Preferences:

The save and restore script editor history is usually on by default but it is better to check.

The echo python commands to output window is off by default but I recommend to use it 

as it is a good way to learn what certain commands looks like in python.

In the script editor when you run a code using a button or the Ctrl+Enter shortcut

it runs all the code in the input pane. To keep the code there for later use the best practise 

is to select a code that you want to run.

### FIRST STEP ###


print ("Hello World!")


### USING VARIABLE ###


name = 'Attila'
age = '30'
country = 'Hungary'
print ('Hello, my name is  ' + name + '! I am ' + age + '. I am from ' + country)

name = 'Attila'
age = 30
country = 'Hungary'
print("Hello, my name is  %s! I am %d. I am from %s." % (name, age, country))

# %d will truncate to integer, %s will maintain formatting, %f will print as float and %g is used for generic number

name = 'Attila'
age = 30
country = 'Hungary'
print("Hello, my name is  {}! I am {}. I am from {}.".format(name, age, country))

### TYPE CONVERSION ###


# Interger - int(x)

x = 12.8
print type(x)
x = int(x)
print type(x)
print x

# Float - float(x)

x = 12
print type(x)
x = float(x)
print type(x)
print x

# String - str(x)

x = 12.5
print type(x)
x = str(x)
print type(x)
print x


### CREATE A NODE ###
## Functions: createNode, setValue ##

# Can check node's Class with the `i` hotkey
nuke.createNode("Blur")

# Make sure you used a right Class

nuke.createNode("Tracker4")

# Can call nodes that are removed from GUI
nuke.createNode("Blocky")

# Set a value
nuke.createNode("Blur")['size'].setValue(80)

# Set multiple values using a variable
m = nuke.createNode("Blur")
m['channels'].setValue("rgb")
m['size'].setValue(50)
m['mix'].setValue(.5)
m['label'].setValue("Size: [value size]\nChannels: [value channels]\nMix: [value mix]")

# Creating node for scripting
nuke.nodes.Blur()

nuke.nodes.Blur(mix=.5,size=10)


### GETTING KNOB VALUE ###
## Functions: toNode, value, getValue, knob ###


# Calling knobs as list items
nuke.toNode('Blur1')["channels"].value()

# Calling knobs with a function
nuke.toNode('Blur1').knob("channels").value()

nuke.toNode('Blur1')["filter"].getValue()


### SETTING KNOB VALUE ###
## Functions: setValue ##

# Setting single value
nuke.toNode('Blur1')["size"].setValue(10)

# Setting multiple values
b = nuke.toNode('Blur1')
b["size"].setValue(20)
b["mix"].setValue(.8)
b["filter"].setValue(0)
b["channels"].setValue("rgb")

 

### SETTING EXPRESSION VALUE ###
## Functions: setExpression ##

nuke.toNode('Blur1')["size"].setExpression('Blur2.size * 2')

nuke.toNode('Transform1')["filter"].setExpression("Transform2.filter")


### REMOVE ANIMATION / EXPRESSION ###
## Functions: clearAnimated ##


nuke.toNode('Transform1')["filter"].clearAnimated()


### CREATE MULTIPLE NODES WITH `FOR LOOP` ###
## Functions: range ##


for i in range(15):
    i = nuke.createNode("Blur")
    i["channels"].setValue('rgb')
    i["size"].setExpression('Blur1.size')


### CONNECT MULTIPLE NODES TO A SINGLE NODE ###
## Functions: selectedNodes, setInput ##

t = nuke.toNode('Transform1')

nodes = nuke.selectedNodes()
for i in nodes:
    i.setInput(0, t)
    i.setInput(1, None)


### RUN ON ANY SELECTED NODES ###
## Functions: selectedNodes ##


nodes = nuke.selectedNodes()
for node in nodes:
    try:
        node.knob("size").setValue(5)
    except Exception:
        pass


### RUN ON ALL NODES IN A SCRIPT ###
## Functions: allNodes ##


nodes = nuke.allNodes()
for node in nodes:
    try:
        node.knob("size").setValue(20)
    except Exception:
        pass


### RUN AN ALL SPECIFIED CLASSES ###


nodes = nuke.allNodes('Merge2')
for node in nodes:
    node.knob("mix").setValue(.5)


### RUN AN SELECTED SPECIFIED CLASSES ###


nodes = nuke.selectedNodes('Merge2')
for node in nodes:
    try:
        node.knob("mix").setValue(.8)
    except Exception:
        pass


### RUN ON ALL MULTIPLE CLASSES ###


nodes_classes = ["Read", "PostageStamp", "Constant", "ColorBars", "CheckerBoard2", "ColorWheel"]

for node in nuke.allNodes(group=nuke.root()):
    if node.Class() not in nodes_classes:
        continue
    try:
        node["postage_stamp"].setValue(False)
    except Exception:
        pass


### RUN ON SELECTED MULTIPLE CLASSES ###


nuke.root().begin()

nodes_classes = ["Read", "PostageStamp", "Constant", "ColorBars", "CheckerBoard2", "ColorWheel"]

for node in nuke.selectedNodes():
    if node.Class() not in nodes_classes:
        continue
    try:
        node["postage_stamp"].setValue(True)
    except Exception:
        pass
nuke.root().end()


### PATH FOR YOUR NUKE FOLDER ###


nuke.pluginPath()


### PERFORMANCE TIMER ###

#start
nuke.startPerformanceTimers()

#reset
nuke.resetPerformanceTimers()

#stop
nuke.stopPerformanceTimers()


# https://learn.foundry.com/nuke/developers/90/pythondevguide/performance.html

### FUN ###

import webbrowser

sel = nuke.selectedNode()
site = 'https://imgur.com/search/score/?q=cat'
name = nuke.PyScript_Knob('button', '<font color=pink>Click HERE', "webbrowser.open(site)")
sel.addKnob(name)


### NOTES ###

# For checkboxes the value can be True or False that equals to 1 or 0

# For dropdown menu values can be the name of the option or the serial number of the option starting with 0 from the top

# To find the Class of the node select it and press `i` over the NodeGraph

Other useful snippets


 

## Select nodes that starts with a specific string ##
 

for node in nuke.allNodes():

    if node['name'].value().startswith("Multiply"):

        node['selected'].setValue(True)
 

#TIP: Type the name of the node you want to select where the `Multiply` is now.


 

## Changing values in selected nodes ##
 

for i in nuke.selectedNodes() :

    i['value'].setValue(2)
 

#TIP: Type the name of the knob you want to change where the `value` is now.

 

You can find the knob`s name if you hover over the mouse of it as

 

it sometimes not what appears on the node ( e.g.: Grade`s `gain` is called `white`)


 

## Changing values in selected specific class ##
 

for i in nuke.selectedNodes():

    nodeClass = i.Class()

    if nodeClass == 'Multiply':

        i.knob("value").setValue(5)
 

#TIP: You can find out the node`s class if you select one and hit `i` which bring out the information of

the node as the node`s class is not necessarily the node`s name ( e.g.: Merge`s class is `Merge2`)
 

## Removes all animation from selected nodes ##
 

for node in nuke.selectedNodes():

    for knob in node.knobs():

        if nuke.Knob.isAnimated(node[knob]):

            nuke.Knob.clearAnimated(node[knob])


 

## Removes all animation from selected nodes 2 ##
 

for a in nuke.selectedNode().knobs():

    nuke.selectedNode()[a].clearAnimated()


 

## Shows all dependencies of the selected node ##
 

for a in nuke.selectedNode().dependencies():

    print a.name()
 

## Reload all Read nodes ##
 

for s in nuke.allNodes('Read'):

    s['reload'].execute()
 

## List knobs of selected node ##
 

print( nuke.selectedNode() )


 

## Delete all nodes that are not selected ##

 

s = nuke.selectedNodes()

b = nuke.allNodes()

for n in b:

    if n not in s:

        nuke.delete(n)

## Adding $gui to selected nodes` 'disable' knob ##

selectedNode = nuke.selectedNode()

selectedNode["disable"].setExpression("$gui")

 

## Adding expression to a node in a Group ##

 

m = nuke.toNode('NodeName')

m.begin()

nuke.toNode('NodeInGroup').[filter].setExpression(frame')

m.end()

 

#TIP: You can use the setExpression function to add expression to knobs that manually don`t take expressions like `Transform/filter`

 

## Adding image to a node`s `icon` knob ##

nodes = nuke.selectedNodes()

img_path = '/Volumes/...'

for node in nodes:

    node.knob('icon').setValue(img_path)

 

#TIP: `icon` is a hidden knob of every nodes that is empty by standard

#TIP: If you want to remove the image you added change the ending of the code to ...setValue('')

## Links I recommend ##

Hope you will find it useful! 

© 2014 by GATIMEDIA