I am trying to remove layers from the TOC using Python Toolbox. It works provided that the layer names have no spaces in their names. Tho whole script looks like:
class LayerprocessingRemoveUntickedLayers(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Remove unticked layers"
self.description = "Removes unticked layers."
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
param0 = parameter("toclayers", "Unticked layers", "GPString", "Optional", multiValue=True)
params = [param0]
return params
def updateParameters(self, parameters):
unticked_set = set()
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
if not lyr.visible:
unticked_set.add(lyr.longName)
del lyr
parameters[0].filter.list = sorted(list(unticked_set))
return
def execute(self, parameters, messages):
toclayers = parameters[0].valueAsText.split(";") # ??? Here is my problem
arcpy.AddMessage("\nTicked layers:")
for t in toclayers:
arcpy.AddMessage("... " + t)
arcpy.AddMessage("\nRemoving chosen layers... ")
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
if not lyr.visible and lyr.longName in toclayers:
arcpy.AddMessage("... " + lyr.longName)
arcpy.mapping.RemoveLayer(df, lyr)
return
Step 1: updateParameters
function reads layers and gives me layers´ names.
Step 2: I tick layers I want to remove (it does no matter whether they are broken or not). There is no group layer.
Step 3: the script removes only those chosen layers that have no spaces in their names (in this case PP_N_eroze_SUp
and PP_N_eroze_SUt
). Obviously because layers with spaces in their names get quotes to their values.
Mr. Che commented that layers with spaces in their names get quotes when passed from tool dialog to script executing. And now I remember that I asked a question with the same problem some time ago as Multivalue input from chosen field giving patchy input strings from ArcPy?
The problem was in arcpy.GetParameterAsText(0)
, the solution was changing it to arcpy.GetParameter(0)
and splitting its strings with ";" as Hornbydd suggested a long time ago.
It worked when the tool was within an ordinary toolbox. Now I have this tool in the Python toolbox but changing parameters[0].valueAsText.split(";")
to str(parameters[0].value).split(";")
is not working. How to get values (this is to say split values from parameters[0]
) correctly?