Restart: Shell - Can I use "Exception Passing/Continue" in "For loop" that is hung up on potentially missing data

247
3
09-08-2021 11:19 AM
EvanSweeney
New Contributor II

Hi There, 

This is a continuation of another question I had that i found a work around for (https://community.esri.com/t5/python-questions/iterate-through-selected-attributes-and-export/m-p/10...)

I am using a For loop to iterate through a selection of SQL queries. These queries were built from request for land units that may no longer be valid. I built the queries with a series of excel workarounds. I have no idea which ones are still valid or not. The problem i am running into is that when start the script it will run through the first few that are still valid and then get hung up on the next one that isnt. I have run into this before when I was setting each variable my self. The maps produced would be for the entire data frame since my zoom to extent was not set, since there was nothing to zoom to. What i believe is happening when the script gets to the missing data value is the extent is zooming to full extent and the outputting map is causing an error, specifically its presenting "Restart: Shell". 

Im wondering if there is a way to set an "except: " to move the program along if the runtime is beyond a certain timeline. Or if there is any other option? I have tried adding a "Try, except" to the code but I'm not clear in how those work or what exception to use. 

This isnt the full code but its enough to explain what i set up. 

 

 

import arcpy, os

########### Specify output path and final output PDF ###########
################################################################
outPath = r'C:\Outputs'
mxd = arcpy.mapping.MapDocument(r'C:\Template.mxd')
df = arcpy.mapping.ListDataFrames(mxd, 'Layers')[0]

##################Specify name for final PDF####################
################################################################
################################################################
pdfPath = os.path.join(outPath, '1. test.pdf')
if os.path.exists(pdfPath):
     os.remove(pdfPath)
finalPdf = arcpy.mapping.PDFDocumentCreate(pdfPath)
            
#################### ASSIGN VARIABLES ###########################
#################################################################
#################################################################
#################################################################


District = ("Wyoming County Soil & Water Conservation District")
County = ("Wyoming")
AssistedBy = ("Bob Conservationist, Resource Conservationist")
FieldOffice = ("Hamilton")
################################################################

# Specify the areas of interest with an SLQ statement
SQL = ["TRACTNBR IN (1831) AND CLUNBR IN ( 1,2)",
       "TRACTNBR IN (1911) AND CLUNBR IN ( 3,5)",
       "TRACTNBR IN (25885) AND CLUNBR IN ( 2)",
       "TRACTNBR IN (25961) AND CLUNBR IN ( 35)",
       "TRACTNBR IN (23498) AND CLUNBR IN ( 6)",
       "TRACTNBR IN (25254) AND CLUNBR IN ( 32,45)",
       "TRACTNBR IN (26101) AND CLUNBR IN ( 12)",
       "TRACTNBR IN (26251) AND CLUNBR IN ( 4,5,6,14,20)",
       "TRACTNBR IN (26767) AND CLUNBR IN ( 1)",]


##  Run for loop through each SQL statement  ##
for SQL in SQL:
     try:
          pdfPath = os.path.join(outPath, '1. test.pdf')
          if os.path.exists(pdfPath):
              os.remove(pdfPath)
          finalPdf = arcpy.mapping.PDFDocumentCreate(pdfPath)

          mxd = arcpy.mapping.MapDocument(r'C:\Template.mxd')
          df = arcpy.mapping.ListDataFrames(mxd, 'Layers')[0]
          lyr = arcpy.mapping.ListLayers(mxd, 'clu', df)[0]
          arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION",'{0}'.format(SQL))
          df.zoomToSelectedFeatures()
          lyr.definitionQuery = '{0}'.format(SQL)

          arcpy.SelectLayerByAttribute_management(lyr, "CLEAR_SELECTION")
          arcpy.RefreshActiveView()

          lyrAlwaysOnList = ['clu','street100k_l_067','wtrcls_l_ny']
          print mxd
          
          ## itterate through all data layers needed for determination##   
          for lyrName in lyrAlwaysOnList:
              lyr = arcpy.mapping.ListLayers(mxd, lyrName, df)[0]
              lyr.visible = True
              print("\tSet layer-visibility for '" + lyr.name + "' to " + str(lyr.visible))

          # Turn on visibility for each theme and export the page
          lyrList = ['Wetspots','National Wetlands Inventory','Wetlands','Soils',
                    'Soil Special Features','Percent Hydric Soil',
                    'Highly Erodible Land (R85)', 'Highly Erodible Land (R80)','Topographic']

          # Don't assume the layers are turned off...Turn them off first.
          print("First, turn off all the layers")
          for lyrName in lyrList:
              lyr = arcpy.mapping.ListLayers(mxd, lyrName, df)[0]
              lyr.visible = False
              print("\tSet layer-visibility for '" + lyr.name + "' to " + str(lyr.visible))

          print("Second, export to PDF")
          for lyrName in lyrList:
              print("---")
              lyr = arcpy.mapping.ListLayers(mxd, lyrName, df)[0]
              lyr.visible = True
              print("\tSet layer-visibility for '" + lyr.name + "' to " + str(lyr.visible))

              #Change Map Title text
              TextElement = arcpy.mapping.ListLayoutElements(mxd,"TEXT_ELEMENT","TextTitle")[0]
              TextElement.text = lyrName

              #Change AssistedBy text
              TextElement = arcpy.mapping.ListLayoutElements(mxd,"TEXT_ELEMENT","AssistedBy")[0]
              TextElement.text = AssistedBy

              #Change Landunits
              TextElement = arcpy.mapping.ListLayoutElements(mxd,"TEXT_ELEMENT","SQL")[0]
              TextElement.text = SQL
              
              #Export each theme to a temporary PDF and append to the final PDF
              tmpPdf = os.path.join(outPath, SQL + lyrName + '_temp.pdf')
              if os.path.exists(tmpPdf):
                   os.remove(tmpPdf)
              arcpy.mapping.ExportToPDF(mxd, tmpPdf)
              print("\tPDF Exported to following path: " + tmpPdf)
              finalPdf.appendPages(tmpPdf)

              #Turn off layer visibility and clean up for next pass through the loop
              lyr.visible = False
              print("\tSet layer-visibility for '" + lyr.name + "' to " + str(lyr.visible))

 finalPdf.saveAndClose()
          del mxd, df, finalPdf

 

 

0 Kudos
3 Replies
nzjs
by
New Contributor III

If I'm understanding correctly, you want to skip a SQL query where it fails inside the for loop's try block? If so, you can simply add an exception at the end of the for loop (same indentation as the try block) with continue statement. 

try: 
  ...

except Exception as e:
  ... (handle the exception e)
  continue
0 Kudos
EvanSweeney
New Contributor II

So I had tried that originally. I'm not sure if except is the proper route because it's more of a timing-out issue. I also added 

except (timeouterror, memoryerror): 
       continue

 

but found that it kept hanging up on a known missing CLU/Fld. I have run this code with the same issue of having a missing CLU or field and the maps it produces is for the extent of the data frame so that is why I think it's a timing out issue or because of the amount of data, perhaps a memory issue. I'm not too sure about it. Ill try the exception  as e next. Thanks!

0 Kudos
JoeBorgione
MVP Esteemed Contributor

Just an extra $00.02...

If you simply use a continue statement in the except portion of you try/except block, you'll never know there was a problem.

Toss in a print() statement or write to a log file that something went south is what I suggest doing.

That should just about do it....
0 Kudos