Reputation: 11
I'm not too proficient in Python - I'd love a little help with some code. I'm trying to select two random nodes out of all selected nodes in nuke.
I've got far enough that I can print two randomly chosen node names in the array of selected nodes, but could anyone help finish off the code so that the two nodes with the matching names are selected? Essentially I'm imagining if a node name contains chosen_nodes
string, select these nodes.
Thanks.
import nuke
import random
array = []
for node in nuke.selectedNodes():
n = node['name'].value()
array.append(n)
chosen_nodes = random.sample(array, k=2)
print chosen_nodes
Upvotes: 1
Views: 745
Reputation: 650
Essentially I'm imagining if a node name contains
chosen_nodes
string, select these nodes.
This should be close to what you want!
match = 'chosen_nodes'
for node in nuke.selectedNodes():
node.setSelected(False)
if match in node['name'].value():
node.setSelected(True)
A slightly more complicated version:
def selectNodesWithFuzzyName(name, nodes=None):
"""
Set the selected nodes to only those that match the passed name.
Parameters
----------
node : str
Glob-style name of a node e.g. 'Grade*'
nodes : Optional[Iterable[nuke.Node]]
If provided, only operate on only these nodes. Otherwise
the currently selected nodes will be used.
"""
import fnmatch
if nodes is None:
nodes = nuke.selectedNodes()
for node in nodes:
node.setSelected(False)
if fnmatch.fnmatch(node['name'].value(), name):
node.setSelected(True)
selectNodesWithFuzzyName('Grade*')
Upvotes: 0
Reputation: 58563
With this code you can select two random nodes out of several selected ones:
import nuke
import random
array = []
for node in nuke.selectedNodes():
name = node['name'].value()
array.append(name)
print(array)
if nuke.selectedNodes():
for index in nuke.selectedNodes():
index['selected'].setValue(False)
for i in range(1, 3, 1): # range(start, non-inclusive stop, step)
r = random.randint(1, len(array))
nuke.toNode(array[r-1]).setSelected(True)
array.remove(array[r-1]) # delete randomly generated element from array
array = []
Upvotes: 0