py工具箱源码:
# coding=utf-8
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 = "批量修复几何工具箱"
self.alias = "RepairGeo"
# List of tool classes associated with this toolbox
self.tools = [Tool]
class Tool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "批量修复几何"
self.description = "修复文件夹和本地数据库的要素类(不深层递归)"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
param = arcpy.Parameter(
displayName="输入文件夹或本地数据库",
name="input_workspace",
datatype="DEWorkspace",
parameterType="Required",
direction="Input"
)
params = [param]
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."""
try:
new_workspace = parameters[0].valueAsText
old_workspace = arcpy.env.workspace
# 转换工作空间
arcpy.env.workspace = new_workspace
desc = arcpy.Describe(new_workspace)
if desc.workspaceType == "FileSystem":
if arcpy.ListFiles("*.shp") != []:
arcpy.AddMessage("正在修复shp文件...")
for shpfile in arcpy.ListFiles("*.shp"):
arcpy.AddMessage(u"执行修复——shp文件:" + shpfile)
arcpy.RepairGeometry_management(shpfile, "DELETE_NULL")
arcpy.AddMessage("修复完成!")
else:
raise Exception("文件夹中没有shp文件!")
elif desc.workspaceType == "LocalDatabase":
flag = False
datasets = arcpy.ListDatasets(feature_type='feature')
datasets = [''] + datasets if datasets is not None else []
for ds in datasets:
arcpy.AddMessage(u"执行修复——要素数据集:" + ds)
for fc in arcpy.ListFeatureClasses(feature_dataset=ds):
if fc is not None: # 这里写为fc != []更合适?
flag = True
arcpy.AddMessage(u" 执行修复——要素类:" + fc)
arcpy.RepairGeometry_management(fc, "DELETE_NULL")
if flag:
arcpy.AddMessage("修复完成!")
else:
arcpy.AddMessage("数据库中没有要素类!")
else:
raise Exception("除文件夹及数据库外,占不支持其他类型!")
except Exception as e:
arcpy.AddMessage(e)
finally:
arcpy.env.workspace = old_workspace
return
核心代码在execute方法中。
在编写脚本过程中,遇到到一些问题总结。
1、在测试gdb里面由于一些可能是误操作的原因粘贴了一些与要素数据集同名的文件。导致ListFeatureClasses方法失效。
2、arcpy.AddMessage(u" 执行修复——要素类:" + fc) 在这行代码中fc为unicode编码,与之串联的字符串也应该是unicode字符串,否则可能报错(大概是报ascii溢出错误)
3、这行代码是帮助文档里来的:datasets = [''] + datasets if datasets is not None else [] 值得品读。
4、getParameterInfo方法返回值应为参数值数组,否则工具会出现无参数输入框的问题。
5、if fc is not None: # 这里写为fc != []更合适?。不过经过测试,数据集没有包含要素类时也没报错。 这里,if fc is not None:可以不用存在,当ListFeatureClasses为[],循环不会进来,所以可以不用做这个判断。