自定义 Python 工具箱中的工具的行为

验证是在按下工具的确定按钮之前要做的全部工作。创建自己的自定义工具时,可通过验证自定义参数与值相互响应交互的方式。通过一个用于控制工具行为的 Python 代码块执行验证。

要了解有关验证的详细信息,请参阅了解脚本工具中的验证

在 Python 工具箱中,每个工具参数都拥有一个具有可用于工具验证的属性和方法的关联参数对象。在 Python 工具箱中,在工具类的 getParameterInfo 方法中定义参数。这些参数的行为、它们彼此之间如何交互以及它们与输入参数如何交互,是通过工具类中的 updateParameters 方法进行验证的。

更新 Python 工具箱中的方案 Python 工具箱中的许可行为

访问工具参数

参数对象构成了在 Python 工具箱中定义参数的方式及其交互方式的基础。标准做法是在工具类的 getParameterInfo 方法中创建参数列表,如以下代码所示。

def getParameterInfo(self):
    #Define parameter definitions

    # First parameter
    param0 = arcpy.Parameter(
        displayName="Input Features",
        name="in_features",
        datatype="GPFeatureLayer",
        parameterType="Required",
        direction="Input")

    return [param0]

有关定义 Python 工具箱中的参数的详细信息,请参阅定义 Python 工具箱中的参数

参数对象

方法

Method name

Usage description

setErrorMessage(message:string)

Marks the parameter as having an error (a red X) with the supplied message. Tools do not execute if any of the parameters have an error.

setWarningMessage(message:string)

Marks the parameter as having a warning (a yellow triangle) with the supplied message. Unlike errors, tools do execute with warning messages.

setIDMessage(messageType: string, messageID: string, {AddArgument1}, {AddArgument2})

Allows you to set a system message. The arguments are the same as the AddIDMessage function.

clearMessage()

Clears out any message text and sets the status to informative (no error or warning).

hasError()

Returns true if the parameter contains an error.

hasWarning()

Returns true if the parameter contains a warning.

isInputValueDerived()

Returns true if the tool is being validated inside a Model and the input value is the output of another tool in the model.

Parameter object methods

属性

属性名称

读/写

说明

名称

只读

字符串

参数名称。

方向

只读

字符串:“Input”、“Output”

参数的输入/输出方向。

datatype

只读

字符串

要获取参数数据类型的列表,请参阅在 Python 工具箱中定义参数数据类型

parameterType

只读

字符串:“Required”、“Optional”、“Derived”

参数类型。

parameterDependencies

读/写

Python 列表

各依存参数的索引列表。

读/写

值对象

参数的值。

defaultEnvironmentName

只读

字符串

默认环境设置。

已启用

读/写

布尔型

如果参数不可用,则为 False。

altered

只读

布尔型

如果用户对值做出了修改,则为 True。

hasBeenValidated

只读

布尔型

如果内部验证例程已检查参数,则为 True。

category

读/写

字符串

参数的类别。

schema

只读

Schema 对象

输出数据集的方案。

过滤器

只读

Filter 对象

要应用于参数中的值的过滤器。

符号系统

读/写

字符串

用于绘制输出的图层文件 (.lyr) 的路径。

message

只读

字符串

要向用户显示的消息。请参阅上文的 SetErrorMessageSetWarningMessage

参数对象属性

parameterDependencies

通常会设置参数依赖项以供 Schema 对象使用。在两种情况下可能已经在工具的 getParameterInfo 方法中设置了依赖项。

  • 对于类型为“派生”的输出数据集参数,依赖项为参数的索引,可由此派生输出。
  • 对于特定的输入数据类型,依赖项为含有控件所用信息的参数的索引,如下表所示。

Input data type

Dependent data type

Description

Field or SQL Expression

Table

The table containing the fields.

INFO Item or INFO Expression

INFO Table

The INFO table containing the items.

Coverage Feature Class

Coverage

The coverage containing features.

Area Units or Linear Units

GeoDataset

A geographic dataset used to determine the default units.

Coordinate System

Workspace

A workspace used to determine the default coordinate system.

Network Analyst Hierarchy Settings

Network Dataset

The network dataset containing hierarchy information.

Geostatistical Value Table

Geostatistical Layer

The analysis layer containing tables.

Obtained from data types

依赖项通常在 getParameterInfo 方法中进行设置:

def getParameterInfo(self):
    #Define parameter definitions

    # First parameter
    param0 = arcpy.Parameter(
        displayName="Input Features",
        name="in_features",
        datatype="GPFeatureLayer",
        parameterType="Required",
        direction="Input")

    # Second parameter
    param1 = arcpy.Parameter(
        displayName="Sinuosity Field",
        name="sinuosity_field",
        datatype="Field",
        parameterType="Optional",
        direction="Input")
    param1.value = "sinuosity"

    # Third parameter
    param2 = arcpy.Parameter(
        displayName="Output Features",
        name="out_features",
        datatype="GPFeatureLayer",
        parameterType="Derived",
        direction="Output")
    param2.parameterDependencies = [param0.name]
    param2.schema.clone = True

    params = [param0, param1, param2]

    return params

这是由用户输入的或者通过编程方式设置的参数值。可以在 getParameterInfo 方法中设置 value,此时它用作参数的初始默认值。还可在 updateParameters 中设置 value 以响应用户输入,如下所示。

def updateParameters(self, parameters):
    # Set the default distance threshold to 1/100 of the larger of the width
    #  or height of the extent of the input features.  Do not set if there is no 
    #  input dataset yet, or the user has set a specific distance (Altered is true).
    #
    if parameters[0].value:
        if not parameters[6].altered:
            extent = arcpy.Describe(parameters[0].value).extent
        if extent.width > extent.height:
            parameters[6].value = extent.width / 100
        else:
            parameters[6].value = extent.height / 100

    return
注注:

参数列表从零开始排序,因此第一个参数位于列表中的零位置上。如果要访问第三个参数,则应使用 parameters[2]

请不要在 updateMessages 中设置参数值,否则内部验证例程将不会验证该值。

value 是具有字符串表达形式的对象。下面的代码片段用于测试 value 是否等于字符串“Get Spatial Weights From File”。该测试能够顺利进行是因为参数数据类型是字符串。

# If the option to use a weights file is selected, enable the 
#   parameter for specifying the file, otherwise disable it
#
if parameters[3].value == "Get Spatial Weights From File":
    parameters[8].enabled = True
else:
    parameters[8].enabled = False

如果参数数据类型为要素类或者任何表示数据集的值,则采用上述代码的测试将无法正常进行。表示磁盘中数据的值(例如要素类和栅格)需要在执行字符串操作之前转换为字符串。内置 Python 函数 str 可将 value 对象转换为字符串,如下所示:

if str(parameters[0].value) == "E:/data/example.gdb/roads":

只需将 str 函数用于具有表示数据集的数据类型的值。对于这些类型的值,str 函数会将目录路径返回至数据集。不需要为其他数据类型(例如长整型或线性单位)使用该函数,因为这些数据类型并不表示数据集,并且会自动转换为字符串。

警告警告:

调用 updateParameters 中的 Describe 函数时,切勿使用值的字符串表达形式。

不正确

desc = arcpy.Describe(str(parameters[0].value))

正确

desc = arcpy.Describe(parameters[0].value)

不应使用字符串表示数据集(该数据集生成数据集的目录路径),因为数据集可能不存在 - 它可能是模型派生变量,因而必须先运行模型,然后才会在磁盘中存在数据集。如果使用字符串表示数据集,Describe 会失败,因为在磁盘上可能尚未存在数据集。

警告警告:

请不要调用采用目录路径的 ArcPy 函数,例如验证方法中的 ListFields。在模型构建器中验证工具时数据集可能并不存在,因此方法可能会失败。(在采用 ListFields 时,可以使用 Describe 对象的 fields 属性。)

如果要测试字符串是否相等,在比较时应区分大小写。下列代码说明了使用 Python lower 函数将要素类的形状类型转换为小写并比较小写字符串的过程。(此外,可使用 upper 函数比较大写字符串。)

fc = parameters[0].value
shapetype = arcpy.Describe(fc).shapeType.lower()
if shapetype in ["point", "multipoint"]:

altered

如果用户更改了参数值(例如通过输入输出路径进行更改),则 altered 为 true。参数更改之后,它会保持更改状态直到用户将该值清空(删除),这时它就恢复到未更改状态。通过验证代码以编程方式更改值不会改变 altered 的状态。也就是说,如果为参数设置了值,参数的 altered 状态不会改变。

altered 用于确定是否可以更改某个参数的值。例如,假设工具拥有要素类参数和关键字参数。如果要素类包含点或面,则关键字为 RED、GREEN 和 BLUE,如果包含线,则关键字为 ORANGE、YELLOW、PURPLE 和 WHITE。

假设用户输入了一个点要素类。如果关键字参数处于未更改状态,则将值设置为 RED,因为它是默认值。

如果输入了线要素类,则将默认值设置为 ORANGE(只要关键字参数处于未更改状态)。

不过,如果用户已更改关键字参数(即,将关键字设置为 GREEN),则不应重置关键字(用户已做出选择 (GREEN),但您还不知道他们的意图),他们可能更改要素类,以使 GREEN 有效,或者可能更改关键字(例如,改为 PURPLE)。由于 GREEN 不是一种为线创建的关键字设置,所以内部验证将参数标记为错误。此时,用户有两种选择:更改输入要素类或者更改关键字。

if not parameters[2].altered:
    parameters[2].value = "POINT"

hasBeenValidated

如果在最后一次调用 updateParameters 和内部验证之后用户修改了参数值,则 hasBeenValidated 为 false。调用内部验证后,地理处理会自动为每个参数将 hasBeenValidated 设置为 true。

hasBeenValidated 用于确定在最后一次调用 updateParameters 后用户是否对值进行了更改。您可以根据此信息决定是否执行您自己的参数检查。

def updateParameters(self, parameters):
    # Set the default distance threshold to 1/100 of the larger of the width
    #  or height of the extent of the input features.  Do not set if there is no 
    #  input dataset yet, or the user has set a specific distance (Altered is true).
    #
    if parameters[0].value:
        if not parameters[6].altered:
            extent = arcpy.Describe(parameters[0].value).extent
        if extent.width > extent.height:
            parameters[6].value = extent.width / 100
        else:
            parameters[6].value = extent.height / 100

    return

相关主题

9/15/2013