Python newbie problem

Discussion created by mfutch78 on Mar 9, 2012
Latest reply on Mar 9, 2012 by clm42

I'm running a python script in 9.3 and running into a problem.  The code cycles through the 800 or so shapefiles and performs the function I need it to, but after some time I start to get the following error message (nested in my print commands):

2012-03-08 12:05:30.544000
Village to District Join Complete
Buffer Complete
NOT NULL = Z://futch//python//outputs//buffer//136_shpbuff.shp
Raster Extraction Complete
Raster to Point Complete
Spatial Join Complete
Field Delete Complete
['id_pseudo', 'id_text', 'BUFF_DIST', 'GRID_CODE']
found 4650229 rows
Traceback Info:
  File "Z:\futch\python\", line 159, in <module>
Error Info:
    <class 'Queue.Empty'>:

Deleting Intermediate Files
2012-03-08 13:57:34.357000

I continue to get that error for more and more shapefiles.  If I run the function on that 136.shp by itself, it works fine.  Also if I start with 136.shp it will work on many more shapefiles until I start to get the same error.  I'd like to be able to run the code all at once and not have to restart once the error pops up.  Any ideas would be greatly appreciated!  Code pasted below:

#This script takes individual district polygon, village points, and slope raster data
#to create comma separated value files for each district.  Each entry will be a cell
#georeferenced to a village and containing an indicator for slope greater than 15 degrees.
#Stata file aggregates and collapses to village level data.

import arcgisscripting, sys, os, traceback

from datetime import datetime
print str(
#Create the Geoprocessor object

GP = arcgisscripting.create()

GP.AddToolbox("C:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
GP.AddToolbox("C:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
GP.AddToolbox("C:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Analysis Tools.tbx")

GP.OverWriteOutput = 1

#Set the input workspace: Feature classes of village points only in this folder
GP.workspace = "Z:/futch/python/outputs/districts"

#Choose the distance in meters for circles around villages - "1000" or "1000;2000"
BufferDistance = "750;1250;1750;2250"

villagefull = "Z://futch//python//outputs//villagefull.shp"
districtpoint = "Z://futch//python//outputs//temp//distpoint.shp"
#Set the clip featureclass
rasterFeatures1 = "Z://futch//python//outputs//reclass"
rasterFeatures2 = "Z://futch/python//outputs//slope_india"
rasterFeatures3 = "Z://futch//python//outputs//indiaproj"
Extract_buff = "Z://futch//python//outputs//extract_buff"
reclass_point = "Z:\\futch\\python\\outputs\\temp\\reclass_point.shp"

#Set the output workspace

outWorkspace = "Z://futch//python//outputs//tables"
outWorkspace2 = "Z://futch//python//outputs//proj"
outWorkspace3 = "Z://futch//python//outputs//buffer"
scratchspace = "Z://futch//python//outputs//scratchspace.gdb"


    #Get a list of the featureclasses in the input folder "Z:/futch/python/outputs/districts"
    #If the function breaks down, move the completed districts to other folder
    fcs = GP.ListFeatureClasses()

    #Loop through the list of feature classes


    #Iterates over features in district folder
    fc = fcs.Next()

    #Add id_pseudo to village file, based off arcgis FID
    GP.AddField_management(villagefull, "id_pseudo", "text", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "")
    GP.CalculateField_management(villagefull, "id_pseudo", "[FID]", "VB", "")

    while fc:

        #Validate the new feature class name for the output workspace.
        GP.workspace = "Z:/futch/python/outputs/districts"

        #Change extent to union in case the intersection is empty, avoids breakdown
        #in spatial join of villages to districts.
        GP.extent = "MAXOF"
        GP.SpatialJoin_analysis(villagefull, fc, districtpoint, "JOIN_ONE_TO_ONE", "KEEP_COMMON", "", "INTERSECTS", "0 Unknown", "")
        GP.extent = "Default"

        print "Village to District Join Complete"

        fc_project = outWorkspace2 + "//" + GP.ValidateTableName(fc,outWorkspace2)+ ".shp"
        bufferFeatureClass = outWorkspace3 + "//" + GP.ValidateTableName(fc, outWorkspace3) + "buff.shp"
        joinFeatureClass = scratchspace + "//" + "join" + GP.ValidateTableName(fc, scratchspace)                                                                
        GP.workspace = "Z:/futch/python/outputs"

        #Buffer around each village in meters
        GP.MultipleRingBuffer_analysis(districtpoint,bufferFeatureClass, BufferDistance, "Meters", "distance", "NONE", "FULL")
        print "Buffer Complete"

        #Delete unnecessary fields.
        GP.DeleteField_management(bufferFeatureClass, "Join_Count;NAME")

        ## gp.GetCount will blow up if the shapefile is NULL so this
        ##  try/except will prevent that from happening.
            if int(GP.GetCount_management(bufferFeatureClass)) != 0:
                print "NOT NULL = "+ bufferFeatureClass

                #Extract slope rasters around each village
                GP.ExtractByMask_sa(rasterFeatures1, bufferFeatureClass, Extract_buff)
                print "Raster Extraction Complete"

                #Convert Slope raster to point data
                GP.RasterToPoint_conversion(Extract_buff, reclass_point, "VALUE")
                print "Raster to Point Complete"

                #Join point data to buffers around villages
                GP.SpatialJoin_analysis(bufferFeatureClass, reclass_point, joinFeatureClass, "JOIN_ONE_TO_MANY", "KEEP_COMMON", "", "INTERSECTS", "0 Unknown", "")
                print "Spatial Join Complete"

                #Delete unnecessary fields
                GP.DeleteField_management(joinFeatureClass, "Id;POINTID;Join_Count")
                print "Field Delete Complete"

                #Next chunk of code converts pointfile with village data to csv
                #file for easy input into stata.  One file for each district.
       will aggregate and collapse to village level data.
                GP.workspace = scratchspace ## workspace of the table or feature class
                table = joinFeatureClass ## table or feature class from wich the attributes should be exported

                outputpath = outWorkspace + "//" + GP.ValidateTableName(fc,outWorkspace) + ".csv" ## path to the file where the output should be written to
                csvseparator = ',' ## column separator field

                def print_exception():
                    tb = sys.exc_info()[2]
                    l = traceback.format_tb(tb)
                    tbinfo = "".join(l)
                    pymsg = "ERROR:\nTraceback Info:\n" + tbinfo + "Error Info:\n    " +  str(sys.exc_type)+ ": " + str(sys.exc_value) + ""
                    print pymsg

                def get_fieldnames(fields, ignorefields=[]):
                    fields_output = []
                    for field in iter(, None):
                        if not in ignorefields:
                    return fields_output

                    fields = GP.listfields(table)
                    fieldnames = get_fieldnames(fields, ignorefields)
                    print fieldnames
                    rows = GP.searchcursor(table)

                    output = []
                    for row in iter(, None):
                        outputrow = []
                        for fieldname in fieldnames:
                        outputrow = csvseparator.join(outputrow)
                    print 'found', str(len(output)), 'rows'
                    f = open(outputpath, 'w')
                    print GP.getmessages(2)

                #Move to the next fc in the list.

                print "Deleting Intermediate Files"

            print "NULL = "+bufferFeatureClass

        print fc
        from datetime import datetime
        print str(

        #iterates to next district
        fc = fcs.Next()


    print GP.GetMessages(2)