程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Creating a custom Python toolkit in ArcGIS

編輯:Python

If you feel like using ArcGIS Of Model Builder It can not meet your customized processing flow , Consider the following use ArcGIS In the middle of python hold-all . Through it, you can python The form of the code , call ArcGIS Things in the toolbox , That is to say ArcPy, It is very convenient for special application scenarios . Developers can put their own logic , Encapsulated as a tool , Directly provide other computers to install ArcGIS The personnel who use .

establish Python hold-all

  1. stay ArcCatalog in My toolbox Right click , choice newly build ——python hold-all
  2. Right click the created toolbox , choice edit , In the pop-up edit box , You can write code by typing

Python Toolbox code

First, a case

import arcpy
import os
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the .pyt file)."""
self.label = "Toolbox"
self.alias = ""
# List of tool classes associated with this toolbox
self.tools = [Tool]
class Tool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = " Check the marking tool "
self.description = " Check the marking tool "
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# Define the parameter form on the tool panel 
param0 = arcpy.Parameter(displayName=u" Map template ",
name="mxd_path",
datatype="DEMapDocument",
parameterType="Required",
direction="Input")
param1 = arcpy.Parameter(displayName=u" Plot Shp file ",
name="dk_layer",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input")
param2 = arcpy.Parameter(displayName=u" Peasant household point Shp",
name="nhd_layer",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input")
param3 = arcpy.Parameter(displayName=u" year ",
name="nf",
datatype="GPString",
parameterType="Required",
direction="Input")
param3.filter.type = "ValueList"
param3.filter.list = [
'2018', '2019', '2020', '2021', '2022', '2023', '2024'
]
param4 = arcpy.Parameter(displayName=u" Result output directory ",
name="dst_dir",
datatype="DEFolder",
parameterType="Required",
direction="Input")
params = [param0, param1, param2, param3, param4]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal validation is performed. This method is called whenever a parameter has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
# Take parameters 
arcpy.env.workspace = r"in_memory"
arcpy.env.scratchWorkspace = r"in_memory"
arcpy.env.overwriteOutput = True
mxd_path = parameters[0].valueAsText
dk_layer_path = parameters[1].valueAsText
nhd_layer_path = parameters[2].valueAsText
nf = parameters[3].valueAsText
dst_dir = parameters[4].valueAsText
# Perform logical 
arcpy.AddMessage("all success")
arcpy.AddMessage(mxd_path)
arcpy.AddMessage(nf)
arcpy.AddMessage(dst_dir)
except arcpy.ExecuteError:
arcpy.AddError(messages)
except Exception:
arcpy.AddError(messages)
return

Be careful :

  1. getParameterInfo Is mainly used to define panel parameters ,
  2. execute The main ones are , Click OK to execute the logic
  3. arcpy.AddMessagearcpy.AddError You can print the log

Parameter type

data type datatype keyword describe Address locator DEAddressLocator Data sets for geocoding , Store address properties 、 The associated index and the rules used to define the process of converting the non spatial description of the location to spatial data . Address locator style GPAddressLocatorStyle Template for creating a new address locator . Analyze pixel size analysis_cell_size The pixel size used by the grid tool . Any value GPType Data types that accept any value .ArcMap file DEMapDocument Contains a map 、 Its layout and its associated layers 、 form 、 Chart and report files . area unit GPArealUnit Area unit type and value , For example, square meters or acres . Boolean type GPBoolean Boolean value .CAD Drawing datasets DECadDrawingDataset Vector data source with multiple feature types and symbol systems . This dataset is not suitable for feature class based queries or analyses . Calculator expression GPCalculatorExpression Calculator expression . Directory root DECatalogRoot Top level nodes in the directory tree . Pixel size GPSACellSizeArcGIS Spatial Analyst Extension module Used pixel size . Pixel size XYGPCellSizeXY Define both sides of the grid cell . Compound Layer GPCompositeLayer References to multiple sublayers , Including Symbology and rendering attributes . Compress GPSAGDBEnvCompression Specifies the compression type used for the grid . Coordinate system GPCoordinateSystem Reference frame , for example UTM System , By a set of points 、 Line and / Or surface , And a set of rules for defining the position of points in two-dimensional and three-dimensional space . Coordinate system folder DESpatialReferencesFolder The folder on the disk where the coordinate system is stored . Coverage DECoveragecoverage Data sets , Used to store geographic features , Just like 、 A proprietary data model for arcs and faces and related feature attribute tables .Coverage Element class DECoverageFeatureClassescoverage Element class , Point for example 、 Arc 、 node 、 Route 、 Route system 、 Arc segment 、 Faces and areas . data elements DETypeArcCatalog Datasets visible in . Data files GPDataFile Data files . Database connection DERemoteDatabaseFolderArcCatalog Database connection folder in . Data sets DEDatasetType A collection of related data , Usually grouped or stored together . date GPDate Date value .dBase surface DEDbaseTable With dBASE Format stored attribute data . extract GP3DADecimate Appoint TIN Node subset of , To create the TIN A generalized version of . Disk connection DEDiskConnection Access path of data storage device . Double precision GPDouble All floating-point numbers will be stored as double 64 A value . Encrypted string GPEncryptedString Password encrypted string .EnvelopeGPEnvelope Define the coordinate pair of the smallest circumscribed rectangle where the data source is located . Assessment level GPEvaluationScale The range of level values and increment values applied to the input values in the weighted overlay operation . Range GPExtent Specifies the coordinate pair that defines the smallest circumscribed rectangle of the data source (x minimum value 、y minimum value 、x Maximum 、y Maximum ). Coordinates of all data sources are within this boundary . Extract value GPSAExtractValues Extract value parameters . Element class DEFeatureClass A collection of spatial data with the same shape type : spot 、 Multipoint 、 Lines and faces . Element data sets DEFeatureDataset A collection of feature classes that share a common geographic area and the same spatial reference system . Element layers GPFeatureLayer References to feature classes , Including Symbology and rendering attributes . Feature set GPFeatureRecordSetLayer Interactive elements ; Draw features while the tool is running . Field Field Column in table , Used to store the value of a single attribute . Field information GPFieldInfoFieldMap Details of the fields in . Field mapping GPFieldMapping A collection of fields in one or more input tables . file DEFile Files on disk . Folder DEFolder Specify the storage location of data on disk . Format grid GPRasterFormulated Grid surface , Its pixel value is expressed by formula or constant . Fuzzy functions GPSAFuzzyFunction Fuzzy functions . Geographic data set DEGeodatasetType A collection of data with a common theme in a geographic database .GeoDataServerDEGeoDataServer Reference the coarse-grained objects of the geographic database . Geometric network DEGeometricNetwork A linear network represented by topologically connected edge and junction features . Feature connectivity is based on their geometric overlap . Geostatistical layer GPGALayer References to geo statistical data sources , Including Symbology and rendering attributes . Geostatistical search neighborhood GPGASearchNeighborhood Define the search neighborhood parameters of the geostatistical layer . Table of geographical statistics GPGALayer Defines a collection of data sources and fields for a geostatistical layer .GlobeServerDEGlobeServerGlobe The server .GPServerDEGPServer Geo processing server . Chart GPGraph Chart . Chart data sheet GPGraphDataTable Chart data sheet . Layer groups GPGroupLayer Display as a single layer , A collection of layers treated as a single layer . Layer groups make organizing maps 、 It becomes easier to specify advanced draw order options and share layers for use with other maps . Horizontal coefficient GPSAHorizontalFactor Relationship between horizontal cost coefficient and horizontal relative movement angle . Video services DEImageServer Video services . Indexes Indexes A data structure used to speed up the search for records in geographic datasets and databases .INFO expression GPINFOExpression Define and manipulate INFO Syntax of data in the table .INFO project GPArcInfoItemINFO Items in the table .INFO surface DEArcInfoTableINFO Tables in the database .LAS Data sets DELasDatasetLAS Datasets are stored on one or more disks LAS References to files and other surface features .LAS File is a binary file , It is specially used to store airborne lidar data .LAS Dataset layer GPLasDatasetLayer Refer to... On disk LAS The layer of the dataset . This layer applies filters to LAS Radar files and surface constraints referenced by the dataset .LayerGPLayer References to data sources , for example shapefile、coverage、 Geodatabase feature class or grid , Including Symbology and rendering attributes . Layer files DELayer Used to store layer definitions , Including Symbology and rendering attributes , extension .lyr The file of . Line GPLine By a series of connected unique x,y A straight or curved shape defined by a coordinate pair . Linear units GPLinearUnit Linear unit type and value , For example, meters or feet . longitude GPLong An integer value .M range GPMDomainM The range of the lowest and highest possible values of coordinates .MapServerDEMapServer Map server . Mosaic data sets DEMosaicDataset A collection of raster and image data , Can be stored 、 View and query data . A mosaic dataset is a data model in a geographic database , Used to manage a set of raster datasets stored in a catalog and viewed as mosaic images ( image ). Mosaic layer GPMosaicLayer Reference the layer of the mosaic dataset . The neighborhood GPSANeighborhood The shape of the area around each pixel used to calculate the statistics . Network analysis class FieldMapNAClassFieldMap In the network analysis layer ( Such as transit point 、 Facilities and accident points ) And the position attribute in the point feature class . Network analysis level setting GPNAHierarchySettings A hierarchical attribute that uses two integers to divide the hierarchical values of a network dataset into three groups . The first integer ,high_rank_ends, Set the end value of the first group ; The second number ,low_rank_begin, Set the starting value of the third group . Network analysis layer GPNALayer A special layer group used to express and solve network path problems .Network Analyst The sub layers stored in the layer represent some aspects of the path problem and solution . Network data sets DENetworkDataset Topology connects a collection of network elements ( edge 、 Intersections and turns ), Derived from a network source and associated with a collection of network properties . Network dataset layer GPNetworkDatasetLayer References to network datasets , Including Symbology and rendering attributes . Parcel structure DECadastralFabric The parcel structure is storage 、 Maintain and edit datasets of contiguous surfaces of contiguous parcels or parcel networks . Parcel structure layer GPCadastralFabricLayer The layer referencing the parcel structure on disk . This layer acts as a layer group , Organize a group of related layers under a single layer . spot GPPointx,y Coordinate pairs . Noodles GPPolygon A series of connected x,y Coordinate pairs , among , The first coordinate pair is the same as the last one . Projection file DEPrjFile A file that stores coordinate system information for spatial data . The pyramid GPSAGDBEnvPyramid Specify... When building the pyramid . radius GPSARadius Specify the surrounding points for interpolation . Random number generator GPRandomNumberGenerator Specify the seed and generator to use when creating random values . Grid band DERasterBand Layers in a grid dataset . Grid calculator expression GPRasterCalculatorExpression Grid calculator expression . Grid catalog DERasterCatalog A collection of raster datasets defined in a table ; Each table record defines a separate grid dataset in the catalog . Grid catalog layer GPRasterCatalogLayer A reference to a grid Directory , Including Symbology and rendering attributes . Grid data layer GPRasterDataLayer Grid data layer . Raster data sets DERasterDataset A single dataset constructed from one or more grids . raster layer GPRasterLayer A reference to a grid , Including Symbology and rendering attributes . Grid statistics GPSAGDBEnvStatistics Specify... When building grid statistics . Grid data type GPRasterBuilder Grid data is added to the mosaic dataset by specifying the grid type . The grid type identifies metadata along with the grid format , For example, geographical registration 、 Acquisition date and sensor type . Recordset GPRecordSet Interaction table ; Input table values when the tool runs . Relationship class DERelationshipClass Details of the relationships between objects in a geographic database . Remap GPSARemap A table that defines the reclassification method for grid pixel values . Path measurement event properties GPRouteMeasureEventProperties Specify a field in the table to describe the events measured by the linear reference path system . Logical footprint dataset DESchematicDataset The logical schematic dataset contains the same application domain ( Such as water network or power grid ) A collection of logical footprint templates and logical footprint feature classes in . The logical footprint dataset can be located in a personal geographic database 、 File Geodatabase or ArcSDE In a geographic database . Logic diagram DESchematicDiagram Logic diagram . Logical footprint folder /Schematic Folder DESchematicFolder Logical footprint folder . Logical footprint layer GPSchematicLayer The logical footprint layer is a composite layer , Consists of feature layers based on the logical footprint feature class associated with the template used to create the logical footprint . Semivariogram GPSASemiVariogram Specifies the distance and direction of the two locations used to quantify autocorrelation .ServerConnectionDEServerConnection Server connection .ShapefileDEShapefileshapefile Format of spatial data . Spatial reference GPSpatialReference For storing spatial datasets ( Including spatial domain ) The coordinate system of .SQL expression GPSQLExpression Syntax for defining and manipulating data in a relational database . character string GPString Text value . surface DETable Tabular data . Table view GPTableView Table data representation for viewing and editing , Stored in memory or disk .Terrain Layers GPTerrainLayer Yes terrain References to , Including Symbology and rendering attributes . It is used to draw terrain. text file DETextfile With ASCII Data stored in different formats . Block size GPSAGDBEnvTileSize Specify the width and height of the data stored in the block . Time configuration GPSATimeConfiguration Specify the time period used to calculate solar radiation at a specific location .TINDETin A vector data structure that divides geographic space into continuous non overlapping triangles . The inflection point of each triangle has x、y and z Value of the sampling data point .TIN Layers GPTinLayer Yes TIN References to , Including topological relations 、 Symbology and rendering properties . Tools DETool Geoprocessing tools .toolboxDEToolbox Geoprocessing toolbox . Topological elements GPSATopoFeatures Features imported into interpolation . Topology DETopology Define and enforce the topology of spatial data integrity rules . Topology layer GPTopologyLayer Reference to Topology , Including Symbology and rendering attributes . Value table GPValueTable Set of value columns . Variable GPVariant Can contain data values of any basic type : Boolean type 、 Date type 、 Double precision type 、 Long integers and strings . Vertical coefficient GPSAVerticalFactor Specify the relationship between the vertical cost factor and the vertical relative movement angle .VPF CoverageDEVPFCoverage Spatial data stored in vector product format .VPF surface DEVPFTable Attribute data stored in vector product format .WCS CoverageDEWCSCoverage Network coverage service (WCS) Is an open specification for sharing grid datasets on the network . Weighted superposition table GPSAWeightedOverlay surface Tables containing data , You can combine multiple grids by using the same measurement scale for each grid value and weighting it according to its importance . Weighted sum GPSAWeightedSum Specifies the data used to overlay multiple grids by multiplying each grid by the specified weight and adding them together .WMS Map DEWMSMapWMS Map . working space DEWorkspace Containers , For example, a geographic database or folder .XY range GPXYDomainx,y The range of the lowest and highest possible values of coordinates .Z range GPZDomainz The range of the lowest and highest possible values of coordinates .
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved