SWITCH_SELECTION无法与SelectLayerByLocation_management一起使用

时间:2015-10-26 19:48:39

标签: python arcgis arcpy arcmap

 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相同的结果。

我的代码中有什么遗漏?

1 个答案:

答案 0 :(得分:2)

<强> 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_managementSelectLayerByLocation_management正在记录中工作。

来自Get Count

  

如果在输入上定义了选择,则返回所选行的计数。

来自Select Layer By Location

  

SWITCH_SELECTION - 切换选择。从选择中删除所选的所有记录,并将所有未选择的记录添加到选择中。选择此选项时,将忽略 select_features overlap_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_CONTAINSmuniLoc,并且只需切换选择。在此调用之前,选择了零功能。此调用将切换选择,以便选择所有42个功能。

postmatchcount = int(arcpy.GetCount_management("lu_lyr").getOutput(0))

由于在lu_lyr上定义了选择,因此仅计算所选要素。上一行选择了所有42个要素,因此postmatchcount现在等于42。

if prematchcount == postmatchcount:

真。他们都是42岁。

你的修复取决于你想做什么,你没说。我的猜测是,您要选择Land_Use中未完全包含Municipalities中的某项功能的所有功能,并将这些选定功能复制到tempMuniLuRatio。如果是,请进行此答案顶部描述的更改。如果没有,请编辑您的问题以解释您想要做什么。