Adding python tool output to arcmap automatically when analysis is complete

7727
12
06-18-2012 12:13 PM
IanLeinwand
New Contributor II
Greeting all...

I've written a python scrip that is run in arctool box given user specified inputs... at this point the tool works but I would like to have the tool automatically
add the resulting output datasets to the ArcMap table of contents.

I've tried a few variation of the following code... keep getting the same error... see below. I think it all goes back to this line of code where its not recognizing which dataset to add to the map. Any help is appreciated.

Code...

mxd = arcpy.mapping.MapDocument(r"D:\Risk_Models\Sample_Design\sample_design_tool.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "*")[0]

print "ready to add layer"
print sample_plots


newlayer1 = arcpy.mapping.Layer(r"D:\Risk_Models\Sample_Design\Sample_design_tool\sample_design_tool.gdb\state_GA")
#newlayer2 = arcpy.mapping.Layer(sample_points)

print newlayer1

arcpy.mapping.AddLayer(df, newlayer1, "TOP")
#arcpy.mapping.AddLayer(df, newlayer2, "Bottom")

arcpy.RefreshActiveView()
arpy.RefreshTOC()
del mxd, df, newlayer1

end code


Error... reported in python

Traceback (most recent call last):
  File "C:\Python26\ArcGIS10.0\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
    exec codeObject in __main__.__dict__
  File "D:\Risk_Models\Sample_Design\Sample_design_tool\FHTET_Sample_Design_Tool\FHTET_sample_design_tool_6_18_2012_add_data_update_test.py", line 94, in <module>
    newlayer1 = arcpy.mapping.Layer(r"D:\Risk_Models\Sample_Design\Sample_design_tool\sample_design_tool.gdb\state_GA")
  File "C:\Program Files\ArcGIS\Desktop10.0\arcpy\arcpy\arcobjects\mixins.py", line 255, in __init__
    super(LayerMixin, self).__init__(lyrfile)
  File "C:\Program Files\ArcGIS\Desktop10.0\arcpy\arcpy\arcobjects\_base.py", line 47, in __init__
    for arg in args))
ValueError: Object: CreateObject Layer invalid data source
Tags (2)
0 Kudos
12 Replies
NobbirAhmed
Esri Regular Contributor
I created a script with your code and it is working.

What is the data type of "state_GA"?

If you want to persist the added new layer (after you get over the exception) to the map, use mxd.save() before del statement.

Note: don't forget to enclose your code with CODE tabs - click on the '#' button above and paste your code insde the tags.
0 Kudos
IanLeinwand
New Contributor II
hmm...

State_GA is  a feature class in a geodatabase. Would you mind posting the code you got to work?

thanks

ian
0 Kudos
NobbirAhmed
Esri Regular Contributor
Here is my code:

import arcpy

try:

    mxd = arcpy.mapping.MapDocument(r"C:\temp\mymap.mxd")

    df = arcpy.mapping.ListDataFrames(mxd)[0]
    

    newlayer1 = arcpy.mapping.Layer(r"C:\data\redlands.gdb\rdls_street")
    print newlayer1
    arcpy.mapping.AddLayer(df, newlayer1, "TOP")
    

    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()

    # save the map to persist the added layer
    mxd.save()

    del mxd, df, newlayer1
    print 'Done'    

except Exception as ex:
    print ex.args[0]


Which version of ArcGIS (service pack) you are using?
0 Kudos
IanLeinwand
New Contributor II
I'm still gettin gthe CreateObject Layer invalid data source error. I used your code and just swithched out the path names for my mxd and files. I even tried
different .mxd docs and both a feature class and a shapefile as the layer source.

Not sure what else to do.
0 Kudos
NobbirAhmed
Esri Regular Contributor
Not sure what's going on. Try both of these:

Make a layer file of your data - in ArcMap, from Table of Content right-click on the layer and select Save Layer as. The file name will have a *.lyr extension.

Use the layerfile.lyr instead of a feature class.

And enclose your code with try-except as in my sample. Write the except block as follows:

except Exception as ex:
    print ex


Let me what error message you get.
0 Kudos
DarrenWiens2
MVP Honored Contributor
Psst! Nobbir, you forgot the "try:" in your previous example.

Ian, the only thing I can think of is that your path is wrong. Later on, there's a typo in your script ("arpy").
0 Kudos
IanLeinwand
New Contributor II
Okay... not sure if I'm making progress or not... I've simplified the code to try to work out the bug. Here is what I'm working with now.

import arcpy

try:
    mxd = arcpy.mapping.MapDocument(r"D:\Risk_Models\Multi_Species_Sampling\multi_species_overlay.mxd")

    df = arcpy.mapping.ListDataFrames(mxd)[0]
    

    newlayer1 = arcpy.mapping.Layer("D:\\Risk_Models\\state_MN_5000_EAB_plots.lyr")
    print newlayer1
    arcpy.mapping.AddLayer(df, newlayer1, "TOP")
    
    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()

    #save the map to persist the added layer
    mxd.save()

    del mxd, df, newlayer1
    print 'Done'    

except Exception as ex:
    print ex.args[0]


Now the code runs through the arcpy.mapping.Layer line and I do not get the invalid source error like before but the layer still does not add to the specified .mxd and then the new error say...

that it is unable to save the map document.

I have the .mxd open... does this matter.

Ideally I want the users of my tool to have the tool output automatically added to their map document once the tool finishes. Also when I use "CURRENT" for the map document rather than a path it doesn't work. So another question is how do I get it to dynamically recognize the map document the user has created. I don't have any control over what my users name their map documents or where they save them.

Thanks for all the help...

Ian
0 Kudos
NobbirAhmed
Esri Regular Contributor
If you want to add the layer to the map and show up instantly (while the map is open) then you can create a script tool with the code as the source of the tool. I've attached a tool with the script.

Open the map document you want to add layer. From the catalog window browse to the location where you unpacked the zip file. Double click on the toolbox named AddLayerToMap - you'll see a tool named AddLayerTool. Open the tool by double-clicking on it. The tool dialog is simple - it asks for a layer. The type of acceptable input is a feature class, a map layer or a layer file (.lyr).

[ATTACH=CONFIG]15360[/ATTACH]

Drag-drop any input and hit 'OK'. If everything goes okay then you'll see the layer added to the first data frame.
0 Kudos
IanLeinwand
New Contributor II
I tried your tool...

when I selected a shape file or feature class... I got the invalid input source

when I tried it with a .lyr file the tool runs but nothing is added to the open map document

I just went back and tried the tool a few more times and its almost like something is added and then immediately disappears.

I would give up on this endeavor at this point but my program manager wants the arctoolbox script I created to automatically add the output dataset to the users map once complete... at this point I feel its easier just to give direction on how to add the data in ArcMap.
0 Kudos