Sunteți pe pagina 1din 25

Python in ArcGIS

LESSON 11

Why learning Python in ArcGIS?


Sometimes you need Python to build extra
intelligence into your geoprocessing, ex.
Conditional Logic
User Input Processing

Programming is similar to playing sports

Python Fundamental

Lists
a type that can store multiple related values together.
Example:
>>>suits = ['Spades', 'Clubs', 'Diamonds', 'Hearts']

you're allowed to put multiple data types into one list.


Example:
>>>values = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']

each item in the list still has an index


>>>print suits[0] Spades
>>>print values[12] King

Lists
Sorting
>>> suits = ['Spades', 'Clubs', 'Diamonds', 'Hearts']
>>> suits.sort()
>>> print suits ['Clubs', 'Diamonds', 'Hearts', 'Spades']

Insert and combine items


>>> listOne = [101,102,103]
>>> listTwo = [104,105,106]
>>> listThree = listOne + listTwo
>>> print listThree [101, 102, 103, 104, 105, 106]
>>> listThree += [107]
>>> print listThree [101, 102, 103, 104, 105, 106, 107]
>>> listThree.append(108)
>>> print listThree [101, 102, 103, 104, 105, 106, 107, 108]

Lists
>>> listThree += [107]
>>> print listThree [101, 102, 103, 104, 105, 106, 107]
>>> listThree.append(108)
>>> print listThree [101, 102, 103, 104, 105, 106, 107, 108]
>>> listThree.insert(4, 999)
>>> print listThree [101, 102, 103, 104, 999, 105, 106, 107, 108]

Length of a list
>>> myList = [4,9,12,3,56,133,27,3]
>>> print len(myList) 8

Loops
A loop is a section of code that repeats an action.

For Loops
>>> for name in ["Carter", "Reagan", "Bush"]:
print name + " was a U.S. president.
Carter was a U.S. president
Reagan was a U.S. president
Bush was a U.S. president

>>> x = 2
>>> multipliers = [1,2,3,4]
>>> for num in multipliers: print x * num
2
4
6
8

For Loops
multiply 2 by every number from 1 to 1000
>>> x = 2
>>> for num in range(1,1001):
print x * num

multiply 2 by every number from 1 to 1000


>>> x = 2
>>> for num in range(1001):
print x * num

While Loops
A while loop executes until some condition is met.
Example:
>>> x = 0
>>> while x < 1001:
print x * 2
x += 1

Nesting Loops
Some situations call for putting one loop inside another, a practice called nesting.
Example:
>>> suits = ['Spades', 'Clubs', 'Diamonds', 'Hearts']
>>> values = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']
>>> for suit in suits:
for value in values:
print str(value) + " of " + str(suit)

Looping in GIS models


arcpy has some methods that can help you create lists
Example1: arcpy.ListFeatureClasses()
First, manually create a new folder C:\Lesson11\PracticeData. Then copy the code below into a new script in
PythonWin and run the script. The script copies all the data in your Lesson9 folder into the new Lesson11\PracticeData
folder you just created.
# Copies all feature classes from one folder to another
import arcpy
try:
arcpy.env.workspace = "C:/Lesson09"
# List the feature classes in the Lesson 09 folder
fcList = arcpy.ListFeatureClasses()
# Loop through the list and copy the feature classes to the Lesson 11 PracticeData folder
for featureClass in fcList:
arcpy.CopyFeatures_management(featureClass, "C:/Lesson11/PracticeData/" + featureClass)
except:
print "Script failed to complete"
print arcpy.GetMessages(2)

Looping in GIS models


Example2: Looping through table.
import arcpy
inTable = "C:/Lesson11/CityBoundaries.shp"
inField = "NAME"
rows = arcpy.SearchCursor(inTable)
#This loop goes through each row in the table
# and gets a requested field value
for row in rows:
currentCity = row.getValue(inField)
print currentCity

Decision Structures

Decision Structures
Example:
>>> x = 3
>>> if x > 2:
print "Greater than two
Greater than two
>>>x = 2
>>> if x > 2:
print "Greater than two"
elif x == 2:
print "Equal to two
else:
print "Less than two"
Equal to two

Decision Structures
Example: picks a random school from a list
import random
# Choose a random school from a list and print it
schools = ["Penn State", "Michigan", "Ohio State", "Indiana"]
randomSchoolIndex = random.randrange(0,4)
chosenSchool = schools[randomSchoolIndex]
print chosenSchool
# Depending on the school, print the mascot
if chosenSchool == "Penn State":
print "You're a Nittany Lion"
elif chosenSchool == "Michigan":
print "You're a Wolverine"
elif chosenSchool == "Ohio State":
print "You're a Buckeye"
elif chosenSchool == "Indiana":
print "You're a Hoosier"
else:
print "This program has an error"

String Manipulation
When using Python with ArcGIS, strings can be useful for storing paths to data
and printing messages to the user.
There are also some geoprocessing tool parameters that you'll need to supply
with strings.

Concatenating Strings
You may need to concatenate strings when working with path names
Example:
# This script clips all datasets in a folder
import arcpy

inFolder = "c:\\data\\inputShapefiles\\"
resultsFolder = "c:\\data\\results\\"
clipFeature = "c:\\data\\states\\Nebraska.shp"
# List feature classes
arcpy.env.workspace = inFolder
featureClassList = arcpy.ListFeatureClasses()
# Loop through each feature class and clip
for featureClass in featureClassList:
# Make the output path by concatenating strings
outputPath = resultsFolder + featureClass
# Clip the feature class
arcpy.Clip_analysis(featureClass, clipFeature, outputPath)

Casting to a String
Casting is a way of forcing your program to think of a variable as a different type.
Example:
x=0
while x < 10:
print x
x += 1
print "You ran the loop " + x + " times."

x=0
while x < 10:
print x
x += 1
print "You ran the loop " + str(x) + " times."

Potential Problems and Quick Diagnosis


Run early, run often, and don't be afraid of things going wrong when you run your code the first
time.
Debugging, or finding mistakes in code, is a part of life for programmers.
Here are some things that can happen:

Your code doesn't run at all, usually because of a syntax error (you typed some illegal Python code).
Your code runs, but the script doesn't complete and reports an error.
Your code runs, but the script never completes. Often this occurs when you've created an infinite loop.
Your code runs and the script completes, but it doesn't give you the expected result. This is called a
logical error and it is often the type of error that takes the most effort to debug.

Using the PythonWin Debugger


Example
# This script calculates the factorial of a given
# integer, which is the product of the integer and
# all positive integers below it.
number = 5
multiplier = 1
while multiplier < number:
number *= multiplier
multiplier += 1
print number

Printing messages from the Esri


geoprocessing framework
try:
...
except:
print arcpy.GetMessages()
three levels of severity: Message, Warning, and Error.
You can pass an index to the arcpy.GetMessages() method to filter through only the messages that reach a
certain level of severity.
For example, arcpy.GetMessages(2) would return only the messages with a severity of "Error.

Details: http://resources.arcgis.com/en/help/main/10.2/index.html#//002z0000000p000000

S-ar putea să vă placă și