Filed under Python

Upcoming Class Schedule

Schedule of Internet Based, Instructor Guided Classes

Programming ArcObjects with .NET for ArcGIS 10.1
November 26th – December 21st

ArcGIS Server Bootcamp for New Developers
November 5th – December 14th

Design and Build GIS Web Sites Like a Pro
November 5th – November 21st

Python ArcGIS Programming Bootcamp
January 7th – February 8th

Building Custom ArcGIS Server Applications with JavaScript
January 14th – February 22nd

Building Mobile ArcGIS Server Applications
January 14th – February 22nd

ArcGIS Server Bootcamp
January 7th – February 15th

Open Source GIS Bootcamp
OpenLayers + GeoServer + PostGIS
January 2013

HTML5 and CSS3 for GIS Web Developers
November 5th – 16th

Schedule of Traditional Instructor Led Courses

ArcGIS Server Bootcamp for New Developers
Atlanta – November 5th-9th

ArcGIS Desktop 3: Analysis and  Workflows
Atlanta – November 8th-9th

GIS Programming 101 for ArcGIS 10
November 29th-30th
Austin, TX

Python ArcGIS Programming Bootcamp
January 28th-30th
Seattle, WA

Programming ArcObjects with .NET for ArcGIS 10.1
February 25th-26th
Seattle, WA

Faster Way to Check for and Delete GIS Data with Python

This is a guest post from Ann Stark (Twitter @StarkAnn) at The GIS Studio Blog.  Ann has put together some really nice posts on the subject of using Python with ArcGIS Desktop.  Check out her blog!

In repeated automated tasks, I often have to delete a set of data I am about to recreate fresh. ArcPy offers a delete function, but the faster way to delete is through the os module.

In this example, I have a folder of shapefiles that I overwrite every time I run the script.   The first step in my script is to make a list of existing shapefiles in the folder and then step through the list deleting them.  Ideally we would just use the arcpy.env.overwrite = True setting, however this does not work with the FCtoShapefile command. Using the ArcPy tools, this deleting process can be pretty slow. Using the os tools, we speed things up significantly.
There are a few checks that help keep errors at bay – the first being a check for the existence of your data folder.  Since the list I generate is of every file in the folder, the second check is to make sure there are not folders in my list of things to delete.  I only want to delete pieces of shapefiles.  Since this folder is only used for shapefile output I’m taking the chance that those are the only types of files in here.  Otherwise I’d be more careful to check for the .shp, .shx. .dbf file extensions.  In the event the shapefile folder has been deleted entirely, the last error check is to create the folder if it doesn’t exist at all.
Here’s the sample:

Want to learn more about using Python with ArcGIS 10 and ArcGIS 10.1?  We have a number of instructor led and self paced training opportunities.

Python ArcGIS Programming Bootcamp
Next Session: July 9th – August 10th

GIS Programming 101 for ArcGIS 10

GIS Programming 201 for ArcGIS 10

ArcGIS Programming with Python Bundle

15 Python and ArcGIS Posts (and 1 Free Lecture) from GeoChalkboard

Through the years we’ve posted a number of informative, how-to style articles related to using Python with ArcGIS Desktop to automate your geoprocessing tasks.  To make it easier for you to find articles of interest I’ve compiled a list of these posts.

Want to learn more about using Python with ArcGIS 10 and ArcGIS 10.1?  We have a number of instructor led and self paced training opportunities.

Python ArcGIS Programming Bootcamp
Next Session: July 9th – August 10th

GIS Programming 101 for ArcGIS 10

GIS Programming 201 for ArcGIS 10

ArcGIS Programming with Python Bundle

 

Checklist for Updating Python Scripts from ArcGIS 9.3 to ArcGIS 10

This is a guest post from Ann Stark (Twitter @StarkAnn) at The GIS Studio Blog.  Ann has put together some really nice posts on the subject of using Python with ArcGIS Desktop.  Check out her blog!

Over the years I have had amassed a collection of  python scripts written in previous versions of ArcMap.  They all start out with the import arcgisscripting command and are full of  gp statements.  And they are still useful scripts, so I have spent some time upgrading them to the new ArcPy site-package for ArcMap version 10. (What is ArcPy?) (More here)

I developed a checklist to help me remember where to look for switching things up and thought I’d share it with others that might have the same task ahead of them. Here’s the checklist.

1. Replace the import statement and remove the geoprocessing creation statement. In other words, remove this

import arcgisscripting
gp = arcgisscripting()

and replace it with

import arcpy

Also in this step I remove any add toolboxes statements that I might have included.  No need to specify any toolboxes in v10!

2. Replace all gp. with arcpy.
I do this with a find/replace command in my code editor. For example

gp.exists(myGDB)

now becomes

arcpy.Exists(myGDB)

3. Check your capitalization.
Previous versions of arcgisscripting allowed for sloppy capitalization.  Now it has to be exact and this can be a real pain to find all the mismatched cases. gp.addmessage worked before but now it has to be arcpy.AddMessage.  And note the capital “Exists” in the example above.  Now that I’ve been working with arcpy a bit I find my eye is trained, however in the beginning this was a common bug to find in my scripts and repair.

4. The result tool is different.
Results were pretty straightforward up until ArcMap 9.3.  At that point they became a little more tricky.

Now, many geoprocessing tools return a result object of the derived output dataset. A print statement will display the string representation of the output.

>>result = arcpy.GetCount_management(“myLayer”)
>>result
<Result ’879′>
>>print result
879

The result object’s getOutput method returns values as a unicode string. To convert to a different Python type, use  built-in Python functions: str(), int(), long(), float().

>>resultValue = result.getOutput(0)
>>resultValue
u’879′
>>count = int(resultValue)
>>print count
879

In your code you can smash it all together to look like this and save a few lines.  Although this makes your code less readable by other novice users that might need or want to modify the script.

>>ItemCount = int(arcpy.GetCount_management(“myLayer”).getOutput(0))
>>ItemCount
879

5. Replace any del gp statements.
I had been taught to always delete the gp module any time you ended the script either at the very end or in an try/except statement.  I was told that it cleaned up any memory usage.  I don’t know how true it is, but what can it hurt, right?   So my scripts are littered with

del gp

statements.  Now, if you’ve never created the geoprocessor in the first place (see step 1), these are little bombs waiting to go off when your script runs into them.  You can’t delete what doesn’t exist.  Be sure to find them all and replace them with a

del arcpy

6. The overwrite tool is different.
You’ll need to find and update all uses of it that you might have. Previously you had something like this:

gp.overwrite = 1

where 1 is true and 0 is false.  Now you can do something like:

arcpy.env.overwriteOutput = True

or even

from arcpy import env
env.overwriteOutput = True

7.  Import the env module from arcpy.
This isn’t a requirement, however I tend to use the environment settings fairly often in my scripts so implicitly importing the env module saves a bit of typing. In the example above you can use the shorter env.overwriteOutput = true statement.  Additionally, another common one that I use is the workspace setting. By importing the env module you can then use a short

env.workspace = ‘c:/my/path’

statement.  If you go this route be sure to remember to put

from arcpy import env

up near the top of your scripts with the other import statements in order for these shorter statements to work.

That’s it! At least for now.  If I find I run into some more common things to remember I’ll update this posting. And please let me know if you have run into any tips while updating your scripts in the comments below.

Want to learn more about using Python with ArcGIS 10 and ArcGIS 10.1?  We have a number of instructor led and self paced training opportunities.

Python ArcGIS Programming Bootcamp
Next Session: July 9th – August 10th

GIS Programming 101 for ArcGIS 10

GIS Programming 201 for ArcGIS 10

ArcGIS Programming with Python Bundle

 

Creating Add-Ins with Python at ArcGIS 10.1

Add-ins provide an easy way to distribute user interface customizations to end users.  No installation programs are necessary.  A single compressed file with a file extension of .esriaddin is copied to a well-known folder and ArcGIS Desktop handles the rest.  To simplify development even further an Add-In Wizard has been provided by ESRI.  You can download the wizard from the ESRI website.

The Python Add-In wizard, which you can download at the link provided above, is a great resource for creating the necessary files for an add-in.  It generates the required files for the add-ins from a visual interface.  After downloading and unzipping the file from the ESRI website you’ll want to double click addin_assistant.exe in the addin_assistant/bin directory  to run the wizard.

The add-in file structure is really quite simple.  Two folders and a set of files comprise the add-in structure.  The images folder contains any icons or other image files used by your add-in.  The Install folder contains the Python script that handles the business logic of the add-in.  This is the file you’ll work with extensively to code the add-in. It performs whatever business logic needs to be performed by the buttons, tools, menu items, etc.  The config.xml file defines the user interface and any static properties such as the name, author, version, etc.  The makeaddin.py file can be double clicked to create the .esriaddin file which wraps everything into a compressed file with an .esriaddin extension.  This .esriaddin file is what will be distributed to end users.

There are a number of add-in types that can be created.  The simplest type of add-ins are buttons and tools.  Buttons simply execute business logic when clicked.  Tools are similar to buttons but require interaction with the map before the business logic is executed.  Combo boxes provide a list of choices for the user to select from.  There are also a number of container objects including menus, toolbars, and tool palettes.  Menus act as a container for buttons or other menus.  Toolbars are a container for buttons, tools, combo boxes, tool palettes, and menus.  They are the most versatile of the add-in container types.  Finally, tool palettes act as a container for tools.  Tool palettes need to be added to a toolbar before the tools will be exposed.  Finally, application extensions are the most complex add-in type.  This type of add in coordinates activities between other components and is responsible for listening for and responding to various events such as the addition or removal of a layer from a data frame.

Creating Add-Ins
Creating an add-in project is the first step in the creation of a new add-in.  To create a project open the ArcGIS Python Add-In Wizard and select a working directory and then enter the various project settings.  Finally, click the Save button, but don’t close the wizard.  You still need to follow specific steps for creating the particular add-in you’d like to deploy.

The creation of an add-in follows a well defined process which is described on this slide.  You must first create a container for the add-in and this will be either a toolbar or a menu.  Next, create the button, tool, or other add-in you want to add to the container.  In this case we’ll just assume it’s a button.  Next, you need to edit the Python script associated with the button.  You’ll also want to test the button to make sure it works as expected.  Finally, you can share the add-in with others.

The first step is to create a container for your add-in.  This is easily accomplished through the Python Add-In Wizard.  Go to the Add-In Contents tab and right click the Toolbars Item.  Select New Toolbar.

After the container Toolbar has been created you can then create the button or other type of add-in.  In this case we’ll assume you’re creating a button.  Right click the new Toolbar and select New Button.  Then, fill in the button details which will be saved to the config.xml file.  Click Save to save this information to config.xml.

Add-ins have a Python script that they are attached to.  This file, by default, will be named AddIns_addin.py and can be found in the install directory of your working project folder.  Inside the script you’ll want to locate the ‘onClick’ event.  You’ll need to alter this function as needed to handle what happens when the button is clicked.

You’ll want to always test add-ins before distributing them to your end users.  To test you first need to install the add-in.  In the working folder for your add-in run the makeaddin.py script by double clicking it.

This copies all files and folders to a compressed add-in folder in a working directory with the file format: <working folder name>.esriaddin.  Double click this .esriaddin file to launch the ESRI ArcGIS Add-In Installation Utility which will install your add-in.  You can then go into ArcGIS Desktop and test your add in. The custom toolbar or menu may already be visible and ready to test. If it is not visible, go to the Customize menu and click Add-in Manager. The Add-In Manager dialog box lists the installed add-ins that are targeting the current application. Add-in information, such as name, description, and image, entered as project settings should be displayed.

If the add-in is listed in the manager, click the Customize button to open the Customize dialog box. To add a toolbar to the application, click the Toolbars tab and choose the toolbar you created. To add a menu to the application, click the Commands tab and scroll down the list of categories to [ MENUS ] and find your custom menu. Drag the menu onto an existing menu or toolbar. If the add-in is an extension, be sure it is enabled. Open the Extensions dialog box and check it to enable it.

Want to learn more about using Python with ArcGIS 10 and ArcGIS 10.1?  We have a number of instructor led and self paced training opportunities.

Python ArcGIS Programming Bootcamp
Next Session: July 9th – August 10th

GIS Programming 101 for ArcGIS 10

GIS Programming 201 for ArcGIS 10

ArcGIS Programming with Python Bundle

 

 

 

 

 

 

 

 

 

 

GIS Programming 201 for ArcGIS 10 Coming Soon (ArcGIS 10.1 Materials Included)

On May 15th, 2012 our new self-paced, GIS Programming 201 for ArcGIS 10: Mastering Python course will be released.  For a limited time you can pre-purchase this course at the discounted rate of $109.00.  The regular price for this course will be $129 when released on May 15th.

All new and updated for ArcGIS Desktop 10.1.  This course builds on the introductory topics you learned in our GIS Programming 101 for ArcGIS 10 course. You will learn more advanced topics in this course including how to select, insert, update, and delete data from tables and feature classes using the new Arcpy Data Access Module (ArcGIS 10.1), develop add-ins for ArcGIS Desktop (ArcGIS 10.1), administer ArcSDE geodatabases (ArcGIS 10.1), create graphs, use custom and remote ArcGIS Server toolboxes, mosaic datasets and publish image services, learn raster analysis with the Arcpy Spatial Analyst module, and more.

Course participants will be led through a series of 8 modules described below.

Bundle this course with our GIS Programming 101 for ArcGIS 10 and save!

Intended Audience
This course is intended to be taken after our GIS Programming 101 for ArcGIS 10 course.

Modules
Module 1: The Arcpy Data Access Module
Module 2: Developing Add-Ins for ArcGIS Desktop with Python
Module 3: Using and Administering ArcSDE Geodatabaeses with Python
Module 4: Creating Graphs with ArcPy
Module 5: Using Custom and Remote Toolboxes
Module 6: Advanced Topics: Mapping Input Fields to Output Fields, MultiValue Inputs, FeatuerSet and RecordSet
Module 7: Creating Mosaic Datasets and Publishing Image Services
Module 8: Beginning Raster Analysis with the Arcpy Spatial Analyst Module

File Handling with Python for GIS Programmers

File handling with Python is a very important topic for GIS programmers.  Text files have long been used as an interchange format for exchanging data between systems.  They are simple, cross-platform, and easy to process.  Comma and tab delimited text files are among the most commonly used formats for text files so we’ll take a look at some of the Python tools available for processing these files.  A common task for GIS programmers is to read comma delimited text files containing x,y coordinates along with other attribute information.  This information is then converted into GIS data formats such as shapefiles or geodatabases.

To use Python’s built in file processing function you must first open the file.  Once open, data within the file is processed using functions provided by Python, and finally the file is closed.  Always remember to close the file when you’re done.   So, the process is as follows:

 

 

 

 

 

 

 

 

 

Opening Files
In Python the ‘open()’ function accepts a path to the file that you’d like to open along with a mode in which the file will be opened.  The most commonly used modes are read, write, and append.  This function creates a new File object which can then be iterated to extract or write information.

 

 

 

 

 

Python’s open function creates a file object which serves as a link to a file residing on your computer.  You must call the open function on a file before reading and/or writing data to a file.  The first parameter for the open function is a path to the file you’d like to open.  The second parameter of the open function corresponds to a mode which is typically read (‘r’), write (‘w’), or append (‘a’).  A value of ‘r’ indicates that you’d like to open the file for read only operations, while a value of ‘w’ indicates you’d like to open the file for write operations.  In the event that you open a file that already exists for write operations this will overwrite any data currently in the file so you must be careful with write mode.  Append mode (‘a’) will open a file for write operations, but instead of overwriting any existing data it will append data to the end of the file.

Below you will find a list of all the available file modes.  As I mentioned in a previous slide the most commonly used are read, write, and append.  However, you can also add the “+” to each of the modes to enable read/write capability.  The contents of a file can be preserved or deleted depending upon the combination that you use.  For example, w+ will open a file for read/write but the contents of the file are deleted while r+ preserves the contents of the file.  Adding a ‘b’ to r, w, or a will open a file in Binary mode.  Finally, the universal or ‘U’ character applies a universal newline translator.

 

 

 

 

 

 

 

 

 

 

 

Universal file mode is an exceptionally useful tool for creating consistency in newline characters.  Applications use different characters to indicate a newline and they aren’t consistent between applications.  Newline characters might include /r, /n, or /r/n.  The universal mode will automatically convert all newline characters to \n.  Python scripts that open files from various sources should use this mode in conjunction with ‘r’,’w’, or ‘a’ to gracefully handle the different possible newline characters.

Reading Data from Files
After a file is open, data can be read from a file in a number of ways and through various methods.  The most typical scenario would be to read data one line at a time from a file through the readline() method (see below).  Readline can be used to read the files one line at a time into a string variable.  You would need to create a looping mechanism in your Python code to read the entire file line by line.  We’ll do just that in a code example later in this article.

 

 

 

If you would prefer to read the entire file into a variable you can use the read() method which will read the file up to EOF marker.   The contents of the file are read into a string variable. You can also use the readlines() method to read the entire contents of a file, separating each line into individual strings , until the EOF is found.  This method reads the file into a list variable where each line occupies an unique index in the list.

 

 

 

 

 

In the case of really large files that might consume all the available memory on the computer running the script the preferred method is to us File.read() with a set number of bytes.  The file would be read from beginning to end in this manner until the ‘read()’ method encounters the EOF character.

Handling Delimited Files
There are several ways that you can process delimited data files in Python.  In this section we’re going to examine the use of the ‘split()’ function for processing these types of files.  The ‘split()’ function, which creates a list from a string based on a delimiter, first requires that you open a file and either read the entire contents of the file into a variable or process the file one line at a time.  This function accepts a delimiter as the argument.  By default, if you leave the parameter empty, it will split a string based on spaces.  In the code example in this section we’re showing you a common scenario wherein we’re working with a comma delimited text file like the one you see below.

 

 

 

 

 

 

 

We call the ‘split()’ function, passing in a comma.  A list is created by this function containing each item as a unique value in the list.  The items are divided by a comma.  In this case we are only interested in retrieving the latitude, longitude, and confidence values from the delimited text file.  By accessing the correct index number we can access each of these individual items.  Notice that all of this is being done inside a ‘for loop’ so the split() function is performed once for each line in the file and the individual items are pulled out.  Presumably we’d do something additional with this data such as creating a new feature class in ArcGIS containing these individual points.

 

 

 

 

 

 

 

Close the file

After you’ve completed your read/write operations from a file you should always close the file by using the close( ) method.

Related Courses from GeoSpatial Training Services

 

 

 

 

GIS Salary Survey Results

We’re keeping the survey open through July 31st.  If you haven’t already participated in the survey please take a few moments to do so and forward this to your colleagues.

To date we have had 731 respondents.  Here are some of the highlights:

  • 40% of respondents list their job titles as either GIS Analyst or GIS Technician.  16% are GIS Managers/Coordinators/Directors, and 6% GIS Developers/Programmers.
  • 40% of respondents have 10 years of experience or greater.
  • 43% have a Master’s degree or higher.  Should You Get a Master’s Degree in GIS?
  • 70% of respondents are male.  I suppose this is better than it was 10 years ago, but we really need to attract more women to the field.
  • 41% of you are between the ages of 30-39.  24%  are between the ages of 40-49.  Less than 2% are above the age of 60.
  • Salaries appear to be widely dispersed with 29% between $50,000-$70,000/year.  I was surprised to see almost 13% below $20,000/year.
  • ESRI is far and away the most popular platform with 93% of respondents indicating this as one of their primary platforms.  This question allows more than one platform to be selected.  Open Source GIS software came in second at 14%.  I suspect this will grow quite a bit in the coming years.
  • Primary programming languages in use include .NET (55%), Python (50%) , JavaScript (27%), Java (20%), and Flex (17%).  You can learn more about Python, JavaScript, and Flex through our training classes.

You can get all the results here.

Spring Training Schedule from GeoSpatial Training Services

Our Spring 2011 training schedule has been released.  Most of these courses are taught in a web based environment but we do have one traditional face to face session of GIS Programming 101 for ArcGIS 10 scheduled for the King County GIS Center in Seattle, WA.  Here is the upcoming schedule:

Download a beta chapter from our upcoming book on the AGIS JavaScript API

Adding a Python Script to a New Toolbar in ArcView 9.3.1 (Tutorial)

From time to time we like to feature guest posts.  Today I’d like to draw your attention to a tutorial from Bob Roberts at the Python and Then Some blog.  We’re going to be re-posting several of Bob’s tutorials.  I think you’ll find them quite helpful.  The first post will teach you how to add a Python script to a toolbar in ArcView 9.3.1.  You could easily apply the same concept to ArcGIS 10.0.  And now…more from Bob.

So you finished your Python ArcToolbox tool and now you want to add a shortcut to the toolbar. This tutorial is based on the assumption that you have already added your script to the ArcToolbox tools. If not I will cover that in another tutorial. I will show how to add a button in addition to how to add a menu to ArcView toolbar. Both are convenient ways to launch your Python script tools without having to open ArcToolbox.

First we will create a button to launch your tool.

  • Go to Tools > Customize.  This will open up the Toolbars tab.  If you do not want to add your own Toolbar, skip this section.
  • Click New for new toolbar:
  • Save it to either the current project (the .mxd) or to the Normal.mxt for use in all projects.
  • This will create an empty toolbar. Drag the toolbar to the top of ArcView.

Now that you have a new and empty toolbar we need to create the button for the Python tool.

  • Click on the Commands tab under Customize:
  • Scroll to the bottom of the Categories window:
  • Highlight [UIControls] and at the bottom click New UIControl
  • Select UIButtonControl and hit Create
  • Click in the box for the name if you wish to rename the tool
  • Next, click and drag the new UIButtonControl1 to your toolbar that was just created.

Now that the button is one the toolbar, we need to set it up to launch your Python tool.

  • Right click on the new button and you should see several options here.
  • You can change the button image to whatever you would like or you can just use “Text Only” for the name of the tool.

Now that we have the button on the toolbar and changed the way that it displays, it is time to add the Visual Basic snippet to launch the tool.

  • Click on “View Source”. This should open up the Microsoft Visual Basic editor:
  • Copy and Paste the following script between the Private Sub UIButtonControl1_Click() and End Sub:
  • You will need to replace “mypythontoolname” with the name of your Python tool.
  • Click the save button at the top of the VB editor.
  • Click on your button and it should open

There are a few things that can cause the button not to open your Python tool. The most common that I have seen is that the Visual Basic reference is not selected as available for using the ESRI GeoprocessingUI Object Library. This can be added by going into the Visual Basic editor again. At the top there is an option for Tools and then select references. Make sure that the ESRI GeoprocessingUI Object Library is checked. If not, check it to make the library available.

If you want to add a drop down menu for listing multiple Python tools the steps are mostly the same. After creating a new toolbar, you can create a new menu before you create the tool buttons.

On the Customize > Commands tab in the left hand pane there is an option for [New Menu]. Create the new menu in the same manner as creating the UIControls button. Add the menu to the toolbar and then you can add tool buttons to the drop down menu by clicking and dragging them to the drop down.

Hope that helps!

Additional Python and ArcGIS tutorials:

The next session of our instructor guided, Internet based course Programming 101 for ArcGIS 10: Mastering Python begins February 21st, 2011.  We still have a few seats available.  A self-paced version of this course is also available.