Avoid error message if layer don't exist

Hi all. I do try to make a script to purge some unnecessary layers and all the geometries inside them and I do found a piece of code that works, the only issue it is that if the layer Booleans does not exist I do get an error popup message. How I can skip this error message?

if rs.IsLayer("Booleans"):
    rs.PurgeLayer("Booleans")

This should work, it checks if the layer name exists before trying to purge it

import rhinoscriptsyntax as rs

# get the layernames in the document as a list
layer_names = rs.LayerNames()
layer_to_purge = "Booleans"

# see if the name is in the list
if layer_to_purge in layer_names:
    if rs.IsLayer(layer_to_purge):
        rs.PurgeLayer(layer_to_purge)
1 Like

Thank you, it is working. It is possible to add an additional option to delete ALL the unused layers from the document?

See if this does what you want

import rhinoscriptsyntax as rs

# get the layernames in the document as a list
layer_names = rs.LayerNames()

# delete the layer if empty
for lyr in layer_names:
    # since rs.DeleteLayer also deletes empty children layers,
    # a layer might already be deleted by the time
    # the for loop cycles through to it. So wrap deletion in
    # try except logic to attempt ot delete, and if it cant 
    # print hte reason
    try:
        rs.DeleteLayer(lyr)
    except Exception as e:
        print e
        pass

rs.DeleteLayer only deletes the layer if it is empty, but it also deletes children layers that are empty. You can avoid errors here by wrapping deletion in python try except logic. If you don’t want the script to print the layers it fails to delete, just comment out / delete the line print e

1 Like

Another way would be to use Rhino’s Purge command which you can call with rs.Command. You would just need to specify if you only want to purge layers by doing the following:

import rhinoscriptsyntax as rs

rs.Command('Purge B=No A=No G=No H=No L=Yes I=No M=No T=No E=No B=No P=No Enter')
1 Like

Yes, Purge seems a lot faster. The DeleteLayer command it is deleting layer by layer while Purge it is deleting all layers at once.

I think built in Rhino commands will always be faster than the equivalent coded in python, but just FYI one reason the 1st method I mentioned feels much slower is because it is refreshing the Rhino window each time a layer is deleted. You can temporarily disable and then re-enable this to speed it up, it should feel faster

import rhinoscriptsyntax as rs
layer_names=rs.LayerNames()
rs.EnableRedraw(False)
for lyr in layer_names:
    try:
        rs.DeleteLayer(lyr)
    except Exception as e:
        pass
rs.EnableRedraw(True)
1 Like