Nuke, Compositing · 2024년 9월 25일 · 읽는 데 1분

Nuke Python Snippets

Contact Sheet node

ContactSheet {
width {{input.width*columns*resMult}}
height {{input.height*rows*resMult}}
rows {{"\[expr \{int( (sqrt( \[numvalue inputs] ) ) )\} ] * \[expr \{int( ceil ( (\[numvalue inputs] /(sqrt( \[numvalue inputs] ) ) )) )\} ] < \[numvalue inputs]   ? \[expr \{int( (sqrt( \[numvalue inputs] ) ) )\} ] +1 : \[expr \{int( (sqrt( \[numvalue inputs] ) ) )\} ]"}}
columns {{"\[expr \{int( ceil ( (\[numvalue inputs] /(sqrt( \[numvalue inputs] )) )) )\} ]"}}
center true
roworder TopBottom
name ContactSheetAuto
tile_color 0xff69f7ff
selected true
xpos -1219
ypos 13555
addUserKnob {20 Settings}
addUserKnob {7 resMult l "Resolution Multiplier" R 0.1 2}
resMult 1
}

What is my Shortcut key?

import nuke
import os
import webbrowser

def save_shortcuts_to_file(file_path):
    def get_commands(menu):
        commands = []
        for item in menu.items():
            if hasattr(item, 'shortcut') and item.shortcut():
                commands.append((item.name(), item.shortcut()))
            elif hasattr(item, 'items'):
                commands.extend(get_commands(item))
        return commands

    # Get the root Nuke menu
    root_menu = nuke.menu('Nuke')
    
    # Get all commands with their shortcuts
    commands = get_commands(root_menu)

    # Sort commands for better readability
    commands.sort(key=lambda x: x[0].lower())

    # Write to the file
    with open(file_path, 'w') as file:
        file.write(f"{'Command':<50} {'Shortcut':<20}\n")
        file.write("="*70 + "\n")
        for command_name, shortcut in commands:
            file.write(f"{command_name:<50} {shortcut if shortcut else 'None':<20}\n")

    print(f"Shortcuts have been saved to {file_path}")

    # Automatically open the file in the default text editor
    try:
        webbrowser.open(f'file://{file_path}')
    except Exception as e:
        print(f"Could not open the file automatically: {e}")

# Define the path to the .nuke folder and the output file
nuke_folder = os.path.expanduser("~/.nuke")
output_file = os.path.join(nuke_folder, "shortcuts.txt")

# Create the .nuke folder if it doesn't exist
if not os.path.exists(nuke_folder):
    os.makedirs(nuke_folder)

# Call the function to save shortcuts to the file
save_shortcuts_to_file(output_file)

Set frame range for all selected read nodes

first = 1001
last = 1062

for n in nuke.selectedNodes('Read'):
    n['first'].setValue(first)
    n['last'].setValue(last)
    n['origfirst'].setValue(first)
    n['origlast'].setValue(last)

for n in nuke.selectedNodes('DeepRead'):
    n['first'].setValue(first)
    n['last'].setValue(last)
    n['origfirst'].setValue(first)
    n['origlast'].setValue(last)

Replace part of your path in the selected Read nodes

sn = nuke.selectedNodes()

for n in sn:
  path = n.knob('file').value()
  new_path = path.replace('%04d.exr','lt.%04d.exr')
  n.knob('file').setValue(new_path)

Remove All Animation from selected node

for a in nuke.selectedNode().knobs():
    nuke.selectedNode()[a].clearAnimated()

Disconnect all viewers at the start (To add on your Menu.py)

def disconnectViewers():
  nuke.selectAll()
  nuke.invertSelection()

  for n in nuke.allNodes():
    if n.Class() == "Viewer":
    n['selected'].setValue(True)

  nuke.extractSelected()
  
nuke.addOnScriptLoad(disconnectViewers)

Converting nuke gizmos into groups

import uuid
import nuke

def is_gizmo(node):
    """Return True if given node is a gizmo (and not allowed gizmo type)"""

    allowed_gizmo_classes = ('Cryptomatte')

    for knob in node.knobs():
        if 'gizmo' in knob and node.Class() not in allowed_gizmo_classes:
            return True

def get_gizmo_names():
    """Return the fullName attribute for all gizmos in script"""

    gizmos = []
    all_nodes = nuke.allNodes(recurseGroups=True)

    if all_nodes:
        gizmos = [node.fullName() for node in all_nodes if is_gizmo(node)]

    return gizmos

def deselect_all_nodes():
    """De-select all nodes"""

    for i in nuke.allNodes(recurseGroups=True):
        i.knob('selected').setValue(False)

def convert_gizmo_to_group(gizmo_full_name):
    """Convert given gizmo (gizmo.fullName) to group"""

    gizmo = nuke.toNode(gizmo_full_name)

    inputs = []
    for x in range(0, gizmo.maximumInputs()):
        if gizmo.input(x):
            inputs.append(gizmo.input(x))
        else:
            inputs.append(False)

    original_name = gizmo.knob('name').value()
    xpos = gizmo.xpos()
    ypos = gizmo.ypos()
    uid_name = uuid.uuid4()

    gizmo.knob('name').setValue('%s' % uid_name)
    deselect_all_nodes()
    gizmo.knob('selected').setValue(True)

    with gizmo:
        new_group = gizmo.makeGroup()

        deselect_all_nodes()
        nuke.delete(gizmo)

        new_group.knob('name').setValue(original_name)
        new_group['xpos'].setValue(xpos)
        new_group['ypos'].setValue(ypos)

        for x in range(0, new_group.maximumInputs()):
            new_group.setInput(x, None)
            if inputs[x]:
                new_group.connectInput(x, inputs[x])

def main():
    """Main script"""
    # Store the current selection
    current_selection = nuke.selectedNodes()

    while get_gizmo_names():
        gizmo_full_name = get_gizmo_names()[0]
        convert_gizmo_to_group(gizmo_full_name)
        print('Converted %s' % gizmo_full_name)

    # Restore original selection
    for n in current_selection:
        try:
            n['selected'].setValue(True)
        except:
            pass

main()
← 모든 글