Create a Python tool in ArcGIS (2), arcgispython
In the previous article, we learned that there are two ways to create a Python tool in ArcGIS. This article will show you how to create a script tool in the standard toolbox.
The Help of the script tool in ArcGIS Help is too boring. Here, I will summarize the process of building the script tool with a specific example, the requirement I want to achieve is to make a small tool that quickly achieves the effect of the Yuhua boundary. The expected results are as follows:
The above results can be achieved by manually running several tools In ArcMap, but the process is a little complicated. So what's the requirement? How can we make a custom one-click tool to generate the Yuhua boundary?
1. Prepare the Python script file.
First, write the python script file, the core of the script tool.
In the script, I want to automatically generate a buffer surface of the 9 Ring Based on the specified ring spacing, and then add a field to store the transparency percentage of each buffer surface.
You can see what I want to do:
Write a py file and connect the tools to be used to achieve your own needs. This is not the final version of the script tool, but to learn how to implement it in advance and modify it later.
__author__ = 'kikita'# FileName: EasyFeathering.pyimport arcpy# arcpy.env.workspace = "D:\something\Data.gdb"# Script Tool ParametersInputFeature = "InterestArea"OutputFeature = "OutFeathering"SingleRingWidth = 10000# Some Predefined Parametersdistances = []level = 9bufferUnit = "meters"NewField = "Percent"# My Easy Feathering functionfor i in range(level): distances.append(SingleRingWidth*(i+1)) i = i+1print str(distances)print "Distance Complete!"arcpy.MultipleRingBuffer_analysis(InputFeature, OutputFeature, distances, bufferUnit, "", "ALL","OUTSIDE_ONLY")print "Success to execute Multi Ring Buffer."arcpy.AddField_management(OutputFeature,NewField,"double")print "Success to add Transparency Percent Field."arcpy.CalculateField_management(OutputFeature, NewField, "!OBJECTID! *10", "PYTHON", "")print "Success to Calculate Transparency Percent Field."
2. Script tool parameter configuration
With the py file, how can I insert it into the toolbox?
In the Catalog window of ArcMap, find any folder you like, create a Toolbox, right-click Add-> Script, and enter the Wizard. If you do not know about these operations, clickHereCheck the help and follow the instructions.
Here I will mainly talk about parameter passing.
In the tools I want to do well, I only specify three parameters: input Feature and Single Ring width ), output Feature ). Preview the tool interface:
Then the question comes again. How can these three parameters be passed to the python script that actually executes the tool from the tool interface? We need to modify the Parameter definition section of the preceding script to useGetParameterAsText()
Function to pass parameters between the tool interface and script. Replace the preceding three parameters with the following code:
# Script Tool ParametersInputFeature = arcpy.GetParameterAsText(0)SingleRingWidth = arcpy.GetParameterAsText(1)OutputFeature = arcpy.GetParameterAsText(2)
Corresponding script tool parameter configuration:
When configuring parameters for the tool, there are two principles to follow:
- The order of parameters in the tool dialog box must be the same as that in the script.Consistent Parameter order.
- Parameters of each script tool are associatedData Type. Geographical processing of ArcGIS does not send values to scripts with incorrect data types. From this point of view, the script tool has an advantage over the script toolbox mentioned in the next article, there will be a data type check before the parameter value is sent to the script.
After modifying the Python script file, run the tool now. Expected results are displayed:
But it is a bit imperfect, that is, during the Running process of the tool, the information returned by the tool is not enough. I only know "Running Script EasyFeathering ...", I don't know what the tool is doing and what steps it takes. This is not a good experience.
3 message
All communication between tools and users is implemented through messages. Next, the question raised in the previous step shows how to pass messages to users in the tool progress window?
Although I added some Print statements when I started to debug the script, as shown in the code at the beginning, so that I can understand the status of my script for independent execution. However, if I run the script tool, these print statements are invisible. You can use the message-related functions provided in ArcPy,AddMessage
,AddWarning
,AddError
Sends messages to the tool progress bar. Here I have made a message prompt for a simple step, and if the result is not recorded, a warning will be prompted.
__author__ = 'kikita'# FileName: EasyFeathering.pyimport arcpy#arcpy.env.workspace = "D:\IncidentSupport2015\something\Data.gdb"# Get the input values from tool UIInputFeature = arcpy.GetParameterAsText(0)SingleRingWidth = arcpy.GetParameterAsText(1)OutputFeature = arcpy.GetParameterAsText(2)# Some Predefined Parametersdistances = []level = 9bufferUnit = "meters"NewField = "Percent"# My Easy Feathering functionfor i in range(level): distances.append(int(SingleRingWidth)*(i+1)) i = i+1arcpy.AddMessage("Step1 Distance list Complete!")arcpy.MultipleRingBuffer_analysis(InputFeature, OutputFeature, distances, bufferUnit, "", "ALL","OUTSIDE_ONLY")arcpy.AddMessage("Step2 Success to execute Multi Ring Buffer.")arcpy.AddField_management(OutputFeature,NewField,"double")arcpy.AddMessage("Step3 Success to add Transparency Percent Field.")arcpy.CalculateField_management(OutputFeature, NewField, "!OBJECTID! *10", "PYTHON", "")InputFeatureCount = int(arcpy.GetCount_management(OutputFeature).getOutput(0))if InputFeatureCount == 0: arcpy.AddWarning("{0} has no features.".format(OutputFeature))else: arcpy.AddMessage("Step4 Success to Calculate Transparency Percent Field.")
In this way, I receive the message during the execution of the tool:
Here, the functions of the tool are complete.
4. display result Layers
I further hope that the script tool will be automatically displayed in the current map document after running, so as to avoid repeated operations to set transparency.
After running the tool, the result is automatically displayed.
5. Configuration path
If you use the script tool on the local machine, we generally use absolute paths. However, if you want to share your tools with others, you must consider the path problem, that is, when a new user runs the script tool, can the related script files and other resources be accessed. My tools are organized according to the following structure:
In the properties of the script tool, you can configure the storage relative path to reference the py file:
PS: but do not think too much about it. This setting will only store the script file location in the relative path, rather than converting the path inside the script.
In this example, I also need to use a layer file as a template. If you want to use a relative path, we recommend that you write the symbolic information in the script instead of configuring it in the parameter window. Therefore, you must continue to modify the Python script file.
Append the last two lines of code to the script file. Here, I will obtain the lyr file in the same directory as the Python script file:
# Layer files are located in same folder as the .py filePythonFilePath = os.path.dirname(__file__)params = arcpy.GetParameterInfo()params[2].symbology = os.path.join(PythonFilePath, "FeatheringEffectTemplate.lyr")# Pass message arcpy.AddMessage("Finding Feathering Effect Template Layer ..." +"/n"+ os.path.join(PythonFilePath, "FeatheringEffectTemplate.lyr"))
OK. The path is resolved.
6. Help document
You can also add help documents for the tool so that more people can learn how to use the tool.
In the Catalog of ArcCatalog or ArcMap, right-click the script tool, click the Item Description menu, and click Edit to Edit the help document of the tool.
In this way, when someone opens your tool, they will see help.
Well, let's talk about the process of using the script tool in ArcGIS.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.