Tuesday 11 July 2017

arcpy - Python window vs Toolbox script in ArcGIS for Desktop?


My question is similar to Adding Layer in current session using ARCPY . My script works in ArcMap python window but not as a script in toolbox. I am running ArcGIS 10.0 SP4. The script is given below, and the error says it fails at line 3, "CreateObject cannot open map document"


import arcpy
import arcpy.mapping as map
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
updateLayer = arcpy.mapping.ListLayers(mxd, "SectionClip",df)[0]

arcpy.MakeFeatureLayer_management(updateLayer,"SectionInner2")
sourceLayer = arcpy.mapping.ListLayers(mxd,"SectionInner",df)[0]
newupdateLayer = arcpy.mapping.ListLayers(mxd, "SectionInner2",df)[0]
arcpy.ApplySymbologyFromLayer_management(newupdateLayer,sourceLayer)
newupdateLayer.showLabels = True
for lyr in map.ListLayers(mxd):
if lyr.name == "SectionInner2":
lyr.showLabels = True
for lblclass in lyr.labelClasses:
lblclass.expression = '"%s" & [SECTION] & "%s"' % ("""""", """""")

lblclass.showClassLabels = True

arcpy.RefreshActiveView()
mxd.save()

I am unable to upgrade to ArcGIS 10.1 any time soon so the option of using a python add-in is not available.



Answer



The only thing I see in your code that could cause this problem is that you are setting the MXD value to "CURRENT", which is fine... IF you have an MXD open (executing the script tool from within ArcMap).


I was able to cause your code to fail with the same response if I tried executing the code form the stand-alone ArcCatalog application. Is that what you were doing?


Screenshot using ArcCatalog to execute a Script Tool enter image description here




If trying to run the script from stand-alone ArcCatalog was your problem, you have two options to run your script.
1. Run the Script Tool from the Catalog tab within the ArcMap enter image description here

2. Application Set the MXD parameter as a path to a valid MXD


arcpy.mapping.MapDocument(r"c:\path\to\your\map.mxd")


You can read more details about the use of the arcpy.Mapping.MapDocument class here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...