Create Python tool in ArcGIS (3), arcgispython
From ArcGIS 10.1, we can createPython toolboxCustomize the script tool. This toolbox is compared with the standard toolbox mentioned in the previous article. It has unique advantages. I have summarized the differences between the two. Let's take a look at this article.
Understanding Python toolbox
The Python Toolkit (. pyt) is a simple text file that can be created, viewed, and edited in any text editor or any Python IDE. To ensure that ArcGIS correctly recognizes the Python toolbox, the toolbox class name must beToolbox
. InToolbox
Class__init__
Defines the attributes of the toolbox in the method. These attributes include alias, label, and description.Help documentationCreate a Python toolbox template.
The following code creates a Python toolbox containing a Tool (named Tool:
import arcpyclass 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 = "Tool" self.description = "" self.canRunInBackground = False def getParameterInfo(self): """Define parameter definitions""" params = None 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.""" return
Do it manually
Next I will write a simple script toolbox based on this template. The requirement is batch cropping. I want to provide only one folder or database.WorkspaceAnd oneCrop areaYou can crop all the data in the workspace in batches, regardless of the grid or vector.
Let the scripting begin ......
1. Create a toolbox
The Toolbox name is the name of the. pyt file. Generally, the toolbox label is displayed when the tool is added to the ArcToolbox window. InToolbox
Class__init__
Define attributes in the method, for example:alias
,label
Anddescription
.
ToolClassAdded to. pyt. The tools attribute of the Toolkit must be set to include all the defined tools.ClassOfList. For example, three tools, ATool, ATool, and CTool, are required, not three scripts, but threeClassAnd put the class name in the list,self.tools = [ATool,ATool,CTool]
.
Here, I only define a tool class ClipWorkspace to describe the build process:
'''Source Name: ClipWorkspace.pytAuthor: KikitaDescription: Python tool to clip spatial data in the same workspace by batch.'''import arcpy# The class name must be "Toolbox" ...class Toolbox(object): def __init__(self): self.label = "Clip Workspace Toolbox" self.alias = "" # List of tool classes associated with this toolbox self.tools = [ClipWorkspace]class ClipWorkspace(object): ……
You can see the prototype of this toolbox in ArcGIS Desktop:
2. Definition Tool
The following is the code inside the tool. Take clw.ectorworkspace as an example.
Each tool class should include at least__init__
Andexecute
Method. You can also choose to usegetParameterInfo
,isLicensed
,updateParameters
AndupdateMessages
Method to add other controls to the behavior of the tool.
In the tool class__init__
The method is the standard Python class initialization method. For tools in the Python toolbox,__init__
This method is used to set the attributes of the tool, such as the label and description of the tool, and whether the tool can be run in the background.
The clw.ectorworkspace tool is created in the following example:
class ClipWorkspace(object): def __init__(self): self.label = "Clip Workspace" self.description = "clip spatial data in the same workspace by batch." self.canRunInBackground = True
With the tool constructor, let's continue to see how to define parameters for the tool. In the Python Toolkit (. pyt ),getParameterInfo
CreateParameter
And set the properties of the object to define the tool parameters.Parameter
Indatatype
The types contained can be queried in the help document.Here.
The parameters in this example are inWorkspace, ClipArea, and outWorkspace ).
def getParameterInfo(self): # Parameter Definitions # First parameter - Input Workspace param0 = arcpy.Parameter( displayName="Input Workspace", name="inWorkspace", datatype="DEWorkspace", parameterType="Required", direction="Input") # Second parameter - Clip Area param1 = arcpy.Parameter( displayName="Clip Area", name="CLipArea", datatype="DEFeatureClass", parameterType="Required", direction="Input") # Third parameter - Output Workspace param2 = arcpy.Parameter( displayName="Output Workspace", name="outWorkspace", datatype="DEWorkspace", parameterType="Required", direction="Input") params = [param0,param1,param2] return params
PS: In the code, if you look at it carefully, you may wonder why the direction of the output workspace is input rather than output? Because the final output of the tool is a Feature Class or Raster, the output workspace is also used as an input parameter input tool. If you don't care, you can ignore these details ...... Continue to understand the Build Process of the tool.
The following is the specific execution part of the Tool. Of course, some messages are added to help you understand the execution status of the tool:
def execute(self, parameters, messages): """The source code of the tool.""" # Get tool parameters inWorkspace = parameters[0].valueAsText arcpy.AddMessage("###Input Workspace is {0}".format(inWorkspace)) ClipArea = parameters[1].valueAsText arcpy.AddMessage("###Clip Area is {0}".format(ClipArea)) outWorkspace = parameters[2].valueAsText arcpy.AddMessage("###Out Workspace is {0}".format(outWorkspace)) # Clip Feature by Batch arcpy.env.workspace = inWorkspace # Clip Vector FeatureClasses = arcpy.ListFeatureClasses() arcpy.AddMessage("Input Workspace contains {0}".format(FeatureClasses)) for fc in FeatureClasses: arcpy.AddMessage(">> Clipping {0}".format(fc)) arcpy.Clip_analysis(fc,ClipArea, os.path.join(outWorkspace,fc)) arcpy.AddMessage("{0} has been clipped.".format(os.path.join(outWorkspace,fc))) # Clip Raster Rasters = arcpy.ListRasters() arcpy.AddMessage("Input Workspace contains {0}".format(Rasters)) for Raster in Rasters: arcpy.AddMessage(">> Clipping {0}".format(Raster)) arcpy.Clip_management(in_raster = Raster, rectangle = "", out_raster = os.path.join(outWorkspace,Raster), in_template_dataset = ClipArea, nodata_value = "", clipping_geometry = "ClippingGeometry", maintain_clipping_extent = "NO_MAINTAIN_EXTENT") arcpy.AddMessage("{0} has been clipped.".format(os.path.join(outWorkspace,Raster))) return
At this point, the core part of the tool has been completed. Run it.
OK, which should be the expected result:
3. Excellent
We found that, unlike the script tools and script files in the standard toolbox, they are stored in a hash. The python toolbox and the code of all the tools are in this pyt file, it is much easier to maintain. To add a tool in the toolbox, you only need to add a tool class.
After the first two steps, you can use the tool. If you want to make the tool more friendly, you can continue to adjust the code so that you can learn more about the cause when exceptions occur. Here we will proceed. The tool is shared with others, so we only need to enrich the tool documentation and edit it in the Item Description of the Python tool.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.