ArcGIS10.x系列 Python工具箱教程
目录
1.前提
2.需要了解的资料
3.Python工具箱制作教程
4. Python工具箱具体样例代码(DEM流域分析-河网等级矢量化)
1.前提
如果你想自己写Python工具箱,那么假定你已经会ArcPy,如果只是自己用,完全没有必要,直接脚本运行。如果是给其他人用,为了简洁明了,适用这里。Python工具箱10.2无法加密,但是工具箱+Script脚本是可以加密的。10.5以上Python工具箱可加密。
本文只介绍Python工具箱,对于工具箱+Script脚本不是特别推荐!
2.需要了解的资料
Python工具箱需要知道哪些内容?
[1]Python工具箱 代码模板 (可自己新建Python工具箱 编辑查看代码)
[2]Arcpy.Parameter (重要*****)
[3]Python工具箱 输入参数类型(data_type) (重要*****)
[4]在 Python 工具箱中定义工具
[5]定义 Python 工具箱中的参数 (重要*****)
3.Python工具箱制作教程
[1]新建python工具箱
[2]右击 新建的Python工具箱 编辑
[3] 随后txt打开了代码,复制所有代码到py文件中,我这里用的vscode连接arcgis python2.7
如上图所示,Python工具箱模板。需要关注的有上述箭头部分。
[4]待代码写完后,将代码复制到 “编辑” 的Python工具箱,然后另存为,选择编码格式“ANSI”,替换!
----------------------------------------------------------------------------------------------------------
小细节:
①Python工具箱不好调试,print无法输出信息,一般采用arcpy.AddMessage、arcpy.AddError输出信息;
②然后parameters[0].value .valueAsText这些都是arcpy.parameter的属性,查看我提供的Parameter官网介绍即可。
③注意中文格式,设置utf-8,另存ANSI格式。
④着重看给的 资料链接 [2]、[3]、[5] 官网说的很明白(中英文可切换),再结合我的样例代码,就很快理解了!
----------------------------------------------------------------------------------------------------------
4. Python工具箱具体样例代码(DEM流域分析-河网等级矢量化)
# 设置中文环境 对于中文字符串 前面加u 打印时 需要在字符串后加 .decode('utf-8')
import sys
defalutencoding = 'utf-8'
if sys.getdefaultencoding() != defalutencoding:reload(sys)sys.setdefaultencoding(defalutencoding)import os
import arcpy
from arcpy import env
from arcpy.sa import * #arcpy栅格计算的基本计算器,高级复杂的在arcpy.gp中# 定义函数
def check_exists_and_delete(dataset_name):# 前提已经设置了env.workspace, 检测存在即删除if arcpy.Exists(dataset_name):arcpy.Delete_management(dataset_name)print(u'已删除:'+str(dataset_name))returnreturnclass Toolbox(object):def __init__(self):"""Define the toolbox (the name of the toolbox is the name of the.pyt file)."""self.label = "Python工具箱-流域分析"self.alias = "Python工具箱-流域分析"# List of tool classes associated with this toolboxself.tools = [Tool]
class Tool(object):def __init__(self):"""Define the tool (tool name is the name of the class)."""self.label = "流域分析"self.description = "流域分析要求数据在gdb中操作!只需导入DEM,即可完成填洼-流向-流量-河网-河网分级-分级矢量化。依次生成的结果名称为输入DEM名称+_填洼"self.canRunInBackground = Falsedef getParameterInfo(self):"""Define parameter definitions"""param_gdb = arcpy.Parameter(displayName = "请输入工作空间(GDB):",name = "in_workspace",datatype = "DEWorkspace",parameterType = "Required",direction="Input")param_gdb.value = env.workspaceparam_dem = arcpy.Parameter(displayName="请输入或选择DEM图层:",name="in_dem",datatype="GPRasterLayer", # , "DERasterDataset", "GPRasterDataLayer"parameterType="Required",direction="Input",)param_threshold = arcpy.Parameter(displayName="请输入河网分级整型阈值(大于):",name="in_threshold",datatype="GPLong",parameterType="Required",direction="Input",)param_threshold.value = 1000params = [param_gdb, param_dem, param_threshold]return paramsdef isLicensed(self):"""Set whether tool is licensed to execute."""return Truedef updateParameters(self, parameters):"""Modify the values and properties of parameters before internalvalidation is performed. This method is called whenever a parameterhas been changed."""return def updateMessages(self, parameters):"""Modify the messages created by internal validation for each toolparameter. This method is called after internal validation."""returndef execute(self, parameters, messages):arcpy.CheckOutExtension("Spatial") # 必须执行,否则默认不打开??env.workspace = parameters[0].valueAsText# 相关操作在 系统工具箱->Spatial Analyst Tools->水文分析or地图代数# 2.DEM填洼DEM_Name = os.path.basename(parameters[1].valueAsText) # 3-需要修改成自己的DEM名称arcpy.AddMessage(u"正在处理DEM图层:" + DEM_Name)DEM_TianWa_Name = DEM_Name + u"_填洼" # 注意 不能有- 可以是_outFill = Fill(DEM_Name)check_exists_and_delete(DEM_TianWa_Name)outFill.save(DEM_TianWa_Name)print(u"完成填洼".decode('utf-8'))arcpy.AddMessage(u"完成填洼")# 3.DEM流向 根据填洼结果 来计算DEM_LiuXiang_Name = DEM_Name + u"_流向"outFlowDirection = FlowDirection(DEM_TianWa_Name)check_exists_and_delete(DEM_LiuXiang_Name)outFlowDirection.save(DEM_LiuXiang_Name)print(u"完成流向".decode('utf-8'))arcpy.AddMessage(u"完成流向")# 4.DEM流量 根据流向结果 来计算DEM_LiuLiang_Name = DEM_Name + u"_流量"outFlowAccumulation = FlowAccumulation(DEM_LiuXiang_Name)check_exists_and_delete(DEM_LiuLiang_Name)outFlowAccumulation.save(DEM_LiuLiang_Name)print(u"完成流量".decode('utf-8'))arcpy.AddMessage(u"完成流量")# 5.DEM河网 根据流量 来计算 (arcpy脚本不允许使用RasterCalculator)DEM_HeWang_Name = DEM_Name + u"_河网"threshold = parameters[2].value # 4-需要修改成自己的流量阈值raster = DEM_LiuLiang_Nameout_A_Calculator = Con(Raster(raster) > threshold, 1)check_exists_and_delete(DEM_HeWang_Name)out_A_Calculator.save(DEM_HeWang_Name)print(u"完成河网".decode('utf-8'))arcpy.AddMessage(u"完成河网")# 6.DEM河网分级 根据河网 流向结果 来计算DEM_HeWang_FenJi_Name = DEM_Name + u"_河网分级"outStreamOrder = StreamOrder(DEM_HeWang_Name, DEM_LiuXiang_Name, "STRAHLER") # STRAHLER分级方法 更合适check_exists_and_delete(DEM_HeWang_FenJi_Name)outStreamOrder.save(DEM_HeWang_FenJi_Name)print(u"完成河网分级".decode('utf-8'))arcpy.AddMessage(u"完成河网分级")# 6.1 DEM河网分级后栅格结果 矢量化 DEM_HeWang_FenJi_SHP_Name = DEM_Name + u"_河网分级矢量"check_exists_and_delete(DEM_HeWang_FenJi_SHP_Name)StreamToFeature(DEM_HeWang_FenJi_Name, DEM_LiuXiang_Name, DEM_HeWang_FenJi_SHP_Name, "NO_SIMPLIFY")print(u"完成河网分级矢量化".decode('utf-8'))arcpy.AddMessage(u"完成河网分级矢量化")return