<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Michalis Avraam &#187; arcgisscripting</title>
	<atom:link href="http://michalisavraam.org/tag/arcgisscripting/feed/" rel="self" type="application/rss+xml" />
	<link>http://michalisavraam.org</link>
	<description>intersecting space and time through gis endeavors</description>
	<lastBuildDate>Wed, 08 Sep 2010 20:03:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>Loading the Geoprocessor Safely</title>
		<link>http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/</link>
		<comments>http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 20:52:25 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=275</guid>
		<description><![CDATA[Often times people write geoprocessing scripts that others try to incorporate in their work. This is done through modules or packages in Python. This is wonderful when one wishes to share their work, but it can also be bothersome if the module you are loading assumes that there is no geoprocessor loaded. This little script <a href='http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/' rel='bookmark' title='Permanent Link: Understanding the Geoprocessor Programming Model part 1'>Understanding the Geoprocessor Programming Model part 1</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Often times people write geoprocessing scripts that others try to incorporate in their work. This is done through modules or packages in Python. This is wonderful when one wishes to share their work, but it can also be bothersome if the module you are loading assumes that there is no geoprocessor loaded. This little script will help you safely load the geoprocessor object, either from an instantiation by the main program, or from scratch.</p>
<p><span id="more-275"></span>The method I use to load the geoprocessor, while verbose, ensures that if anyone loads the geoprocessor before they use any of my module functions, any of their settings remain intact. This is achieved as follows:</p>
<ol>
<li>Check if the <em>arcgisscripting</em> module was loaded.
<ol>
<li>If it was not loaded, obviously the geoprocessor is not instantiated. Import, instantiate and return.</li>
</ol>
</li>
<li>If the <em>arcgisscripting</em> module was loaded, check the variables the user created in the main program.
<ol>
<li>If a variable is found to be of type &#8216;<em>geoprocessor object</em>&#8216;, then return that object.</li>
</ol>
</li>
<li>If no variable is found of type &#8216;<em>geoprocessor object</em>&#8216;, create it and return it.</li>
</ol>
<p>The code can be found below. Please review and use as you wish. If you have any comments or questions about it, please leave a comment.</p>
<pre class="brush: python; title: ;">
&quot;&quot;&quot;
Loads the geoprocessor safely, ensuring that it is not loaded
twice (to avoid overwriting parameters).

Usage: load()

Returns: a geoprocessor object.

Note: Geoprocessor Version returned is 9.3

&quot;&quot;&quot;
import sys

def load(version=None):
    # Check if the arcgisscripting module was loaded
    if &quot;arcgisscripting&quot; not in sys.modules:
        # The arcgisscripting module was never loaded Try to load it.
        print &quot;arcgisscripting not loaded&quot;
        print &quot;Trying to load arcgisscripting&quot;
        try:
            import arcgisscripting
        except ImportError, errorDetail:
            sys.exit(&quot;Error loading arcgisscriping. Is ArcGIS installed?\n&quot; + errorDetail)
        # Try to create a geoprocessor instantiation
        print &quot;Trying to create the geoprocessor instance&quot;
        try:
            gp = arcgisscripting.create(9.3)
        except:
            sys.exit(&quot;Error creating geoprocessor object. Exiting\n&quot; + str(sys.exc_info()))
        # Return the geoprocessor instance
        print &quot;Done!&quot;
        return gp
    else:
        # arcgisscripting was loaded. Is the geoprocessor instantiated?
        print &quot;arcgisscripting was already loaded. Searching for geoprocessor...&quot;
        # Get the global variables
        globalVars = vars(sys.modules[&quot;__main__&quot;])
        for item, value in globalVars.iteritems():
            # Loop through global variables, ignore internals
            if not item.startswith(&quot;__&quot;):
                # Check the type of the variable
                if type(globalVars[item]).__name__ == 'geoprocessing object':
                    # If the variable is the geoprocessor, return it
                    print &quot;Found geoprocessor instance as&quot;, item
                    return globalVars[item]
        # If we are here, the module is loaded but no gp instantiated
        # Try to create a geoprocessor instantiation
        try:
            print &quot;arcgisscripting loaded but not instantiated. Instantiating now...&quot;
            gp = sys.modules[&quot;arcgisscripting&quot;].create(9.3)
        except:
            sys.exit(&quot;Error creating geoprocessor object. Exiting\n&quot; + str(sys.exc_info()))
        # Return the geoprocessor instance
        return gp
 </pre>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/' rel='bookmark' title='Permanent Link: Understanding the Geoprocessor Programming Model part 1'>Understanding the Geoprocessor Programming Model part 1</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>7 wishes for the new Geoprocessor</title>
		<link>http://michalisavraam.org/2010/02/7-wishes-for-the-new-geoprocessor/</link>
		<comments>http://michalisavraam.org/2010/02/7-wishes-for-the-new-geoprocessor/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 01:33:05 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[ESRI]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[ArcGIS]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=259</guid>
		<description><![CDATA[With the new version of ArcGIS coming out soon (9.4, now 10, tomorrow maybe X), it is nice to revisit the things I would love to see change in the geoprocessor. This is by no means a study on what is missing or what ESRI is doing wrong, but rather what I would like to <a href='http://michalisavraam.org/2010/02/7-wishes-for-the-new-geoprocessor/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/' rel='bookmark' title='Permanent Link: Understanding the Geoprocessor Programming Model part 1'>Understanding the Geoprocessor Programming Model part 1</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>With the new version of ArcGIS coming out soon (9.4, now 10, tomorrow maybe X), it is nice to revisit the things I would love to see change in the geoprocessor. This is by no means a study on what is missing or what ESRI is doing wrong, but rather what I would like to see in the future. If you have any suggestions, please do write a comment and I will gladly add them to the post (and attribute the addition to you).</p>
<p><span id="more-259"></span></p>
<table style="border: 2px solid #000000; width: 280px;" border="2" cellspacing="1" cellpadding="2" align="right">
<tbody>
<tr>
<td><strong>Wish</strong></td>
<td><strong>Likely</strong></td>
<td><strong>In v.</strong><strong>10?</strong></td>
</tr>
<tr>
<td>Free gp</td>
<td>No</td>
<td></td>
</tr>
<tr>
<td>Path traversal</td>
<td>Maybe</td>
<td></td>
</tr>
<tr>
<td>Expose numpy</td>
<td>No</td>
<td></td>
</tr>
<tr>
<td>Faster startup</td>
<td>Maybe</td>
<td></td>
</tr>
<tr>
<td>Desktop exposure</td>
<td>Yes</td>
<td>Hopefully</td>
</tr>
<tr>
<td>Multi-core</td>
<td>Yes</td>
<td>Hopefully</td>
</tr>
<tr>
<td>List returns</td>
<td>No</td>
<td></td>
</tr>
</tbody>
</table>
<ol>
<li><strong>A free geoprocessor</strong>: While this is unlikely to happen in the foreseeable future, there are elements of the geoprocessor that can be made freely available, either as a separate Python module or through a license check for parts of the objects. Specifically, I am referring to some of the List* methods (ListRasters(), ListFeatureClasses(), etc.) that do not require deep access to data (this would include ProductInfo(), validators, and hopefully even the Describe object). <em>Why would ESRI want to do this?</em> To ensure that limited functionality is available to everyone independent of cost. Why restrict people from seeing the power of the geoprocessor? Let them join the fun, and perhaps become customers too.</li>
<li><strong>Path traversal options</strong>: The List*() methods come in the list again, with a slight change. Since many users use directory structures to store data that are deep (subfolder within a subfolder within a folder), it would be nice if the geoprocessor could read through them all and return refernces to them based on the current folder. Before one jumps in to say that the Python os module can help, please remember that most users are not aware of os.walk, and trying to deal with ERI GRIDS (which are a folder themselves) presents a challenge even for experienced Python programmers. <em>Why would ESRI want to do this?</em> To make life easier for the majority of users out there with data in directory trees.</li>
<li><strong>Expose numpy in the geoprocessor</strong>: The geoprocessor as is right now (9.3.1) uses the excellent numpy module to perform matrix algebra (think of raster manipulation). Yet, when one wishes to run numpy commands, one needs to manually read raster files with GDAL, import them as numpy arrays (default), perform operations, and translate back to raster. ESRI must have modules for dealing with this, and we want them. <em>Why would ESRI want to do this?</em> Right now, raster manipulation through Python is done outside the geoprocessor. Most people turn to open source tools to manipulate data, which leads to less and less users relying on ESRI for this. Why pay when free software will do it? The capability is there, and we need to access it too.</li>
<li><strong>A faster starting geoprocessor</strong>: Right now, on my dual-core, 4GB RAM machine, creating the geoprocessing object takes a noticeably long time (in the orders of a few seconds). Why is that the case today? If the geoprocessor is written as C module, the bottleneck is somewhere else. Regardless, this needs to be address, especially for using an interactive shell or multiple parallel processes involving the geoprocessor. <em>Why would ESRI want to do this?</em> Simply because a faster startup time is time-saving and psychologically makes people feel better about the tools at hand.</li>
<li><strong>Multi-core aware geoprocessor</strong>: Right now, ESRI operates on one core per command (on the desktop). Similarly, the geoprocessor is a one-core operation. Yet many operations can run in parallel, and indeed, many people on the ESRI forums try endlessly to achieve multi-core operations. This is not easy of course, and not many people know how to do it. <em>Why would ESRI want to do this?</em> Increase in speed for one, but most importantly, to introduce a way to achieve this for everyone that wants it. Right now, there are as many solutions to this as there are people needing it. One simple and good way to achieve this would allow for unification of effort, and some good documentation be written.</li>
<li><strong>Exposure to the desktop application when run through it</strong>: If you remember the good old VBA days (which will not be included on any version after 10, beware), you could manipulate the application via scripting. You could add data to a map, reference the 3rd item on the table of contents, etc. We want a return to this regime, but this time with Python. <em>Why would ESRI want to do this?</em> Something will need to replace VBA, and what better language than the chosen one for geoprocessing scripting? Also, access to such functionality opens up development to a larger audience, which can help bolster the industry by itself.</li>
<li><strong>Make every method return a Python list for multiple data</strong>: The cursor methods in ArcGIS right now return an enumeration object. While this is understandable (ESRI doesn&#8217;t want people manipulating the order of items or inserting items in the middle of the list), it is not to the best interest of the geoprocessing model to return both enumeration objects and Python lists. At the very least, the enumeration object should have more Pythonic methods, like append() to add an element in the end or pop() to remove the last item. <em>Why would ESRI want to do this?</em> Consistency. There was an attempt to become more Pythonic in 9.3, so why not keep up with the theme and be more consistent at the same time?</li>
</ol>
<p>Do you have any suggestions to include in this list? Please leave a comment. Or if you think I am off my head and don&#8217;t know what I am talking about.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/' rel='bookmark' title='Permanent Link: Understanding the Geoprocessor Programming Model part 1'>Understanding the Geoprocessor Programming Model part 1</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2010/02/7-wishes-for-the-new-geoprocessor/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Understanding the Geoprocessor Programming Model part 3</title>
		<link>http://michalisavraam.org/2010/02/understanding-the-geoprocessor-programming-model-part-3/</link>
		<comments>http://michalisavraam.org/2010/02/understanding-the-geoprocessor-programming-model-part-3/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 01:47:02 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[describe]]></category>
		<category><![CDATA[ESRI]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=229</guid>
		<description><![CDATA[After a long delay, it is time for the third installment of understanding the Geoprocessor Programming Model that will deal with the Describe object. If you missed the last two parts, feel free to look at them first (Part 1: understanding what the geoprocessor is, and Part 2: accessing data with the geoprocessor). As always, <a href='http://michalisavraam.org/2010/02/understanding-the-geoprocessor-programming-model-part-3/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/' rel='bookmark' title='Permanent Link: Accessing Geometries using the Geoprocessor (Updated)'>Accessing Geometries using the Geoprocessor (Updated)</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>After a long delay, it is time for the third installment of understanding the Geoprocessor Programming Model that will deal with the Describe object. If you missed the last two parts, feel free to look at them first (<a href="http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/">Part 1: understanding what the geoprocessor is</a>, and <a href="http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/">Part 2: accessing data with the geoprocessor</a>). As always, comments are welcomed and encouraged.<span id="more-229"></span></p>
<div id="attachment_234" class="wp-caption alignright" style="width: 510px"><a href="http://michalisavraam.org/wp-content/uploads/2009/11/describe.png"><img class="size-full wp-image-234" title="The Describe Object" src="http://michalisavraam.org/wp-content/uploads/2009/11/describe.png" alt="The Describe Object" width="500" height="540" /></a><p class="wp-caption-text">The Describe Realm</p></div>
<p>As mentioned earlier, the geoprocessor gives us the ability to access or create data to perform various operations. These operation vary in type and content, but more often than not are performed on data we are not intimately familiar with. This can become a problem quite quickly, as we need to know the names of fields in the datasets, as well as other characteristics (the type of data we are dealing with, spatial references, geographical extent and other). The solution to this lack of knowledge comes through the <em>describe</em> object which provides users with methods to identify all unknown information beforehand. In the most basic form of usage, one uses the <em>describe</em> object on a dataset, accessing the bottom left box in the diagram, the <em>Describe Object Properties</em>. The Python code to achieve this follows:</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

dataset = r&quot;c:\data\testData.shp&quot;
# The location of the data. This is usually
#   not hardcoded but discovered with List methods

dsc = gp.Describe(dataset)
# Create a describe object for the dataset

print dsc.DataType
# Print the data type of our dataset

print dsc.CatalogPath
# Print the path to the dataset
</pre>
<p>With the above simple example, we managed to read the Data Type and Catalog Path of a dataset. While this seems simple, it can become a very powerful tool, when on considers the possible return values (listed below).</p>
<table border="1" cellspacing="0" cellpadding="2" align="center">
<tbody>
<tr style="background-color: #dcdcdc;">
<td align="left"><strong>Return Value</strong></td>
<td align="left"><strong>Data Type</strong></td>
</tr>
<tr>
<td align="left">FeatureDataset</td>
<td align="left">Containers for data that include spatial reference and extent of contents.</td>
</tr>
<tr>
<td align="left">FeatureClass</td>
<td align="left">Feature class in a geodatabase, a shapefile if standalone.</td>
</tr>
<tr>
<td align="left">Table</td>
<td align="left">A geodatabase or standalone table.</td>
</tr>
<tr>
<td align="left">RelationshipClass</td>
<td align="left">A geodatabase class storing relationships.</td>
</tr>
<tr>
<td align="left">RasterDataset</td>
<td align="left">A raster dataset type.</td>
</tr>
<tr>
<td align="left">RasterBand</td>
<td align="left">A raster band.</td>
</tr>
<tr>
<td align="left">RasterCatalog</td>
<td align="left">A raster catalog.</td>
</tr>
<tr>
<td align="left">Workspace</td>
<td align="left">A workspace as defined by ESRI (directory or database).</td>
</tr>
</tbody>
</table>
<p>As you can see, the return values as listed above correspond to different objects in our diagram (the boxes in the first image above). This means that it would be trivial for us to move between the first access we have into the <em>Describe</em> realm (through the Describe object) and move to any other box of our choice when we are not familiar with what possible data we have.</p>
<h2>Retrieving Information about data: Feature Classes</h2>
<div id="attachment_236" class="wp-caption alignleft" style="width: 210px"><a href="http://michalisavraam.org/wp-content/uploads/2009/11/featureClass.png"><img class="size-full wp-image-236" title="FeatureClass Object Properties" src="http://michalisavraam.org/wp-content/uploads/2009/11/featureClass.png" alt="FeatureClass Object Properties" width="200" height="209" /></a><p class="wp-caption-text">FeatureClass Object Properties</p></div>
<p>The most commonly used types of data in GIS now seems to be feature classes, either standalone (in the form of shapefiles) or in a geodatabase. As such, we will use the example of a feature class to retrieve information about out data. This is of course not the only type of data one can use, so please refer to the image on the top for more information.</p>
<p>As you can see from the diagram on the left, feature classes have specific information associated with them, including what feature type they are of, their shape type, and the shape field name we used in part two of this series. We will dive right into it by trying to identify what shape type our feature class has, and what type of feature it is.</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

dataset = r&quot;c:\data\testData.shp&quot;
# The location of the data. This is usually
#   not hardcoded but discovered with List methods

dsc = gp.Describe(dataset)
# Create a describe object for the dataset
# As we know the dataset is of type FeatureClass,
#   all the properties of the FeatureClass object
#   are available to us now.

print dsc.ShapeType
# Print what type of shape we have
#   (point, polygon, polyline, etc)

print dsc.FeatureType
# Print what type of features are stored
#   (simple, annotation, dimension, etc)
</pre>
<p>With the above code we can identify what type of shape we have and the type of feature stored. For possible values to these properties, please <a href="http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=FeatureClass_properties">check this help file</a>.</p>
<div id="attachment_237" class="wp-caption alignright" style="width: 210px"><a href="http://michalisavraam.org/wp-content/uploads/2009/11/table.png"><img class="size-full wp-image-237" title="Table Properties" src="http://michalisavraam.org/wp-content/uploads/2009/11/table.png" alt="Table Properties" width="200" height="108" /></a><p class="wp-caption-text">Table Properties</p></div>
<p>In the FeatureClass Properties object image above, on the bottom, you can see that there are also <em>Table Properties</em> and<em> Dataset Properties</em> listed. This means that when you have a feature class, you automatically gain access to those properties as well (as a feature class has them embedded). Therefore, we can use this to our advantage to further retrieve information about our feature class, like the name of all fields within the feature class. The example below shows you how to achieve this.</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

data = r&quot;c:\data\testData.shp&quot;
# The location of the data. This is usually
#   not hardcoded but discovered with List methods

dsc = gp.Describe(data)
# Create a describe object for the data
# As we know the dataset is of type FeatureClass,
#   all the properties of the FeatureClass object
#   and inherited objects are available to us now.

dataFlds = dsc.Fields
# Retrieve a list of fields in the table of the
#   feature class as a Python list. Note the fields
#   are of Field Object type.

for fld in dataFields:
    print fld.Name
</pre>
<div id="attachment_235" class="wp-caption alignright" style="width: 210px"><a href="http://michalisavraam.org/wp-content/uploads/2009/11/dataset.png"><img class="size-full wp-image-235" title="Dataset Properties" src="http://michalisavraam.org/wp-content/uploads/2009/11/dataset.png" alt="Dataset Properties" width="200" height="118" /></a><p class="wp-caption-text">Dataset Properties</p></div>
<p>What he have done on the above example is run the ListFields() method mentioned in an older article (<a href="http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/">Using the Geoprocessor&#8217;s List Methods</a>). Similarly, one can follow the Dataset Properties object (shown on your right) to access information like the extent of the data, or the spatial reference system. Don&#8217;t forget, both of those return an object, which has a corresponding box in the geoprocessor programming model diagram, so you need to treat them as such.</p>
<p>In this installment, I have shown you how one can use the <em>Describe</em> object the geoprocessor makes available to us to retrieve information about our data. While I did not provide complete examples of every single possible option available, hopefully by reading this post you are able to navigate your options better to achieve your goals.</p>
<p>As always, comments are encouraged and I am willing to answer any questions you may have.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/' rel='bookmark' title='Permanent Link: Accessing Geometries using the Geoprocessor (Updated)'>Accessing Geometries using the Geoprocessor (Updated)</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2010/02/understanding-the-geoprocessor-programming-model-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding the Geoprocessor Programming Model part 2</title>
		<link>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/</link>
		<comments>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/#comments</comments>
		<pubDate>Mon, 19 Oct 2009 17:00:04 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[ESRI]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=198</guid>
		<description><![CDATA[In the first part of this series I covered access to the geoprocessor and how one can navigate the first part of the diagram of the model. If you are not familiar with the geoprocessor, please have a quick look at that post to understand the geoprocessing model ESRI provides. In this post I will <a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/' rel='bookmark' title='Permanent Link: Accessing Geometries using the Geoprocessor (Updated)'>Accessing Geometries using the Geoprocessor (Updated)</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/">first part of this series</a> I covered access to the geoprocessor and how one can navigate the first part of the diagram of the model. If you are not familiar with the geoprocessor, please have a quick look at that post to understand the geoprocessing model ESRI provides.</p>
<p>In this post I will finish covering the bottom left part of the model that deals with direct access to features and their geometry. In order to do that, we will discuss cursors, features and geometries.</p>
<h3><span id="more-198"></span>Spatial Data Primer</h3>
<p>Before we begin discussing deep access to data, we need to define what spatial data are. In essence, there are two types of spatial data, vector and raster data. An easy way to understand the difference is to imagine raster data as images, while vector data are defined by points, lines and polygons. What is special about spatial data is their dimension of space, or location. Raster data offer extensive coverage of an area, in which our spatial data offer a regular grid of cells that provide data. Space in this case is depended on the location of the cell in the raster file (and therefore implicit location). Vector files on the other hand contain explicit information about the location of things (providing coordinates). Data are then associated with the locations of features. We will be dealing with vector data mostly, so a further investigation is warranted.</p>
<p>In order to represent the world in spatial data, we choose a type of vector data we want to use (for example, choosing points to represent trees, lines to represent road networks, etc). Each of the features in the world get assigned two types of data: spatial characteristics (for a point, an x,y pairs, for a line, a series of points, etc.) and non-spatial characteristics (think of them as attributes). A file that contains all the trees in a neighborhood then includes a list of all the trees, with each tree having a location attribute, and a set of attributes that describe the tree (like type of tree, or age of tree, etc). Therefore, spatial data are defined as follows:</p>
<ul>
<li>A file dealing with a specific type of feature in the world.
<ul>
<li>The file has a list of features that all satisfy the requirement of belonging in that type of feature.
<ul>
<li>Each feature contains a spatial footprint for where it is located.</li>
<li>Along with location, each feature contains zero or more characteristics that are aspatial but refer to the feature itself.</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>Similarly, when one tries to access the geometry or the characteristics of a specific feature in our data, one has to first access the file we need, within the file, identify the right feature we need, and then eventually, within the feature find the geometry and/or the characteristics associated with it.</p>
<h3>Accessing Data Using the Geoprocessor</h3>
<div id="attachment_199" class="wp-caption aligncenter" style="width: 810px"><img class="size-full wp-image-199" title="From the Geoprocessor to Geometry" src="http://michalisavraam.org/wp-content/uploads/2009/10/gpToGeometry.png" alt="From the Geoprocessor to Geometry" width="800" height="180" /><p class="wp-caption-text">From the Geoprocessor to Geometry</p></div>
<p>The image above shows the path one needs to travel within the Geoprocessor to access a Geometry. The cyan box on the left represents the commands available to the geoprocessor object, as discusses in the previous post. The commands that include the word Cursor have an arrow to their right, that show they can access rows, which is actually a representation of the spatial data file in Python. From there on, one can access a single row (the third box from the left), which can eventually lead to the <em>Geometry</em> object on the left. So in the geoprocessing world, in order to access a geometry (or spatial characterics of a feature), we need to do the following:</p>
<ol>
<li>Create the geoprocessor object.</li>
<li>Call the appropriate cursor command to receive a <em>rows</em> object, which is a Python representation of the file we need to access.</li>
<li>Within the <em>rows</em> object, we call the <em>Next()</em> or <em>NewRow()</em> command to receive an individual feature, represented as a single <em>row</em>.</li>
<li>The <em>row</em> object allows us to directly access characteristics of the file, including the <em>Geometry</em> object. Please note that the characteristics are actually variables now, and not methods.</li>
</ol>
<p>A question people often ask is how one knows which path to follow when they need to access a specific object (or box in the diagram). If you are not intimately familiar with the model, there is one method to follow: Identify the object you want, and then follow the arrows in reverse to find the methods that can get you there. Once you have those steps reverse them and you have a workflow. Remember, you will always need to end up in the cyan, geoprocessor object, as this is your only starting point.</p>
<h4>From the Geoprocessor to Spatial File Access</h4>
<p>There are three methods to access your spatial file, as shown in the diagram, explained below:</p>
<ul>
<li><strong>InsertCursor</strong>: The insert cursor allows you to access a spatial file with the sole purpose of adding new features (or rows). Use this cursor to add more features to a file.</li>
<li><strong>SearchCursor</strong>: The search cursor allows you to access a spatial file with the sole purpose of reading features (rows). Use this cursor to read the characteristics of each feature.</li>
<li><strong>UpdateCursor</strong>: The update cursor allows you to access a spatial file in order to update values in each feature (row), or completely remove it. Use this cursor to update characteristics (including geometry) of a feature, or to remove the feature itself.</li>
</ul>
<p>The required parameter for each of these cursor is the file you want to access, called InputValue in the diagram. Here is an example of how to use each cursor:</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcWrite = gp.InsertCursor(r&quot;c:\data\testWrite.shp&quot;)
# Create an insert cursor that points to the testWrite.shp file.
# The returned value fcWrite is actually a rows object.
# You are now able to add new features to the file.

fcRead = gp.SearchCursor(r&quot;c:\data\testRead.shp&quot;)
# Create a search cursor that points to the testRead.shp file.
# The returned value fcRead is actually a rows object.
# You are now able to read the information about features from the file.

fcUpdate = gp.UpdateCursor(r&quot;c:\data\testUpdate.shp&quot;)
# Create an update cursor that points to the testUpadate.shp file.
# The returned value fcUpdate is actually a rows object.
# You are now able to update values in features, of completely remove them from the file.
</pre>
<p>If you follow the above examples, you manage to escape from the geoprocessor object (the cyan box) and move to the <em>rows</em> object, the first yellow box on the left. Note that the <em>rows</em> object has different methods available depending on how you access it.</p>
<h4>From the Rows Object to a Single Row</h4>
<div id="attachment_200" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-200 " title="From the Rows Object to the Row Object" src="http://michalisavraam.org/wp-content/uploads/2009/10/rowsToRow.png" alt="From the file to a single row" width="600" height="305" /><p class="wp-caption-text">From the file to a single row</p></div>
<p>Now that you have access to the <em>rows</em> object, you can continue accessing the file by individual feature (or row). Depending on the Cursor method you used, you will have the following options available to you:</p>
<ul>
<li><strong>SearchCursor <em>Rows</em> Object</strong>: This provides you with read-only access to the elements/features of your file. As such, there are two methods available: Next() and Reset(). As you may infer from their name, Next() will provide to you the next feature as a <em>row</em> object, while the Reset() method simply returns the pointed to the specific row in the beginning of the file.</li>
<li><strong>InsertCursor <em>Rows</em> Object</strong>: As the InsertCursor() method provides the ability to add new features in the file, the methods available are NewRow(), InsertRow() and Reset(). This creates some confusion, but it is easy to distinguish what happens when you understand the internals. NewRow() creates a new and empty <em>row</em> object in memory, which allows you to create your new feature. This <em>row</em> object remains in memory until one calls the InsertRow() function, which will save the <em>row</em> object to your file. The Reset() method functions as with the SearchCursor <em>Rows</em> object explained above.</li>
<li><strong>UpdateCursor <em>Rows</em> Object</strong>: As the UpdateCursor() provides you the most functionality, it comes with more methods: Next(), Reset(), UpdateRow() and DeleteRow(). The Next() and Reset() methods function the same way as with the SearchCursor <em>Rows</em> object. UpdateRow() is similar to the InsertRow() method of the InsertCursor <em>Rows</em> object. Given a <em>row</em> object, it will update the feature the cursor is set on. Similarly, the DeleteRow() method will delete the current <em>row</em> object the cursor points to.</li>
</ul>
<p>Examples on how to use the commands follow:</p>
<p>Example 1: Writing a new feature</p>
<pre class="brush: python; title: ;">
# Example 1: Create a new Row
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcWrite = gp.InsertCursor(r&quot;c:\data\testWrite.shp&quot;)
# Create an insert cursor that points to the testWrite.shp file.
# The returned value fcWrite is actually a rows object.

fcWrite.Reset()
# Reset the cursor to the rows object

fcRow = fcWrite.NewRow()
# Create a new row object in memory, saved in the fcRow variable

# Manipulate the row here.

fcWrite.InsertRow(fcRow)
# Save the row object back to our file
</pre>
<p>Example 2: Reading a feature</p>
<pre class="brush: python; title: ;">
 # Example 2: Read the n feature of a file
 import arcgisscripting
 # Import the module provided by ESRI

 gp = arcgisscripting.create(9.3)
 # Create the geoprocessor object

 fcRead = gp.InsertCursor(r&quot;c:\data\testRead.shp&quot;)
 # Create an insert cursor that points to the testRead.shp file.
 # The returned value fcRead is actually a rows object.

 fcRead.Reset()
 # Reset the cursor to the rows object

 fcRow = fcRead.Next()
 # Read the first row of the file and save it to the fcRow variable

 # Read the information for the feature here

# If you need to find a specific feature, you need to continue your search
# Use a while loop to achieve this
while fcRow:
    # Test whether this feature is the one you want
    # When you found the feature, you can use break to end the loop
    # If the feature is not the right one, keep trying
    fcRow = fcRead.Next()
 </pre>
<p>Example 3: Updating and Deleting Rows</p>
<pre class="brush: python; title: ;">
# Example 3: Updating and Deleting Rows
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcUpdate = gp.UpdateCursor(r&quot;c:\data\testUpdate.shp&quot;)
# Create an update cursor that points to the testUpadate.shp file.
# The returned value fcUpdate is actually a rows object.

fcUpdate.Reset()
# Reset the cursor to the rows object

fcRow = fcUpdate.Next()
# Receive the first row

# Loop through the rows until you find one to delete and one to update
while fcRow:
    # If this is the row that needs deleting, then
        fcUpdate.DeleteRow(fcRow)
        # Call the DeleteRow() method with the current row as a parameter
    # If this is the row that needs updating, then
        # Perform the update to the row
        fcUpdate.UpdateRow(fcRow)
        # Call the UpdateRow() method with the current row as a parameter
</pre>
<h4>Manipulating Individual Features and Geometries</h4>
<p>If you followed the above examples, then you are aware on how one can access an individual feature from a file. The question then remains on how one manipulates that row. Below are some explanations on how one can perform this.</p>
<div id="attachment_201" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-201" title="Rows and Geometries " src="http://michalisavraam.org/wp-content/uploads/2009/10/rowToGeometry.png" alt="Individual Features (row) and their Geometry" width="600" height="227" /><p class="wp-caption-text">Individual Features (row) and their Geometry</p></div>
<p>As with the <em>Rows</em> object, there are different versions of the <em>Row</em> object depending on who calls it. The two possibilities are:</p>
<ul>
<li><strong><em>Row</em> object derived from a SearchCursor</strong>: This object provides the GetValue() method that allows one to read values associated with a field. Along with the method, there is a collection of read-only variables that represent the fields/attributes the row represents.</li>
<li><strong><em>Row</em> object derived from an InsertCursor or UpdateCursor</strong>: This object provides what the read-only version provides, with the variables representing fields/attributes being write-enabled as well. The SetValue() method is also provided to allow one to set new values to fields.</li>
</ul>
<div id="attachment_202" class="wp-caption alignright" style="width: 310px"><img class="size-full wp-image-202" title="fieldObject" src="http://michalisavraam.org/wp-content/uploads/2009/10/fieldObject.png" alt="The Field Object" width="300" height="224" /><p class="wp-caption-text">The Field Object</p></div>
<p>Before we continue on with the idea of geometries, we need to show how one can access the field names. Often we know the names of fields/attributes because we are familiar with the dataset or have access to the metadata. Another way to get familiar with the names of the fields though exists, and is through the ListFields() method available to the geoprocessor object. This command will return a Python list that includes all the attributes available to you, as <em>Field</em> objects. What this object provides to you is a set of variables that are read-only and make available to you information like the name, alias, domain, editable ability and more information about the field. Please have a look at the diagram on the right for a full listing of information included in a <em>Field</em> object.</p>
<pre class="brush: python; title: ;">
# Example of finding out the fields available in a file
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fieldsList = gp.ListFields(r&quot;c:\data\test.shp&quot;)
# Call the ListFields() method on the test.shp file
# The returned list is saved in fieldsList

for field in fieldsList:
# Loop through all the field
    print field.Name
# Print the name of the field
</pre>
<p>This is one way to also identify the field that includes the geometry. Unfortunately, depending on the type of file you have (or database for that matter), the name may change. There is a trick to find the actual name of the field that stores geometry, but it will be covered in another part. For now, here is how one can do it:</p>
<pre class="brush: python; title: ;">
# Example of finding out the fields available in a file
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcDsc = gp.Describe(r&quot;c:\data\test.shp&quot;)
# Get the descriptor of the file
geometryField = fcDsc.ShapeFieldName
# Get the geometry(shape) field name from the description
</pre>
<p>As you now know what the name of the geometry field is, you can access is as mentioned before with the GetValue() method. Similarly, you can save a geometry using the SetValue() method. It is important to remember that geometries in the ESRI world are <em>Geometry</em> objects of multiple parts which are held in <em>Array</em> objects holding one or more <em>Point</em> objects. This means when you use the GetValue() method, you first receive a <em>Geometry</em> object. Within that object, you will call the GetPart() method to receive an <em>Array</em> object, which in turn holds a number of <em>Point</em> objects, which are called through the Next() method. An example follows to help you understand this.</p>
<pre class="brush: python; title: ;">
# Example of accessing a Geometry of a feature / print geometry type
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcDsc = gp.Describe(r&quot;c:\data\test.shp&quot;)
# Get the descriptor of the file
geometryField = fcDsc.ShapeFieldName
# Get the geometry(shape) field name from the description

srcCursor = gp.SearchCursor(r&quot;c:\data\test.shp&quot;)
# Create a search cursor to the file

row = srcCursor.Next()
# Grab the first row

while row:
# Loop through the features/rows
rowGeom = row.Getvalue(geometryField)
# Grab the geometry of the row

print rowGeom.Type
# Print the type of the geometry

row = srcCursor.Next()
# Grab the next row
</pre>
<p>With this installment, you should have the knowledge to navigate the Geoprocessor Programming Model on the bottom, where accessor methods for files reside. Also, you should be able to access a Geometry object for every vector dataset you have available. In the next installment we will further navigate the programming model.</p>
<p>Note: Thanks to Eric for catching a Python error.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/' rel='bookmark' title='Permanent Link: Accessing Geometries using the Geoprocessor (Updated)'>Accessing Geometries using the Geoprocessor (Updated)</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Understanding the Geoprocessor Programming Model part 1</title>
		<link>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/</link>
		<comments>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 18:21:31 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[ESRI]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=183</guid>
		<description><![CDATA[A question often asked when people venture into the wonderful world of Python Geoprocessing with ESRI is how one can read the programming model they make available on their website. As it may not be easily interpreted when one begins programming, I will do my best to unpack it and explain how one can use <a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/' rel='bookmark' title='Permanent Link: Loading the Geoprocessor Safely'>Loading the Geoprocessor Safely</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://webhelp.esri.com/arcgisdesktop/9.3/pdf/Geoprocessor_93.pdf"><img class="size-full wp-image-185 alignright" title="ESRI's Geoprocessing Programming Model" src="http://michalisavraam.org/wp-content/uploads/2009/10/esriGeoprocessingProgrammingModel1.png" alt="ESRI's Geoprocessing Prorgamming Model" width="150" height="67" /></a></p>
<p>A question often asked when people venture into the wonderful world of Python Geoprocessing with <a href="http://www.esri.com/">ESRI</a> is how one can read the <a href="http://webhelp.esri.com/arcgisdesktop/9.3/pdf/Geoprocessor_93.pdf">programming model</a> they make available on their website. As it may not be easily interpreted when one begins programming, I will do my best to unpack it and explain how one can use it more effectively. All images presented here are extracts from the actual model presented by ESRI on their website.</p>
<p><span id="more-183"></span></p>
<h3>Dual Usages for the Geoprocessor</h3>
<p>The geoprocessor within Python can be used for two different purposes: to access tools provided by ESRI to manipulate data (the tools one sees in the ArcToolbox), and to programatically manipulate data using the underlying structures provided by ESRI. To further explain this process, a little understanding of how software works is needed. A software package usually involves multiple components. At the heart of software are basic operations and data models, the core of your software. This core deals with things like accessing and saving data, manipulating numbers and the like. This functionality is usually bundled together to create the tools the software produces. In the case of ArcMap, a tool like buffer could use components about reading and writing data, coordinate transformation routines, and probably some sort of functionality that allows manipulation of spatial data. To bring it back to the geoprocessor, and why it is so much more powerful than using the software by itself, what you get access to is not only the tools ESRI has created for you by compiling multiple elements, but you also get access to a lot of those elements yourself that allows you to write your own buffer tool for example.</p>
<h3>Understanding what the Geoprocessor is</h3>
<p>When one talks about the geoprocessor, one is referring to a <a href="http://docs.python.org/tutorial/classes.html">Python object</a> built by ESRI, that allows one to call many different functions to perform operations. As in most Python code, the definitions of the object reside in a <a href="http://docs.python.org/tutorial/modules.html">module</a> that is provided to you. As with any other module, in order to access it through Python you need to import it. This is done by simply typing<em> import arcgisscripting</em> in your Python code.</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Imports the module provided by ESRI
</pre>
<p>In this case, the module provides a single command accessible to you called <em>create</em>. This exposed function allows one to instantiate the geoprocessor object. Simply calling the create() command is enough to return to you a geoprocessor object. You can also pass parameters to it, but the only one at the moment is the number 9.3, to create a geoprocessor object that returns values based on the 9.3 iteration of the programming model.</p>
<pre class="brush: python; title: ;">
gp = arcgisscripting.create(9.3)
# Instantiates the geoprocessor and assigns the name gp to it
</pre>
<h3>Beginning our Travel in the Geoprocessor Programming Model</h3>
<div id="attachment_186" class="wp-caption alignright" style="width: 210px"><img class="size-full wp-image-186" title="Geoprocessor Object" src="http://michalisavraam.org/wp-content/uploads/2009/10/arcgisscripting.png" alt="Geoprocessor Object" width="200" height="803" /><p class="wp-caption-text">Geoprocessor Object</p></div>
<p>The box on the right represents your geoprocessor. While it seems that these are the commands available to the<em> arcgisscripting</em> module, that is incorrect. Therefore, in the Geoprocessor Programming Model, one always enters through the cyan box, as seen on your right. There are few interesting things to note here:</p>
<ol>
<li>There are a lot of names appearing on the list.</li>
<li>Each name has a symbol ahead of it.</li>
<li>Most name have a parenthesis to their right.</li>
<li>A few of those names also have more information on the very right.</li>
</ol>
<p>Here is how one needs to interpret this part of the diagram. The symbols on the left define what the name represents.</p>
<h4>Geoprocessor Variables</h4>
<p>If there is a box connected to a dash, or two boxes, then the name represents a variable. What this means is that the name represents a value. There are a few options here:</p>
<ol>
<li><strong>Box on the left of the dash</strong>: This represents a built-in variable that is read-only. You as a user have no power to change these value, but can only read it. An example is the variable called <em>MessageCount</em>. The value represents how many messages the geoprocessor object has thus far.</li>
<li>Box on both sides of the dash: This represents a variable you can also write too. This is a value that the software can use, and you are allowed to overwrite it with your own value. An example is the <em>OverwriteOutput</em> variable, which allows you to tell the geoprocessor whether it has permission to overwrite existing files.</li>
</ol>
<p>Example usages for geoprocessor variables is below (click to expand):</p>
<pre class="brush: python; collapse: true; light: false; title: ; toolbar: true;">
import arcgisscripting
# Import the module provided by ESRI
gp = arcgisscripting.create(9.3)
# Instantiate the geoprocessor object

gp.OverwriteOutput = True
# Set the OverwriteOutput variable to True

print gp.MessageCount
# Print the number of messages on the object
</pre>
<h4>Geoprocessor methods</h4>
<p>Boxes are not the only symbols that appear on the dashes. There is also an arrow, which represents a function or procedure you are allowed to call. What this means is that by using that name, one is telling the geoprocessor to perform an operation. Some operations also allow you to define variables to be used on the operations. For example, <em>RemoveToolBox</em> is an operation that will remove a Toolbox from the geoprocessor, as long as you can provide its name. There are two types of operations available to you, and to distinguish them one needs to see what appears to the right of the name. here are the possibilities:</p>
<ol>
<li><strong>Methods that do not return anything</strong>: A lot of functions do not return anything to the user, and you can see this by the lack of any more information to the right of the name of the function. They perform an operation the user asks for, but do not return something the user can work with, other than a message of their success or a preset value. <em>ResetEnvironments()</em> is an example of such a method.</li>
<li><strong>Methods that return objects one can manipulate</strong>: Some of the functions in the list return a new object that the user can manipulate. These objects are often Python objects (like a Python List) that contain other ESRI objects, or sometimes an ESRI defined object directly that allows us to further manipulate what the software does. An example is the <em>InsertCursor()</em> method, that will return an object back called a <em>rows</em> object. The <em>ListFields()</em> method returns a Python List object populated with ESRI defined Field objects.</li>
</ol>
<p>The methods that return an object or a collection of objects also have an arrow on their right linking them with the object they return. For example, all the cursor methods connect to the row object to allow the user to see what that object provides. Similarly, the list methods oftentimes have an arrow to connect them to other objects, like the field object. The special case is the method called CreateObject(), which allows you to create a large set of objects from scratch, like spatial reference, points, valute table, etc.</p>
<p>Example usages of methods follow:</p>
<pre class="brush: python; title: ;">
 import arcgisscripting
 # Import the module provided by ESRI
 gp = arcgisscripting.create(9.3)
 # Instantiate the geoprocessor object

 gp.ResetEnvironments()
 # Reset all environments on the geoprocessor object

 tools = gp.ListTools()
 # Returns a Python list of all the tools available, save in the tools variable
for tool in tools:
print tool
# Loop through each tool and print it
 </pre>
<p>In the net part of this series I will investigate the objects connected with cursors (meaning the rows object and all connected object, like the row object (singular) and geometry).</p>
<h4>Geoprocessor Access to Tools</h4>
<p>The geoprocessor object also allows users to call on tools that ESRI provides. Those tools are identical to the tools found in the ArcToolbox. A list of them, with a description, is available from ESRI <a href="http://webhelp.esri.com/arcgisdesktop/9.3/pdf/Geoprocessing_Quick_Guide.pdf">here</a> (note, it is a large PDF file). Note that the Python scripting syntax is not included in that file, but the help file contains a Python example for each tool. You will need to search for it yourself unfortunately, but the thing one needs to remember is that the tool name remains the same, and all parameters to be passed to it must be within parenthesis.</p>
<p>I hope you enjoyed this article and be sure to visit for the remaining parts.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/' rel='bookmark' title='Permanent Link: Loading the Geoprocessor Safely'>Loading the Geoprocessor Safely</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Python Geoprocessing in ArcGIS 9.2 vs. 9.3</title>
		<link>http://michalisavraam.org/2009/07/python-geoprocessing-in-arcgis-9-2-vs-9-3/</link>
		<comments>http://michalisavraam.org/2009/07/python-geoprocessing-in-arcgis-9-2-vs-9-3/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 07:20:39 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[9.2]]></category>
		<category><![CDATA[9.2 vs. 9.3]]></category>
		<category><![CDATA[9.3]]></category>
		<category><![CDATA[ArcGIS]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=86</guid>
		<description><![CDATA[There are some fundamental differences between geoprocessing performed in ArcGIS version 9.2 and 9.3. While I will not cover them all in this post, I will attempt to show the most fundamental differences that people seem to encounter more often. The fundamental differences are as follows: The method of invoking the geoprocessor is very similar <a href='http://michalisavraam.org/2009/07/python-geoprocessing-in-arcgis-9-2-vs-9-3/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/' rel='bookmark' title='Permanent Link: Geoprocessing Iteration with Python'>Geoprocessing Iteration with Python</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>There are some fundamental differences between geoprocessing performed in ArcGIS version 9.2 and 9.3. While I will not cover them all in this post, I will attempt to show the most fundamental differences that people seem to encounter more often.<br />
<span id="more-86"></span><br />
The fundamental differences are as follows:</p>
<ol>
<li>The method of invoking the geoprocessor is very similar for both, with the exception of an optional parameters when creating the object.</li>
<li>Geoprocessing methods do not return Python built-in data types but rather ESRI iterable objects.</li>
<li>Methods that used to return True/False values now return the Python True or False object rather than a string or 0/1.</li>
</ol>
<p>The following table illustrates the differences:</p>
<table border="0">
<tbody>
<tr>
<th> ArcGIS version 9.2</th>
<th> ArcGIS version 9.3</th>
</tr>
<tr>
<td>
<pre class="brush: python; title: ;">
gp = arcgisscripting.create()
</pre>
</td>
<td valign="top">
<pre class="brush: python; title: ;">
gp = arcgisscripting.create(9.3)
</pre>
</td>
</tr>
<tr>
<td>
<pre class="brush: python; title: ;">
# Create a list of available feature classes
fcs = gp.ListFeatureClasses()
# Iterate through said feature classes
fcs.Reset()
fc = fcs.Next()
while fc:
    # Do work here
    fc = fcs.Next()
</pre>
</td>
<td valign="top">
<pre class="brush: python; title: ;">
# Create a list of available feature classes
fcs = gp.ListFeatureClasses()
# Iterate through said feature classes
for fc in fcs:
    # Do work here
</pre>
</td>
</tr>
<tr>
<td>
<pre class="brush: python; title: ;">
# Identify the fields of a feature class
dsc = gp.describe(fc)
# Get the fields from the description
flds = dsc.Fields
# Iterate through the fields
flds.Reset()
field = flds.Next()
while field:
    # Do work here
    field = flds.Next()
</pre>
</td>
<td valign="top">
<pre class="brush: python; title: ;">
# Identify the files of a feature class
dsc = gp.describe(fc)
# Get the fields from the description
flds = dsc.Fields
# Iterate through the fields
for field in flds:
    # Do work here
</pre>
</td>
</tr>
<tr>
<td>
<pre class="brush: python; title: ;">
# Tell the geoprocessor to overwrite output by default.
gp.OverWriteOutput = 1
</pre>
</td>
<td>
<pre class="brush: python; title: ;">
# Tell the geoprocessor to overwrite output by default
gp.OverWriteOutput = True
</pre>
</td>
</tr>
</tbody>
</table>
<p>There is not list of commands that need the changes to the best of my knowledge. But a quick look through the <a href="http://webhelp.esri.com/arcgisdesktop/9.2/pdf/Geoprocessor.pdf">Geoprocessor Programming Model for ArcGIS 9.2</a> can show which methods return an enumeration unit. In brief, ListDatasets, ListFeatureClasses, ListRasters, ListTables, ListWorkspaces, ListEnvironments, ListToolboxes, ListTools and all other methods that return an Array Object. For a complete listing of the changes, please read the ESRI document for <a href="http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Differences_between_geoprocessor_versions">Geoprocessor changes in 9.3</a>.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/' rel='bookmark' title='Permanent Link: Geoprocessing Iteration with Python'>Geoprocessing Iteration with Python</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/07/python-geoprocessing-in-arcgis-9-2-vs-9-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Geoprocessing Iteration with Python</title>
		<link>http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/</link>
		<comments>http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/#comments</comments>
		<pubDate>Fri, 12 Jun 2009 02:05:05 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[iteration]]></category>
		<category><![CDATA[ListDatasets]]></category>
		<category><![CDATA[ListFeatureClasses]]></category>
		<category><![CDATA[ListWorkspaces]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/teaching/36-pygeoprocessing/56-geoprocessing-iteration-with-python</guid>
		<description><![CDATA[There are multiple problems analysts face when they have to deal with processing multiple data files. There is the issue of identifying similarities and commonalities in files, and then of course how to automate the processing so they don&#8217;t have to run a program multiple times with the same parameters of separate files. In the <a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/' rel='bookmark' title='Permanent Link: Using the geoprocessor&#8217;s List* Methods'>Using the geoprocessor&#8217;s List* Methods</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>There are multiple problems analysts face when they have to deal with processing multiple data files. There is the issue of identifying similarities and commonalities in files, and then of course how to automate the processing so they don&#8217;t have to run a program multiple times with the same parameters of separate files. In the world of ESRI&#8217;s GIS analysis, this can be performed quite easily with the help of Geoprocessing, either in Python or the Model Builder. Below is sample code that allows the iteration over a number of datasets.<span id="more-18"></span></p>
<p>Geoprocessing in Python provides multiple methods that can help one iterate. Depending on the dataset types you have, you can access list of data easily and effortlessly. The following code will show you how this is done in version 9.3, although earlier versions are as easy to use as well.</p>
<p>In order to iterate a process, we need a list of files we will use, and then a series of commands to be run on those files. There are multiple ways to achieve this through the operating system (os and sys modules), but since we do have that pesky little problem of shapefiles having multiple files associated with them, or geodatabases being a single representation for the OS, we need a different solution. And here lies the power of the geoprocessor. It allows one to list data the way ESRI can recognize them: workspaces, (feature) datasets, feature classes, tables and rasters. So let&#8217;s begin.</p>
<p>Oftentimes, analysts store data in folders. If you are conducting a study in 10 different regions, it is often the case you save the data files for each region in a different folder. A folder structure like the following is common:</p>
<ul>
<li>\myStudy\</li>
<li>\myStudy\region1\</li>
<li>\myStudy\region2\</li>
<li>\myStudy\region3\</li>
<li>&#8230;</li>
</ul>
<p>We therefore need a method that allows us to go into the master folder (\myStudy\ in this case) and read the files in each folder. To achive this, we will read the names of folders first. The command <strong>ListWorkspaces(widcard, type)</strong> can help us do that, by accepting a wildcard as a first argument (any combination of * can help narrow things down) and the type of workspace we want (from Access, Coverage, FileGDB Folder, SDE or ALL). An example follows:</p>
<pre class="brush: python; title: ;">
import arcgisscripting # Import the geoprocessor capabilities
gp = arcgisscripting.create(9.3) # Create the geoprocessor object
masterFolder = r&quot;path\to\folder&quot; # Define the master folder
gp.workspace = masterFolder # Define the location to run the commands on
workspaces = gp.ListWorkspaces(&quot;*&quot;, &quot;Folder&quot;) # List all FOLDERS in master workspace
for workspace in workspaces: # Iterate through the workspaces one at a time
print workspace # Print the workspace name
# Do you work here
</pre>
<p>At this point, you have a Python list object that holds the names of all the subfolders that you may want to use. The next step is to identify a list of all data within that folder. To achieve that, we use one of the following commands, depending on the type of data we have: <strong>ListDatasets(wildcard, type)</strong>, <strong>ListFeatureClasses(wildcard, type)</strong>, <strong>ListTables(wildcard, type)</strong> or <strong>ListRasters(wildcard, type)</strong>. The wildcard is defined as above, but the type is different. Type actually refers to the type of listing. For datasets, the type is feature,TIN, raster, CAD or ALL. For feature classes the types are Annotation, arc, dimension, label, line, node, point, polygon, region, route or tic. Table types can be DBF, INFO or ALL. Similarly, raster types can be BMP, GIF, IMG, JP2, JPG, PNG, TIFF, GRID or ALL. We will contnue our example by searching for feature classes (shapefiles) in the folders we identified above.</p>
<pre class="brush: python; title: ;">
import arcgisscripting # Import the geoprocessor capabilities
gp = arcgisscripting.create(9.3) # Create the geoprocessor object
masterFolder = r&quot;path\to\folder&quot; # Define the master folder
gp.workspace = masterFolder # Define the location to run the commands on
workspaces = gp.ListWorkspaces(&quot;*&quot;, &quot;Folder&quot;) # List all FOLDERS in master workspace
for workspace in workspaces: # Iterate through the workspaces one at a time
gp.workspace = workspace # Change to the new workspace
fcs = gp.ListFeatureClasses() # No parameter defaults to all
for fc in fcs: # Iterate through each file in the folder now
print fc # print the feature class
# Do individual file work here
</pre>
<p>As you can see we managed to begin with a master folder and continue to analyze individual files within all subfolders of the initial master folder. This is all done in a few lines of code, minimize complexity and confussion for us. In less that 6 lines of Python code you can begin processing each file in your computer quickly and easily.</p>
<p>While listing of other types of files has not been shown, it is quite easy to do by using the appropriate command (as mentioned above). Dealing with databases is similar, as you can imagine and use the database as your master folder. Do not forget that &#8220;subfolders&#8221; in the database are called datasets, so you will need to use ListDatasets() instead of ListWorkspaces().</p>
<p>I hope this will be useful to some of you out there.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/' rel='bookmark' title='Permanent Link: Using the geoprocessor&#8217;s List* Methods'>Using the geoprocessor&#8217;s List* Methods</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>MakeFeatureLayer in Python</title>
		<link>http://michalisavraam.org/2009/06/makefeaturelayer-in-python/</link>
		<comments>http://michalisavraam.org/2009/06/makefeaturelayer-in-python/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 04:11:11 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[geodatabase]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[MakeFeatureLayer]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[registry fix]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/teaching/36-pygeoprocessing/55-makefeaturelayer-in-python</guid>
		<description><![CDATA[In the many methods present at the Python interface to ArcGIS (Python geoprocessing through the arcgisscripting module), one that is quite useful when processing individual elements on a feature class is called MakeFeaturelayer(). The behavior, while predictable with a small number of runs, can prove problematic when dealing with large datasets. ESRI apparently recognizes this <a href='http://michalisavraam.org/2009/06/makefeaturelayer-in-python/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/' rel='bookmark' title='Permanent Link: Geoprocessing Iteration with Python'>Geoprocessing Iteration with Python</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>In the many methods present at the Python interface to ArcGIS (Python geoprocessing through the arcgisscripting module), one that is quite useful when processing individual elements on a feature class is called MakeFeaturelayer(). The behavior, while predictable with a small number of runs, can prove problematic when dealing with large datasets.<span id="more-17"></span></p>
<p>ESRI apparently recognizes this issue, and has produced a Technical Article for it (<a title="ESRI Technical Article on MakeFeatureLayer" href="http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&amp;d=22668">#22668</a>) that discusses the issue when people use enterprise geodatabases. I was running up the same problem though myself when dealing with a personal geodatabase (Jet Engine). Here is what I was trying to do (in Python):</p>
<ol>
<li>Read the results of the OD Matrix (origin destination matrix)</li>
<li>When one record is read, do the following:
<ol>
<li> Extract information about source ID and destination ID</li>
<li>Using MakeFeatureLayer with a query, built two layers (one for origins, one for destinations)</li>
<li>Run a network Route solution based on the two files</li>
<li>Store the resulting route into a feature class collecting them all</li>
</ol>
</li>
</ol>
<p>Now, while this may sound simple (and also makes people wonder why ESRI does not give the option of presenting the actual route with the OD Matrix command), there are problems. What I noticed was that the results of MakeFeatureLayer were inconsistent through the loop. Always, when reaching a specific OD Matrix record, the command returned an empty feature layer. This was happening 48 times over my 393 routes, so it was bothering me.</p>
<p>Searching through the excellent <a title="ESRI Support Portal" href="http://support.esri.com/">ESRI Support</a> site,  I found a <a title="Forum posting about MakeFeatureLayer" href="http://forums.esri.com/Thread.asp?c=93&amp;f=1729&amp;t=280014">Forum Posting</a> describing similar problems, which also referenced Technical Article #22668 (link above). The technical article though mentions that the problem is only exhibited with enterprise level geodatabases (in essense, the memory the command has to store these is limited, so it saves things to the database, which the command isn&#8217;t aware of). I thought I should give it a try, and to my amazement, it worked wonders. I used the value they recommended to change and I had only 8 unsolvable routes (6 times less than before!). Increasing the value slightly yielded only 6 unsolvable routes, so this seems promising.</p>
<p>The details on what one is to do are mentioned in the technical article, and recreated here for your convenience. Please remember to backup before these changes, and don&#8217;t forget that messing with the registry can mess with your operating system.</p>
<ol>
<li>Use regedit and open the <em>HKEY_CURRENT_USER</em> registry entry.</li>
<li>Navigate to the <em>Software</em> key</li>
<li>Expand the <em>ESRI</em> Key</li>
<li>Open the <em>Geodatabase</em> Key (if it does not exist, simply right-click on <em>ESRI</em> and create a new one)</li>
<li>Expand the <em>Settings</em> Key (or create it if not present)</li>
<li>Add a DWORD value called <em>SelectionThreshold</em> if not already present.</li>
<li>Enter a new value, in decimal base, of 5000 (ESRI recommendation, I used 7000 myself)</li>
<li>Close regedit and you are done.</li>
</ol>
<p>I hope someone else finds this useful out there.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/' rel='bookmark' title='Permanent Link: Geoprocessing Iteration with Python'>Geoprocessing Iteration with Python</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/06/makefeaturelayer-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Accessing Geometries using the Geoprocessor (Updated)</title>
		<link>http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/</link>
		<comments>http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 09:01:13 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[cursor]]></category>
		<category><![CDATA[feature class]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[InsertCursor]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[searchCursor]]></category>
		<category><![CDATA[shape]]></category>
		<category><![CDATA[UpdateCursor]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/teaching/36-pygeoprocessing/49-accessing-geometries-using-the-geoprocessor</guid>
		<description><![CDATA[Accessing Geometries using the Geoprocessor is an easy task when one uses Python. All you need is a cursor to a feature class and you are there. Some terminology may help, before we dive into the code. Geometry: A geometry in this case is the geographical representation of an object as a point, or line, <a href='http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/' rel='bookmark' title='Permanent Link: Understanding the Geoprocessor Programming Model part 2'>Understanding the Geoprocessor Programming Model part 2</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Accessing Geometries using the Geoprocessor is an easy task when one uses Python. All you need is a cursor to a feature class and you are there. Some terminology may help, before we dive into the code. <span id="more-25"></span></p>
<p><em><strong><img class="alignright size-medium wp-image-37" title="featureClassToGeometry" src="http://michalisavraam.org/wp-content/uploads/2009/02/featureClassToGeometry-272x300.png" alt="featureClassToGeometry" width="272" height="300" />Geometry</strong>:</em> A geometry in this case is the geographical representation of an object as a point, or line, or polygon.<br />
<strong><em>Feature Class</em>:</strong> Many people get confused by the term. In essence, if you are in the shapefile world, this would be your shapefile. If you are using geodatabases, a feature class is a collection of objects. In both cases, it is a collection of features.<br />
<strong><em>Feature</em></strong>: A feature is the digital representation of an object in the real world using a vector-based data type. For example, a tree can be a point, a road can be a line, countries would be polygons. Each tree would be a feature, as would each roads, etc. Features have both a spatial representation as well as an attribute representation (think of the object in the world and its properties).<br />
<strong><em>Cursor</em></strong>: A cursor is an object that provides us access to a feature class. In other worlds, it is our way to communicate with a feature class through our programming language (Python). There are three types of cursors: Search (only reads feature classes), Insert (only adds features) and Update (can update or delete a feature).</p>
<p>Accessing geometries then, from the above definitions, would require us to (1) create a cursor to a feature class, (2) find the feature we want to read the geometry of, and (3) read the actual geometry. In reverse order, you may want to think of it this way: a geometry belongs to a specific feature, which belongs to a feature class, which is accessible through a cursor. Similarly, our Python code would do something similar, as shown below (only reads a geometry object):</p>
<pre class="brush: python; title: ;">

import arcgisscripting # Import the geoprocessor capabilities
gp = arcgisscripting.create(9.3) # Create the geoprocessor object
featureClassToRead = r&amp;quot;path\to\file&amp;quot; # Define the feature class to read
searchCursor = gp.SearchCursor(featureClassToRead) # Create a SEARCH cursor
feature = searchCursor.Next() # Grab the first feature (row) from the feature class
featureGeometry = feature.shape # Grab the feature's geometry object </pre>
<p>After importing (line 1) and initializing (line 2) the geoprocessor, we create a search cursor (line 4) that pointed to our feature class. Within the cursor, we requested the first feature (line 5) and proceeded retrieving the feature&#8217;s geometry (line 6).</p>
<p>All other cursors will use a very similar approach. The difference will be line 4, in which we run the method that creates a cursor. If there is a need for an Insert cursor, you would run the InsertCursor command, or the UpdateCursor if you need the update cursor. With each cursor, you grab the first feature (row) and then manipulate it by accessing its individual variable (one of which is the geometry, called <em>Shape</em>).</p>
<p>Another important element is how one accesses the geometry. While there is no problem accessing the geometry by requesting the .shape variable present in each feature, this changes depending on your use of a shapefile or a geodatabase. To solve this problem, you can use the feature class description, and retrieve its .ShapeFieldName parameter. This is shown below:</p>
<pre class="brush: python; title: ;">
import arcgisscripting # Import the geoprocessor capabilities
gp = arcgisscripting.create(9.3) # Create the geoprocessor object
featureClass = &amp;quot;path\to\file&amp;quot; # Define the feature class to describe
description = gp.Describe(featureClass) # Call the Describe function
shapeFieldName = description.ShapeFieldName # Grab the parameter and save it
searchCursor = gp.SearchCursor(featureClass) # Create a new search cursor
feature = searchCursor.Next() # Grab the first feature
featureGeometry = feature.GetValue(shapeFieldName) # Grab the feature's geometry</pre>
<p>You would  now receive the geometry object, as with the sample code above, independent of the type of file you are reading.</p>
<p>Of course, we rarely need to read only the very first feature of a feature class. An easy method to read each feature is using a while loop, as follows:</p>
<pre class="brush: python; title: ;">
import arcgisscripting # Import the geoprocessor capabilities
gp = arcgisscripting.create(9.3) # Create the geoprocessor object
featureClass = &amp;quot;path\to\file&amp;quot; # Define the feature class to describe
description = gp.Describe(featureClass) # Call the Describe function
shapeFieldName = description.ShapeFieldName # Grab the parameter and save it
searchCursor = gp.SearchCursor(featureClass) # Create a new search cursor
feature = searchCursor.Next() # Grab the first feature
while feature: # Create a loop that runs while we have features
# Work with the feature here
feature = searchCursor.Next() # Grab the next feature in feature classs</pre>
<p>This take advantage of the fact that the geoprocessor will return a None object when we reach the end of the feature class, which would let the loop know we are done.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/' rel='bookmark' title='Permanent Link: Understanding the Geoprocessor Programming Model part 2'>Understanding the Geoprocessor Programming Model part 2</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

