1 Getting Started With Python
-
Upload
ck-ius-nu-nhan -
Category
Documents
-
view
56 -
download
0
Transcript of 1 Getting Started With Python
-
7/16/2019 1 Getting Started With Python
1/38
Getting Started With Python In ArcGIS
David Wynne
-
7/16/2019 1 Getting Started With Python
2/38
8:308:30 9:30: Python 101 and9:30: Python 101 and ArcPyArcPy 101101
Essentials of the languageEssentials of the language
UsinUsin ArcPArcP to execute eo rocessin toolsto execute eo rocessin tools
Python windowPython window
9:309:30 10:00: Script and Script tool basics10:00: Script and Script tool basics
Creating a standalone scriptCreating a standalone script Creating a script toolCreating a script tool
10:0010:00 10:15: Ma automation10:15: Ma automation
10:1510:15 10:45: Break10:45: Break
10:4510:45 11:00: Raster analysis and Map Algebra11:00: Raster analysis and Map Algebra
11:0011:00 11:45: Tool Design and Validation11:45: Tool Design and Validation
-
7/16/2019 1 Getting Started With Python
3/38
Python 101Python 101
-
7/16/2019 1 Getting Started With Python
4/38
ESRI has embraced Python forESRI has embraced Python for ArcGISArcGIS 1010
Python is the language that fulfil ls the needs of our userPython is the language that fulfil ls the needs of our user
communitcommunit
Easy to learnEasy to learn
Excellent for beginners and expertsExcellent for beginners and experts
u a e or arge pro ec s or sma scr p su a e or arge pro ec s or sma scr p s CrossCross--platformplatform
-
7/16/2019 1 Getting Started With Python
5/38
Clear, easy to read syntaxClear, easy to read syntax
Easy to use, makes it simple to get startedEasy to use, makes it simple to get started
Including lists and dictionariesIncluding lists and dictionaries
Comes with a large standard libraryComes with a large standard library
Supports raising and catching exceptionsSupports raising and catching exceptionsCode can be grouped into modules and packagesCode can be grouped into modules and packages
uppor s o ecuppor s o ec --or en e programm ngor en e programm ng
http://www.python.org/about/
-
7/16/2019 1 Getting Started With Python
6/38
..
ESRI has ful ly embraced Python as its language forESRI has ful ly embraced Python as its language for
automationautomation
1.1. ArcPyArcPy sitesite--packagepackage
Includes mapping and Map Algebra supportIncludes mapping and Map Algebra support
Successor to theSuccessor to the arcgisscriptingarcgisscripting modulemodule2.2. Python windowPython window
3.3. Python script tool frameworkPython script tool framework
-
7/16/2019 1 Getting Started With Python
7/38
dispatchbased Geoprocessor
.
arcgisscripting module
Cross- latform
Python 2.4
arcgisscripting module, 9.3 version
Pythonic
Python 2.5
ArcP site- acka e
Mapping & Map Algebra support
Python window
.
-
7/16/2019 1 Getting Started With Python
8/38
ArcPyArcPy 101101
-
7/16/2019 1 Getting Started With Python
9/38
A cornerstone for automation inA cornerstone for automation in ArcGISArcGIS
data analysisdata analysis
data conversiondata conversion
data managementdata management
map automationmap automation
ArcPyArcPy is a native Python siteis a native Python site--packagepackage
Access to 800+Access to 800+ eo rocessineo rocessin toolstools
Provides embedded reference documentation for eachProvides embedded reference documentation for each
function, class and modulefunction, class and module
Python editorPython editor
Familiar toFamiliar to arcgisscriptingarcgisscripting usersusers
-
7/16/2019 1 Getting Started With Python
10/38
Improved coding experience, such as:Improved coding experience, such as:
CursorsCursors
ClassesClasses
MultiMulti--value parameters can be expressed as Python listsvalue parameters can be expressed as Python lists
Ability to convertAbility to convert rastersrasters to and fromto and from NumPyNumPy arraysarrays
ArcPyArcPy is supported by modules, including:is supported by modules, including:
A ma in moduleA ma in module arc .ma inarc .ma in
A Spatial Analyst module (arcpy.sa) to support map algebraA Spatial Analyst module (arcpy.sa) to support map algebra
AA GeostatisticalGeostatistical Analyst module (arcpy.ga)Analyst module (arcpy.ga)
-
7/16/2019 1 Getting Started With Python
11/38
An embedded Interactive Python window withinAn embedded Interactive Python window within ArcGISArcGIS
Can accessCan access ArcPyArcPy, including tools and environments, including tools and environments
Can access an other P thon functionalitCan access an other P thon functionalit
Better code completion and intelligenceBetter code completion and intelligence
The P thon window is for:The P thon window is for:
Testing ideasTesting ideas
Experimenting with and learning PythonExperimenting with and learning Python
Building quick and easy workflows in PythonBuilding quick and easy workflows in Python
-
7/16/2019 1 Getting Started With Python
12/38
Demo:Demo:
A tour ofA tour of ArcPyArcPyandand
-
7/16/2019 1 Getting Started With Python
13/38
Desktop helpDesktop help
Resource CenterResource Center http://resourcesbeta.esri.com/http://resourcesbeta.esri.com/
-
7/16/2019 1 Getting Started With Python
14/38
Tools are accessed as functions onTools are accessed as functions on arcpyarcpy
Environments as properties from arcpy.env classEnvironments as properties from arcpy.env class
# ~~~ PYTHON CODE ~~~
import arcpy
# Set the workspacearcpy.env.workspace = "c:/st_Johns/GISData.gdb"
# Execute Geoprocessing tool
arcpy.Intersect_analysis(["roads","urban_area","urban_roads",
5 " oin"
-
7/16/2019 1 Getting Started With Python
15/38
Script writers set the environment and tools use itScript writers set the environment and tools use it
General settingsGeneral settings
Current Workspace, Output Spatial Reference, ExtentCurrent Workspace, Output Spatial Reference, Extent
Raster analysis settingsRaster analysis settings
Cell Size, MaskCell Size, Mask
arcpy.env.workspacearcpy.env.workspace
arcpy.env.outputCoordinateSystemarcpy.env.outputCoordinateSystem
arcpy.env.extentarcpy.env.extentarc .env.cellSizearc .env.cellSize
arcpy.env.maskarcpy.env.mask
-
7/16/2019 1 Getting Started With Python
16/38
xecu ng a oo w pro uce ypes o messages.xecu ng a oo w pro uce ypes o messages.
Informative messages (severity = 0)Informative messages (severity = 0)
Warning messages (severity = 1)Warning messages (severity = 1) Error messages (severity = 2)Error messages (severity = 2)
# start try block
try:
arcpy.Buffer("c:/ws/roads.shp", "c:/outws/roads10.shp", 10)
,
# print the tool messages
except arcpy.ExecuteError:print arcpy.GetMessages(2)
# Any other error
except Exception as e:
.
-
7/16/2019 1 Getting Started With Python
17/38
Functions perform useful scripting tasksFunctions perform useful scripting tasks
AccessAccess geoprocessinggeoprocessing tool messages (tool messages (GetMessagesGetMessages))
List data to for batch rocessinList data to for batch rocessin ListFeatureClassesListFeatureClasses ListFieldsListFields, nine other List functions), nine other List functions)
Retrieve a datasets properties (Retrieve a datasets properties (DescribeDescribe))
import arcpy
# Set the workspace for ListFeatureClasses function
" ". .
# For each fc, create a scratch name and clipfor fc in arcpy.ListFeatureClasses():
outName = arcpy.CreateScratchName("clipped_" + fc,
"", "featureclass",
arcpy.env.workspace)
" ". _ , ,
-
7/16/2019 1 Getting Started With Python
18/38
Returns an object with dynamic propertiesReturns an object with dynamic properties
Allows script to determine properties of dataAllows script to determine properties of data
, , ,, , ,
Shape type (point, polygon, line, etc)Shape type (point, polygon, line, etc)
Spatial referenceSpatial reference
Extent of featuresExtent of features List of f ieldsList of f ields
Lo ic can be added to a scri t to branch if statementLo ic can be added to a scri t to branch if statement
based data propertiesbased data properties
-
7/16/2019 1 Getting Started With Python
19/38
# Describe a feature class
d = arcpy.Describe("c:/base.gdb/rivers")
# Branch based on the
# in uts Sha eT e ro ert
if d.shapeType == "Polygon":
arcpy.FeatureToLine_management(inFC, outFC)
e se:
arcpy.CopyFeatures_management(inFC, outFC)
-
7/16/2019 1 Getting Started With Python
20/38
Most tool parameters can be easily definedMost tool parameters can be easily defined
Such as a path or buffer distanceSuch as a path or buffer distance
Such as a spatial reference or field mappingSuch as a spatial reference or field mapping
Classes can be used to define parametersClasses can be used to define parameters
prjFile = "c:/North America Equidistant Conic.prj"
Create a s atial reference usin a ro ection file
spatialRef = arcpy.SpatialReference(prjFile)
# Run CreateFeatureclass using the spatial referencearc .CreateFeatureclass mana ement in utWorks ace_
outputName, "POLYLINE", "", "", "", spatialRef)
-
7/16/2019 1 Getting Started With Python
21/38
Cursors allowsCursors allows
Iteration over the set of rows in a tableIteration over the set of rows in a table
Abilit to insert new rows into a tableAbilit to insert new rows into a table
Geometry accessGeometry access
Cursors have three formsCursors have three forms
Search, Insert and UpdateSearch, Insert and Updateimport arcpy
# Print road name and road type
for row in arcpy.SearchCursor("D:/data.gdb/roads"):
print Road name: row.roadname
pr n oa ype: row.ge a ue roa ype
del row
-
7/16/2019 1 Getting Started With Python
22/38
Demo:Demo:
Converting GPS in XMLConverting GPS in XMLto useable Geographic datato useable Geographic data
-
7/16/2019 1 Getting Started With Python
23/38
ArcPyArcPy cursors support iterationcursors support iteration
At 9.3rows = gp.SearchCursor(myTable)
row = rows.next()
while row:
print row.GetValue(Rank)
row = rows.next()
At 10
for row in arcpy.SearchCursor(myTable)print row.GetValue(Rank)
-
7/16/2019 1 Getting Started With Python
24/38
Cursors support creation of new geometriesCursors support creation of new geometries
# Open an insert cursor for the feature class
cur = arcpy.InsertCursor(fc)
# Create array and point objectsptList = [arcpy.Point(358331, 5273193),
arcpy.Point(358337, 5272830)]lineArray = arcpy.Array(ptList)
# Create a new row for the feature classfeat = cur.newRow()
# Set the geometry of the new feature to the
# array of pointsfeat.Shape = lineArray
# Insert the featurecur.insertRow(feat)
# Delete objectsdel cur, feat
-
7/16/2019 1 Getting Started With Python
25/38
Creating Python script toolsCreating Python script tools
-
7/16/2019 1 Getting Started With Python
26/38
-
7/16/2019 1 Getting Started With Python
27/38
-
7/16/2019 1 Getting Started With Python
28/38
-
7/16/2019 1 Getting Started With Python
29/38
Map automation toolsMap automation tools
-
7/16/2019 1 Getting Started With Python
30/38
BREAK!BREAK!
-
7/16/2019 1 Getting Started With Python
31/38
Raster analysis and Map AlgebraRaster analysis and Map Algebra
-
7/16/2019 1 Getting Started With Python
32/38
Returned output from Spatial Analyst toolsReturned output from Spatial Analyst tools
Used to represent a raster dataset on diskUsed to represent a raster dataset on disk
Can be used as in uts to tools and S atial Anal st MaCan be used as in uts to tools and S atial Anal st MaAlgebra expressionsAlgebra expressions
Supports operators (or arithmetic operations in MapSupports operators (or arithmetic operations in Map
Has properties and methods for analysisHas properties and methods for analysis
raster.minraster.min
raster.maxraster.max
raster.saveraster.save()()
-
7/16/2019 1 Getting Started With Python
33/38
-
7/16/2019 1 Getting Started With Python
34/38
Spatial Analyst module that integrates Map Algebra intoSpatial Analyst module that integrates Map Algebra into
PythonPython
Includes all S atial Anal st toolsIncludes all S atial Anal st tools Supports operators in Map Algebra expressionsSupports operators in Map Algebra expressions
Helper classes that can be used to support complex parameterHelper classes that can be used to support complex parameter
--
from arcpy.sa import *
demm = Raster("DEM") / 3.28
slpdeg = Slope(demm, "DEGREE")
= " " " ", , ,
-
7/16/2019 1 Getting Started With Python
35/38
NumPyNumPy is a 3is a 3rr party Python library for scientif ic computingparty Python library for scientif ic computing
A powerful array objectA powerful array object
So histicated anal sis ca abilitiesSo histicated anal sis ca abilities
ArcPyArcPy Raster objects can be converted toRaster objects can be converted to NumPyNumPy arraysarrays
for analysisfor analysis
as er o um y rrayas er o um y rray ,, um y rray o as er um y rray o as er
inras = "ras100"
conver ras er o umnpy array.
rasArray = arcpy.RasterToNumPyArray(inras)
# ARRAY SLICING: et the total sum of ever third value
# from every third row of the raster
sampArray = rasArray[::3,::3]
sum = NUM.sum(sampArray)
pr n sum
-
7/16/2019 1 Getting Started With Python
36/38
Demo:Demo:
Working with Map AlgebraWorking with Map Algebraandand NumPyNumPy
-
7/16/2019 1 Getting Started With Python
37/38
Tool Design and ValidationTool Design and Validation
-
7/16/2019 1 Getting Started With Python
38/38