ArcPy(1):比较自定义工具箱和Python工具箱创建地理处理工具

0 版本

  • ArcGIS:10.6
  • python:2.7.14

1 两种工具箱对比

注:以下内容总结自Esri官网

自 ArcGIS 10.1 起,使用 Python 创建自定义地理处理工具的方式有以下两种:自定义工具箱中的脚本工具和 Python 工具箱中的脚本工具。二者异同:

自定义工具箱Python 工具箱
组织方式
  1. 通过向导定义的工具和参数定义。
  2. 对参数行为提供额外控制的可选验证代码,其位于工具箱中。
  3. 在单独的文件中为每个工具维护的源代码,通常作为 Python 脚本 (.py)。
  1. Python 工具箱是一个具有 .pyt 扩展名的 Python 脚本;
  2. 其包含工具箱及其工具的所有方面:参数、验证和执行。
  3. 通过以下 Python 类实现:一个类用于工具箱,一个类用于各工具。

优缺点:自定义工具箱各部分都是分离的,而且很难进行集中管理;而在Python工具箱中,参数定义、代码验证和源代码都在同一位置进行处理,因而Python工具的创建和维护更加容易。


2 创建自定义地理处理工具

注:按照上表中的步骤,以“为文件夹内shp文件批量添加字段”这一功能为例说明,代码中的具体函数不做进一步说明

2.1 使用自定义工具箱

2.1.1 编写批量添加字段代码

from imp import reload
import arcpy
# import os
# from os import path
import sys
import traceback

reload(sys)
sys.setdefaultencoding('utf8')

inFCDir = arcpy.GetParameterAsText(0)
fieldName = arcpy.GetParameterAsText(1)
fieldType = arcpy.GetParameterAsText(2)

arcpy.env.workspace = inFCDir

try:
    fileList = arcpy.ListFiles("*.shp")
    for file in fileList:
        arcpy.AddField_management(file, fieldName, fieldType)
        arcpy.AddMessage("{0} successfully".format(file))
    printSuccess() #封装方法:打印成功提示信息
except arcpy.ExecuteError:
    printArcPyException() #封装方法:打印arcpy异常信息
except:
    printException() #封装方法:打印python异常信息

2.1.2 通过向导定义的工具和参数定义

  • 在“ArcGIS->我的工具箱->右键->新建工具箱”创建自定义工具箱;
  • 在“自定义工具箱->右键->添加脚本”创建自定义地理处理工具,并设置上步的源文件及参数定义(工具参数定义需对应源码中arcpy.GetParameterAsText创建的参数),如下图所示;


 2.2 使用Python工具箱

2.2.1 新建Python工具箱

在“ArcGIS->我的工具箱->右键->新建Python工具箱”创建Python工具箱;

2.2.2 Python工具箱模板

创建新 Python 工具箱时,工具箱创建为名为 Toolbox 的类。在 Toolbox 类的 __init__ 方法中已定义工具箱的属性,其中包括 alias、label 和 description。工具箱的名称由 .pyt 文件的名称定义。必须将 tools 属性设置为包含工具箱中定义的所有工具类的列表。本例中,创建一个名为 BatAddField 的工具。直接上代码,哈哈。

import arcpy
class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "pptools"
        self.alias = "pp arcpy tools"
        # List of tool classes associated with this toolbox
        self.tools = [BatAddField]

class BatAddField(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Bat Add Field"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions """
        param0 = arcpy.Parameter(displayName="Input folder",
                                 name="in_dir",
                                 datatype="DEFolder",
                                 parameterType="Required",
                                 direction="Input")
        param1 = arcpy.Parameter(displayName="Field Name",
                                 name="field_name",
                                 datatype="GPString",
                                 parameterType="Required",
                                 direction="Input")
        param2 = arcpy.Parameter(displayName="Field Type",
                                 name="field_type",
                                 datatype="GPString",
                                 parameterType="Required",
                                 direction="Input")
        param2.filter.type = "ValueList"
        param2.filter.list = [
            'Short', 'Long', 'Float', 'Single', 'Double', 'Text', 'Date'
        ]
        params = [param0, param1, param2]
        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."""
        arcpy.env.workspace = parameters[0].valueAsText
        fieldName = parameters[1].valueAsText
        fieldType = parameters[2].valueAsText
        try:
            fileList = arcpy.ListFiles("*.shp")
            for file in fileList:
                 arcpy.AddField_management(file, fieldName, fieldType)
                 arcpy.AddMessage("{0} successfully".format(file))
            #addField(fileList, fieldName, fieldType)
            printSuccess(messages)
        except arcpy.ExecuteError:
            printArcPyException(messages)
        except:
            printException(messages)
        return

函数说明:

  • getParameterInfo(self):用于定义工具参数;

  • isLicensed(self):工具是否可用;

  • updateParameters(self, parameters):当更改参数值时候触发

  • updateMessages(self, parameters):This method is called after internal validation.

  • execute(self, parameters, messages):执行工具


3 最终工具展示

最终两种工具展示的结果是一样的,但是python工具箱的参数定义、代码验证和源代码都在同一位置进行处理,所以更易于维护。

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

碰碰qaq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值