Arcpy SelectLayerByLocation выдает ошибку

Предполагается, что этот сценарий выбирает объекты на расстоянии в два слоя на основе некоторых их характеристик. Один объект получит оценку (например: водопроводные трубы, пересекающие естественно чувствительные области, такие как реки, тип этой реки и ее постоянство, влияющие на оценку, поэтому каждый тип будет выбран, а затем использован в функции выбора по лактации, чтобы дать водопроводным трубам, которые находятся на расстоянии своего балла

это ошибка, которую я получаю при запуске этих кодов:

Выполнение: SelectLayerByLocation water_mains WITHIN_A_DISTANCE Just_selected "2,5 метра" NEW_SELECTION Время запуска: чт 25 сентября 15:21:09 2014 ОШИБКА 999999: Ошибка выполнения функции. Был указан столбец, который не существует. Был указан столбец, который не существует. Не удалось выполнить (SelectLayerByLocation).

слой выбора по местоположению находится в сценарии, который вызывается другим сценарием (основной сценарий)

основной скрипт:

def main():

    try:

        import arcpy
        from arcpy import env
        # pathing to avoid retyping 
        env.workspace = "C:/Users/abusheikan/Desktop/prev_files/RiskAnalysisModel"
        dataPath = 'C:\\Users\\abusheikan\\Desktop\\prev_files\\RiskAnalysisModel\\ToolData2'

        arcpy.env.overwriteOutput = True

        import imp

        ##Defines INPUT variables
        #some variable wont be used but are there for future use, I'm starting off as simple as possible
        creekLayer = dataPath + "\\ENVIRONMENTAL\\OHN_WaterCourse.shp"
        PipeLayer=dataPath + "\\SERVICES\\water_mains.shp"

        nameField = 'ROW_1'
        scoreField = 'ROW_SCORE1'
        crossingField = 'CROSS_ROW1'
        ROWfield = 'ROW_TRUE1'

        diaField='INTERNAL_D'
        rangeVal= 416

        Field = 'WARTERCOURS'
        Field2='PERMANENCY'

        arcpy.MakeFeatureLayer_management(PipeLayer,"water_mains")
        inFeatures = "water_mains"

        #The following lists contain road classes. Format is (a, b, c,d) such that a is the creek class name,
        #b is an average permencnacy of flow, c is the width, nd d is the xscore to be given .
        #Lower value of c means lower criticality.

        creeks = [('Vertual Flow','intermittent',10,1),
                  ('Vertual Connector','intermittent', 10,2),
                  ('Vertual Flow','Permanent', 10,1),
                  ('Vertual Connector', 'Permanent', 10,2),
                  ('Ditch','Intermittent',5,3),
                  ('Ditch','Permanent',5,4),
                  ('Stream','Intermittent',5,3),
                  ('Stream','Intermittent',5,4)]
       ## the following isnt used yet
        creeks2 = [('Vertual Flow','intermittent',10,1),
                  ('Vertual Connector','intermittent', 10,2),
                  ('Vertual Flow','Permanent', 10,1),
                  ('Vertual Connector', 'Permanent', 10,2),
                  ('Ditch','Intermittent',5,3),
                  ('Ditch','Permanent',5,4),
                  ('Stream','Intermittent',5,3),
                  ('Stream','Intermittent',5,4)]        


  ## This codeblock isnt utilized yet and will always return row_score, it is supposed to adjusts the value of ROW_SCORE
  ##based on whether the water main crosses a creek, by looking up the value in CROSS_ROW1 feild that is obtained later on 
        expression = "crossing(!CROSS_ROW1!,!ROW_SCORE1!)"

        codeblock = """def crossing(crosses, row_score):
            if crosses != 0:
                return 5
            else:
                return row_score"""



    except:
        arcpy.AddError("Definitions failed")
        arcpy.AddMessage(arcpy.GetMessages())

    try:
        ## pathing to a funtion to be called
        fpath = 'C:\\Users\\abusheikan\\Desktop\\prev_files\\RiskAnalysisModel\\Scripts\\'
        ## defining the function pathing we retyped anyway for debugging purpuses.
        functions = imp.load_source('functions', 'C:\\Users\\abusheikan\\Desktop\\prev_files\\RiskAnalysisModel\\Scripts\\functions_creeks.py')
         ## check check :-p
        arcpy.AddMessage("Funtions Loaded")

    except:
        arcpy.AddMessage("Functions not loaded")

    try:


    ##Clear all selections, because otherwise commands will be applied only to selected features, why? I ont know pls explain where this is
        ## supposed to be used and where not to. THANKs!

        arcpy.SelectLayerByAttribute_management(inFeatures, "CLEAR_SELECTION")
        arcpy.AddMessage("Selected")

    ##This new field will show the road overlying the pipe. Default value of "no Creek" will be assigned.
        arcpy.AddField_management(inFeatures, nameField, "TEXT")

        arcpy.CalculateField_management(inFeatures, nameField, '"No Creek"')

    ##This field will contain a score for the highest creek class over the pipe.
    ##  Default of 0 means no creeks 
        arcpy.AddField_management(inFeatures, scoreField, "SHORT")

        arcpy.CalculateField_management(inFeatures, scoreField, 1)

        arcpy.AddField_management(inFeatures, crossingField, "SHORT")


##        arcpy.AddField_management(mainRoadLayer, ROWfield, "FLOAT",3,1)
##        arcpy.CalculateField_management("t_Pavement_Line", ROWfield, expressionROW, "PYTHON_9.3", codeblockROW)

    except:

        #Report error
        arcpy.AddError("Could not create new fields")

        #Report error messages
        arcpy.AddMessage(arcpy.GetMessages())

    try:

##        functions.roadclass_loop is a function that loops through all creek classes in
##        a list, selects the water mains within a distance of each one, and assigns the
##        appropriate score. Full script is in the called function.


## the following s a failed test so never mind that commented out line, it may ciome in handy so left it in there
       ## arcpy.MakeFeatureLayer_management(PipeLayer, 
           ## "JUST_MADE",str(dialField) + " <= "+ str(rangeVal)) 


         ## calls creek_loop funtion() i think here is where the error is created pls check the inputs they may be where problem is! but i cant see anything wrong with them.
        functions.roadclass_loop(creeks, creekLayer, Field, inFeatures, "WITHIN_A_DISTANCE",
                                                 nameField, scoreField)
        arcpy.AddMessage("small pipes")            

        ## same as b4 but with the second tuple list.       
        functions.roadclass_loop(creeks2, creekLayer, Field, inFeatures, "WITHIN_A_DISTANCE",
                                 nameField, scoreField)
        arcpy.AddMessage("BIG PIPES")


       ## functions.roadclass_loop(provincial, provincialLayer, Field3, inFeatures, "INTERSECT",
       ##                          "", crossingField)

##        If the CROSS_ROW field has a nonzero value (i.e. if the water main crosses a large road)
##        the road class score will be increased to 5(the maximum). 
        ## inserts the scores into the 
        arcpy.CalculateField_management(inFeatures, scoreField, expression, "PYTHON_9.3", codeblock)

    except:
        arcpy.AddMessage("Could not run")
        arcpy.AddMessage(arcpy.GetMessages())


if __name__== "__main__":
    main()

вызываемая функция:

def test():
##    import arcpy
    arcpy.AddMessage("This function works")

##def roadclass_loop(listOfClassTuples, sourceLayer, fieldName, targetLayer,
##                   outputField1, outputField2):

def roadclass_loop(listOfClassTuples, sourceLayer, fieldName, targetLayer, crossingType,
                   outputField1, outputField2):

    import arcpy
    from arcpy import env

    env.workspace = "C:/data/"

    ##try: 

    for creekclass in listOfClassTuples:

            (classname, Permanency, creekWidth, score) = creekclass

            bufferDistance = creekWidth*0.5
    try:
            if crossingType == "INTERSECT":
                stringBuffer = ""
            else: 
                stringBuffer = "%s Meters" % str(bufferDistance)
    except:
            arcpy.AddMessage("its here")
    arcpy.MakeFeatureLayer_management(sourceLayer, "Just_selected",
                                      fieldName + "= '"+ classname + "'")
    #arcpy.MakeFeatureLayer_management("Just_Selected", "JUST_SELECTED", FieldName2+" = '"+ Permanency + "'") 

    arcpy.SelectLayerByLocation_management(targetLayer, crossingType,
                                           "Just_selected", stringBuffer, "NEW_SELECTION")

    classname = classname.lower()

    if outputField1!= "":                                        

                arcpy.CalculateField_management(targetLayer, outputField1,   classname )

                arcpy.CalculateField_management(targetLayer, outputField2,   score )


    arcpy.Delete_management("Just_selected")
    arcpy.SelectLayerByAttribute_management(targetLayer, "CLEAR_SELECTION")

    ##except:

       # arcpy.AddMessage("Function failed")
        #arcpy.AddMessage(arcpy.GetMessages())

2 ответа

См. Этот вопрос в GIS StackExchange: Точки в счетчике полигонов: ошибка с arcpy.selectLayerByLocation_management. Они допустили ошибку при вызове MakeFeatureLayer_management, но ошибка была выбрана SelectLayerByLocation_management. У вас может быть похожая ситуация.

В вашем случае вы уверены, что класс пространственных объектов хранится в dataPath + "\\ENVIRONMENTAL\\OHN_WaterCourse.shp" имеет поле под названием WARTERCOURS? Может там опечатка? (Слово WARTERCOURS привлекло мое внимание; Google говорит, что вы первый человек в Интернете, чтобы использовать его.)

Является ли ваш listOfClassTuples, который подается переменной creeks, набором полей в вашем creekLayer (dataPath + "\ENVIRONMENTAL\OHN_WaterCourse.shp)?

Другие вопросы по тегам