ArcGIS10.x系列 Python工具箱教程

ArcGIS10.x系列 Python工具箱教程

目录

1.前提

2.需要了解的资料

3.Python工具箱制作教程

[4. Python工具箱具体样例代码(DEM流域分析-河网等级矢量化)](#4. Python工具箱具体样例代码(DEM流域分析-河网等级矢量化))


1.前提

如果你想自己写Python工具箱,那么假定你已经会ArcPy,如果只是自己用,完全没有必要,直接脚本运行。如果是给其他人用,为了简洁明了,适用这里。Python工具箱10.2无法加密,但是工具箱+Script脚本是可以加密的。10.5以上Python工具箱可加密。

本文只介绍Python工具箱,对于工具箱+Script脚本不是特别推荐!

2.需要了解的资料

Python工具箱需要知道哪些内容?

1Python工具箱 代码模板 (可自己新建Python工具箱 编辑查看代码)

2Arcpy.Parameter(重要*****)

3Python工具箱 输入参数类型(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输出信息;

②然后parameters0.value .valueAsText这些都是arcpy.parameter的属性,查看我提供的Parameter官网介绍即可。

③注意中文格式,设置utf-8,另存ANSI格式。

④着重看给的 资料链接 235 官网说的很明白(中英文可切换),再结合我的样例代码,就很快理解了!


4. Python工具箱具体样例代码(DEM流域分析-河网等级矢量化)

python 复制代码
# 设置中文环境 对于中文字符串 前面加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))
        return
    return

class 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 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 = "流域分析要求数据在gdb中操作!只需导入DEM,即可完成填洼-流向-流量-河网-河网分级-分级矢量化。依次生成的结果名称为输入DEM名称+_填洼"
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""
        param_gdb = arcpy.Parameter(
            displayName = "请输入工作空间(GDB):",
            name = "in_workspace",
            datatype = "DEWorkspace",
            parameterType = "Required",
            direction="Input"
        )
        param_gdb.value = env.workspace

        param_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 = 1000

        params = [param_gdb, param_dem, param_threshold]
        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):
        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_Name
        out_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
相关推荐
雪的季节3 小时前
GIS 矢量数据格式
arcgis
非科班Java出身GISer4 小时前
ArcGIS JS 基础教程(11):飞行定位 goTo
arcgis·arcgis js 飞行定位·arcgis js 定位·arcgis js 各种定位·arcgis js 飞行·arcgis js 定位到对象
我是Superman丶4 小时前
前端技术手势识别
arcgis
da-peng-song3 天前
ArcGIS Desktop使用入门(四)——生成经纬度坐标
arcgis·经纬度坐标
da-peng-song3 天前
ArcGIS Desktop使用入门(三)图层右键工具——定义查询
数据库·arcgis·拆分数据·定义查询
星座5283 天前
破解水环境空间分析难题,迈向智慧水环境管理:ArcGIS水质评价、污染预测与洪水监测核心技术揭秘
arcgis·水环境·水文
非科班Java出身GISer4 天前
ArcGIS JS 基础教程(10):Camera 相机控制
arcgis·arcgis js 相机·arcgis js 相机控制·arcgis js 视角控制·arcgis js 飞行定位·arcgis js 定位·arcgis js 各种定位
码语智行5 天前
Shapefile获取空间数据和中心点坐标
java·arcgis
码语智行5 天前
地图上图、空间拓扑查询示例
java·arcgis
DXM05215 天前
第10期| 卷积神经网络CNN通俗详解:AI遥感的底层核心
人工智能·python·神经网络·机器学习·arcgis·cnn·文心一言