• 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
  • 相关阅读:
    mysql查询太慢,我们如何进行性能优化?
    详解MySQL事务原理
    精通MySQL之锁篇
    精通MySQL之索引篇,这篇注重练习!
    mysql数据结构及mvcc
    mysql-主从同步
    redis分布式锁
    售后系统构建和商品状态重构经验与总结
    【更新2021-4-25】如何处理PoshSSH 连接主机时的"New-SSHSession : Key exchange negotiation failed."故障
    计算几何---大牛们
  • 原文地址:https://www.cnblogs.com/gisoracle/p/13579901.html
Copyright © 2020-2023  润新知