starry

arcpy.mapping ListBookmarks error

Discussion created by starry on Mar 20, 2014
I get the following error when using the arcpy.mapping ListBookmarks function in a script:

Traceback (most recent call last):
File "X:\Temp\Tools\MXD_Bookmarks_to_Polygon.py", line 28, in <module>
for bkmk in arcpy.mapping.ListBookmarks(mxd):
File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\mapping.py", line 1448, in ListBookmarks
for data_frame in dfs]
AttributeError: 'NoneType' object has no attribute 'bookmarks'

Failed to execute (MXDBookmarkstoPolygon).


Upon closer inspection of the mxd I was running the code on, I found that there were multiple data frames with the same name and also the same bookmarks. The code works for sure on mxds with one data frame.

Is this a bug or should I be implementing some means to catch that condition?

Here is the code. It is modified from example 3 of this help article.

import arcpy, os, string

# Input list of MXDs
mxdList = string.split(arcpy.GetParameterAsText(0), ";")
# A template feature class that contains the attribute schema
# Including a "Name" field to store the bookmark name
template = arcpy.GetParameterAsText(1)

#Loop through each MXD in the list, export bookmarks to shapefile
for mxdPath in mxdList:
    mxd = arcpy.mapping.MapDocument(mxdPath)
    shpPath = mxdPath[:-4] + "_ply.shp"
    if arcpy.Exists(shpPath):
        arcpy.Delete_management(shpPath)
    arcpy.CreateFeatureclass_management(os.path.dirname(shpPath),
                                    os.path.basename(shpPath), 
                                    "POLYGON", template, 
                                    spatial_reference=template)
    
    cur = arcpy.da.InsertCursor(shpPath, ["SHAPE@", "Name"])
    array = arcpy.Array()
    #Check to see if the list is empty (if there are no bookmarks)
    testmxd = arcpy.mapping.ListBookmarks(mxd)
    if not testmxd:
        arcpy.Delete_management(shpPath)
        arcpy.AddMessage("No bookmarks in " + os.path.basename(mxdPath))
    else:
        for bkmk in arcpy.mapping.ListBookmarks(mxd):
            array.add(arcpy.Point(bkmk.extent.XMin, bkmk.extent.YMin))
            array.add(arcpy.Point(bkmk.extent.XMin, bkmk.extent.YMax))
            array.add(arcpy.Point(bkmk.extent.XMax, bkmk.extent.YMax))
            array.add(arcpy.Point(bkmk.extent.XMax, bkmk.extent.YMin))
            # To close the polygon, add the first point again
            array.add(arcpy.Point(bkmk.extent.XMin, bkmk.extent.YMin))
            cur.insertRow([arcpy.Polygon(array), bkmk.name])
            array.removeAll()
        arcpy.AddMessage("Bookmark polygons created for " + os.path.basename(mxdPath))

Outcomes