def __init__(self): self.label = "Add Layer" self.description = "Adds a layer to ArcMap" self.canRunInBackground = False ######################## def execute(self, parameters, messages): arcpy.MakeFeatureLayer_management("C:\BILL\CB_TEMP\cb.shp", "LAYER") mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "*")[0] addLayer = arcpy.mapping.Layer("LAYER") arcpy.mapping.AddLayer(df, addLayer, "TOP") arcpy.RefreshTOC() arcpy.RefreshActiveView() # del mxd
Solved! Go to Solution.
arcpy.MakeFeatureLayer_management(r"C:\BILL\CB_TEMP\cb.shp", "LAYER") arcpy.SetParameterAsText(1, "LAYER")
arcpy.MakeFeatureLayer_management(r"C:\BILL\CB_TEMP\cb.shp", "LAYER") arcpy.SetParameterAsText(1, "LAYER")
I've been trying to figure out how to add outputs to the display for Python Toolbox scripts for an embarrassingly long time. I'd pretty much given up when I came upon this exchange. I'm dealing with rasters, so substituted arcpy.MakeRasterLayer_management instead, and it worked great! A quick and easy way to get the job done, seeing as the arcpy.env.addOutputsToMap doesn't function when run from within a tool.
For those who are looking to do the same thing, add an additional parameter for the Derived output:
# Eighth parameter: output layer to add to project outlayer = arcpy.Parameter( name = "outlayer", displayName = "Derived output for final product raster", datatype = "GPRasterLayer", parameterType = "Derived", direction = "Output")
Then once you've generated the output raster in your code, add it to the display, referencing the index number for the derived parameter in the arcpy.SetParameterAsText function (in this example it was the 8th parameter, so has an index value of 7). Note that you cannot have the same name for the input raster and the display raster; I just removed the .tif extension from my raster filename to differentiate the two while still making it clear what dataset was added. In this example, the outpath variable is the full path to the newly-generated raster that I want to add to the map.
dispname = os.path.splitext(outname)[0] arcpy.MakeRasterLayer_management(outpath, dispname) arcpy.SetParameterAsText(7, dispname) arcpy.AddMessage("Added RGB raster layer to map display.")