3

The part of the script I'm having trouble with is the arcpy.SearchCursor. The cursor runs 1x and then does not re-run. The goal was to re-retrieve the field value and apply it to the image layout. It works on the first run but then applys the same value to every image layout after. The SQL query I'm using limits the records to 1 record, but I was hoping it would re-run and apply the new SQL query.

x = 1    

while x <= formatted_rand_ct:
    row_rand = random.randint(0,record_count)        
    sqlExp = new_name + "=" + str(row_rand)
    rows = arcpy.SearchCursor(newlayer, sqlExp)
    for row in rows:
        l = row.getValue(field_label)
    arcpy.SelectLayerByAttribute_management(newlayer, "NEW_SELECTION", sqlExp)
    df.zoomToSelectedFeatures()
    if desc.shapeType == "Point":
        df.scale = scale
    if desc.shapeType == "Point" or desc.shapeType == "Polygon":               
        elm = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT")[0]
        elm.text = str(field) + " " + str(row_rand)                        
        elm2 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT")[3]
        elm2.text = str(l)                                               
        arcpy.mapping.ExportToJPEG(mxd, output + str(row_rand))
        arcpy.RefreshActiveView()
        arcpy.AddMessage("Finished Export of Image: OBJECTID" + " " + str(row_rand))
        x += 1           
    else:
        arcpy.AddMessage("Points or Polygons Only")
        break
del mxd   
arcpy.AddMessage("\nDone!\n")
2
  • Are you sure it's not your while that isn't broken. for row in rows: will only return one row when you just limit it to one in your sqlExp – Nathan W Oct 23 '13 at 13:31
  • The while loop seems to work fine as it loops through and creates the jpeg exports correctly. Is there an easier way to retrieve a specific field value than search cursor? – RustyShackleford Oct 23 '13 at 13:46
1

I figured it out, the combination of using the selectbyattributes and searchcursor was locking up the cursor.

0

You should always delete your cursor objects. (Workaround is to use with, if you have ArcGIS 10.1+)

Try changing this part:

rows = arcpy.SearchCursor(newlayer, sqlExp)
for row in rows:
    l = row.getValue(field_label)

into this:

rows = arcpy.SearchCursor(newlayer, sqlExp)
for row in rows:
    l = row.getValue(field_label)
del rows
del row

del l

By also deleting l you ensure to have a new value (or an error) each loop, although you should have that part at the very end of your loop.

1
  • yea I don't have 10.1 yet, but I tried your suggestion and I got an error "name 'row' is not defined" after it exported the first image. So it looped through once and then stopped working – RustyShackleford Oct 23 '13 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.