How to use Python script to judge whether a node exists or not

segmentationNode = slicer.mrmlScene.AddNewNodeByClass(“vtkMRMLSegmentationNode”)
After creating a node, you don’t want to create a new node. How to judge whether a node has been created

I don’t know exactly what you want to do but here is a snippet of code I used to check whether there are any segmentation nodes in the scene and if so, cycle through them all and turn their visibility off so that they are hidden. You may be able to use some part of it or something similar for what you are doing.

  # Hide all Segments
  noOfSegmentationNodes = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLSegmentationNode')
  if noOfSegmentationNodes > 0:
    for i in range(0, noOfSegmentationNodes):
      currentSegment = slicer.mrmlScene.GetNthNodeByClass(i, 'vtkMRMLSegmentationNode')
      currentSegment.SetDisplayVisibility(0)
1 Like

If you develop a module: You would normally store the selected node as a node reference in a parameter node. If you create a new module using Extension Wizard module then the generated module already works like this. You can also look at many other Python modules in Slicer core and extensions.

If you develop a script: store the node in some variable. If you create the node in a function then return that variable from the function.