The key is the
difference method on geometry objects. The following code is far from efficient, since a new update cursor is opened for each polygon. But it has the added benefit of supporting multiple polygons on the same line:
import itertools, arcpy
arcpy.env.overwriteOutput = True
line_FC = r'<path to lines>'
poly_FC = r'<path to polygons>'
output = r'<path to result>'
#clone input lines to memory for fast processing
temp = arcpy.CopyFeatures_management(line_FC, "in_memory/temp")
polygons = arcpy.CopyFeatures_management(poly_FC, arcpy.Geometry())
for poly in polygons:
with arcpy.da.UpdateCursor(temp, ["SHAPE@"]) as uCursor:
for line in uCursor:
line = line
diff = line.difference(poly)
#if the two lines are not equal, that means it intersected the polygon
if not line.equals(diff):
#the result of geometry.difference() is a multipart line of only those
#parts that lie outside the polyon
parts = diff.getPart()
#if parts is empty that means the line is completely within the polygon
#i.e., no difference
#We'll need to "join" the end of part1 to the beginning of part2
#so we'll just flatten the list of lists
joined = list(itertools.chain.from_iterable(parts))
#and create a new polyline object to update the shape
poly_trimmed = arcpy.Polyline(arcpy.Array(joined))
I haven't tested it with edge cases, but this should get you started.