Introduction to Use Python in Arcgis

  • Python窗口
  • 执行工具
  • 设置环境变量
  • 创建工作流
  • 自定义工具箱
  • 自定义窗口

Python窗口

Enter multiple commands

第一行命令输入完成后按住 ctrl 键并按 enter
example:

1
2
3
>>> x = 1
... y = 2
... print x + y

Path

编程语言(如 Python)将反斜线\用作转义字符。例如, \n表示换行符,\t 表示制表符。指定路径时,可使用正斜线(/)代替反斜线。使用两条反斜线(而不是一条)以避免语法错误。也可通过在包含反斜线的字符串前放置字母r以便正确解释)来使用字符串文本。

1
2
3
arcpy.GetCount_management("c:/temp/streams.shp")
arcpy.GetCount_management("c:\\temp\\streams.shp")
arcpy.GetCount_management(r"c:\temp\streams.shp")

执行工具

跳过可选参数

1
2
3
4
5
6
7
8
#Use empty strings to skip optional parameters
arcpy.AddField_management("c:/data/streets.shp", "Address", "TEXT", "", "", 120)

#Use the # sign to skip optional arguments
arcpy.AddField_management("c:/data/streets.shp", "Address", "TEXT", "#", "#", 120)

#Use the parameter name to bypass unused optional arguments
arcpy.AddField_management("c:/data/streets.shp", "Address", "TEXT", field_length=120)

多值参数

1
arcpy.DeleteField_management("c:/base/rivers.shp", ["Type", "Turbidity", "Depth"])

设置环境变量

Path Default environment

1
2
3
4
>>> print arcpy.env.overwriteOutput
True
>>> print arcpy.env.workspace
None

Set new environment

1
2
arcpy.env.overwriteOutput = False
arcpy.env.workspace = "c:/temp"

Check new environment

1
2
3
4
>>> print arcpy.env.overwriteOutput
False
>>> print arcpy.env.workspace
c:/temp

Restore the default environment

1
arcpy.ResetEnvironments()

Output all the environment

1
2
3
4
5
>>> environments = arcpy.ListEnvironments()
... for environment in environments:
... envSetting = eval("arcpy.env." + environment)
... print "%-30s: %s" % (environment, envSetting)
...

创建工作流

Create functions

1
2
3
4
5
6
def listFieldNames(table, wildcard=None, fieldtype=None):
fields = arcpy.ListFields(table, wildcard, fieldtype)
nameList = []
for field in fields:
nameList.append(field.name)
return nameList

可返回字段名称

1
fieldNames = listFieldNames("c:/data/water.gdb/water_pipes")

创建自定义脚本工具

自定义工具箱

调用ImportToolbox函数

使用 Python 访问自定义工具箱中包含的工具。导入该工具箱后,即能够以 arcpy.<工具名称>_<别名> 形式访问自定义工具。

1
2
arcpy.ImportToolbox("c:/mytools/geometrytools.tbx")
arcpy.CreateRegularPolygons_geometry(

设置临时别名

1
2
arcpy.ImportToolbox("c:/mytools/geometrytools.tbx", "mytools")
arcpy.CreateRegularPolygons_mytools(

自定义窗口

预加载Python工具

Python窗口识别系统环境变量PYTHONSTARTUP,将PYTHONSTARTUP设置为某一Python文件,则打开Python窗口时,Python将自动执行此文件的代码。

PYTHONSTARTUP

1 右键单击我的电脑,然后单击属性。
2 单击高级选项卡,然后单击环境变量。
3 在系统变量下,单击新建。
4 将PYTHONSTARTUP添加到变量名中。
5 将Python文件的路径添加到变量值,然后单击确定。
6 单击确定。

示例文件

打开Python窗口时,将导入arcpy、numpy和time,并将打开overwriteOutput设置。

1
2
3
4
import arcpy  from arcpy
import env import numpy
import time
env.overwriteOutput = True
-------------文章结束啦 ฅ●ω●ฅ 感谢您的阅读-------------