1. 程式人生 > 實用技巧 >11章程式碼

11章程式碼

10.2 自動獲得Excel工作表和欄位

#coding: UTF-8
import arcpy
import os
import xlrd
class ToolValidator(object):
  """Class for validating a tool's parameter values and controlling
  the behavior of the tool's dialog."""

  def __init__(self):
    """Setup arcpy and the list of tool parameters."""
    self.params 
= arcpy.GetParameterInfo() def get_sheet_names(in_excel): """ Returns a list of sheet names for the selected excel file. This function is used in the script tool's Validation """ workbook = xlrd.open_workbook(in_excel) return [sheet.name for sheet in workbook.sheets()]
def getField(sheet): out_fields = [] colnum=sheet.ncols # Generate the list of output fields for i in range (1,colnum): out_fields.append(sheet.cell(1,i).value) return out_fields def initializeParameters(self): """Refine the properties of a tool's parameters. This method is called when the tool is opened.
""" return def updateParameters(self): import ExcelToTable # Check that excel file exists, and that validation should be performed in_excel = unicode(self.params[0].value) if os.path.basename(sys.executable) in ['ArcMap.exe', 'ArcCatalog.exe', 'ArcScene.exe', 'ArcGlobe.exe']: if arcpy.Exists(in_excel) and os.path.splitext(in_excel)[1] in ['.xls', '.xlsx']: # Set the output table properties to depend on the input excel file self.params[1].parameterDependencies = [0] if (not self.params[0].hasBeenValidated) or (not self.params[2].filter.list) : # Get a list of the sheets in the excel file, for user choice sheet_names=ExcelToTable.get_sheet_names(in_excel) self.params[1].filter.list =sheet_names # Automatically change the sheet value to the first sheet if not self.params[1].altered: self.params[1].value = sheet_names[0] try: if self.params[1].value: sheet_name=self.params[1].value worksheet, workbook=ExcelToTable.open_excel_table(in_excel,sheet_name) fields = [] colnum=worksheet.ncols #self.params[2].value="YL"+str(colnum) # Generate the list of output fields for i in range (0,colnum): #self.params[2].value="MY"+str(i) fields.append(worksheet.cell(0,i).value) #self.params[2].value=out_fields[0] #self.params[3].value="YY" #x self.params[2].filter.list = fields # Automatically change the sheet value to the first sheet if not self.params[2].altered: if self.params[2].value==None: self.params[2].value = fields[0] #y self.params[3].filter.list = fields # Automatically change the sheet value to the first sheet if not self.params[3].altered: if self.params[3].value==None: self.params[3].value =fields[1] except Exception, ErrorDesc: arcpy.AddError(u"error:"+str(ErrorDesc)) return def updateMessages(self): """Modify the messages created by internal validation for each tool parameter. This method is called after internal validation.""" return

10.3 自動獲得MXD的圖層

#coding: UTF-8
import arcpy
class ToolValidator(object):
 
  def updateParameters(self):

    if self.params[0].value:
        mymxd=self.params[0].value.value
        #self.params[1].value=mymxd
        mxd = arcpy.mapping.MapDocument(mymxd)

        #Generate unique list of layer names
        lyrs = arcpy.mapping.ListLayers(mxd)
        layerList = []
        for lyr in lyrs:
            layerList.append(lyr.name)
        uniqueLayerList = list(set(layerList))
        uniqueLayerList.sort()

        if not self.params[1].altered:#沒有修改
            self.params[1].filter.list = uniqueLayerList
            if len(uniqueLayerList)>0:
                self.params[1].value=uniqueLayerList[0]
        return

10.4 根據範圍,自動設定柵格解析度

import arcpy
class ToolValidator(object):
  """Class for validating a tool's parameter values and controlling
  the behavior of the tool's dialog."""
  
  def updateParameters(self):
    if self.params[2].value:
        desc= arcpy.Describe(self.params[2].value)
        extent=desc.extent
        width = extent.width#extent.XMax - extent.XMin
        height = extent.YMax - extent.YMin
        nn=250
        #if self.params[3].value==None:
        if not self.params[3].altered:
            if width < height:
                self.params[3].value = width /nn
            else:
                self.params[3].value = height /nn
    return

10.5 拓撲檢查根據型別讓使用者選擇不同的拓撲規則

def updateParameters(self):
  """Modify the values and properties of parameters before internal
  validation is performed.  This method is called whenever a parameter
  has been changed."""
  if self.params[0].value:
      desc = arcpy.Describe(self.params[0].value)
      shapeType = desc.shapeType
      if shapeType.upper() == "POINT":
          self.params[2].filter.list = ["Must Be Disjoint (Point)"]
      elif shapeType.upper() == "POLYGON":
          self.params[2].filter.list = ["Must Not Have Gaps (Area)", "Must Not Overlap (Area)"]
      elif shapeType.upper() == "POLYLINE":
          self.params[2].filter.list = ["Must Not Overlap (Line)","Must Not Intersect (Line)",
          "Must Not Have Dangles (Line)","Must Not Have Pseudo-Nodes (Line)","Must Not Self-Overlap (Line)"
           ,"Must Not Self-Intersect (Line)",
           "Must Not Intersect Or Touch Interior (Line)","Must Be Single Part (Line)"]
      else:
          self.params[2].enabled=False

      if self.params[2].enabled:
          if self.params[2].value=="" or self.params[2].value==None:
              self.params[2].value=self.params[2].filter.list[0]
  return

10.6 選擇資料庫自動列出表

def updateParameters(self):
    if self.params[0].value:
        mypath=self.params[0].value
        arcpy.env.workspace =mypath
        #=======引數的型別必須必須是字串,切記切記切記======================
     
        tables = arcpy.ListTables()
        if not self.params[1].altered:
            self.params[1].filter.list = tables
            if len(tables)>0:
                self.params[1].value=tables[0]
##        if self.params[1].value=="" or self.params[1].value==None:
##            self.params[1].value=self.params[1].filter.list[0]

    return

10.7 選擇資料庫自動列出要素類

def updateParameters(self):
    if self.params[0].value:
        mypath=str(self.params[0].value) #str python TypeError: unsupported operand type(s) for +: 'geoprocessing value object' and 'str'
        arcpy.env.workspace =mypath
       #=======引數的型別必須必須是字串,切記切記切記======================
        featureclasses = arcpy.ListFeatureClasses() #feature_type="Polygon"
        datasets = arcpy.ListDatasets("", "Feature")
        for dataset in datasets:
            cpath=mypath+os.sep+dataset
            arcpy.env.workspace =cpath
            fclasses = arcpy.ListFeatureClasses()
            for fc in fclasses:
                featureclasses.append(str(fc))
                ##arcpy.AddMessage(fc)
##        for fc in featureclasses:
##            arcpy.AddMessage(fc)
        if not self.params[1].altered:
            self.params[1].filter.list = featureclasses
            if len(featureclasses)>0:
                self.params[1].value=featureclasses[0]
    return

10.8 選擇資料庫自動列出所有資料集

def updateParameters(self):
    if self.params[0].value:
        arcpy.env.workspace =  self.params[0].value
        dList=[]
      #=======引數的型別必須必須是字串,切記切記切記======================
        datasets = arcpy.ListDatasets("", "Feature")
        for dataset in datasets:
            dList.append(dataset)
        dList.sort()
        if not self.params[1].altered:
            self.params[1].filter.list = dList
            if len(dList)>0:
                self.params[1].value=dList[0]
                self.params[1].enabled=True
            else:
                self.params[1].enabled=False

##        if self.params[1].value=="" or self.params[1].value==None:
##            self.params[1].value=self.params[1].filter.list[0]

    return

10.9 選擇要素列出數字欄位

def updateParameters(self):
  if self.params[0].value:
      inFeature = self.params[0].value #原始資料
      Fields=[]
      try:
          fieldList = arcpy.ListFields(inFeature)
          for field in fieldList:
              if field.type=="Double" and field.editable:
                  Fields.append(field.name)

          if not self.params[1].altered:
              self.params[1].filter.list =Fields
              if len(Fields)>0:
                  self.params[1].value = Fields[0]

      except Exception,e:
          print e.message();
  return