import arcpy,sys
sdeConn = r"Database Connections\\Test.sde"
muniLoc = "Municipalities"
luLoc = "Land_Use"
tempLoc = "tempMuniLuRatio"
arcpy.env.workspace = sdeConn
try:
print "MakeFeatureLayer_management lu_lyr"
arcpy.MakeFeatureLayer_management(luLoc, "lu_lyr")
prematchcount = int(arcpy.GetCount_management("lu_lyr").getOutput(0))
print "MakeFeatureLayer_management muni_lyr"
#arcpy.MakeFeatureLayer_management(muniLoc, "muni_lyr")
print "SelectLayerByLocation_management COMPLETELY_WITHIN"
arcpy.SelectLayerByLocation_management("lu_lyr", "COMPLETELY_CONTAINS",muniLoc,"","SWITCH_SELECTION")
postmatchcount = int(arcpy.GetCount_management("lu_lyr").getOutput(0))
if prematchcount == postmatchcount:
print "SelectLayerByLocation_management DID NOT WORK"
else:
print "SelectLayerByLocation_management LOOKS GOOD"
if arcpy.Exists(tempLoc):
print "Delete_management "
arcpy.Delete_management(tempLoc)
print "CopyFeatures_management "
arcpy.CopyFeatures_management('lu_lyr',tempLoc)
except Exception:
e = sys.exc_info()[1]
print(e.args[0])
所以我加
if prematchcount == postmatchcount:
查看
SWITCH_SELECTION
是否有效。每次返回与源要素
class
相同的结果。我在代码中错过了什么吗?
最佳答案
TL; DR
更改此:
arcpy.SelectLayerByLocation_management("lu_lyr", "COMPLETELY_CONTAINS",muniLoc,"","SWITCH_SELECTION")
对此:
arcpy.SelectLayerByLocation_management("lu_lyr", "COMPLETELY_CONTAINS",muniLoc)
arcpy.SelectLayerByLocation_management("lu_lyr", None, None, "", "SWITCH_SELECTION")
细节
GetCount_management
和SelectLayerByLocation_management
如文档所述工作。从Get Count:
如果在输入上定义了选择,则返回所选行的计数。
从Select Layer By Location:
SWITCH_SELECTION —切换选择。所有选择的记录都将从选择中删除,所有未选择的记录都添加到选择中。选择此选项时,将忽略select_features和overlay_type参数。
让我解释一下您的代码在做什么以及为什么它是正确的。
arcpy.MakeFeatureLayer_management(luLoc, "lu_lyr")
您创建没有选择的要素图层。假设
Land_Use
要素类具有42个要素。prematchcount = int(arcpy.GetCount_management("lu_lyr").getOutput(0))
由于在
lu_lyr
上未定义选择,因此将计算要素类中的所有要素,并且prematchcount
现在等于42。arcpy.SelectLayerByLocation_management("lu_lyr", "COMPLETELY_CONTAINS",muniLoc,"","SWITCH_SELECTION")
由于使用的是
SWITCH_SELECTION
,因此将忽略COMPLETELY_CONTAINS
和muniLoc
,只需切换选择即可。在此呼叫之前,选择了零个功能。此调用切换选择,以便选择所有42个功能。postmatchcount = int(arcpy.GetCount_management("lu_lyr").getOutput(0))
由于选择是在
lu_lyr
上定义的,因此仅对所选特征进行计数。上一行选择了全部42个特征,因此postmatchcount
现在等于42。if prematchcount == postmatchcount:
真正。他们都是42岁。
您的解决方案取决于您想做什么,而您没有说。我的猜测是,您想在
Land_Use
中选择不完全包含Municipalities
中所有功能的所有功能,然后将这些选定的功能复制到tempMuniLuRatio
中。如果是这样,请进行此答案顶部所述的更改。如果不是,请编辑您的问题以解释您要做什么。关于python - SWITCH_SELECTION不适用于SelectLayerByLocation_management,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33354363/