ArcGIS ModelBuilder provides the user with a simple way to capture geoprocessing instructions as a Python script. This presentation explores the path to promote that script into formal production level code. Beginning with the geoprocessing foundation exported from ModelBuilder, we augment the code to:
• clarify the command line parameters
• organize the directories
• set the SDE workspace
• insert print commands
• check if feature classes exist
• use try / catch blocks to trap errors
• execute operating system commands
• add logging throughout the code
The end result of these additions is production level code that is easy to maintain and deploy. It is particularly well-suited to run automatically as a Windows Scheduled Task.
This session is intended for users who are getting started with Python, or even just thinking about it.
21. PyWin:
PyWin
Python for Windows extensions
by
Mark Hammond
http://sourceforge.net/projects/pywin32/
pywin32-218.win32-py2.7.exe
22. Process Steps:
Delete Features from simple_conduits
Append from SDE into simple_conduits,
just COND_NUM and WATER_TYPE
Delete NO_Zero_Conduits
Select from simple_conduits into N0_Zero_Conduits
Delete dissolved_conduits
Dissolve N0_Zero_Conduits into dissolved_conduits
23. Fix up Process Steps:
• # Process: Append
• arcpy.Append_management(ARG_CONDUIT, simple_conduits, "NO_TEST",
"COND_NUM "COND_NUM" true true false 2 Short 0 0 ,First,#,Database
ConnectionsConnection to
DWGIS3.sdeARG.DistributionSystemARG.CONDUIT,COND_NUM,-1,-
1;WATER_TYPE "WATER_TYPE" true true false 5 Text 0 0 ,First,#,Database
ConnectionsConnection to
DWGIS3.sdeARG.DistributionSystemARG.CONDUIT,WATER_TYPE,-1,-
1;Shape_Length "Shape_Length" false true true 8 Double 0 0 ,First,#", "")
Becomes…
• # Process: Append
• arcpy.Append_management(
• "'Database ConnectionsConnection to DWGIS3.sde
• ARG.DistributionSystemARG.CONDUIT'", simple_conduits,
• "NO_TEST", "COND_NUM "COND_NUM" true true false 2 Short 0 0 ,First,#,Database C
31. Either way, explain:
>>> # There feature classes probably already exist.
>>> # They are left over from the last time we ran this script.
>>> # Deleting the old versions makes room for the new ones.
32. Geek Speak – Try / Catch:
>>> try:
>>> # .. To do something that might blow up
>>> # and it “throws” an Exception
>>> except Exception ex:
>>> print ex
>>>
34. Test Exception:
>>> try:
>>> bogus = 1.0 / 0.0 # forces exception
>>> arcpy.Append_management(ARG_CONDUIT,
>>> except Exception as ex:
>>> print ex
35. Logging:
import logging
logfile = "C:/temp/demo.log"
logging.basicConfig(
level=logging.INFO,
filename=logfile)
logger = logging.getLogger()
logger.info("A swallow beats its wings 43 times every second.")
logger.warning("Go away or I shall taunt you a second time.")
logger.error("Run away! Run away!")
print "Done."
36. C:tempdemo.log:
INFO:A swallow beats its wings 43 times every second.
WARNING:Go away or I shall taunt you a second time.
ERROR:Run away! Run away!
37. Logging:
logging.info(" checking for " + HYDRANT_BRANCH )
if arcpy.Exists(HYDRANT_BRANCH ):
try:
arcpy.Append_management(APPEND_HYD_BR, hyd_branch, ...)
logging.info(" HYDRANT_BRANCH_shp appended to SDE")
except Exception as ex:
logging.error(" HYDRANT_BRANCH_shp append FAILED")
logging.Exeception(ex)
38. Recap – Do These 3 Things…
1. Organize variable names
2. Trap Errors
3. Write a log file
"First shalt thou take out the Holy Pin.
Then shalt thou count to three, no more, no less.
Three shall be the number thou shalt count, and the
number of the counting shall be three.”
39. Pythonic:
• Explicit is better than implicit.
• Simple is better than complex.
• Readability counts.
The Zen of Python, by Tim Peters,
includes:
40. Geek Speak - Blocks:
>>> if arcpy.Exists(simple_conduits):
>>>
arcpy.DeleteFeatures_management(simple_conduits)
>>> # maybe do something else
>>> # some additional processing
>>> else:
>>> print "Missing feature class -> " + simple_conduits
41. Duck Typing:
If it looks like a duck, quacks like a duck, etc.
Works with strings,
integers,
floating point,
lists,
etc.
42. Strings:
Enclosed in either ‘single’ or “double” quotes.
Concatenate using + sign.
>>> topic = "GIS"
>>> location = "Rockies“
>>> event = topic + " in the " + location
>>> print event
GIS in the Rockies
43. Strings:
More built-in functions:
>>> event = "GIS in the Rockies"
>>> print event.lower()
>>> print event.upper()
>>> print event.title()
>>> string_length = len(event)
>>> print string_length
>>> print event.find("Rockies",0,string_length)
gis in the rockies
GIS IN THE ROCKIES
Gis In The Rockies
18
11
44. Triple quotes can span multiple
lines:
“””The Dead Collector: Bring out yer dead.
Large Man: Here's one.
The Dead Collector: That'll be ninepence.
The Dead Body: I'm not dead.
The Dead Collector: 'Ere, he says he's not dead.
Large Man: Yes he is.
The Dead Body: I'm not.
The Dead Collector: He isn't.
Large Man: Well, he will be soon, he's very ill.
The Dead Body: I'm getting better. “””
46. For loop:
>>> for funny_bit sketch in python_sketch:
>>> print funny_bit + ' hahaha‘
Dead Parrot hahaha
Confuse-a-Cat hahaha
Silly Walks hahaha
Four Yorkshiremen hahaha
Fish Slap hahaha
Limberjack Song hahaha
47. Command Line Args:
>>> userid = arcpy.GetParameterAsText(0)
>>> if not userid:
>>> print ‘Usage: python.exe my_script.py userid password ‘
>>> pword = arcpy.GetParameterAsText(1)
>>> if not pword:
>>> print ‘Usage: python.exe my_script.py userid password ‘
48. Command Line Args:
C:> D:python27python.exe my_script.py zeke password
Python.exe is located on D:python27
my_script.py is some python code
Userid is zeke
My Oracle password is at the end