MakeFeatureLayer_management does not add layer to TOC?

10231
8
Jump to solution
02-01-2016 01:39 PM
AustinRobey1
New Contributor II

I have written a python script that utilizes arcpy.MakeFeatureLayer_management to create a layer from a selection set. If I run this script in the Python window in ArcMap it works -- it updates the Table of Contents with a temporary layer (i.e. referencing existing data rather than copying new data to disk). However, if I execute this script as a tool (script saved to a toolbox and run as geoprocessing) it runs but does not update the Table of Contents with a new layer. It is the exact same script (see below), just run in different ways. Can someone help me understand why the tool is not adding the layer, but the Python window does? Thanks!

import arcpy 
arcpy.env.overwiteOutput = True
#Specify the MXD project (CURRENT), dataframe (Layers), MapPage (004-21)
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
pagenm = "004-21"
#Defintion query expressions
apndq = "APN LIKE '" + pagenm + "%'"
#Apply defintion query to specified layer group
for lyr in arcpy.mapping.ListLayers(mxd, "AssessorsParcels"):
 if lyr.supports("DEFINITIONQUERY"):
  lyr.definitionQuery = str(apndq)
#Create MapPage Boundary Selection
arcpy.SelectLayerByLocation_management(r"Cadastral Data\Boundary","HAVE_THEIR_CENTER_IN",r"Cadastral Data\AssessorsParcels","","NEW_SELECTION")
#Create layer from selection and update symbology
arcpy.MakeFeatureLayer_management(r"Cadastral Data\Boundary", "BoundarySelection")
arcpy.ApplySymbologyFromLayer_management("BoundarySelection","H:\\Data\\Layers\\Boundary.lyr")

#Refresh the Active View
arcpy.RefreshTOC()
arcpy.RefreshActiveView()       
del mxd, df, pagenm
0 Kudos
1 Solution

Accepted Solutions
RebeccaStrauch__GISP
MVP Emeritus

This thread might be helpful

Re: Get Attribute Value from Selected Feature

Explains a bit about MakeFeatureLayer  and includes the "arcpy.mapping.AddLayer(df, addLayer, "TOP")" similar to my code above, but in a more straightforward manner.

View solution in original post

8 Replies
RebeccaStrauch__GISP
MVP Emeritus

From the help Make Feature Layer—Help | ArcGIS for Desktop

Creates a feature layer from an input feature class or layer file. The layer that is created by the tool is temporary and will not persist after the session ends unless the layer is saved to disk or the map document is saved.

I was just needing the same thing and had to refresh my memory.  Take a look at the second code sample on the help page.

EDIT:....but I'm not getting it to work right now either....just fyi.

0 Kudos
AustinRobey1
New Contributor II

Thanks for replying Rebecca! The problem I have with the code sample is that it copies the data selection to disk. I was hoping to avoid this because I only need the data temporarily. If I run MakeFeatureLayer in the Python window, it adds a layer in my TOC without actually copying the data anywhere. I am curious as to why it does not do this when I run the same script as a tool. The help says: "...will not persist after the session ends unless... the map document is saved." Maybe I need to add some code to save my MXD before the tool finishes processing?

0 Kudos
RebeccaStrauch__GISP
MVP Emeritus

I remember how I was doing it in other scripts.  I tested to make sure I was in ArcMap (in case I'm running in ArcCatalog instead)

try:
    #my variables pElevClass, unionOut and outDissolved are set to full paths of the output
    mxd = arcpy.mapping.MapDocument("CURRENT")
except RuntimeError:
    print("Not using ArcMap")
else:
    df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
    layerList = [pElevClass, unionOut, outDissolved] 
    for layer in layerList:
        addLayer = arcpy.mapping.Layer(layer)
        if arcpy.Exists(addLayer):
            arcpy.mapping.AddLayer(df, addLayer, "TOP")
            print("-> Added {0} to map.".format(layer)) #, finalLayer))

I have

arcpy.env.overwriteOutput = True

Set so I can use the names multiple times...and actually have a section that I run thru an delete all my temp files so I don't end up with so many temps that I have to clean up later. 

I had this working in another script last week.  With the temp files I wanted to add to the TOC, it sometimes added the layer to the TOC EACH time I ran it, but since they always pointed to the same file, even the previous versions in the TOC reflected the new data (as it should).  My guess is this paragraph doesn't make much sense....but maybe the code above will make it more clear.

JoshuaBixby
MVP Esteemed Contributor

What are your script properties in terms of running the script in process and always running in the foreground?  Also, do you have Background Processing enabled in ArcGIS Desktop? 

0 Kudos
AustinRobey1
New Contributor II

I have it set to always run in foreground and run script in process. Background Processing is disabled. On the Geoprocessing Options window, under the Display/Temporary Data section, I have Add results of geoprocessing to the display enabled, and Results are temporary by default disabled.

0 Kudos
RebeccaStrauch__GISP
MVP Emeritus

This thread might be helpful

Re: Get Attribute Value from Selected Feature

Explains a bit about MakeFeatureLayer  and includes the "arcpy.mapping.AddLayer(df, addLayer, "TOP")" similar to my code above, but in a more straightforward manner.

AustinRobey1
New Contributor II

Yes! I was able to fix the problem using the below code:

#Create layer from selection
arcpy.SelectLayerByLocation_management("Target_Layer","HAVE_THEIR_CENTER_IN","Source_Layer","","NEW_SELECTION")
arcpy.MakeFeatureLayer_management("Target_Layer", "Selection_LayerName")
selection = arcpy.mapping.Layer("Selection_LayerName")
arcpy.mapping.AddLayer(df, selection, "TOP")

It is still a bit odd to me that the tool requires lines 04 & 05 yet the Python window did not. Alas, it works now, so I am satisfied. Thank you!

0 Kudos
RebeccaStrauch__GISP
MVP Emeritus

Glad you got it to work (I have mine working too).  Make sure to close this thread out by marking any answers that were helpful, and one as the correct. answer.