Layers being removed from "CURRENT" MapDocument on script completion

Discussion created by incandescentgoat on Dec 29, 2010
Latest reply on Dec 29, 2010 by JScheirer-esristaff
I'm running a python script which adds layers to a "CURRENT" MapDocument, however whenever the script finishes all the layers added in the script are removed from the map. I know it's adding them since I can see them added in ArcMap's TOC as it runs, however when the script is complete it quickly removes each of the newly added layers.

Here's a complete script which can reproduce my problem for me:

import arcpy
from os import path

fc = arcpy.GetParameterAsText(0)

layerPath = path.join(path.dirname(fc), "someFileName")

arcpy.MakeFeatureLayer_management(fc, "someLayerName")
arcpy.SaveToLayerFile_management("someLayerName", layerPath)

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
layer = arcpy.mapping.Layer("%s.lyr" % layerPath)

for i in xrange(10):
    arcpy.mapping.AddLayer(df, layer)

The script is run in-process. I can save the map before it removes the layers and then open it with them preserved, so it's definitely putting them in there. In the split second before they're removed, they're slightly grayed out with the little red exlamation indicating a missing source. Also, any existing layers are maintained - only ones added by the script get removed at script completion.

Alternatively I can just not use a "CURRENT" map however given my requirements I'd really like to add them to the current one, and I'm at a loss as to why it's removing them.