Looking at the code, I would do a number of things differently. Some pointers below:
- create dictionaries with the required data on the from and to points (seer lines 22 - 23)
- include a validation to see if there are any from or to points that do not match with the to and from points resp. (see lines 25 - 33)
- only create the output if there is any matching from and to point (line 37)
- although I didn't do this in the code, I would also work with file geodatabase featureclasses so that you don't have to add any length fields (and due to other advantages)
BTW, I did not test the code, so there are likely errors in it. If you want, post some data and I will test to see if it works,
def main():
import arcpy
import os
try:
from_pts = arcpy.GetParameterAsText(0)
from_fld = arcpy.GetParameterAsText(1)
to_pts = arcpy.GetParameterAsText(2)
to_fld = arcpy.GetParameterAsText(3)
out_file = arcpy.GetParameterAsText(4)
fld_id = "Link_ID"
dct_from = {r[0]: r[1] for r in arcpy.da.SearchCursor(from_pts, (from_fld, 'SHAPE@'))}
dct_to = {r[0]: r[1] for r in arcpy.da.SearchCursor(to_pts, (to_fld, 'SHAPE@'))}
from_ids = set(dct_from.keys())
to_ids = set(dct_to.keys())
from_dangles = list(from_ids - to_ids)
to_dangles = list(to_ids - from_ids)
if len(from_dangles) > 0:
arcpy.AddWarning("From dangels:\n:{}".format(from_dangles))
if len(to_dangles) > 0:
arcpy.AddWarning("To dangels:\n:{}".format(to_dangles))
line_ids = list(from_ids & to_ids)
if len(line_ids) > 0:
ws, fc_name = os.path.split(out_file)
spatialRef = arcpy.Describe(from_pts).spatialReference
arcpy.CreateFeatureclass_management(ws, fc_name, "POLYLINE", None, None, None, spatialRef)
fld_from_id = arcpy.ListFields(from_pts, from_fld)
AddField(out_file, fld_id, fld_from_id)
with arcpy.da.InsertCursor(out_file, (fld_id, 'SHAPE@')) as curs:
for link_id in line_ids:
try:
pntg1 = dct_from[link_id]
pntg2 = dct_to[link_id]
polyline = arcpy.Polyline(arcpy.Array([pntg1.firstPoint, pntg2.firstPoint]), spatialRef)
curs.insertRow((link_id, polyline, ))
except Exception, err:
print err.message, link_id
arcpy.AddGeometryAttributes_management(out_file, "LENGTH")
except Exception, err:
print err.message
def AddField(fc, fld_name, fld_templeate):
arcpy.AddField_management(fc, fld_name, fld.type, fld.precision, fld.scale, fld.length)
if __name__ == '__main__':
main()