Sunday, 5 July 2015

arcpy - Python script has execution error first time through on a JoinField, but not the second time


I have some Python code that takes a shapefile, creates its centroids via FeatureToPoint, joins an auxillary field from the shapefile to the centroid via JoinField, and then goes on to do some more work with the centroids.


The relevant code is:


centroids = arcpy.FeatureToPoint_management(shapefile, "centroids", "CENTROID")

arcpy.JoinField_management(centroids, "ORIG_FID", shapefile, "FID", "EXTRA_FIELD")

When I execute this script the first time, I get an error for the JoinField line:


arcgisscripting.ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000732: Input Table: Dataset centroids does not exist or is not supported
Failed to execute (JoinField).

However, checking for the generated centroids shows that it has been created and exists on disk.


When I then execute the script a second time around there is no error and the script proceeds as normal.


While I'm glad to continue executing it twice as far as getting results I need, I'd really like to debug this and figure out why it fails the first time through.



Update


I believe I am running into problems because of how I try to assign the results of FeatureToPoint to the variable centroids and then use centroids in the rest of the code. I added some sanity checks to the above snippet like so:


print(shapefile)
centroids = arcpy.FeatureToPoint_management(shapefile, "centroids", "CENTROID")
print(centroids)
arcpy.JoinField_management(centroids, "ORIG_FID", shapefile, "FID", "EXTRA_FIELD")

The first time through it reads (before failing on the JoinField of course):


D:/temp/boundary.shp
centroids


The second time through it reads (and continues on with rest of the script):


D:/temp/boundary.shp
D:/temp/centroids.shp


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...