pythonlisttuplesnodesnuke

Get selected node names into a list or tuple in Nuke with Python


I am trying to obtain a list of the names of selected nodes with Python in Nuke. I have tried:

for s in nuke.selectedNodes():
    n = s['name'].value()
    print n

This gives me the names of the selected nodes, but as separate strings. There is nothing I can do to them that will combine each string. If I have three Merges selected, in the Nuke script editor I get:

Result: Merge3 Merge2 Merge1

If I wrap the last variable n in brackets, I get:

Result: ['Merge3']
['Merge2']
['Merge1']

That's how I know they are separate strings. I found one other way to return selected nodes. I used:

s = nuke.tcl("selected_nodes")
print s

I get odd names back like node3a7c000, but these names work in anything that calls a node, like nuke.toNode() and they are all on one line. I tried to force these results into a list or a tuple, like so:

s = nuke.tcl("selected_nodes")

print s

Result: node3a7c000 node3a7c400 node3a7c800

s = nuke.tcl("selected_nodes")

s2 = s.replace(" ","', '")

s3 = "(" + "'" + s2 + "'" + ")"

print s3

Result: ('node3a7c000', 'node3a7c400', 'node3a7c800')

My result looks to have the standard construct of a tuple, but if I try to call the first value from the tuple, I get a parentheses back. This is as if my created tuple is still a string.

Is there anything I can do to gather a list or tuple of selected nodes names? I'm not sure what I am doing wrong and it seems that my last solution should have worked.


Solution

  • As you iterate over each node, you'll want to add its name to a list ([]), and then return that. For instance:

    names = []
    for s in nuke.selectedNodes():
        n = s['name'].value()
        names.append(n)
    print names
    

    This will give you:

    # Result: ['Merge3', 'Merge2', 'Merge1']
    

    If you're familiar with list comprehensions, you can also use one to make names in one line:

    names = [s['name'].value() for s in nuke.selectedNodes()]