Python Code Snippets

This is where I keep my python code snippets

This page contains a collection of python scripts that you might find handy. I have included a small description for each about what they do, and how you might use them

Use Ctrl+F in your browser to search the page for what you are looking for!

If you really want to learn more about Python, I suggest this tutorial by W3 schools

or this official documentation by The Foundry

Fundamentals

Manipulating Knob Values

Almost everything in Nuke uses knobs to store its values, and as a result most scripting boils down to getting, or setting knob values in some capacity. There are three main ways to interact with knobs, targeting a specific node by name with nuke.toNode(), a selected node with nuke.selectedNode(), or when using python buttons, or callbacks you can use nuke.thisNode() to tell the script to look for knobs on the same node it exists on

Targeting a specific node

##setting knob values
nuke.toNode("Blur1").knob('size').setValue(100)
#or
nuke.toNode("Blur1")['size'].setValue(100)

##getting knob values as numbers 
nuke.toNode("Blur1").knob('filter').getValue()
#or
nuke.toNode("Blur1")['filter'].getValue()

##getting knob values as strings 
nuke.toNode("Blur1").knob('filter').value()
#or
nuke.toNode("Blur1")['filter'].value()

##getting knob values at a specific frame 
nuke.toNode("Blur1").knob('size').valueAt(100)
#or
nuke.toNode("Blur1")['size'].valueAt(100)

Targeting a selected node

##setting knob values
nuke.selectedNode().knob('size').setValue(100)
#or
nuke.selectedNode()['size'].setValue(100)

##getting knob values as numbers 
nuke.selectedNode().knob('filter').getValue()
#or
nuke.selectedNode()['filter'].getValue()

##getting knob values as strings 
nuke.selectedNode().knob('filter').value()
#or
nuke.selectedNode()['filter'].value()

##getting knob values at a specific frame
nuke.selectedNode().knob('size').valueAt(100)
#or
nuke.selectedNode()['size'].valueAt(100)

Targeting the current node

##setting knob values
nuke.thisNode().knob('size').setValue(100)
#or
nuke.thisNode()['size'].setValue(100)

##getting knob values as numbers 
nuke.thisNode().knob('filter').getValue()
#or
nuke.thisNode()['filter'].getValue()

##getting knob values as strings 
nuke.thisNode().knob('filter').value()
#or
nuke.thisNode()['filter'].value()

##getting knob values at a specific frame
nuke.thisNode().knob('valueAt').value(100)
#or
nuke.thisNode()['valueAt'].value(100)

Knobs With Multiple Values

Some knobs, like the colour and bbox knobs, store multiple values in a list, and as a result interacting with them is a bit different. We use the same getValue()/setValue() methods above, but we now have to specify what value to target. We can do this by providing a list index within the brackets

##get red value only
nuke.toNode('Grade1').knob('white').getValue(0)
##get green value only
nuke.toNode('Grade1').knob('white').getValue(1)
##get blue value only
nuke.toNode('Grade1').knob('white').getValue(2)
##get alpha value only
nuke.toNode('Grade1').knob('white').getValue(3)

#or

##get all values at once
nuke.toNode('Grade1').knob('white').getValue()

##set red value only
nuke.toNode('Grade1').knob('white').setValue(1.1, 0)
##set green value only
nuke.toNode('Grade1').knob('white').setValue(1.2, 1)
##set blue value only
nuke.toNode('Grade1').knob('white').setValue(1.3, 2)
##set alpha value only
nuke.toNode('Grade1').knob('white').setValue(1.4, 3)

#or

##set all values at once
nuke.toNode('Crop1').knob('box').setValue((10, 20, 30, 40))

Printing Things

Print is a way to politely ask python to tell you exactly what it is doing. This is very useful for debugging your scripts, and collecting information

##print a general statment for a user to read
print ("I don't get paid enough!")

##print the data stored in a knob
print (nuke.selectedNode().knob('name').value())

#or use a variable
nodeName = nuke.selectedNode().knob('name').value()
print(nodeName)

##insert variables into a string using concatenation
firstName = "Hiram"
lastName = "Gifford"
print("Hello " + firstName + " " + lastName + "! Welcome to Python for Nuke")

##insert variables into a string using formatting
firstName = "Hiram"
lastName = "Gifford"
print("Hello {} {}! Welcome to Python for Nuke".format(firstName,lastName))

##check a string for a word and print a conditional statement based on result
mystring = "the secret to success is learning python"
if "success" in mystring: 
    print ("Success found!")
else:
    print ("Success not found :(") 

Selecting/Deselecting Nodes

Here’s how you can select or deselect nodes without moving a finger

##selecting a node
nuke.toNode("Blur1").knob('selected').setValue(True)
#or
nuke.toNode("Blur1")['selected'].setValue(True)

##deselecting a node
nuke.toNode("Blur1").knob('selected').setValue(False)
#or
nuke.toNode("Blur1")['selected'].setValue(False)

##selecting all nodes
for node in nuke.allNodes():
    node.knob('selected').setValue(True)
#or
for node in nuke.allNodes():
    node['selected'].setValue(True)

##deselecting all nodes
for node in nuke.selectedNodes():
    node.knob('selected').setValue(False)
#or
for node in nuke.selectedNodes():
    node['selected'].setValue(False)

Variables

A variable is a container for data. We create them to store, and reuse important things throughout the rest of the script

You can learn more about Python variables here

##create a variable to store a value and use it elsewhere
newValue = 10
nuke.toNode("Blur1").knob('size').setValue(newValue)

##create a variable to store a list of values and use them elsewhere
newValues = [10, 20, 30, 40]
nuke.toNode("Crop1").knob('box').setValue(newValues)

##create a variable for Grade1 and use it to get the channel knob value and select the node
myGrade = nuke.toNode("Grade1")
print (myGrade.knob('channels').value())
myGrade.knob('selected').setValue(True)

##use a variable to store a list of nodes and iterate through them
myGrades = nuke.selectedNodes()
for node in myGrades:
    node.knob('channels').setValue("rgba")

Get Node Class

The class of a node is not the same as the name. A user can change the name of a node to anything they want, so we often use the unchangeable class value to reliably find, create and manipulate things with python. This can also be done in the GUI by selecting a node and hitting the “i“ hotkey

##Get selected nodes class
nodeClass = nuke.selectedNode().Class()
print (nodeClass) 

Creating Nodes

There are a few different way to create nodes in nuke, and alter their knob values post creation

##create node
nuke.createNode('Blur')
#or
nuke.nodes.Blur()

##create node and don't open the properties panel
nuke.createNode('Blur', inpanel=False)
#or
nuke.nodes.Blur()

##create node and set a value 
nuke.createNode('Blur', 'size 11')
#or
nuke.nodes.Blur(size=11)

##create node and set multiple values 
myBlur = nuke.createNode('Blur')
myBlur.knob('size').setValue(111)
myBlur.knob('channels').setValue("rgba")
#or
nuke.nodes.Blur(size=11, quality=14, channels="rgba")

If, Elif & Else

So you want to take the scripts outlined above, and only run them if a condition is met? Python if statements are what you need!

You can read more about Python if statements here

##sets the quality value depending on filter type, and returns a message if it doesn't recognize the type
myBlur = nuke.toNode("Blur1")
myBlurFilter = myBlur.knob('filter').value()
if myBlurFilter == "gaussian":
    myBlur.knob('quality').setValue(15)      
elif myBlurFilter == "box":
    myBlur.knob('quality').setValue(10)         
else:
    nuke.message('Filter value not found')

For & While Loops

So you want to take the scripts outlined above, and do more with them, faster? Python loops are what you need!

You can read more about Python For Loops and While Loops at these links

##change knob values on all selected blur nodes
for myBlurs in nuke.selectedNodes():
    myBlurs.knob('size').setValue(100)
    myBlurs.knob('channels').setValue("rgba")
    myBlurs.knob('quality').setValue(20)
#or
for myBlurs in nuke.selectedNodes():
    myBlurs['size'].setValue(100)
    myBlurs['channels'].setValue("rgba")
    myBlurs['quality'].setValue(20)

##create 10 blur nodes and set their knob values
myBlurs = 0
while (myBlurs < 10):
    myBlurs = myBlurs + 1
    newBlur = nuke.nodes.Blur()
    newBlur.knob('size').setValue(10)
#or
myBlurs = 0
while (myBlurs < 10):
    myBlurs = myBlurs + 1
    newBlur = nuke.nodes.Blur()
    newBlur['size'].setValue(10)

Try & Except

Try/except can be used in a similar way to if/else, but these are better for catching errors. In the below script we can try to set a knob value, and if the value isn’t accepted by the knob type (In this case we are trying to set a string value on a knob that only accepts integers and floats) it will print a specific message to the user

You can read more about Python exception handling here

##try to set new value, if valueError exception is hit, print message
node = nuke.selectedNode()
newValue = "100"

try:
  node.knob('size').setValue(newValue)
except ValueError:
  print("Knob class doesn't accept this value type")
except:
  print("Not sure what's wrong, please see error logs")

Setting & Removing Inputs

After making a node, or finding one with the methods above, you will often want to connect/disconnect it

##create a new node, connect it to what is selected, and place it right below
nuke.nodes.Blur().setInput(0, nuke.selectedNode())

##connect two known nodes together
InputNode = nuke.toNode("Blur1")
OutputNode = nuke.toNode("Grade1")
OutputNode.setInput(0,InputNode)

##create two nodes and connect them to a merge 
myBlur = nuke.nodes.Blur()
myGrade = nuke.nodes.Grade()
myMerge = nuke.nodes.Merge(inputs=[myBlur, myGrade])


##disconnect selected nodes 0 input
nuke.selectedNode().setInput(0, None)

##disconnect all inputs from selected node
for input in range(0, nuke.selectedNode().inputs()):
    nuke.selectedNode().setInput(input, None)

Moving Nodes Around

Why do it the hard way? Here’s how you can use python to quickly get and set node positions in the node graph

##get selected nodes position in the node graph
node = nuke.selectedNode()
print ("xpos = " + str(node['xpos'].value()))
print ("ypos = " + str(node['ypos'].value()))

##set selected nodes position in the node graph
node = nuke.selectedNode()
node['xpos'].setValue( 100 )
node['ypos'].setValue( -25 )
#or
node = nuke.selectedNode()
node.setXpos( 100 )
node.setYpos( -25 )
#or
node = nuke.selectedNode()
node.setXYpos( 100, -25 )

Getting Help

In Nukes Script editor you can access documentation directly using the help() statement. This will print out a description similar to what you can find in the official documentation online

##get overall help
help()

##pick a category of help
help("modules")
help("keywords")
help("topics")

##examples of using help on a specific module/topic or keyword
help("zlib")
help("LOOPING")
help("elif")

#examples of using help on a specific nuke node/knob/function
help(nuke.root)
help(nuke.Knob.setExpression)
help(nuke.activeViewer)

Advanced

Functions

A function is used to define a block of code, which only runs when called. This allows us to reuse it elsewhere, as many times as we want, and pass each instance unique parameters

##define a function with 3 parameters  
def set_knob_values(node_class,knob_name,knob_value):
    #put any script inside the function
    CLASS_SEARCH = nuke.allNodes(node_class)
    for node in CLASS_SEARCH:
        if node.knob(knob_name):
            node.knob(knob_name).setValue(knob_value)

##then reuse the function with unique data for each parameter anywhere
set_knob_values("Grade", 'white', 2)
set_knob_values("Blur", 'size', 100)
set_knob_values("Merge2", 'operation', "plus")

Working Inside Groups

By default python scripts will usually only run at the root, or top level of the node graph. If you want to change things within groups, or from within groups, there are a few extra steps

##tells python to run within a specific group
myGroup = nuke.toNode('Group1')
myGroup.begin()
for node in nuke.allNodes():
    if node.Class() == "Shuffle":
        node['selected'].setValue(True)

myGroup.end()

#or
for node in nuke.toNode('Group1').nodes():
    if node.Class() == "Shuffle":
        node['selected'].setValue(True)

#or
for node in nuke.allNodes(group = nuke.selectedNode()):
    if node.Class() == "Shuffle":
        node['disable'].setValue(True)

##print group name from inside group
group = '.'.join(nuke.thisNode().fullName().split('.')[:-1])
groupNode = nuke.toNode(group)
print (groupNode.name())

##run a script at the root level from within a group
with nuke.root():
    #put any script below here to run at root
    nuke.nodes.Blur()

##tells python to run within all groups and at the root level
shuffle_nodes = [node for node in nuke.allNodes(recurseGroups=True) if node.Class() == 'Shuffle']

for n in shuffle_nodes:
    if 'disable' in n.knobs():
        n['disable'].setValue(True)

##tells python to run within all groups and NOT at the root level
group_nodes = [node for node in nuke.allNodes() if node.Class() == 'Group']

for group in group_nodes:
    with group:
        shuffle_nodes = [node for node in nuke.allNodes(recurseGroups=True) if node.Class() == 'Shuffle']
        
        for n in shuffle_nodes:
            if 'disable' in n.knobs():
                n['disable'].setValue(True)

Manipulating Animations

Use these scripts to manipulate animations and expressions with Python

##set keyframe on knob by first setting it to be animated and then providing a value
nuke.selectedNode().knob('disable').setAnimated()
nuke.selectedNode().knob('disable').setValue(1)

##set keyframe on knob at a specific frame
nuke.selectedNode().knob('disable').setAnimated()
nuke.selectedNode().knob('disable').setValueAt(1,100)

##set expression on knob
nuke.selectedNode().knob('disable').setExpression('$gui')

##get expression on knob
nuke.selectedNode().knob('disable').toScript()

##create a link expression from one node to another
nuke.selectedNode().knob('size').setExpression("Blur1.size")

##copy expression from one nodes knob to another
myBlur = nuke.toNode("Blur1").knob('size')
yourBlur = nuke.toNode("Blur2").knob('size')
yourBlur.copyAnimations(myBlur.animations())

##check if a knob has animation
nuke.selectedNode().knob('size').isAnimated()

##check if a knob has an expression
nuke.selectedNode().knob('size').hasExpression()

##check if a knob has a keyframe at the current frame
nuke.selectedNode().knob('size').isKey()

##check if a knob has a keyframe at a specific frame
nuke.selectedNode().knob('size').isKey(100)

##remove all animation/expressions from knob
nuke.selectedNode().knob('size').clearAnimated()

Using startswith()

It’s generally safer to search for nodes by class, but sometimes that isn’t possible, like with group/gizmo based tools. An alternative is to search by name, but use the startswith() method. This tells python check the string from start to end for a matching word and ignore any letters that come after it. So a search for “Blur” will return a list of Blur1, Blur2, Blur119, but not MyBlur

You can learn more about Python string methods here

##finds blurs by the start of the node name
for node in nuke.allNodes():
    nodeName = node['name'].value()
    if nodeName.startswith("Blur"): 
        node['selected'].setValue(True)

Performance Timers

Nuke has the ability to profile all the nodes within a script, and show how much resources they are using. This is very useful for optimizing heavy scripts or diagnosing issues with tools that might be on the heavy side.

Below is the older method of running performance timers, if you are using Nuke 11.1 or higher I suggest using the new Profile Node instead

##enables performance timers for all nodes in script
nuke.startPerformanceTimers()

##disables performance timers for all nodes in script
nuke.stopPerformanceTimers()

##keeps the timers running, but resets them to default
nuke.resetPerformanceTimers()

Working With Tile Colours

Node colours are stored in a knob called ‘tile_color’ as a whole number. You can manually change this knob on any node, and then use the first script below to find out its number, to use it elsewhere. Alternatively you might prefer working with HEX codes, in which case use the last script to convert them into something nuke understands

##get a nodes tile colour as whole number
nuke.selectedNode().knob('tile_color').value()

##set a nodes tile colour based on a whole number
nuke.selectedNode().knob('tile_color').setValue(59309311)

##set a nodes tile colour based on a HEX code. 
##make sure to add "ff" to the end of the HEX code or it won't work!
nuke.selectedNode().knob('tile_color').setValue(int("eb4034ff", 16))

Node Dependencies & Dependents

When you want to find out what node is connect to another’s input, you want to find its dependencies

When you want to find all the nodes connected to the output, you want to find its dependent nodes

Both of these methods return a list of nodes connected to either the inputs or output of the selected node. You can then use a for loop to iterate through the list, and return a specific value, like the nodes name, as show in the last two examples below

##get a nodes dependencies (Upstream/Inputs) by node
NodeDependencies = nuke.selectedNode().dependencies()
print (NodeDependencies)

##get dependent nodes (Downstream/Outputs) by node
dependantNodes = nuke.selectedNode().dependent()
print (dependantNodes)


##get a nodes dependencies (Upstream/Inputs) by name
NodeDependencies = nuke.selectedNode().dependencies()
for node in NodeDependencies:
    nodeName = node['name'].value()
    print (nodeName)

##get dependent nodes (Downstream/Outputs) by name
dependantNodes = nuke.selectedNode().dependent()
for node in dependantNodes:
    nodeName = node['name'].value()
    print (nodeName)

Metadata

Metadata can store a lot of important information! Every pipeline is a bit different, but it’s worth checking out what metadata is available to you, it may contain important info like what version of anim/fx were used in the lighting file, the camera information, artist names, etc…

##get all metadata from node
nuke.toNode("Read1").metadata()

##get specific metadata from node
nuke.toNode("Read1").metadata('exr/dataWindow')

Knob Flags

Knobs have some special, kind of secret features called Flags, which can be used to tell knobs how to behave. One of the most common ones I’ve seen is the INVISIBLE flag, if you’ve ever used a tool where knobs appear, and disappear when you press a button, or change a dropdown, it could be using this Flag

All flags have a name, and an ID number. Try to set/clear your flags with the name first because it is more readable, but I find that the name doesn’t always work, in which case you can fall back on the ID numbers

You can read more about all the types of Knob Flags here

##set flag by name
nuke.selectedNode().knob('box').setFlag(nuke.INVISIBLE)

##set flag by ID number
nuke.selectedNode().knob('box').setFlag(0x0000000000000400)

##remove flag by name
nuke.selectedNode().knob('box').clearFlag(nuke.INVISIBLE)

##remove flag by ID number
nuke.selectedNode().knob('box').clearFlag(0x0000000000000400)

Callbacks

Coming soon…

##nothing here but hopes and dreams

Getting Nukes Version Number

Often when making scripts/tools you run into compatibility issues, where a feature doesn’t exist in older versions. You can use these snippets, combined with if/else statements, to find out what version the user is currently in, and alter your code to fit the situation

##get major version - e.g. 12
nuke.NUKE_VERSION_MAJOR

##get minor version - e.g. 2
nuke.NUKE_VERSION_MINOR

##get version release number - e.g. 11
nuke.NUKE_VERSION_RELEASE

##get all of the above as a combined string - e.g. '12.2v11'
nuke.NUKE_VERSION_STRING

##get release date - e.g. 'Jul 13 2022'
nuke.NUKE_VERSION_DATE

Helpful Snippets

Select All Nodes By Class

This is how you might uses a class based search, instead of a name based on to find a certain type of node. A class based search is much more reliable and generally preferred when possible, because a node class never changes

##selects all nodes of a class
for node in nuke.allNodes("Blur"):
    node['selected'].setValue(True)

#or
for node in nuke.allNodes():
    if node.Class() == "Blur":
        node['selected'].setValue(True)

Print All Knobs

This will print out a list of all visible and invisible knobs on the selected node(s). A lot of nuke nodes have knobs which are not visible in the properties, node info, or in the “Manage User Knobs” window and this can help you get their proper names for other python scripts

#prints all visible and invisible knobs by name only 
for knob in nuke.selectedNode().knobs():
    print knob

#prints all visible knobs by name and knob class
for knob in nuke.selectedNode().allKnobs():
    print( "Knob Name = " + knob.name() + " - " + "Knob Class = " + knob.Class() )

Create Knobs

This will print allow you to create knobs dynamically via python. This is useful for tools where the UI needs to be responsive to incoming data, or user interactions, and can’t be rigid like tradition gizmos

#creates a new knob on the top level of a group to a internal node
node = nuke.selectedNode()
knob = nuke.Channel_Knob("knob_name", "Knob Label")
node.addKnob(knob)

#creates a linked knob on the top level of a group to a internal node
node = nuke.selectedNode()
linkKnob = nuke.Link_Knob("knob_name", "Knob Label")
linkKnob.setLink('Shuffle1.in1')  
node.addKnob(linkKnob)

Delete Selected Nodes

This is a useful little clean up script that can be used to delete any selected nodes

##delete selected nodes
for PURGE in nuke.selectedNodes(): 
    nuke.delete(PURGE)

Remove Animation From All Knobs

This is a useful little clean up script that can be used to delete any animation from selected nodes

##remove all animation on selected nodes
for node in nuke.selectedNodes():
    for knob in node.knobs():
        node.knob(knob).clearAnimated()

Find All Knobs With Animation

This script can be used to find all knobs with keyframe animation on them, it ignores expressions and prints the node and knob name in script editor

##find nodes and their keyframed knobs
nodes_with_keyframed_knobs = []

for node in nuke.allNodes():
    keyframed_knobs = []
    for knob_name, knob in node.knobs().items():
        if knob.isAnimated() and not knob.hasExpression():
            keyframed_knobs.append(knob_name)
    if keyframed_knobs:
        nodes_with_keyframed_knobs.append((node.name(), keyframed_knobs))

##print out nodes and their keyframed knobs
for node_name, keyframed_knobs in nodes_with_keyframed_knobs:
    print(f"Node: {node_name} - Keyframed Knobs: {', '.join(keyframed_knobs)}")

Set Selected Nodes Tile Colour Based On A HEX Code

You can use an online colour picker like this one to generate a HEX code and then batch change a group of nodes to that colour by selecting them and running this script. You can also do this with the Ctrl+Shift+C hotkey in nuke if you don’t have a HEX Code already, and just want to pick a colour in the moment

##recolor selected nodes based on a hex value
hexValue = "5c2959"
newColour = (hexValue + "ff")
nodeToColour = nuke.selectedNodes()
for node in nodeToColour:
    node['tile_color'].setValue(int(newColour, 16))

Print All Plugin Paths

This will print out a list of all the plugin paths nuke has access to. This can be useful when trying to diagnose why a gizmo, script or toolset won’t load into nuke. If it’s not in the printed results, then nuke can’t see it

#print plugin paths
for path in nuke.pluginPath():
    print path

Find All Knobs With $gui Expression

This will search all nodes in the script for knobs that use the $gui expression, and then print out the node/knob name to the script editor. It will also select them and focus the node graph on them. I find this handy when troubleshooting a script that isn’t rendering correctly, often times it’s because the artist has $gui scripts they don’t know about, or have forgotten

#finds and prints all knobs that have a $gui expression on them
for node in nuke.allNodes():
    for knob in node.knobs():
        if node[knob].hasExpression():
            if '$gui' in node[knob].toScript():
                print (node.name() + (" Knob = ") + knob)
                node['selected'].setValue(True)

#zooms the dag to show the nodes with the $gui expression                
nuke.zoomToFitSelected()

Find All Node Label Knobs With A Certain Character

This will search all nodes in the script for label knobs that contain a specific character, and then print out the node name to the script editor. In some environments you can run into errors rendering on the farm because of the use of special characters. These errors can look like this "ERROR: 'ascii' codec can't decode byte 0xc2 in position 126224: ordinal not in range(128)" in the render logs

##put bad character here
badCharacter = "Â"

##find all nodes with labels containing bad character
for node in nuke.allNodes(recurseGroups = True):
    if node.knob('label'):
        labelValue = node.knob('label').value()
        if badCharacter in labelValue:
            if node.parent().name() != "Root":
                groupNode = node.parent().name()
                print (" > ".join((groupNode, node.name())))
            else:
                print node.name()

Organize Nodes With Custom Spacing

This function can line up a group of selected nodes beside each other with custom spacing between each in the x axis

##Organize nodes with custom spacing in the x axis
def organize_nodes():
    nodesToOrganize = nuke.selectedNodes()
    relativeXpos = int(nuke.selectedNode().knob('xpos').value())
    relativeYpos = int(nuke.selectedNode().knob('ypos').value())
    spacing = 150

    for node in nodesToOrganize:
        node.setXpos(relativeXpos)
        node.setYpos(relativeYpos)
        relativeXpos += spacing

Reset Viewer Gain/Gamma & Proxy

These can be used to reset the all viewers in a script to their default states

##disables proxy mode to stop nuke files from crashing on the farm
def disableProxyMode():
    nuke.root().knob('proxy').setValue(0)

##resets viewer gain and gamma controls to defaults on load
def reset_viewers_gain_gamma():
    for node in nuke.allNodes():
        if node.Class() == 'Viewer':
            node.knob('gain').setValue(1)
            node.knob('gamma').setValue(1)

Check If A Node Exists

This snippet will check for a node by name, and only execute the script if it is found, otherwise it returns a message to the user saying that the node is missing, and what its name should be. This simple logic structure can be very useful in user scripts that are dependent on something existing to run

##check if a node exists and run a script if it does
nodeName = ("Blur1")
checkForNode = nuke.exists(nodeName)
if str(checkForNode)=="True":
    nuke.toNode(nodeName).knob('size').setValue(100)
        
else:
    nuke.message("Node '%s' is missing" % nodeName)

Connect Two Nodes If They Exist

This function allows you to connect two nodes together by their 0 input, if they exist, otherwise it does nothing. These kinds of scripts are useful for template systems that load in modules, that might need to be connected to each other

##connects two nodes if they both exist
def connect_nodes(node_to_connect, target_node):
    if nuke.exists(node_to_connect) and nuke.exists(target_node):
        target = nuke.toNode(target_node)
        node = nuke.toNode(node_to_connect)
        node.setInput(0,target)    

Batch Rename Nodes

This script renames a group of nodes and appends a incrementing number to the end to prevent duplicates

You can, and probably should use the setName() function however

##batch rename selected nodes to use the same new name
selectedNodes = nuke.selectedNodes()
prefix = 'NewName'

for i, node in enumerate(selectedNodes):
    node['name'].setValue(prefix + str(i+1))

Set Backdrops Type To Fill or Border

You can use the Python scripts below to change the backdrops in a nuke script to use either the fill or border type

#set all backdrops to fill
for node in nuke.allNodes(recurseGroups=True):
    if node.Class() == 'BackdropNode':
        node['appearance'].setValue('Fill')

#set all backdrops to border
for node in nuke.allNodes(recurseGroups=True):
    if node.Class() == 'BackdropNode':
        node['appearance'].setValue('Border')

#set selected backdrops to fill
for node in nuke.selectedNodes():
    if node.Class() == 'BackdropNode':
        node['appearance'].setValue('Fill')

#set selected backdrops to border
for node in nuke.selectedNodes():
    if node.Class() == 'BackdropNode':
        node['appearance'].setValue('Border')

Shuffle All AOVs From Selected Read Node

This will create a Shuffle node for every AOV in the selected Read node and label it with the AOV name. If no node is selected, or the node is the wrong class, the user will be prompted with an error message

#select the Read node you want to shuffle your AOVs from
try: 
    selected_node = nuke.selectedNode()    
    #checks the class of selected node
    if selected_node and selected_node.Class() == "Read":
        aovs = selected_node.channels()
        aovs = list(set([i.split('.')[0] for i in aovs]))
    
        #creates a shuffle node for each AOV
        for aov_name in aovs:
            shuffle = nuke.nodes.Shuffle()
            shuffle['label'].setValue(aov_name)
            shuffle['in'].setValue(aov_name)
            shuffle.setInput(0, selected_node)
            shuffle['postage_stamp'].setValue(1)
    else:
        nuke.message("Please select a read node")
except:
    nuke.message("Please select a read node")

Lock & Unlock Node

This allows you to completely lock down a node and prevent someone from moving it in the node graph or adjusting its knobs. It’s a bit overkill imo, but I have found it useful to lockdown important backdrop nodes in templates and prevent them from being changed

#locks selected nodes position in node graph and disables its knobs
nuke.selectedNode().lock()

#unlocks selected nodes in node graph and enables its knobs
nuke.selectedNode().unlock()

#locks all selected nodes position in node graph and disables their knobs
nodes = nuke.selectedNodes()
for n in nodes:
    n.lock()

#unlocks all selected nodes position in node graph and enables their knobs
nodes = nuke.selectedNodes()
for n in nodes:
    n.unlock()

Generic Node Name Search & Execute Functions

These functions can be used as a base for larger scripts, or just to change some knob values in a relatively safe way

##function to find nodes by name, check if button exists and press if it does 
def press_button(node_name,knob_name):

    SEARCH = [i for i in nuke.allNodes() if i.name().startswith(node_name)]

    for node in SEARCH:
        if node.knob(knob_name):
            node.knob(knob_name).execute()

##function to find nodes by name inside groups, check if button exists and press if it does
def press_button_recursive(node_name,knob_name):

    SEARCH = [i for i in nuke.allNodes(recurseGroups = True) if i.name().startswith(node_name)]

    for node in SEARCH:
        if node.knob(knob_name):
            node.knob(knob_name).execute()

##function to find nodes by name, check if knob exists and set a value if it does
def set_knob_value(node_name,knob_name,knob_value):

    SEARCH = [i for i in nuke.allNodes() if i.name().startswith(node_name)]

    for node in SEARCH:
        if node.knob(knob_name):
            node.knob(knob_name).setValue(knob_value)


##function to find nodes by name inside groups, check if knob exists and set a value if it does
def set_knob_value_recursive(node_name,knob_name,knob_value):

    SEARCH = [i for i in nuke.allNodes(recurseGroups = True) if i.name().startswith(node_name)]

    for node in SEARCH:
        if node.knob(knob_name):
            node.knob(knob_name).setValue(knob_value)

Generic Node Class Search & Execute Functions

These functions can be used as a base for larger scripts, or just to change some knob values in a relatively safe way

##function to find nodes by class, check if button exists and press if it does 
def press_button(node_class,knob_name):

    SEARCH = nuke.allNodes(node_class)

    for node in SEARCH:
        if node.knob(knob_name):
            node.knob(knob_name).execute()

##function to find nodes by class inside groups, check if button exists and press if it does
def press_button_recursive(node_class,knob_name):

    SEARCH = [i for i in nuke.allNodes(recurseGroups = True) if i.Class() == node_class]

    for node in SEARCH:
        if node.knob(knob_name):
            node.knob(knob_name).execute()

##function to find nodes by class, check if knob exists and set a value if it does
def set_knob_value(node_class,knob_name,knob_value):

    SEARCH = nuke.allNodes(node_class)

    for node in SEARCH:
        if node.knob(knob_name):
            node.knob(knob_name).setValue(knob_value)

##function to find nodes by class inside groups, check if knob exists and set a value if it does
def set_knob_value_recursive(node_class,knob_name,knob_value):

    SEARCH = [i for i in nuke.allNodes(recurseGroups = True) if i.Class() == node_class]

    for node in SEARCH:
        if node.knob(knob_name):
            node.knob(knob_name).setValue(knob_value)

Set Read Frame Range To Root

This functions can be used to set all your reads frame ranges to match the root script range

##function to set all reads to match root frame range
def set_reads_frame_range_to_root():
    firstFrame = int(nuke.root()['first_frame'].getValue())
    lastFrame = int(nuke.root()['last_frame'].getValue())
    Reads = nuke.allNodes("Read")
    for node in Reads:
        node.knob('first').setValue(firstFrame)
        node.knob('last').setValue(lastFrame)
        node.knob('origfirst').setValue(firstFrame)
        node.knob('origlast').setValue(lastFrame)

Help

Request A Code Snippet

If there are sections, or code snippets you think are missing above, you can request them be added here

Previous
Previous

RenderSwitch

Next
Next

Adjust Backdrops