ericmeyers

lyr.symbology.reclassify() -  causes python crash

Discussion created by ericmeyers on Mar 27, 2014
Hello All:

I've been trying to get a code to execute for a couple of days now and I have been unsuccessful, I've even started contacting ESRI about it. I'm a mid-level developer and know most of the basics of python and other programming languages. My script continues to crash on the same line of code over and over. I'm attempting to create 1,000+ maps using a template document that continues to be updated based upon different SQL queries. Everytime the code seems to crash on the 73rd iteration of lyr.symbology.reclassify()

I'm not exactly sure why this is happening as I cannot get a decent answer from this output in pyCharms

Process finished with exit code -1073741819

I've tried running the program in three seperate IDE's and it still does not work.

#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      emeyers
#
# Created:     17/03/2014
# Copyright:   (c) emeyers 2014
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import arcpy
import arcpy.mapping as am
import pyodbc
import datetime

def rpwSearchCursor():

    rpwRows = arcpy.SearchCursor("Database Connections\\DNAu_GIS_P.sde\\DNAu_GIS_P.EMeyers.RPW_ZONES", "", "", "WrapZone; FIRST_Name", "WrapZone A")

    for rpwRow in rpwRows:

        rpwZone = str(rpwRow.WrapZone)
        rpwZoneName = str(rpwRow.FIRST_Name.replace("'", " "))

        con = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = 'HIDDEN', database = 'DNAu_GIS_P')
        cur = con.cursor()

        rpwUpdateQuery =\
        """
    INSERT INTO DNAU_GIS_S.EMeyers.DT_RPW_STORE_PROFILES (SHAPE, Store_Num)
    SELECT DriveTime.SHAPE, DriveTime.Store
    FROM EMeyers.DRIVE_TIME DriveTime
    WHERE (SELECT EMeyers.RPW_ZONES.Shape FROM EMeyers.RPW_ZONES WHERE WrapZone = '""" + rpwZone +"""').STIntersects(DriveTime.SHAPE) = 1

    UPDATE DNAU_GIS_S.EMeyers.DT_RPW_STORE_PROFILES
    SET RPW = '""" + rpwZone + """', Name = '""" + rpwZoneName + """'
    FROM DNAU_GIS_S.EMeyers.DT_RPW_STORE_PROFILES
    WHERE DNAU_GIS_S.EMeyers.DT_RPW_STORE_PROFILES.RPW IS NULL
    """

        cur.execute(rpwUpdateQuery)
        con.commit()



today = datetime.date.today()

firstOfMonth = datetime.date(day=1, month=today.month, year=today.year)

monthYear = datetime.datetime.strptime(str(firstOfMonth), '%Y-%m-%d')
monthYear = monthYear.strftime('%m-%Y')

salesQueryF = str(datetime.date(day=1, month=today.month, year=today.year - 1))

salesQueryT = str(firstOfMonth - datetime.timedelta(days=1))
salesQueryT = salesQueryT.replace(salesQueryT[len(salesQueryT)-2:], '01')

today = today.strftime('%m_%d_%Y')

DT_RPW_Profiles = "Z:\\Maps\\Base_GIS_Data\\Base_Data.gdb\\RedPlumWrap\\DT_RPW_StoreProfiles"
DT_RPW_Profiles_SQL = "Database Connections\\DNAu_GIS_S.sde\\DNAu_GIS_S.EMeyers.DT_RPW_STORE_PROFILES"
DT_RPW_Profiles_TEMP = "Database Connections\\DNAu_GIS_S.sde\\DNAu_GIS_S.EMeyers.DT_RPW_STORE_PROFILES_TEMP"
salesByZipSym = am.Layer("Z:\\Maps\\Base_GIS_Data\\DOCUMENTS\\RPW_Maps_JasonH\\Layers\\SalesByZip.lyr")
rpw_DT_List = []


arcpy.Delete_management(DT_RPW_Profiles)
arcpy.Delete_management(DT_RPW_Profiles_TEMP)
arcpy.TruncateTable_management(DT_RPW_Profiles_SQL)

rpwSearchCursor()

arcpy.Dissolve_management(DT_RPW_Profiles_SQL, DT_RPW_Profiles, "RPW", [["Name", "FIRST"]])
arcpy.CopyFeatures_management(DT_RPW_Profiles, DT_RPW_Profiles_TEMP)

mxd = am.MapDocument("Z:\\Maps\\Base_GIS_Data\\Maps\\RedPlumWraps_JasonH\\working.mxd")
df = am.ListDataFrames(mxd, "Layers")[0]
hftStoresLayer = am.ListLayers(mxd, "Stores", df)[0]
dissolvedDTLayer = am.ListLayers(mxd, "Affected Drive Times-L", df)[0]
dissolvedDTLayerOutline = am.ListLayers(mxd, "Affected Drive Times", df)[0]
RPW_CoverageLayer = am.ListLayers(mxd, "RPW ATZ Coverage", df)[0]

rpwRows = arcpy.SearchCursor(DT_RPW_Profiles_TEMP, "", "", "RPW; FIRST_Name", "RPW A")

for rpwRow in rpwRows:

    rpwZone = str(rpwRow.RPW)
    rpwZoneName = str(rpwRow.FIRST_Name.replace("'", " "))

    rpw_DT_Rows = arcpy.SearchCursor("Database Connections\\DNAu_GIS_S.sde\\DNAu_GIS_S.EMeyers.DT_RPW_STORE_PROFILES", "RPW = '" + rpwZone + "'", "", "Store_Num", "Store_Num A")

    for rpw_DT_Row in rpw_DT_Rows:

        rpw_DT_List.append(rpw_DT_Row.Store_Num)

    rpw_DT_ListESRI = ["%s" % value for value in rpw_DT_List]
    rpw_DT_ListSQL = ["'%s'" % value for value in rpw_DT_List]

    whereClause_STORES = "%s IN(%s)" % ("Str_Num", ', '.join(map(str, rpw_DT_ListESRI)))
    whereClause_ALL = "Date Between '" + str(salesQueryF) + "' AND '" + str(salesQueryT) + "' AND (source = 1) AND %s IN(%s)" % ("Store", ', '.join(map(str, rpw_DT_ListSQL)))

    con = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = 'HIDDEN', database = 'DNAu_GIS_S')
    cur = con.cursor()

    salesUpdateQuery =\
    """
    UPDATE EMeyers.SALES_NEW_CUST_BY_ZIP
    SET StoreNumSales = 0, Total_Sales = 0

    UPDATE EMeyers.SALES_NEW_CUST_BY_ZIP
    SET Total_Sales = Annual_Sales.Total_Sales
    FROM
     (SELECT MAX(Store) AS Store, MAX(Store_Name) AS Store_Name, Zipcode, SUM(Sales) AS Total_Sales
     FROM SALES_BY_ZIP_062010_CURRENT
     WHERE """ + whereClause_ALL + """
     GROUP BY Zipcode) Annual_Sales

    Inner Join EMeyers.SALES_NEW_CUST_BY_ZIP
    ON Annual_Sales.Zipcode = EMeyers.SALES_NEW_CUST_BY_ZIP.Zip
    """

    # Execute SQL query and finalize edits by closing connection and removing 'schema lock'
    cur.execute(salesUpdateQuery)
    con.commit()

    hftStoresLayer.definitionQuery = ""
    dissolvedDTLayerOutline.definitionQuery = ""
    dissolvedDTLayer.definitionQuery = ""
    RPW_CoverageLayer.definitionQuery = ""

    hftStoresLayer.definitionQuery = whereClause_STORES
    dissolvedDTLayerOutline.definitionQuery = "RPW = '" + rpwZone + "'"
    dissolvedDTLayer.definitionQuery = "RPW = '" + rpwZone + "'"
    RPW_CoverageLayer.definitionQuery = "WrapZone = '" + rpwZone + "'"

    arcpy.SelectLayerByAttribute_management(dissolvedDTLayer, "NEW_SELECTION", "RPW = '" + rpwZone + "'")
    arcpy.SelectLayerByAttribute_management(RPW_CoverageLayer, "NEW_SELECTION", "WrapZone = '" + rpwZone + "'")

    df.zoomToSelectedFeatures()
    #df.scale = df.scale * 1.2

    arcpy.SelectLayerByAttribute_management(dissolvedDTLayer, "CLEAR_SELECTION")
    arcpy.SelectLayerByAttribute_management(RPW_CoverageLayer, "CLEAR_SELECTION")

    for lyr in am.ListLayers(mxd, "", df):

        if lyr.name == "Annual Sales By Zip":

            if lyr.symbologyType == "GRADUATED_COLORS":

               lyr.symbology.reclassify()
                arcpy.ApplySymbologyFromLayer_management(lyr, salesByZipSym)

    for name in am.ListLayoutElements(mxd, "TEXT_ELEMENT"):

            if name.name == "RPW":
                name.text = rpwZone

            elif name.name == "RPW_Name":
                name.text = rpwZoneName

            elif name.name == "Date":
                name.text = monthYear

    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()

    mxd.saveACopy("Z:\\Maps\\Base_GIS_Data\\Maps\\RedPlumWraps_JasonH\\RPW_Maps\\Audit\\" + rpwZone + ".mxd")

    am.ExportToPDF(mxd, "Z:\\Maps\\Base_GIS_Data\\PDFs\\RedPlumWrap_JasonH\\Audit\\" + rpwZone + ".PDF")

    rpw_DT_List[:] = []


The line that is bolded and in red is where the crash happens. I have hiddent the Server names for security reasons but believe me, they work. I've written code before to do similar things to what I have here for 400+ stores and don't have an issue.

I also tested to make sure that it wasn't an issue with that particular record and sure enough, if I set the where clause to the individual record, the code works perfectly...

Any suggestions?

Outcomes