Select to view content in your preferred language

Will anything in "with arcpy.da.SearchCursor(fc,fields,'1=2') as cursor" execute?

627
2
Jump to solution
03-08-2013 08:14 AM
StormwaterWater_Resources
Regular Contributor
Does a "with" block always execute even when passed an empty cursor?

For testing purposes I've tried this:

with arcpy.da.SearchCursor(fc, "ST_ID", "1=2") as cursor:     arcpy.AddMessage("In the With")     try:         test = cursor.next()         arcpy.AddError("ERROR:  There is more than one ...")         sys.exit(1)     except StopIteration:         arcpy.AddMessage("All is good, there's one and only one ...")         pass


Note the "where" clause. 

I'm expecting this search cursor to return 0 or 1 rows.  I was thinking that the "with" block would only be executed if I had a row.  Then my intent with the "try" was to catch a 2nd row which I shouldn't ever have.

However in testing this I realized I'm always going into the with block.  To be sure I put in the False where clause.  Even with that where clause I'm seeing the "In the With" statement in my results window. 

I'm trying to wrap my head around the with statement, but even though others have said I have a big head it's not fitting...

PS: or am I not understanding something about the search cursor?
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
JimCousins
MVP Alum
Yes, a with statement will always step in, attempt the try, and move into the except as necessary. For a deeper explanation: http://effbot.org/zone/python-with-statement.htm

View solution in original post

0 Kudos
2 Replies
curtvprice
MVP Alum
If you don't expect a lot of rows, GetCount would probably be very quick for this test:

numRows = int(arcpy.GetCount_management(fc).getOutput(0))
if numRows == 1:
    arcpy.AddMessage("All is good, there's one and only one ...")
else:
    arcpy.AddError("All is not good: {0} rows found".format(numRows))


This worked for me too:

with arcpy.da.SearchCursor(fc, "ST_ID") as cursor:
    arcpy.AddMessage("In the With")
    try:
        test = cursor.next()
        arcpy.AddMessage("Got one.")
        test = cursor.next() # try get a second row
    except StopIteration:
        arcpy.AddError("ERROR:  There is more than one ...")
        sys.exit(1)
    except:
        arcpy.AddError("Something else happened!")
 
0 Kudos
JimCousins
MVP Alum
Yes, a with statement will always step in, attempt the try, and move into the except as necessary. For a deeper explanation: http://effbot.org/zone/python-with-statement.htm
0 Kudos