Upload
doanduong
View
236
Download
5
Embed Size (px)
Citation preview
Today’s Agenda
This seminar is designed to help you understand:
1) Python and how it can be used
2) What’s new in Python in ArcGIS 10.1
3) How to develop Add-ins for ArcGIS Desktop with Python
Python (The Essentials)
Why Python
Fulfills the needs of our user community
• Simple and easy to learn
• Scalable
• Modular
• Object Oriented
• Easy to maintain
• Cross platform
• Established and active user community
What is ArcPy?
ArcPy is a native Python site-package
• Includes code completion and intellisense
• Provides direct access to many ArcGIS modules
• Data access (new)
• Mapping (updated)
• Extensions - Spatial Analyst (updated)
• Network Analyst (new)
• Time (new)
Functions
The ArcPy module contains functions that are necessary for performing scripting tasks
• Listing data
• Describing data
• Geodatabase management
• Validating table and field names
• Analyzing & Updating data
• Map production
These functions allow users to automate manual tasks
Basics of Scripting
Where do I write Python code?
Python Window (ArcGIS), PyScripter & PyWin, text editors etc.
Simple python excerpt:
# The import statement imports the arcpy site package import arcpy # Variables are assigned using an ‘=‘ featureclass = r“d:\data\roads.gdb\highways” # Geoprocessing tools can be run using two methods
arcpy.management.GetCount(featureclass) # Using the management toolbox arcpy.Getcount_management(featureclass) # Using the arcpy toolbox
Basics of Scripting (2)
Proper Syntax
• Colons should be placed at the end of statements and conditions
• Indentations determine what is executed
• Operators (==, >, <, !=)
• Loops (for, while, list)
# A simple if , else statement var = “a” if var == “a”: # Execute the indented lines print (“variable is a”) else: print (“variable is not a”)
# while loop x = 1 while x <5: print (x) x = x+1 # for loop x =[1,2,3,4] for num in x: print (num)
Basics of Scripting (3)
Case sensitivity
• Variables and functions etc. are all case sensitive
• Common error: name ‘x’ is not defined
Specifying file paths
• Using forward-slashes: “d:/data/roads.gdb/highways”
• Using back-slashes: r“d:\data\roads.gdb\highways”
Functions & modules
• A module is where the function is located
• A function is used to perform a specific task
arcpy.mapping.PDFDocumentCreate(r“d:\maps\canada.pdf”)
Demonstration I
• Python window
• Importing ArcPy
• Running a geoprocessing task using Python
What’s new in Python in
ArcGIS 10.1
Have a number of advantages over custom toolboxes
• Tools that work just like core geoprocessing tools
• Messages can be written to the results window
• A single place to edit parameter definitions, validation code, and source code)
• Implement licensing checks
• Create Value Table parameters
• Create composite data type
• i.e. A parameter than can accept a
feature layer or a raster layer
Python Toolboxes
Data Access Module
Data Access Cursors (e.g. arcpy.da.SearchCursor)
• Much faster than traditional cursors (e.g. arcpy.SearchCursor)
• Support ‘with’ statements
• No need to access the full geometry
# Import arcpy reference library import arcpy # Print the tower id, type, and the feature’s locations (lat, long) fields = [“TOWER_ID”, “TOWER_TYPE”, “SHAPE@XY”] with arcpy.da.SearchCursor (r”c:\data\utilities.gdb\towers”, fields) as cursor: for row in cursor: print (“{0},{1},{2}”.format(row[0], row[1], row[2]))
Accessing Geometry
The geometry of features can be accessed using a new “shape@” token
• Traditionally geometries slowed down the cursor since they could not be individually returned
• ‘shape@area’ , ‘shape@length’, ‘shape@xy’, ‘shape@m’, ‘shape@z’, ‘shape@trueCentroid’
# Import arcpy reference library import arcpy # Calculate the sum (length) of all the ferry lines in Canada with arcpy.da.SearchCursor(r“c:\data\transportation.gdb\ferry","shape@length") as rows: print sum([row[0]for row in rows])
Writing Feature Geometry
Insert cursors must be used to create new features
• Point and Array objects are used to create the feature parts
Update cursors can be used to replace a row’s existing geometry
# Add a new ferry line to the ferry feature class using an InsertCursor with arcpy.da.InsertCursor(r“c:\data\transportation.gdb\ferry","shape@") as ferrycursor: # Create an array using a series of point objects ptList = [arcpy.Point(-9090915.5, 5662586.6), arcpy.Point(-8916290.1, 5674228.3)] lineArray = arcpy.Array(ptList) # Create a stream polyline from the array polyline = arcpy.Polyline (lineArray) # Insert stream polyline into the dataset ferrycursor.insertRow([polyline])
Editor Class
Allows use of edit sessions and operations to manage database transactions
• Similar to editing with the GUI (Editor Toolbar)
• Edits are temporary until saved and applied to the session
fc = r“Database Connections\Brampton.sde\brampton.jgp.schools“ workspace = os.path.dirname(fc) #Start an edit session – since editing is usually tied to a specific database this variable must be provided. edit = arcpy.da.Editor(workspace) #Edit session is started without undo/redo stack for versioned data. The second arg. states whether the data is versioned. edit.startEditing(False, False) #Insert a row into the school table with arcpy.da.InsertCursor(fc, (’NAME’, ‘SHAPE@’)) as schoolcursor: schoolcursor.InsertRow([‘School of Hard Rock’, (45.5151, -79.85858)]) # Stop the edit session and commit the changes to the table edit.stopEditing(True)
Demonstration II
• Creating a python toolbox
• Using the data access module to query data
Python Add-ins
What is an Add-in?
An add-in is a customization such as a collection of tools that plugs into ArcGIS Desktop
• Introduced at 10.0 to make it easier for users to extend ArcGIS
• Can be authored using .NET Language & JAVA (ArcGIS 10.0)
• ArcGIS 10.1 introduces python to the list of supported languages
Python Add-in Wizard
Introduced to streamline the add-in creation process
• Download available from the ArcGIS Resources Center http://bit.ly/pythonwizard
• Specify what product it’s for
• Project properties can be defined easily within the wizard
• Creates all of the directories and files required for the add-in to work
• Button – Simple click to execute
• Tool – Requires user interaction
• Combo Box – Provide a set of choices
• Menu – Container for buttons or other menus
• Toolbar – Container for every add-in type
• Tool Palette – Container of tools
• Application Extension
• Coordinates activities between other components – i.e. If an extension is not enabled then the related series of tools will not be enabled
Types of Python Add-ins
File Structure
• Images – contains graphics used in the add-in
• Install – holds the python script where the custom behaviour is stored
• Config – describes the add-in
• Makeaddin.py – utility used to package the files into an add-in
Testing / Debugging Add-ins
• It is important to fully test an add-in before it is shared
• Steps to conducting a successful test
• Make the add-in file (run the makeaddin.py)
• Install the add-in (double click the new add-in file created)
• Use the add-in
• In some cases you may not be able to see the custom add-in
• Ensure its been installed (Customize >> Add-in Manager)
• Debugging Tips and Tricks
• Use print statements
• If tools do not load in correctly (i.e. missing on the toolbar) check your python syntax
Demonstration III
• Creating a python add-in
Summary
In this seminar you were introduced to:
1) Python scripting basics
2) New scripting functionality available in ArcGIS 10.1
3) Developing python add-ins
Resources
• Using Python Help
• http://resources.arcgis.com/en/communities/python/
ArcGIS Python Recipes
• http://arcpy.wordpress.com/
• Related Training Courses
• Introduction to Geoprocessing Scripts Using Python
• Follow us:
twitter.com/EsriCanada facebook.com/EsriCanada