编写 ToolValidator 类

有关 ToolValidator 类的概述和参数方法的使用,请参阅自定义脚本工具行为

参数对象

访问工具参数

每个工具参数都拥有一个包含可用于工具验证的属性和方法的关联参数对象。参数包含在 Python 列表中。标准做法是在 ToolValidator 类的 __init__ 方法中创建参数列表,如以下代码所示。

def __init__(self):
  import arcpy 
  self.params = arcpy.GetParameterInfo()

还可访问脚本(相对于 ToolValidator 类)中的参数,如下所示。只有要设置符号系统属性时才会访问脚本中的参数列表。

import arcpy
params = arcpy.GetParameterInfo()

了解有关在脚本中设置符号系统的详细信息

参数顺序

工具参数及其顺序在工具属性的参数选项卡中进行定义,如下图所示。

参数及其顺序
注注:

参数列表从零开始排序,因此第一个参数位于列表中的零位置上。要访问第三个参数,应输入 p3 = self.params[2]

方法

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

属性

Property name

Read/Write

Value(s)

Description

name

Read-only

String

Parameter name as defined on the Parameters tab of the tool's properties.

direction

Read-only

String: "Input", "Output"

Input/Output direction of the parameter as defined on the Parameters tab of the tool's properties.

datatype

Read-only

String

Data type as defined on the Parameters tab of the tool's properties.

parameterType

Read-only

String: "Required", "Optional", "Derived"

Type as defined on the Parameters tab of the tool's properties.

parameterDependencies

Read/write

Python List

A list of indexes of each dependent parameter.

value

Read/write

Value object

The value of the parameter.

defaultEnvironmentName

Read-only

String

The default environment setting as defined on the Parameters tab of the tool's properties.

enabled

Read/write

Boolean

False if the parameter is dimmed (unavailable).

altered

Read-only

Boolean

True if the user has modified the value.

hasBeenValidated

Read-only

Boolean

True if the internal validation routine has checked the parameter.

category

Read/write

String

The category of the parameter.

schema

Read-only

GP Schema object

The schema of the output dataset.

filter

Read-only

GP Filter object

The filter to apply to values in the parameter.

symbology

Read/write

String

The path to a layer file (.lyr) used for drawing the output.

message

Read-only

String

The message to be displayed to the user. See SetErrorMessage and SetWarningMessage above.

Parameter object properties

下面显示了一些代码示例。有关其他代码示例,请参阅自定义脚本工具行为

ToolValidator 属性与脚本工具属性

参数的默认值、过滤器、符号系统和依赖性既可在脚本工具的属性对话框的参数选项卡上进行设置,也可在 ToolValidator 类中设置。

ToolValidator 中设置的属性会始终覆盖在脚本工具属性对话框中设置的属性。例如,如果在脚本工具属性对话框中将参数的默认值设置为“BLUE”,然后使用 initializeParameters() 将它重置为“RED”,则默认值会变为“RED”。调用 initializeParameters() 后,脚本工具属性对话框会将“RED”显示为默认值。如果您(或您的用户)遇到在脚本的属性对话框中对这四个参数属性中某一个所作更改未得到保存的情况,则可能是因为属性在 ToolValidator 类内被覆盖。

parameterDependencies

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

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

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

依赖项通常在 initializeParameters() 方法中进行设置:

def initializeParameters(self):
  # Set the dependencies for the output and its schema properties
  #
  self.params[2].parameterDependencies = [0, 1]

这是由用户输入的或者通过编程方式设置的参数值。可以在 initializeParameters() 中设置 value,此时它用作参数的初始默认值。还可在 updateParameters() 中设置 value 以响应用户输入(查看示例)。

请不要在 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 self.params[3].value == "Get Spatial Weights From File":
  self.params[8].enabled = True
else:
  self.params[8].enabled = False

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

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

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

警告警告:

使用 ToolValidator 中的地理处理 Describe() 方法时,切勿使用值的字符串表达形式。

不正确(使用了 str 函数):

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

正确:(未使用 str

desc = arcpy.Describe(self.params[0].value)

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

警告警告:

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

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

fc = self.params[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 self.params[2].altered:
      self.params[2].value = "POINT"

hasBeenValidated

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

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

# 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 if the input features have already been validated,
#  or the user has set a specific distance (Altered is true).
# 
import string
if self.params[0].value and not self.params[0].hasBeenValidated:
  if not self.params[6].altered: 
    extent = arcpy.Describe(self.params[0].value).extent
    width = extent.width
    height = extent.height
    if width > height:
      self.params[6].value = width / 100
    else:
      self.params[6].value = height / 100

category

您可以通过将参数放入不同类别来最小化工具对话框的大小。ArcGIS Network Analyst 扩展模块工具使用了各种类别,如下所示。

参数类别

您仅可设置类别一次,请在 initializeParameters() 中进行设置。在 updateParameters() 中设置类别不起任何作用。下面的代码表示,将参数 4 和 5 放入“Options”类别并将参数 6 和 7 放入“Advanced”类别。

def initializeParameters(self):
    self.params[4].category = "Options"
    self.params[5].category = "Options"
    self.params[6].category = "Advanced"
    self.params[7].category = "Advanced"

类别始终显示在非类别化参数之后。请不要将必需参数放入类别中,因为工具对话框上可能不会显示。

符号系统

symbology 属性用于将图层文件 (.lyr) 与输出参数关联在一起。

params[2].symbology = "E:/tools/extraction/ToolData/ClassByDist.lyr"

了解有关输出符号系统的详细信息

schema 对象

类型为要素类、表、栅格或工作空间的每个输出参数都具有 schema 对象。只有输出要素类、表、栅格和工作空间具有 schema,其他类型则没有。schema 对象通过地理处理进行创建。可以通过参数对象访问此方案,或者设置规则以便描述工具的输出。在设置方案规则并从 ToolValidator 类获得返回值之后,地理处理内部验证代码会检查设置的规则并更新输出的描述。

回顾一下,控制流程如下:

  1. 在首次打开工具对话框时调用 initializeParameters()。设置静态规则(不会因用户输入而发生改变的规则)以描述输出。此时不会创建任何输出描述,因为用户尚未指定任何参数的值(除非已提供默认值)。
  2. 一旦用户与工具对话框通过任何方式发生交互,就会调用 updateParameters()
  3. updateParameters() 可通过修改 schema 对象来解释无法根据参数依赖项确定的动态行为(例如像“添加字段”工具一样添加新字段)。
  4. updateParameters() 获得返回值后,调用内部验证例程并通过应用 schema 对象中的规则更新输出数据的描述。
  5. 然后调用 updateMessages()。您可以检查内部验证可能已创建的警告消息和错误消息,然后修改它们或者添加您自己的自定义警告消息和错误消息。

type 是只读属性以外,其他所有 schema 属性均是可读写的。

Property name

Value(s)

type

String: "Feature", "Table", "Raster" , "Container" (for workspaces and feature datasets) (Read-only property)

clone

Boolean

featureTypeRule

String: "AsSpecified", "FirstDependency"

featureType

String: "Simple", "Annotation", "Dimension"

geometryTypeRule

String: "Unknown", "FirstDependency", "Min", "Max", "AsSpecified"

geometryType

String: "Point", "Multipoint", "Polyline", "Polygon"

extentRule

String: "AsSpecified", "FirstDependency", "Intersection", "Union", "Environment"

extent

Extent object

fieldsRule

String: "None", "FirstDependency", "FirstDependencyFIDs", "All", "AllNoFIDs", "AllFIDsOnly"

additionalFields

Python list of field objects

cellSizeRule

String: "AsSpecified", "FirstDependency", "Min", "Max", "Environment"

cellsize

Double

rasterRule

String: "FirstDependency", "Min", "Max", "Integer", "Float"

rasterFormatRule

String: "Img", "Grid"

additionalChildren

Python list of datasets to add to a workspace schema

Schema object properties

使用 FirstDependency

许多规则都可设置为“FirstDependency”,这表示将使用通过 parameter.parameterDependencies 设置的参数依赖项数组中的第一个参数值。在以下代码示例中,参数 2 具有两个依存参数:参数 0 和参数 1,第一个依赖项是参数 0。

# Set the dependencies for the output and its schema properties
#
self.params[2].parameterDependencies = [0, 1]

如果任一依存参数为多值(值列表),则会使用多值列表中的第一个值。

类型

type 属性是只读的,并通过地理处理进行设置。

clone

如果为 true,则指示地理处理以精确复制(克隆)第一个依存参数中的描述。默认值为 false。通常,在 initializeParameters() 方法中将 clone 设置为 true。如果第一个依存参数为多值(值列表),则会克隆多值列表中的第一个值。

  • 如果 parameter.parameterType 为“Derived”,则会进行精确复制。这与“添加字段”工具的行为相同。
  • 如果 parameter.parameterType 为“Required”,仍会进行精确复制,但是会更改数据集的目录路径。目录路径包括两部分:工作空间和基本名称。例如:

    E:/Data/TestData/netcity.gdb/infrastructure/roads

    • 工作空间 = E:/Data/TestData/netcity.gdb/infrastructure
    • 基本名称 = roads
    用于构造新输出名称的规则如下:
    • 基本名称与含有数据集的第一个输入参数(不是第一个依赖项,而是第一个参数)的基本名称相同,还会附加脚本工具名称(例如 roads_MyTool)。
    • 将工作空间设置为临时工作空间环境设置。如果未设置临时工作空间环境,则使用当前工作空间环境设置。如果当前工作空间环境也未设置,则使用包含数据集的第一个输入参数的工作空间。如果该工作空间为只读,那么就使用系统临时目录。

clone 设置为 true 后,所有基于规则的方法(例如 featureTypeRulegeometryTypeRuleextentRule)均设置为“FirstDependency”。

下面的两个代码示例有着相同作用。两个示例均基于使用裁剪工具创建输出方案的过程。

示例 1:显式设置所有规则
def initializeParameters(self):
    # Set the dependencies for the output and its schema properties
    #  The two input parameters are feature classes.
    #
    self.params[2].parameterDependencies = [0, 1]

    # Feature type, geometry type, and fields all come from the first 
    #  dependency (parameter 0), the input features
    #
    self.params[2].schema.featureTypeRule = "FirstDependency"
    self.params[2].schema.geometryTypeRule = "FirstDependency"
    self.params[2].schema.fieldsRule = "FirstDependency"

    # The extent of the output is the intersection of the input features 
    #  and the clip features (parameter 1)
    #
    self.params[2].schema.extentRule = "Intersection"

    return
示例 2:使用 clone 将规则设置为 FirstDependency,然后覆盖范围规则:
def initializeParameters(self):
    # Set the dependencies for the output and its schema properties
    #  The two input parameters are feature classes.
    #
    self.params[2].parameterDependencies = [0, 1]
    self.params[2].schema.clone = True
    return
    
def updateParameters(self):
    # The only property of the clone that changes is that the extent 
    #  of the output is the intersection of the input features 
    #  and the clip features (parameter 1)
    #
    self.params[2].schema.extentRule = "Intersection"
    return

featureTypeRule

该设置用于确定输出要素类的要素类型。此规则对输出栅格或输出表不起作用。

Value

Description

"AsSpecified"

The feature type will be determined by the featureType property.

"FirstDependency"

The feature type will be the same as the first parameter in the dependencies. If the first dependent parameter is a multivalue (a list of values), the first value in the multivalue list is used.

featureTypeRule values

featureType

featureTypeRule 为“AsSpecified”时,featureType 中的值用于指定输出的要素类型。

Value

Description

"Simple"

The output will contain simple features. The geometry type of the features is specified with geometryTypeRule.

"Annotation"

The output will contain annotation features.

"Dimension"

The output will contain dimension features.

featureType values

geometryTypeRule

该设置用于确定输出要素类的几何类型(例如点或面)。

Value

Description

"Unknown"

This is the default setting. Typically, you should be able to determine the geometry type in updateParameters() based on the values of other parameters. You'd only set the rule to "Unknown" if you don't have enough information to determine the geometry type.

"FirstDependency"

The geometry type is the same as the first dependent parameter. If the first dependent parameter is a multivalue (a list of values), the first value in the multivalue list is used.

"Min", "Max"

Examines the geometries of all dependent parameters and sets the output geometry type to the minimum or maximum type found. "Min" and "Max" are defined as follows:

  • Point and Multipoint = 0
  • Polyline = 1
  • Polygon = 2
So, if the dependent parameters were a point and polygon feature class, the minimum would be point, and the maximum would be polygon.

"AsSpecified"

The geometry type will be determined by the value of the geometryType property.

geometryTypeRule values

geometryType

geometryTypeRule 为“AsSpecified”时,将该属性设置为要使用的几何类型(“Point”、“Multipoint”、“Polyline”或“Polygon”)。

extentRule

Value

Description

"AsSpecified"

The output extent will be specified in the extent property.

"FirstDependency"

The output extent is the same as the first dependent parameter. If the first dependent parameter is a multivalue (a list of values), the first value in the multivalue list is used.

"Intersection"

The output extent will be the geometric intersection of all dependent parameters. (This is what the Clip tool uses, as shown below.)

"Union"

The output extent will be the geometric union of all dependent parameters.

"Environment"

The output extent will be calculated based on the output extent environment setting.

extentRule values

示例

# The extent of the output is the intersection of the input features 
#  and the clip features (the dependent parameters)
#
self.params[2].schema.extentRule = "Intersection"

范围

extentRule 为“AsSpecified”时,将该属性设置为要使用的范围。可使用以空格分隔的字符串或者使用含有四个值的 Python 列表对象来设置范围。顺序为 xmin、ymin、xmax、ymax。

示例

self.params[2].schema.extentRule = "AsSpecified"
self.params[2].schema.extent = "123.32 435.8 987.3 567.9"

或者使用 Python 列表

xmin = 123.32
ymin = 435.8
xmax = 987.3
ext = [xmin, ymin, xmax, 567.9]
self.params[2].schema.extent = ext

fieldsRule

fieldsRule 用于确定将在输出要素类或输出表上存在的字段。

在下表中,FID 代表“要素 ID”,但实际上是指每个要素类或表中的 ObjectID 字段。

Value

Description

"None"

No fields will be output except for the object ID.

"FirstDependency"

Output fields will be the same as the first dependent parameter. If the first dependent parameter is a multivalue (a list of values), the first value in the multivalue list is used.

"FirstDependencyFIDs"

Only the ObjectID of the first dependent input will be written to the output.

"All"

All fields in the list of dependent parameters will be output.

"AllNoFIDs"

All fields except for the ObjectIDs will be written to the output.

"AllFIDsOnly"

All ObjectID fields are written to the output, but no other fields from the inputs will be written.

fieldsRule values

使用 fieldsRule 为“FirstDependency”的裁剪工具示例

def initializeParameters(self):
    # Set the dependencies for the output and its schema properties
    #  The two input parameters are feature classes.
    #
    self.params[2].parameterDependencies = [0, 1]

    # Feature type, geometry type, and fields all come from the first 
    #  dependency (parameter 0), the input features
    #
    self.params[2].schema.featureTypeRule = "FirstDependency"
    self.params[2].schema.geometryTypeRule = "FirstDependency"
    self.params[2].schema.fieldsRule = "FirstDependency"

    # The extent of the output is the intersection of the input features 
    #  and the clip features (parameter 1)
    #
    self.params[2].schema.extentRule = "Intersection"

    return

additionalFields

除了通过应用 fieldsRule 而添加的字段以外,还可向输出添加其他字段。additionalFields 将采用字段对象的 Python 列表。

查看 AdditionalFields 使用过程的示例

cellSizeRule

此属性用于确定输出栅格或输出格网的像元大小。

Value

Description

"AsSpecified"

The output cellsize is specified in the cellSize property.

"FirstDependency"

The cell size is calculated from the first dependent parameter. If the dependent parameter is a raster, then its cellsize is used. For other types of dependent parameters, such as feature classes or feature datasets, the extent of the data is used to calculate a cellsize. If the first dependent parameter is a multivalue (a list of values), the first value in the multivalue list is used.

"Min", "Max"

"Min" means the output cellsize is the smallest cellsize of the dependent parameters. "Max" means it is the largest cellsize of the dependent parameters.

"Environment"

The output cellsize is calculated based on the cellsize environment setting.

cellSizeRule values

cellSize

cellSizeRule 为“AsSpecified”时,将该属性设置为要使用的像元大小。

rasterRule

该属性将确定输出栅格中包含的数据类型(整型或浮点型)。

Value

Description

"FirstDependency"

The data type (integer or float) is the same as the first dependent parameter. If the first dependent parameter is a multivalue (a list of values), the first value in the multivalue list is used.

"Min", "Max"

Integer is considered smaller than float. For example, if there are two dependent parameters, one containing integers and the other containing floats, "Min" creates an integer output, and "Max" creates a float output.

"Integer"

The output raster contains integers (whole numbers).

"Float"

The output raster contains floats (fractional numbers).

rasterRule values

rasterFormatRule

该属性确定输出栅格格式,“Grid”或“Img”。默认值为“Img”,它是 ERDAS IMAGINE 格式。“Grid”是 Esri 的格式。

了解有关栅格数据格式的详细信息

additionalChildren

工作空间是保存数据集(要素、表和栅格)的容器。这些数据集相当于工作空间的子辈(如果将工作空间看作父辈的话)。如果工具将数据集添加到新的或者现有的工作空间中,那么可通过添加对子辈的描述来更新工作空间的描述。例如,工具可采用要素类列表(多值),以某种方式进行修改,然后将修改后的要素类写入现有工作空间。在模型构建器中使用此工具时,工作空间就是派生的工具输出,可能会需要将该工作空间用作选择数据工具的输入。通过选择数据可以选择容器中的某个子数据集,并将它用作其他工具的输入。

additionalChildren 的输入是对子辈的一个或多个描述。对子辈的描述分为两种形式:

Form

Description

value object

A feature class, table, raster, dimension, or annotation value, as returned by the value property.

Python list object of the form [type, name, fields, extent, spatial reference]

A Python list containing a description of the child to be added. Only the first two entries in the list, type and name, are required. The remaining arguments are optional.

Member lists for additionalChildren

添加多个子辈时,可以提供子辈描述的列表。如果使用 Python 列表对象形式添加子辈,将会为 additionalChildren 创建列表的列表。

Python 列表形式具有五个参数,如下表中所述。

Argument

Type

Description

type

required

One of the following: "Point", "Multipoint", "Polyline", "Polygon", "Table", "Raster", "Annotation", "Dimension"

name

required

The name of the dataset. It can just be the base name of the dataset ("streets") or the full catalog path ("E:\mydata\test.gdb\infrastructure\streets"). When a full catalog path is given, all but the base name ("streets") is ignored.

fields

optional

A Python list of field objects. This contains the fields appearing on the child, if known.

extent

optional

A string or Python list containing the spatial extent of the child.

spatial reference

optional

A spatial reference object.

Contents of the child list

这些参数必须按照下列顺序提供。要跳过可选参数,可使用 Python 关键字 None“#”

以下是设置工作空间方案的一些示例。这些示例基于具有下列参数的脚本工具:

Parameter name

Properties

0

Input feature class

Feature class—input.

1

Input table

Table—input.

2

Input workspace

Workspace—input (an existing workspace that contains the results of the tool).

3

Derived workspace

Workspace—Derived output, obtained from Input_workspace. The schema of this workspace is modified to contain additional children.

Example tool parameters

此工具获取输入要素类和表,将它们复制到工作空间,向要素类添加新字段,然后在工作空间中创建新的面要素类。(此工具的实际作用并不是很重要,因为它仅仅是用于举例说明工作空间方案的设置。)以下代码示例基于另一个代码示例,从 additionalChildren 的简单用法开始。如果选择实施和测试以下代码示例中的某些代码,可使用下面的模型测试代码。

用于查看验证结果的模型

initializeParameters() 中,输出工作空间通过其依存参数(参数 2)进行克隆。此依赖项不仅可在工具属性中设置,还可在 initializeParameters() 中设置,以防止用户移除工具属性中的依赖项。

class ToolValidator:
  def __init__(self):
     import arcpy 
     self.params = arcpy.GetParameterInfo()

  def initializeParameters(self):
    self.params[3].parameterDependencies = [2]  # input workspace
    self.params[3].schema.clone = True  # Copy all existing contents to output
    return

示例:将两个输入(未修改)复制到输出工作空间:

def updateParameters(self):
  inFC = self.params[0].value     # input feature class
  inTable = self.params[1].value  # input table
  inWS = self.params[2].value     # input workspace
  if inFC and inTable and inWS:
    self.params[3].schema.additionalChildren = [inFC, inTable]
  return

示例:此工具可创建一个新的面要素类。与该新要素类有关的已知属性(验证时)仅有名称(“SummaryPolygon”)和类型(“polygon”)。

children = []    # New empty list
children.append(inFC)
children.append(inTable)
children.append(["polygon", "SummaryPolygon"])
self.params[3].schema.additionalChildren = children

示例:向输入要素类添加一个字段。

# Create a field object with the name "Category" and type "Long"
#
newField = arcpy.Field()
newField.name = "Category"
newField.type = "Long"

# Describe the input feature class in order to get its list of fields. The 9.3
#  version of the geoprocessing object returns fields in a Python list, unlike
#  previous versions, which returned fields in an enumerator.
#
desc = arcpy.Describe(inFC)
fieldList = desc.fields

# Add the new field to the list
#
fieldList.append(newField)

# Create a new child based on the input feature class, but with the 
#  additional field added
#
newChild = [desc.shapeType, desc.catalogPath, fieldList,
            desc.extent, desc.spatialReference]

# Now create our list of children and add to the schema
#
children = []
children.append(newChild)
children.append(inTable)
children.append(["polygon", "SummaryPolygon"])
self.params[3].schema.additionalChildren = children

要为 SummaryPolygon(新的面要素类)创建字段,请创建与上面示例中所示模式相似的字段对象的列表。

示例:多值输入

在该示例中,第一个参数是由要素类构成的多值。多值中的每个要素类均复制到派生工作空间中。新字段“ProjectID”将添加到每个复制的要素类中。

# 0 - input features (multivalue)
# 1 - input workspace
# 2 - derived workspace

class ToolValidator:
  def __init__(self):
     import arcpy 
     self.params = arcpy.GetParameterInfo()

  def initializeParameters(self):
    self.params[2].parameterDependencies = [1]
    self.params[2].schema.clone = True
    return

  def updateParameters(self):
    inVT = self.params[0].value   # multivalue ValueTable
    inWS = self.params[1].value   # WorkSpace

    # Add each feature class to the output workspace. In addition,
    #  add a new field "ProjectID" to each feature class
    #
    if inVT and inWS:
        rowCount = inVT.rowCount  # Number of rows in the MultiValue table
        children = []
        newField = arcpy.Field()
        newField.name = "ProjectID"
        newField.type = "Long"
        for row in range(0, rowCount):
            value = inVT.getValue(row, 0)
            if value:
                d = arcpy.Describe(value)
                fieldList = d.fields

                # Note -- not checking if field already exists
                #
                fieldList.append(newField)

                # Create new child with additional ProjectID field and
                #  add child to list of children
                #
                child = [d.shapeType, d.catalogPath, fieldList]
                children.append(child)            
                      
        self.params[2].schema.additionalChildren = children
    return

  def updateMessages(self):
    return

filter 对象

filter 对象允许为参数指定用户可用的选择。例如,可设置仅限选择文本字段的字段过滤器。过滤器执行三项工作:

可通过两种方式指定过滤器:

过滤器分为六种类型,如下表所示:

Filter type

Values

ValueList

A list of string or numeric values. Used with String, Long, Double, and Boolean data types.

Range

A minimum and maximum value. Used with Long and Double data types.

FeatureClass

A list of allowable feature class types, specified with the values "Point", "Multipoint", "Polyline", "Polygon", "MultiPatch", "Sphere", "Annotation", "Dimension". More than one value can be supplied to the filter.

File

A list of file suffixes, for example, ".txt", ".e00", ".ditamap".

Field

A list of allowable field types, specified by the values "Short", "Long", "Single", "Double", "Text", "Date", "OID", "Geometry", "Blob", "Raster", "GUID", "GlobalID", "XML". More than one value can be supplied to the filter.

Workspace

A list of allowable workspace types, specified by the values "FileSystem", "LocalDatabase", and "RemoteDatabase". More than one value can be supplied.

Filter type and values

属性

Property

Description

type

The type of filter (ValueList, Range, FeatureClass, File, Field, and Workspace). You can set the type of filter when dealing with Long and Double parameters (see note below). For other types of parameters, there is only one valid type of filter, so setting the type on these parameters is ignored. If you do not want to filter values, set the list property to an empty list.

list

A Python list of values for the filter. If you do not want to filter values, set the list property to an empty list.

filter properties

ValueList

用于字符串参数的 ValueList

对于字符串参数,列表可包含任意数量的字符串。下面是在 initializeParameters() 中设置字符串值列表的示例。参数包含两个选项:“NEW_FORMAT”和“OLD_FORMAT”。

def initializeParameters(self):
    # Set the fixed list of "file format type" parameter choices and its
    #  default value
    #
    self.params[1].filter.list = ["OLD_FORMAT", "NEW_FORMAT"]
    self.params[1].value = "OLD_FORMAT"
    return

在上面的示例中,设置值列表像在工具的“属性”对话框的“参数”选项卡中进行设置一样轻松。事实上,如果之前在工具的属性对话框中已将值列表设置为其他值(例如“OLD”和“NEW”),则在调用 initializeParameters() 时会使用“OLD_FORMAT”和“NEW_FORMAT”进行替换。对于默认值来说也是这样 - 它可在工具的“属性”对话框中进行设置,然后在 ToolValidator 中重置。

注注:

在 ToolValidator 中提供的值列表会始终替换工具的“属性”对话框中设置的值。这样便可以基于其他参数更新值。

继续讲述该示例,以下代码显示了 updateParameters() 根据用户选择“OLD_FORMAT”还是“NEW_FORMAT”来更改另一个参数中的值列表:

def updateParameters(self):
    # Update the value list filter of the "feature type in file" parameter 
    #   depending on the "file format type" parameter.
    #
    if self.params[1].value.upper() == "OLD_FORMAT":
      self.params[2].filter.list = ["POINT", "LINE", "POLYGON"]
    elif self.params[1].value.upper() == "NEW_FORMAT":
      self.params[2].filter.list = ["POINT", "LINE", "POLYGON", 
                                    "POINT_WITH_ANNO", 
                                    "LINE_WITH_ANNO", 
                                    "POLYGON_WITH_ANNO"]

    # Provide default value for "feature type in file" parameter
    #
    if not self.params[2].altered:
      self.params[2].value = "POINT"

用于长整型参数和双精度型参数的 ValueList

长整型参数或双精度型参数可具有数值列表。用户仅可选择或输入列表中的值。

# Set filter for a Long parameter
#
self.params[7].filter.list = [10, 20, 30, 40, 50]

# Set filter for a Double parameter
#
self.params[8].filter.list = [10.0, 12.5, 15.0]

用于布尔型参数的 ValueList

对于布尔型参数,存在两个值:值 true 和值 false。值 true 始终是列表中的最初值。

def initializeParameters(self):
  # Set the Boolean choice for including or excluding angles
  #
  self.params[6].filter.list = ["ANGLE", "NO_ANGLE"]

  # Set the default value to false (no angle)
  #
  self.params[6].value = "NO_ANGLE"
  return

def updateParameters(self):
  # Enable angle format parameter if user wants angles
  #
  if self.params[6].value.upper() == "ANGLE":
    self.params[7].enabled = True

范围

“长整型”或“双精度”参数可具有范围过滤器。范围过滤器有两个值,即最小值和最大值。列表中的第一个值是最小值。包括范围边界值,这表示最小值和最大值也是有效数据。

def initializeParameters(self):
  # Utility values must be between -10 and 10.
  #
  self.params[7].filter.list = [-10, 10]

为长整型参数和双精度型参数设置过滤器类型

对于长整型参数和双精度型参数,默认过滤器类型为 ValueList。如果要更改为范围过滤器,可在 initializeParameters() 中设置过滤器类型,如下所示:

def initializeParameters(self):
  # Set the 'score' value parameters to a range filter
  #
  self.params[7].filter.type = "Range"
  self.params[7].filter.list = [-10, 10]

仅可为长整型和双精度型参数设置过滤器类型。

要素类

以下示例显示了如何根据另一个输入参数的要素类型设置某个输入参数的要素类型。

def updateParameters(self):
    # Set the input feature type of the second parameter based
    #  on the feature type of the first parameter.
    #
    if self.params[0].value:
      desc = arcpy.Describe(self.params[0].value)
      feature_type = desc.shapeType.lower()

      if feature_type == "polygon":
        self.params[1].filter.list = ["point", "multipoint"]

      elif feature_type == "polyline":
        self.params[1].filter.list = ["polygon"]
      
      elif feature_type == "point" or \
           feature_type == "multipoint":
        self.params[1].filter.list = ["polyline"]

      else:
        self.params[1].filter.list = []
      
    return

文件

文件过滤器包含文件可具有的文件后缀的列表,例如“.txt”(简单文本文件)和“.csv”(逗号分隔值)。您可以提供任何后缀的文本,不必是 ArcGIS 可识别的后缀。后缀可为任意长度,且不包含句点。以下示例显示了如何为输入的“文件”类型参数设置过滤器。

def initializeParameters(self):
  # Set the input file type to our recognized options file suffixes
  #
  self.params[0].filter.list = ["opt56", "opt57", "globalopt"]
  return

字段

字段过滤器用于定义允许的字段类型:可用的值包括“短整型”、“长整型”、“浮点型”、“单精度”、“双精度”、“文本”、“日期”、“OID”、“几何”、“Blob”、“栅格”、“GUID”、“GlobalID”和“XML”。

显示名称与内部名称

具有内部名称的字段类型有四种,如下表所示。

Display name

Internal name

Short

SmallInteger

Long

Integer

Float

Single

Text

String

Field filter aliases

在指定字段过滤器时,可以使用显示名称,也可以使用内部名称。也就是说,下列两行代码是等效的:

self.params[1].filter.list = ["short", "long", "float", "text"]
self.params[1].filter.list = ["smallinteger", "integer", "single", "string"]

如果提供了显示名称,例如“短整型”,在过滤器中就会转换并存储为“SmallInteger”。您基本上不需要访问字段过滤器中的值,但是如果需要,请注意存储的是内部名称。下面的代码片段对这一点做出解释:

self.params[1].filter.list = ["short", "long"]
# 
if self.params[1].filter.list[0].lower() == "smallinteger":
  # do something

设置默认字段值

您可能需要为字段参数提供默认值。实现方法就是在整个输入表的字段中循环查找,然后挑选满足过滤器条件的第一个字段,如下所示:

def initializeParameters(self):
  self.params[1].filter.list = ["short", "long", "float", "double"]
  return

def updateParameters(self):
  if self.params[0].value and not self.params[1].altered:
    self.params[1].value = ""
    desc = arcpy.Describe(self.params[0].value)
    fields = desc.fields

    # Set default to the first field that matches our filter
    #
    for field in fields:
      fType = field.type.lower()
      if fType in ["smallinteger", "integer", "single", "double"]:
        self.params[1].value = field.name
        break
  return
警告警告:

请不要使用 ToolValidator 中的地理处理 ListFields 函数。应使用 Describe 函数,如上所示。

工作空间

工作空间过滤器用于指定允许的输入工作空间的类型。共有三个值:

Workspace filter

Description

"FileSystem"

A system folder, used to store shapefiles, coverages, INFO tables, and grids

"LocalDatabase"

A personal or file geodatabase

"RemoteDatabase"

An ArcSDE database connection

相关主题

9/15/2013