Select to view content in your preferred language

arcpy.mapping.AddLayer not working properly with Python toolbox

1653
2
05-23-2014 08:44 AM
TomMacDonald
Deactivated User
I have ArcMap 10.1 SP1 (Build 3143) for Desktop.  I'm trying to execute the following simple code.
import arcpy

class Toolbox(object):
    def __init__(self):
        self.label = 'Tools'
        self.alias = 'Tools'
        self.tools = [Tool]

class Tool(object):
    def __init__(self):
        self.label = 'Get it to work'
        self.canRunInBackground = False

    def getParameterInfo(self):
        parameters = []
        return parameters

    def isLicensed(self):
        return True

    def updateParameters(self, parameters):
        return

    def updateMessages(self, parameters):
        return

    def execute(self, parameters, messages):
        mxd = arcpy.mapping.MapDocument('CURRENT')
        df = arcpy.mapping.ListDataFrames(mxd)[0]
        
        layer = arcpy.mapping.Layer(r'O:\shp\mn.lyr')
        arcpy.mapping.AddLayer(df, layer)
        
        return


It does not raise any exceptions and the layers are added to the dataframe but they disappear as soon as they're added.  I'm trying to automate map production and I need to add these layers.
Tags (2)
0 Kudos
2 Replies
TomMacDonald
Deactivated User
Wanted to add that I run the same code within the Python window and it works fine.
0 Kudos
TomMacDonald
Deactivated User
After calling tech support I think I found an answer.  Using the current map seems to introduce bugs so specify a path.  Also I should be put mxd.save(), del mxd, and arcpy.RefreshActiveView() and arcpy.RefreshTOC() at the end.  This gets it to work.