通过 Python 使用函数

函数是用于执行某项特定任务并能够纳入更大的程序的已定义功能。

在 ArcPy 中,所有地理处理工具均以函数形式提供,但并非所有函数都是地理处理工具。除工具之外,ArcPy 还提供多个函数以更好地支持使用 Python 的地理处理工作流。函数可用于列出某些数据集检索数据集的属性、在将表添加到地理数据库之前验证表名称或执行其他许多有用的地理处理任务。这些函数只能从 ArcPy 获得,而不能作为 ArcGIS 应用程序中的工具,因为它们专为 Python 工作流所设计。

函数的一般形式与工具类似;它接受参数(可能需要也可能不需要)并返回某些结果。非工具函数的返回值可以为各种类型 - 从字符串到地理处理对象。工具函数会始终返回 Result 对象,并提供地理处理消息支持。

下面的示例使用两个 ArcPy 函数,GetParameterAsText 用于接收输入参数,Exists 用于确定输入是否存在。Exists 函数返回一个布尔值(“真”或“假”)。

import arcpy

input = arcpy.GetParameterAsText(0)
if arcpy.Exists(input):
    print("Data exists")
else: 
    print("Data does not exist")

下面的示例使用 ListFeatureClasses 函数创建一个要素类列表,然后循环列表,裁剪具有边界要素类的各个要素类。

import arcpy
import os

# The workspace environment needs to be set before ListFeatureClasses
#    to identify which workspace the list will be based on
#   
arcpy.env.workspace = "c:/data"
out_workspace = "c:/data/results/"
clip_features = "c:/data/testarea/boundary.shp"

# Loop through a list of feature classes in the workspace
#
for fc in arcpy.ListFeatureClasses():
    # Set the output name to be the same as the input name, and 
    #    locate in the 'out_workspace' workspace
    #
    output = os.path.join(out_workspace, fc)

    # Clip each input feature class in the list
    #
    arcpy.Clip_analysis(fc, clip_features, output, 0.1)

相关主题