0% found this document useful (0 votes)
16 views95 pages

Prueba 4

Uploaded by

Félix Martin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views95 pages

Prueba 4

Uploaded by

Félix Martin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 95

What is Python?

Page 1 of 95

What is Python?
ArcGIS 10.8

Locate topic

Python is a free, cross-platform, open-source programming language that is both powerful and easy to
learn. It is widely used and supported. To learn more about Python, visit python.org.
Python was introduced to the ArcGIS community at 9.0. Since then, it has been accepted as the scripting
language of choice for geoprocessing users and continues to grow. Each release has furthered the Python
experience, providing you with more capabilities and a richer, more Python-friendly experience.
ESRI has fully embraced Python for ArcGIS and sees Python as the language that fulfills the needs of our
user community. Here are just some of the advantages of Python:
l Easy to learn and excellent for beginners, yet superb for experts
l Highly scalable, suitable for large projects or small one-off programs known as scripts
l Portable, cross-platform
l Embeddable (making ArcGIS scriptable)
l Stable and mature
l A large user community
Python extends across ArcGIS and becomes the language for data analysis, data conversion, data
management, and map automation, helping increase productivity.

Learning Python
The information contained here is not a Python language reference. Certain Python syntax and
behavior are explained with respect to examples and concepts used to demonstrate how to write a
geoprocessing script.
A suitable Python reference book is strongly recommended to augment the information you find here.
For Python beginners, Learning Python by Mark Lutz and David Ascher, published by O’Reilly &
Associates, and Core Python Programming by Wesley J. Chun, published by Prentice Hall, are both
good introductions to the language and are not overwhelming in scope. There are many other books on
Python and its particular uses, with new ones being released regularly, so explore what is available.
The Python Web site has full documentation for Python, but it is concise and developer oriented. There
is a large online Python community with many online resources that are accessible from the Python
home page.

Python tutorials
If you're new to Python, the external tutorials listed here are recommended for you.
l Python Tutorial is part of Python's own documentation.
l Python for Non-Programmers provides tutorials for those with limited programming experience.
l Python Language Reference describes the syntax and semantics of Python.

Python tutorials for programmers


The external tutorials listed here are aimed at those who have previous experience with other
programming languages (Perl, Visual Basic, C).
l Python Tutorial is part of Python's own documentation.
l Python for Programmers provides tutorials for those with experience in other programming
languages.

Related topics

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 2 of 95

Essential Python vocabulary


A quick tour of Python
What is ArcPy?
What is the Python window?

Copyright © 1995-2019 Esri. All rights reserved.

Essential Python vocabulary

Locate topic

This document introduces some vocabulary that is essential to understanding geoprocessing with Python
help.

Term Description

Python Python is an open-source programming language that was conceived in the late
1980s by Guido van Rossum and introduced in 1991. It was first incorporated with
ArcGIS 9.0 and has since become the preferred choice for users creating
geoprocessing workflows.
Python is supported by a growing and varied user community and provides easy
readability, clean syntax, dynamic typing, and an extensive collection of standard and
third-party libraries.

ArcPy ArcPy (often referred to as the ArcPy site package) provides Python access for all
geoprocessing tools, including extensions, as well as a wide variety of useful functions
and classes for working with and interrogating GIS data. Using Python and ArcPy, you
can develop an infinite number of useful programs that operate on geographic data.

ArcPy A module is a Python file that generally includes functions and classes. ArcPy is
modules supported by a series of modules, including a data access module (arcpy.da),
mapping module (arcpy.mapping), an ArcGIS Spatial Analyst extension module
(arcpy.sa), and an ArcGIS Network Analyst extension module (arcpy.na).

ArcPy A class is analogous to an architectural blueprint. The blueprint provides the


classes framework for how to create something. Classes can be used to create objects, often
referred to as an instance. ArcPy classes, such as the SpatialReference and Extent
classes, are often used as shortcuts to complete geoprocessing tool parameters that
would otherwise have a more complicated string equivalent.

ArcPy A function is a defined bit of functionality that does a specific task and can be
functions incorporated into a larger program.
In ArcPy, all geoprocessing tools are provided as functions, but not all functions are
geoprocessing tools. In addition to tools, ArcPy provides a number of functions to
better support geoprocessing Python workflows. Functions (often referred to as
methods) can be used to list certain datasets, retrieve a dataset's properties, validate
a table name before adding it to a geodatabase, or perform many other useful
scripting tasks.

Stand- A stand-alone Python script is a .py file that can be executed from the operating
alone system prompt, a Python Integrated Development Environment (IDE), or by double-
Python clicking the .py file in Windows Explorer.
script

Python A Python script tool is a Python script that has been added to a geoprocessing
script tool toolbox. Once added as a script tool, the script tool becomes like any other
geoprocessing tool—it can be opened and executed from the tool dialog box, used in
the Python window and ModelBuilder, and called from other scripts and script tools.

Python The Python window is a quick and convenient place to use Python from within ArcGIS
window to interactively run geoprocessing tools and functionality as well as take advantage of
other Python modules and libraries. This window also provides a gateway for you to
learn Python.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 3 of 95

The Python window can be used to execute a single line of Python code, with the
resulting messages printed to the window. It is a useful place to experiment with
syntax and work with short lengths of code and provides an opportunity to test your
ideas outside a larger script.

Python A Python add-in is a customization written in Python, such as a collection of tools on a


add-in toolbar, that plugs into an ArcGIS Desktop application that provides supplemental
functionality for accomplishing custom tasks. To clarify the development of Python
add-ins, you must download and use the Python Add-In Wizard to declare the type of
customization. The wizard will generate all the required files necessary for the add-in
to work. Click here to download the Python Add-In Wizard from the Geoprocessing
Resource Center.

Python Python toolboxes are geoprocessing toolboxes that are created entirely in Python. A
toolbox Python toolbox and the tools contained within look, act, and work just like toolboxes
and tools created in any other way.
A Python toolbox (.pyt) is an ASCII-based file that defines a toolbox and one or more
tools.

Related topics
What is Python?
A quick tour of Python

Copyright © 1995-2019 Esri. All rights reserved.

A quick tour of Python

Locate topic

Python is an open-source, general-purpose programming language used as a scripting language in ArcGIS


geoprocessing. Geoprocessing functionality is accessible through Python using ArcGIS software's ArcPy
site-package. ArcPy provides access to geoprocessing tools as well as additional functions, classes, and
modules that allow you to create simple or complex workflows quickly and easily.
ArcGIS applications and scripts written using ArcPy benefit from being able to access and work with the
numerous Python modules developed by GIS professionals and programmers from many different
disciplines. The additional power of using ArcPy within Python is the fact that Python is a general-purpose
programming language that is easy to learn and use. It is interpreted and dynamically typed, which
provides you with the ability to quickly prototype and test scripts in an interactive environment while still
being powerful enough to support the writing of large applications.
Broadly speaking, ArcPy is organized in tools, environments, functions, classes, and modules.

Running a tool
This next example shows how to execute the Buffer tool. As the tool executes, the messages will
appear by default on the right side of the Python window in the help section.

>>> arcpy.Buffer_analysis("c:/data/Portland.gdb/streets", "c:/data/Portland.gdb/steets_buf


 
Here is another example of running tools. This example uses tools in the data management and
conversion toolboxes. A field is added to the input streets feature class, the field is calculated, and the
feature class is then loaded into an enterprise geodatabase.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 4 of 95

>>> import arcpy


>>> arcpy.AddField_management("c:/data/Portland.gdb/streets", "LENGTH_MILES", "TEXT")
>>> arcpy.CalculateField_management("c:/data/Portland.gdb/streets", "LENGTH_MILES", "!shap
>>> arcpy.FeatureClassToFeatureClass_conversion("c:/data/Portland.gdb/streets", "Database
 
Learn more about using tools in Python

Getting results from a tool


When a geoprocessing tool is executed, the results of the tool are returned in a Result object.
Typically, this object is the path to the output dataset produced or updated by the tool. In other
cases, it may contain other value types, such as a number or Boolean. If an output for a tool is a
multivalue parameter, the values can be returned as a list within a list.
The following code examples show how return values are captured and what their values could be:
Return the path of the output feature class. The result can be used as input to another function.

>>> result = arcpy.Buffer_analysis("rivers", "riverBuf", "50 METERS")


>>> print result
C:\Portland\Portland_OR.gdb\riverBuf
>>> arcpy.Clip_analysis("streets", result, "streets_50m_of_rivers")

Return the number of features.

>>> result = arcpy.GetCount_management("streets_50m_of_rivers")


>>> print result.getOutput(0)
54

Return a list of default spatial grid indexes for a feature class.

>>> result = arcpy.CalculateDefaultGridIndex_management("streets_50m_of_rivers")


>>> for i in range(0, result.outputCount):
... print result.getOutput(i)
...
560
200
0
 
Using environment settings
Geoprocessing environment settings can be thought of as additional parameters that affect a tool's
results. They differ from normal tool parameters in that they are set separately from the tool and are
interrogated and used by tools when they are run. Environment settings, such as an area of interest,
the coordinate system of the output dataset, and the cell size of a new raster dataset, can all be
specified and honored by the tools.
Environment settings are available from the env class as properties. These properties can be used to
retrieve the current environment values and set them. Below are examples of how to use environment
values:

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 5 of 95

Set the workspace environment.

>>> arcpy.env.workspace = "c:/data/Portland.gdb"


>>> arcpy.Buffer_analysis("streets", "streetBuf", "500 METERS")

Set the spatial grid index to the return value of a tool.

>>> arcpy.env.spatialGrid1 = arcpy.CalculateDefaultSpatialGridIndex_management("streets").


 
Get the current raster cell size setting and make sure it is a specific size for standard output.

if arcpy.env.cellSize != 30:
arcpy.env.cellSize = 30

Learn more about using environment settings in Python

Using functions
A function is a defined bit of functionality that does a specific task and can be incorporated into a larger
program. In addition to tools, ArcPy exposes a number of functions to better support geoprocessing
workflows. Functions can be used to list certain datasets, retrieve a dataset's properties, check for
existence of data, validate a table name before adding it to a geodatabase, or perform many other
useful scripting tasks.
The example code below shows getting the properties of data and checking out an extension:

import arcpy

# prints True
print arcpy.Exists("c:/data/Portland.gdb/streets")

# prints NAD_1983_StatePlane_Oregon_North_FIPS_3601_Feet
sr = arcpy.Describe("c:/data/Portland.gdb/streets").spatialReference
print sr.name

# prints Available
print arcpy.CheckExtension("spatial")

arcpy.CheckOutExtension("spatial")

Learn more about using functions in Python

Using classes
ArcPy classes, such as the SpatialReference and Extent classes, are often used as shortcuts to
complete geoprocessing tool parameters that would otherwise have a more complicated string
equivalent. A class is analogous to an architectural blueprint. The blueprint provides the framework for
how to create something. Classes can be used to create objects; this is often referred to as an

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 6 of 95

instance.

import arcpy

spatial_ref = arcpy.SpatialReference("Hawaii Albers Equal Area Conic")

Learn more about using classes in Python

Working with modules


ArcPy includes modules covering other areas of ArcGIS. ArcPy is supported by a series of modules,
including a data access module (arcpy.da), a mapping module (arcpy.mapping), an ArcGIS Spatial
Analyst extension module (arcpy.sa), and an ArcGIS Network Analyst extension module (arcpy.na).
For example, the tools of the arcpy.sa module use tools in the Spatial Analyst toolbox but are
configured to support Map Algebra. Thus, executing arcpy.sa.Slope is the same as executing the
Slope tool from the Spatial Analyst toolbox.

Related topics
What is Python?
Essential Python vocabulary

Copyright © 1995-2019 Esri. All rights reserved.

Importing ArcPy

Locate topic

ArcGIS 10 introduced ArcPy, a Python site package that encompasses and further enhances the
arcgisscripting module introduced at ArcGIS 9.2. ArcPy provides a rich and dynamic environment for
developing Python scripts while offering code completion and integrated documentation for each function,
module, and class.
ArcGIS applications and scripts written using ArcPy benefit from being able to access and work with the
numerous Python modules developed by GIS professionals and programmers from many different
disciplines. The additional power of using ArcPy within Python is the fact that Python is a general-purpose
programming language that is easy to learn and use. It is interpreted and dynamically typed, which
provides you with the ability to quickly prototype and test scripts in an interactive environment while still
being powerful enough to support the writing of large applications.

# Importing arcpy
#
import arcpy

# Set the workspace environment and run Clip_analysis


arcpy.env.workspace = "C:/Data/Tongass"
arcpy.Clip_analysis("standb4", "clipcov", "standby_clip", "1.25")

Once you have imported ArcPy, you can run all geoprocessing tools found in the standard toolboxes
installed with ArcGIS:
Analysis toolbox

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 7 of 95

Cartography toolbox
Conversion toolbox
Data Management toolbox
Editing toolbox
Geocoding toolbox
Linear Referencing toolbox
Multidimension toolbox
Spatial Statistics toolbox

Importing modules
A module is a Python file that generally includes functions and classes. ArcPy is supported by a series
of modules, including a data access module (arcpy.da), mapping module (arcpy.mapping), an ArcGIS
Spatial Analyst extension module (arcpy.sa), and an ArcGIS Network Analyst extension module
(arcpy.na).
To import an entire module, use the import module:

# Import only arcpy.mapping


#
import arcpy.mapping

Of course, Python has many other core and third-party modules. If you wanted to also work with
Python's core os and sys modules, you might use a similar import:

# Import arcpy, os and sys


#
import arcpy
import os
import sys

In many cases, you might not plan or need to use the entire module. One way to import only a portion
of a module is to use a from-import statement. The below example imports the env class (the env
class contains all the geoprocessing environments). Now, instead of having to access environments as
arcpy.env, you can simplify it as env.

# Import env from arcpy and set the workspace environment


#
from arcpy import env
env.workspace = "c:/data"

Following the same thought process, sometimes you might want to draw attention to what a module or
part of a module is identified as to make your script more readable, or perhaps the default name is just
too long for your preferences. In any of these cases, you can use the form from-import-as. Like the
previous example, the below example also imports the env class but assigns it the name ENV:

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 8 of 95

# Import env from arcpy as ENV and set the workspace environment
#
from arcpy import env as ENV
ENV.workspace = "c:/data"

You could import the mapping module in the same fashion:

# Import the mapping module from arcpy as MAP and create a MapDocument
# object
#
from arcpy import mapping as MAP
mxd = MAP.MapDocument("C:/maps/basemap.mxd")

Another version of importing is the form from-import-*. The contents of the module are imported
directly into the namespace, meaning you can then use all those contents directly without needing to
prefix them. For example:

# Import management from arcpy as *


#
from arcpy.management import *

However, there are some risks associated with this approach. Other objects, variables, modules, and
so forth, with the same name will be overwritten, not to mention that with large modules, your
namespace can become particularly crowded and busy. Think about it this way: In the following
example, both the management and analysis module are being imported as *. Both of these modules
have a Clip tool. If you now try to use Clip, which Clip are you actually using? The answer is the second
one, but this approach can lead to uncertainty and difficulty in reading the script.

# Import the management and analysis modules from arcpy as *


#
from arcpy.management import *
from arcpy.analysis import *

# Which Clip is it?


#
Clip("standb4", "clipcov", "standby_clip", "1.25")

However, in some cases, from-import-* can simplify your code, as in the case of the ArcGIS Spatial
Analyst extension's sa module. One of the benefits of the sa module is that you can nest multiple
classes and functions in a single line to produce an output raster object.

License: Both of the following samples require the ArcGIS Spatial Analyst
extension to run.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 9 of 95

# Import arcpy and the sa module as *


#
import arcpy
from arcpy.sa import *

arcpy.CheckOutExtension("spatial")

# Get input parameters


#
inRaster1 = arcpy.GetParameterAsText(0)
inRaster2 = arcpy.GetParameterAsText(1)
inRaster3 = arcpy.GetParameterAsText(2)

outRaster = (Raster(inRaster1) + (Raster(inRaster2) - Raster(inRaster3)))


 
Now compare the next code block, which uses the conventional import-from statement. Now imagine
adding a few more classes and functions into the code—the simple addition of sa. for every function
and class adds up quickly, disrupting the readability and adding more bulk to the line.

# Import arcpy and the sa module


#
import arcpy
from arcpy import sa

arcpy.CheckOutExtension("spatial")

# Get input parameters


#
inRaster1 = arcpy.GetParameterAsText(0)
inRaster2 = arcpy.GetParameterAsText(1)
inRaster3 = arcpy.GetParameterAsText(2)

outRaster = (sa.Raster(inRaster1) + (sa.Raster(inRaster2) - sa.Raster(inRaster3


 
Paths and import
When using an import statement, Python looks for a module matching that name in the following
locations (and in the following order):
1. Paths specified in the PYTHONPATH system environment variable
2. A set of standard Python folders (the current folder, c:\python2x\lib,
c:\python2x\Lib\site-packages, and so on)
3. Paths specified inside any .pth file found in 1 and 2

For more information on this, see the following: https://docs.python.org/install/index.html#modifying-


python-s-search-path.
The installation of ArcGIS 10.8 products will install Python 2.7 if it isn't already installed. The
installation will also add the file Desktop10.3.pth (or Engine10.3.pth or Server10.3.pth) into python27
\Lib\site-packages. The contents of this file include two lines containing the paths to your system's
ArcGIS installation's arcpy and bin folders. These two paths are required to import ArcPy successfully in
Python version 2.7.
When using an import statement, Python refers to your system's PYTHONPATH environment variable to

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 10 of 95

locate module files. This variable is set to a list of directories.

Tip: If importing ArcPy produces either of the following errors, the required
modules could not be found:
l ImportError: No module named arcpy
l ImportError: No module named arcgisscripting
To address this, browse using Windows Explorer to the python27
\Lib\site-packages folder and add or edit the Desktop10.3.pth file.
The file should contain the three lines shown below (corrected to your
system's path if they do not match):

c:\Program Files\ArcGIS\Desktop10.3\arcpy
c:\Program Files\ArcGIS\Desktop10.3\bin
c:\Program Files\ArcGIS\Desktop10.3\ArcToolbox\Scripts
 

Related topics
What is ArcPy?

Copyright © 1995-2019 Esri. All rights reserved.

Using tools in Python

Locate topic

A geoprocessing tool has a fixed set of parameters that provide the tool with the information required for
execution. Tools usually have input parameters that define the dataset or datasets that are typically used
to generate new output data. Parameters have several important properties:
l Each parameter expects a specific data type or data types, such as feature class, integer, string, or
raster.
l A parameter expects either an input or output value.
l A parameter either requires a value or is optional.
l Each tool parameter has a unique name.
When a tool is used in Python, its parameter values must be correctly set so it can execute when the
script is run. Once a valid set of parameter values is provided, the tool is ready to be executed.
Parameters are specified as either strings or objects.
Strings are text that uniquely identifies a parameter value, such as a path to a dataset or a keyword. In
the following code example, input and output parameters are defined for the Buffer tool. Note that the
tool name is appended with its toolbox alias. In the example, two string variables are used to define the
input and output parameters to make the call to the tool easier to read.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 11 of 95

import arcpy

roads = "c:/base/data.gdb/roads"
output = "c:/base/data.gdb/roads_Buffer"

# Run Buffer using the variables set above and pass the remaining
# parameters in as strings
arcpy.Buffer_analysis(roads, output, "distance", "FULL", "ROUND", "NONE")

For some parameters, such as a spatial reference, an object can also be specified. In the following code
example, the Create Feature Class tool is executed using a SpatialReference object for its optional
Coordinate System parameter.

import arcpy

in_workspace = "c:/temp"
output_name = "rivers.shp"

# Create a spatial reference object


spatial_ref = arcpy.SpatialReference('North America Equidistant Conic')

# Run CreateFeatureclass using the spatial reference object


arcpy.CreateFeatureclass_management(
in_workspace, output_name, spatial_reference=spatial_ref)

Most geoprocessing tools include both required and optional arguments. Oftentimes there are cases in
which there are many optional arguments that don't need to be specified. There are a couple of strategies
for dealing with these unused arguments. One is to keep all optional arguments in order, and reference
those you don't need as either an empty string "", a pound sign "#", or with a None type. A second
strategy is to use keyword arguments and use the argument name to assign a value. Using keyword
arguments allows you to skip unused optional arguments or specify them in different orders.
Skipping optional arguments using empty strings.

import arcpy
arcpy.AddField_management("schools", "school_id", "LONG", "", "", "", "", "NON_NULLABLE"
 
A better alternative; skipping optional arguments using keyword arguments.

import arcpy
arcpy.AddField_management("schools", "school_id", "LONG", field_is_nullable
 
Tool output
ArcPy returns the output values of a tool when it is executed as a Result object. The advantage of a
result object is that you can maintain information about the execution of tools, including messages,
parameters, and output. These results can be maintained even after several other tools have been run.
The following examples show how to get the output from a result object following the execution of a

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 12 of 95

geoprocessing tool.

import arcpy

arcpy.env.workspace = "c:/city/data.gdb"

# Geoprocessing tools return a result object of the derived output dataset.


result = arcpy.CopyFeatures_management("roads", "urban_roads")

# A print statement will display the string representation of the output.


print(result)

# A result object can be indexed to get the output value. Note: a result object
# also has a getOutput() method that can be used for the same purpose.
result_value = result[0]
 
When indexing the result object or using its getOutput() method, the return value is a string. This is
an important consideration when running a tool with a derived output parameter such as Get Count,
which provides a count of records in a table, or Calculate Default Cluster Tolerance, which provides a
cluster tolerance value. To convert to the expected type, built-in Python functions, such as int() or
float(), can be used.

Note: A derived parameter requires no interaction from the user and does
not show up on the tool dialog box or as an argument to the tool in
Python. Derived types are always output parameters.

import arcpy
import types

arcpy.env.workspace = "c:/base/data.gdb"

# Many geoprocessing tools return a result object of the derived output dataset.
result = arcpy.GetCount_management("roads")
result_value = result[0]

# 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(), float()
count = int(result_value)
print(count)
print(type(count))
 
If creating output that is just an intermediate stage in a larger workflow, the output argument can be
omitted to allow the tool to create a unique path and name for the output. This can be accomplished by
setting the output either to "#" or None, or if the output would be the last argument used, skip it
entirely. In each case, the returned value is the full path to the new datasource.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 13 of 95

import arcpy
arcpy.env.workspace = "c:/city/data.gdb"

result = arcpy.CopyFeatures_management("roads", "#")


result = arcpy.CopyFeatures_management("roads", "")
result = arcpy.CopyFeatures_management("roads")

Tool organization in ArcPy


Geoprocessing tools are organized in two ways. All tools are available as functions on ArcPy but are
also available in modules matching the toolbox alias name. Although most of the examples in the help
show tools organized as functions available from ArcPy, both approaches are equally valid. Which
approach you use will come down to a matter of personal preference and coding habits. In the
following example, the Get Count tool is shown using both approaches.

import arcpy

in_features = "c:/temp/rivers.shp"

# Tools can be accessed as functions on the arcpy module


arcpy.GetCount_management(in_features)

# Or from modules matching the toolbox name


arcpy.management.GetCount(in_features)

When using tools in modules, sometimes you may want to draw attention to how a module is identified
to make your script more readable. In this case, you can use the form from - import - as.

# Clean up street centerlines that were digitized without


# having set proper snapping environments
import arcpy
from arcpy import edit as EDIT
from arcpy import management as DM

streets = "c:/data/streets.gdb/majorrds"
streets_copy = "c:/output/Output.gdb/streetsBackup"

DM.CopyFeatures(streets, streets_copy)
EDIT.TrimLine(streets, "10 Feet", "KEEP_SHORT")
EDIT.ExtendLine(streets, "15 Feet", "EXTENSION")

License: Spatial Analyst tools are handled differently to accommodate Map


Algebra, and they are available only in the arcpy.sa module and not
as functions on ArcPy.

Related topics
Using functions in Python
Using classes in Python

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 14 of 95

A quick tour of geoprocessing tool references


Alphabetical list of ArcPy classes

Copyright © 1995-2019 Esri. All rights reserved.

Using geoprocessing services in Python

Locate topic

Like other geoprocessing tools, geoprocessing server tools have a fixed set of parameters that provide the
tool with the information it needs for execution. When using asynchronous server tools in a script, the
output can be retrieved by the Result's getOutput method.

Tip: The IsSynchronous function can be used to determine whether a tool is


run synchronously or asynchronously. When a tool is synchronous, the
results are automatically returned, but no other action may be taken
until the tool has completed.

In the following example, the GetParameterValue function is used to get a FeatureSet object from a
server tool. This FeatureSet object contains the schema of the tool's input parameter. The FeatureSet
object is then loaded with a feature class, and the server tool is executed on the server. The script ends
by using the result object's getOutput method to get the tool output's, which is then saved locally by
using the FeatureSet's save method.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 15 of 95

import arcpy
import time

# Add a toolbox from a server


#
arcpy.ImportToolbox("http://flame7/arcgis/services;GP/BufferByVal", "mytools"

# Use GetParameterValue to get a featureset object with the default


# schema of the first parameter of the tool 'bufferpoints'
#
inFeatureSet = arcpy.GetParameterValue("bufferpoints", 0)

# Load a shapefile into the featureset


#
inFeatureSet.load("c:/base/roads.shp")

# Run a server tool named BufferPoints with featureset created above


#
result = arcpy.BufferPoints_mytools(inFeatureSet, "5 feet")

# Check the status of the result object every 0.2 seconds until it has a value
# of 4 (succeeded) or greater
#
while result.status < 4:
time.sleep(0.2)

# Get the output FeatureSet back from the server and save to a local geodatabase
#
outFeatSet = result.getOutput(0)
outFeatSet.save("c:/temp/base.gdb/towers_buffer")
 
Getting a raster result from a server tool
Raster results are returned as Tagged Image File Format (TIFF). By default, when using getOutput,
the TIFF is written to your system's TEMP folder. To control the location of the TIFF, set the
scratchWorkspace environment to a folder.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 16 of 95

import arcpy
import time

# Set the scratchworkspace to a folder.


#
arcpy.env.scratchWorkspace = "c:/temp/rasteroutput"

# Add a toolbox from a server


#
arcpy.ImportToolbox("http://flame7/arcgis/services;SlopeByVal", "mytools")

dem = "c:/dems/k_ne_g"

# Run a server tool named RunSlope


#
result = arcpy.RunSlope_mytools(dem)

# Check the status of the result object every 0.2 seconds until it has a value
# of 4 (succeeded) or greater
#
while result.status < 4:
print result.status
time.sleep(0.2)

# Raster output will be written to the scratchworkspace


#
outTIFF = result.getOutput(0)
 
Getting a map image
Geoprocessing services can have a result map service to create a digital map image of task results.
Digital maps contain visual representations of geographic datasets that communicate information.
Digital maps are transported across the Web as images (such as a .jpeg). A map image, byte for byte,
contains far more human-interpretable information than raw features in a feature class. Map images
are also manageable—they are easily compressed, they can be tiled into manageable chunks, and
there are established methods for transporting and viewing them across the Web.
Map images are created by an ArcGIS Server map service and are the result of publishing an ArcMap
document (.mxd). Because of the characteristics of a map image, you may want to create one for the
results of your geoprocessing task and transport the image across the Web rather than transporting
the result dataset or datasets. Geoprocessing services can have a result map service used by ArcGIS
Server to create map images of your output data.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 17 of 95

import arcpy
import time
import urllib

# Add a toolbox from a server


#
arcpy.ImportToolbox("http://flame7/arcgis/services;GP/BufferByVal", "mytools"

# Use GetParameterValue to get a featureset object with the default schema of the
# first parameter of the tool 'bufferpoints'
#
inFeatureSet = arcpy.GetParameterValue("bufferpoints", 0)

# Load a shapefile into the featureset


#
inFeatureSet.load("c:/base/roads.shp")

# Run a server tool named BufferPoints with featureset created above


#
result = arcpy.BufferPoints_mytools(inFeatureSet, "5 feet")

# Check the status of the result object every 0.2 seconds until it has a value
# of 4 (succeeded) or greater
#
while result.status < 4:
time.sleep(0.2)
print result.status

# Return a map service


#
mapimage = result.getMapImageURL(0)

# Use Python's urllib module's urlretrieve method to copy the image locally
#
urllib.urlretrieve(mapimage, "c:/base/road_buffer.jpg")
 

Copyright © 1995-2019 Esri. All rights reserved.

Adding toolboxes in Python

Locate topic

Python is initially only aware of tools stored in ArcGIS system toolboxes like the Data Management Tools,
Conversion Tools, and Analysis Tools toolboxes. Custom tools created by an individual, third party, or
organization and stored in a custom toolbox can be accessed in the Python window like any system tool by
importing the custom toolbox into the ArcPy site package.
In the following example, the ImportToolbox function is used to allow tools contained in a custom toolbox
to be accessed in Python. After importing the toolbox, the custom tools can be accessed as
arcpy.<toolname>_<alias>.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 18 of 95

>>> arcpy.ImportToolbox("c:/mytools/geometrytools.tbx")
>>> arcpy.CreateRegularPolygons_geometry(

When a tool is accessed through the ArcPy site package, the toolbox alias where the tool is contained is a
required suffix (arcpy.<toolname>_<alias>). Since ArcPy depends on toolbox aliases to access and
execute the correct tool, aliases are extremely important when importing custom toolboxes. A good
practice is to always define a custom toolbox's alias. However, if the toolbox alias is not defined, a
temporary alias can be set as the second parameter of the ImportToolbox function.

>>> arcpy.ImportToolbox("c:/mytools/geometrytools.tbx", "mytools")


>>> arcpy.CreateRegularPolygons_mytools(

Adding and removing server toolboxes


Geoprocessing services can also be added to the scripting environment using ImportToolbox. Whether
adding the geoprocessing service from a local or Internet server, the server and toolbox name are
semicolon delimited.
Sample syntax for adding a geoprocessing service

# Import a geoprocessing service


#
import arcpy

# To add a toolbox from a Internet server, provide the url and toolbox name
# delimited by a semi-colon
#
arcpy.ImportToolbox("http://lab13/arcgis/services;BufferByVal")
 
Sample syntax for adding a local geoprocessing service

# Import a local geoprocessing service


#
import arcpy

# To add a toolbox from a local server, provide the server and toolbox name
# delimited by a semi-colon
#
arcpy.ImportToolbox("lab13;BufferByVal")
 
Related topics
ImportToolbox
Creating a toolbox
Renaming a toolbox: name, label, and alias

Copyright © 1995-2019 Esri. All rights reserved.

Using functions in Python

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 19 of 95

Locate topic

A function is a defined bit of functionality that does a specific task and can be incorporated into a larger
program.
In ArcPy, all geoprocessing tools are provided as functions, but not all functions are geoprocessing tools.
In addition to tools, ArcPy provides a number of functions to better support geoprocessing workflows
using Python. Functions can be used to list certain datasets, retrieve a dataset's properties, validate a
table name before adding it to a geodatabase, or perform many other useful geoprocessing tasks. These
functions are available only from ArcPy and not as tools in ArcGIS applications, since they are designed for
Python workflows.
The general form of a function is similar to that of tool; it takes arguments, which may or may not be
required, and returns something. The returned value of a nontool function can be varied—anything from
strings to geoprocessing objects. Tool functions will always return a Result object and provide
geoprocessing messages support.
The following example uses two ArcPy functions, GetParameterAsText to receive an input argument, and
Exists to determine whether or not the input exists. The Exists function returns a Boolean value (either
True or False).

import arcpy

input = arcpy.GetParameterAsText(0)
if arcpy.Exists(input):
print("Data exists")
else:
print("Data does not exist")

The following example creates a list of feature classes using the ListFeatureClasses function, and then
loops through the list, clipping each individual feature class with a boundary feature class.

import arcpy
import os

# The workspace environment needs to be set before ListFeatureClasses


# to identify which workspace the list will be based on
#
arcpy.env.workspace = "c:/data"
out_workspace = "c:/data/results/"
clip_features = "c:/data/testarea/boundary.shp"

# Loop through a list of feature classes in the workspace


#
for fc in arcpy.ListFeatureClasses():
# Set the output name to be the same as the input name, and
# locate in the 'out_workspace' workspace
#
output = os.path.join(out_workspace, fc)

# Clip each input feature class in the list


#
arcpy.Clip_analysis(fc, clip_features, output, 0.1)

Related topics

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 20 of 95

Using tools in Python


Using classes in Python
Alphabetical list of ArcPy functions

Copyright © 1995-2019 Esri. All rights reserved.

Using classes in Python

Locate topic

A class is analogous to an architectural blueprint. The blueprint provides the framework for how to create
something. Classes can be used to create objects, often referred to as an instance. ArcPy classes, such as
the SpatialReference and Extent classes, are often used as shortcuts to complete geoprocessing tool
parameters that would otherwise have a more complicated string equivalent.
ArcPy includes several classes, including SpatialReference, ValueTable, and Point. Once instantiated,
its properties and methods may be used. Classes have one or more methods called constructors. A
constructor is a method for initializing a new instance of a class. In the example below,
SpatialReference(prjFile) is the class constructor—it creates the spatialRef object by reading a
projection file.

import arcpy

prjFile = "c:/projections/North America Equidistant Conic.prj"


spatialRef = arcpy.SpatialReference(prjFile)

Like most other classes, SpatialReference contains a number of methods and properties. Building on the
previous sample, you can access the properties of spatialRef.

import arcpy

prjFile = "c:/projections/North America Equidistant Conic.prj"


spatialRef = arcpy.SpatialReference(prjFile)

# Print the SpatialReference's name, and type


#
print(spatialRef.name)
print(spatialRef.type)

Classes can be used repeatedly; in the following example, two unique point objects are created by using
the Point class.

import arcpy

pointA = arcpy.Point(2.0, 4.5)


pointB = arcpy.Point(3.0, 7.0)

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 21 of 95

Note: The CreateObject function can also be used to create many of the
objects that can be created using classes. However, using classes is
both easier to use and more readable.

Using classes with geoprocessing tools


Tool parameters are usually defined using simple text strings. Dataset names, paths, keywords, field
names, tolerances, and domain names can be specified using a quoted string.
Some parameters are harder to define using simple strings; they are more complex parameters that
require many properties. Instead of using long, complicated text strings to define these parameters,
you can use classes (for example, SpatialReference, ValueTable, and Point classes). The
documentation for each tool contains a scripting example of how each tool parameter is defined and
used.
In the following example, a SpatialReference object is created and used to define the output
coordinate system of a new feature class created using the CreateFeatureClass tool.

import arcpy

inputWorkspace = "c:/temp"
outputName = "rivers.shp"

prjFile = "c:/projections/North America Equidistant Conic.prj"


spatialRef = arcpy.SpatialReference(prjFile)

# Run CreateFeatureclass using the spatial reference object


#
arcpy.CreateFeatureclass_management(inputWorkspace, outputName, "POLYLINE"
spatial_reference=spatialRef)
 
The string equivalent for this parameter looks something like this: PROJCS
['North_America_Equidistant_Conic',GEOGCS['GCS_North_American_1983',DATUM
['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM
['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION
['Equidistant_Conic'],PARAMETER['False_Easting',0.0],PARAMETER
['False_Northing',0.0],PARAMETER['Central_Meridian',-96.0],PARAMETER
['Standard_Parallel_1',20.0],PARAMETER['Standard_Parallel_2',60.0],PARAMETER
['Latitude_Of_Origin',40.0],UNIT['Meter',1.0]];IsHighPrecision

Related topics
Using tools in Python
Using functions in Python

Copyright © 1995-2019 Esri. All rights reserved.

Using environment settings in Python

Locate topic

Each tool has a set of parameters it uses to execute an operation. Some of these parameters are common

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 22 of 95

among all tools, such as a tolerance or output location. These parameters may obtain their default values
from a geoprocessing environment that all tools use during their operation. When a tool is executed, the
current environment settings can also be used as global input parameter values. Settings such as an area
of interest, the spatial reference of the output dataset, and the cell size of a new raster dataset can all be
specified with geoprocessing environments.
A script can be executed in several ways. It can be run as a script tool in an ArcGIS application. It can
also be run from another script or by itself from the Python window. When a script is run inside a tool
from an ArcGIS application or from another geoprocessing script, the environment settings used by the
calling application or script are passed to it. These settings become the default settings used by the tool's
script when it is executed. The called script may alter the settings passed to it, but those changes are only
used within that script or by any other tool it may call. Changes are not passed back to the calling script
or application. The environment model can best be described as cascading, where values flow down to any
process that uses the geoprocessing environment.

Getting and setting environment settings


Environment settings are exposed as properties on the arcpy.env class. These properties can be used
to retrieve the current values or to set them. Environments can be accessed as read/write properties
from the environment class.

import arcpy

arcpy.env.workspace = "c:/data"

Example 1: Setting environment values

import arcpy

# Set the workspace environment setting


arcpy.env.workspace = "c:/St_Johns/data.gdb"

# Set the XYTolerance environment setting


arcpy.env.XYTolerance = 2.5

# Calculate the default spatial grid index, divide in half, then


# set the spatial grid 1 environment setting
grid_index = arcpy.CalculateDefaultGridIndex_management("roads")[0]

arcpy.env.spatialGrid1 = float(grid_index) / 2

# Clip the roads by the urban area feature class


arcpy.Clip_analysis("roads", "urban_area", "urban_roads")

Example 2: Getting and setting an environment value

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 23 of 95

import arcpy

# Check the current raster cell size and make sure it is a certain size
# for standard output
arcpy.env.workspace = "c:/avalon/data"

if arcpy.env.cellSize < 10:


arcpy.env.cellSize = 10
elif arcpy.env.cellSize > 20:
arcpy.env.cellSize = 20

arcpy.HillShade_3d("island_dem", "island_shade", 300)

Caution: Spelling and case matter when setting properties in Python. Assigning
a value to arcpy.env.Workspace is not the same as setting
arcpy.env.workspace. (Note: arcpy.env.workspace is the correct
form.) If you set an environment but are not seeing the effect on
subsequent tools, check the spelling and case.

Using environment settings to handle scratch data


The scratchGDB and scratchFolder environments are read-only environments that provide a
geodatabase and folder location that are guaranteed to exist. This means that you can reliably use a
geodatabase or folder at any time without creating or managing one.

import arcpy

inputFC = arcpy.GetParameterAsText(0)
clipFC = arcpy.GetParameterAsText(1)
outputFC = arcpy.GetParameterAsText(2)

# Use scratchGDB environment to write intermediate data


tempData = arcpy.CreateScratchName(workspace=arcpy.env.scratchGDB)

result = arcpy.Buffer_analysis(inputFC, tempData, "50 METERS")


arcpy.Clip_analysis(clipFC, result, outputFC)

The scratchFolder environment is set as follows:


l If scratchWorkspace is not set, scratchFolder defaults to the current user's temporary files
directory.
l If scratchWorkspace references a geodatabase, scratchFolder will be the folder containing the
geodatabase.
l If scratchWorkspace is set to a folder, scratchFolder will be the same as scratchWorkspace.
The scratchGDB environment is set as follows:
l If scratchWorkspace is not set, scratchGDB defaults to a geodatabase named scratch.gdb in the
current user's temporary files directory.
l If scratchWorkspace references a geodatabase, scratchGDB will be the same as
scratchWorkspace.
l If scratchWorkspace is set to a folder, scratchGDB will be set to a geodatabase named

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 24 of 95

scratch.gdb in the scratchWorkspace folder.

Resetting environments
Since geoprocessing environments can significantly affect tool operation and output, it is important to
keep track of environment settings and to reset environments to their default states when necessary.
Used within a with statement, the EnvManager class can be used to temporarily set one or more
environments. When you exit the with block, the environments will be reset to their previous values.
In the following code, the cellSize and extent environments are set only for the duration of the with
statement.

import arcpy

with arcpy.EnvManager(cellSize=10, extent='-16, 25, 44, 64'):


# Code to be executed with the environments set

Additionally, the ResetEnvironments function can be used to restore all environments to their default
values, or the ClearEnvironment function can be used to reset a specific environment.

import arcpy

# Reset geoprocessing environment settings


arcpy.ResetEnvironments()

# Reset a specific environment setting


arcpy.ClearEnvironment("workspace")

Related topics
Setting environments in the Python window
env

Copyright © 1995-2019 Esri. All rights reserved.

Understanding message types and severity

Locate topic

During execution of a tool, messages are written that can be retrieved with geoprocessing functions, such
as GetMessages. These messages include such information as the following:
l When the operation started and ended
l The parameter values used
l General information about the operation's progress (information message)
l Warnings of potential problems (warning message)
l Errors that cause the tool to stop execution (error message)
All communication between tools and users is done with messages. Depending on where you are running
the tools from, messages appear in the Result window, the Python window, and the progress dialog box.
From Python, you can fetch these messages within your script, interrogate them, print them, or write
them to a file. All messages have a severity property, either informative, warning, or error. The severity is

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 25 of 95

an integer, where 0 = informative, 1 = warning, and 2 = error.

Severity Description

Informative An informative message is information about a tool execution. It is never used to


message indicate problems. Only general information, such as a tool's progress, what time
(severity = 0) a tool started or completed, output data characteristics, or tool results, is found
in informative messages.

Warning Warning messages are generated when a tool experiences a situation that may
message cause a problem during its execution or when the result may not be what you
(severity = 1) expect. For example, defining a coordinate system for a dataset that already has
a coordinate system defined generates a warning. You can take action when a
warning returns, such as canceling the tool's execution or making another
parameter choice.

Error message Error messages indicate a critical event that prevented a tool from executing.
(severity = 2) Errors are generated when one or more parameters have invalid values, or when
a critical execution process or routine has failed.

Both warning and error messages are accompanied by a six-digit ID code. These ID codes have been
documented to provide additional information on their causes and how they can be dealt with. When error
or warning codes are shown in the tool or progress dialog box, Python window, or Result window, they
have a link that allows you to go directly to the additional help for that message.

Getting messages
Messages from the last tool executed are maintained by ArcPy and can be retrieved using the
GetMessages function. This function returns a single string containing all the messages from the tool
that was last executed. The returned messages can be filtered to include only those with a certain
severity using the severity option. When using ArcPy, the first message gives the tool executed, and
the last message gives the ending and elapsed time for the tool's execution. The tool's second and last
messages always give the start and end time, respectively, for the tool's execution.
Getting geoprocessing messages

import arcpy

# Execute the GetCount tool


arcpy.GetCount_management("c:/base/data.gdb/roads")

# Get the resulting messages and print them


print(arcpy.GetMessages())

Individual messages can be retrieved using the GetMessage function. This function has one parameter,
which is the index position of the message. The GetMessageCount function returns the number of
messages from the last tool executed. The example below shows how to print information about which
tool was executed with ending and elapsed times for the tool.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 26 of 95

import arcpy

arcpy.env.workspace = "D:/base/data.gdb"

arcpy.Clip_analysis("roads", "urban_area", "urban_roads")

# Print the first message


print(arcpy.GetMessage(0))

# Print the last message - ending and elapsed times for tool
print(arcpy.GetMessage(arcpy.GetMessageCount - 1))

Getting messages from a result object


Messages can also be accessed from a tool using a Result object. Unlike getting messages from ArcPy,
messages on a Result object can be maintained even after running multiple tools. The Result object
supports several of the same functions used to get and interpret geoprocessing tool messages.
Result properties and methods
Result properties and methods

Properties and methods Explanation

inputCount Returns the number of inputs.

outputCount Returns the number of outputs.

messageCount Returns the number of messages.

maxSeverity Returns the maximum severity. The returned severity can


be 0 (no errors/warnings raised), 1 (warnings raised), or
2 (errors raised).

resultID Returns the unique result ID. If the tool is not a


geoprocessing service, the resultID will be "".

status Returns the status of the job on the server.


l 0—New
l 1—Submitted
l 2—Waiting
l 3—Executing
l 4—Succeeded
l 5—Failed
l 6—Timed Out
l 7—Canceling
l 8—Canceled
l 9—Deleting
l 10—Deleted

cancel() Cancels the job on the server.

getInput(index) Returns a given input. If a record set or raster data


object, a RecordSet or RasterData object is returned.

getMapImageURL(ParameterList, Gets map service image for a given output.


Height, Width, Resolution)

getMessage(index) Returns a specific message.

getMessages(severity) The type of messages returned: 0=message, 1=warning,

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 27 of 95

2=error. Not specifying a value returns all message types.

getOutput(index) Returns a given output. If a record set or raster data


object, a RecordSet, or RasterData object is returned.

getSeverity(index) Returns the severity of a specific message.

The following sample runs two geoprocessing tools but waits until the tools are executed before
reviewing the messages.

import arcpy

arcpy.env.workspace = "D:/base/data.gdb"

# Execute the Clip and GetCount tools


clipResult = arcpy.Clip_analysis("roads", "urban_area", "urban_roads")
countResult = arcpy.GetCount_management("urban_roads")

# Get the resulting messages and print them


print(clipResult.getMessages())
print(countResult.getMessages())

As with geoprocessing tools, server tool messages are classified as information, a warning, or an error.
A message's type is indicated by its severity property, which is a numeric value. The following sample
shows how to get the messages from a server tool after it has completed.

import arcpy
import time

# Add the server toolbox


arcpy.ImportToolbox("http://lab13/arcgis/services;BufferByVal", "mytools")

featset = arcpy.FeatureSet()
featset.load("//flames/gpqa/coredata/global/redlands/control.shp")

# Run a server tool named BufferPoints


result = arcpy.BufferPoints_mytools(featset, "1000 feet")

# Wait until the tool completes


while result.status < 4:
time.sleep(0.2)

# Print all messages from the result object


print(result.getMessages())
 
Related topics
Writing messages in script tools

Copyright © 1995-2019 Esri. All rights reserved.

Error handling with Python

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 28 of 95

Locate topic

Errors happen. Writing scripts that expect and handle errors can save time and frustration. When a tool
returns an error message, ArcPy generates a system error or exception. In Python, you can provide a
variety of structures and methods that can handle exceptions. Of course, a script can fail for other reasons
not related to a geoprocessing tool. These also need to be caught and dealt with in an appropriate
manner. The following sections offer a few techniques that introduce the basics of Python exception
handling.
When a tool writes an error message, ArcPy generates an arcpy.ExecuteError exception. Python allows
you to write a routine that automatically runs when a system error is generated. In this error-handling
routine, retrieve the error message from ArcPy and react accordingly. If a script does not have an error-
handling routine, it fails immediately, which decreases its robustness. Use error-handling routines to
manage errors and improve a script's usability.

try-except statement
A try-except statement can be used to wrap entire programs or just particular portions of code to
trap and identify errors. If an error occurs within the try statement, an exception is raised, and the
code under the except statement is executed. Using a basic except statement is the most basic form of
error handling.
In the following code, Buffer fails because the required buffer_distance_or_field argument has not
been provided. Instead of failing without explanation, the except statement is used to trap the error,
then fetch and print the error message generated by Buffer. Note that the except block is only
executed if Buffer returns an error.

import arcpy
import sys

try:
# Execute the Buffer tool
arcpy.Buffer_analysis("c:/transport/roads.shp", "c:/transport/roads_buffer.shp"
except Exception:
e = sys.exc_info()[1]
print(e.args[0])

# If using this code within a script tool, AddError can be used to return messages
# back to a script tool. If not, AddError will have no effect.
arcpy.AddError(e.args[0])
 
The try statement has an optional finally clause that can be used for tasks that should always be
executed, whether an exception occurs or not. In the following example, the ArcGIS 3D Analyst
extension is checked in under a finally clause, ensuring that the extension is always checked in.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 29 of 95

class LicenseError(Exception):
pass

import arcpy

try:
if arcpy.CheckExtension("3D") == "Available":
arcpy.CheckOutExtension("3D")
else:
# Raise a custom exception
raise LicenseError

arcpy.env.workspace = "D:/GrosMorne"
arcpy.HillShade_3d("WesternBrook", "westbrook_hill", 300)
arcpy.Aspect_3d("WesternBrook", "westbrook_aspect")

except LicenseError:
print "3D Analyst license is unavailable"
except arcpy.ExecuteError:
print(arcpy.GetMessages(2))
finally:
# Check in the 3D Analyst extension
arcpy.CheckInExtension("3D")

raise statement
The previous example deals with an exception that occurred in the code. In some cases, it may be
necessary to create custom exceptions. A raise statement can be used for this purpose. In the
following code, a raise statement is used when an input feature class has been identified as having no
features. This is not strictly an error but a condition that the code can be used to guard against.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 30 of 95

class NoFeatures(Exception):
pass

import arcpy
import os
import sys

arcpy.env.overwriteOutput = True
fc = arcpy.GetParameterAsText(0)

try:
# Check that the input has features
result = arcpy.GetCount_management(fc)
if int(result[0]) > 0:
arcpy.FeatureToPolygon_management(
fc, os.path.join(os.path.dirname(fc), 'out_poly.shp'))
else:
# Raise custom exception
raise NoFeatures(result)

except NoFeatures:
# The input has no features
print('{} has no features'.format(fc))
except:
# By default any other errors will be caught here
e = sys.exc_info()[1]
print(e.args[0])

ExecuteError class
When a geoprocessing tool fails, it throws an arcpy.ExecuteError exception class, which means that
you can divide errors into different groups, geoprocessing errors (those that throw the
arcpy.ExecuteError exception) and other exception types. You can then handle the errors differently,
as demonstrated in the code below:

import arcpy
import sys

try:
result = arcpy.GetCount_management("C:/invalid.shp")

# Return geoprocessing specific errors


except arcpy.ExecuteError:
arcpy.AddError(arcpy.GetMessages(2))

# Return any other type of error


except:
# By default any other errors will be caught here
e = sys.exc_info()[1]
print(e.args[0])

traceback
In larger, more complex scripts, it can be difficult to determine the precise location of an error.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 31 of 95

Python's sys and traceback modules can be used together to isolate the exact location and cause of
the error, identifying the cause of an error more accurately and saving valuable debugging time.

# Import the required modules


#
import arcpy
import sys
import traceback

arcpy.env.workspace = "C:/Data/myData.gdb"
try:
arcpy.CreateSpatialReference_management()
#--------------------------
# Your code goes here
#
# See the table below for examples
#--------------------------
except arcpy.ExecuteError:
# Get the tool error messages
msgs = arcpy.GetMessages(2)

# Return tool error messages for use with a script tool


arcpy.AddError(msgs)

# Print tool error messages for use in Python/PythonWin


print(msgs)

except:
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]

# Concatenate information together concerning the error into a message string


pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"

# Return python error messages for use in script tool or Python window
arcpy.AddError(pymsg)
arcpy.AddError(msgs)

# Print Python error messages for use in Python / Python window


print(pymsg)
print(msgs)
 
If the above code was used and a geoprocessing tool error occurred, such an invalid input, this would
raise arcpy.ExecuteError, and the first except statement would be used. This statement would print
the error messages using the GetMessages function. If the same code was used, but a different type of
error occurred, the second except statement would be used. Instead of printing geoprocessing
messages, it gets a traceback object and prints the appropriate system error messages.
The table below shows the expected errors that result from three different lines of codes that could be
substituted into the code above. The first is a geoprocessing tool error, which prints out the traceback
information and the geoprocessing error messages. The second and third examples are not specifically
caught and print only the traceback information.
Error results

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 32 of 95

Your code Resulting error

arcpy.GetCount_management
("")
PYTHON ERRORS:
Traceback info:
File "c:\temp\errortest.py", line 10, in <module>
arcpy.GetCount_management("")

Error Info:
Failed to execute. Parameters are not valid.
ERROR 000735: Input Rows: value is required
Failed to execute (GetCount).

ArcPy ERRORS:
Failed to execute. Parameters are not valid.
ERROR 000735: Input Rows: value is required
Failed to execute (GetCount).
 
x = "a" + 1

PYTHON ERRORS:
Traceback info:
File "c:\temp\errortest.py", line 10, in <module>

x = "a" + 1

Error Info:
cannot concatenate 'str' and 'int' objects
 
float("a text string")

PYTHON ERRORS:
Traceback info:
File "c:\temp\errortest.py", line 10, in <module>

float("a text string")


Error Info:
invalid literal for float(): a text string
 

Getting error messages from a result object


A quick word about the Result object, shown below:

result = arcpy.GetCount_management("c:/data/rivers.shp")

If the call to GetCount_management raises an exception, the Result object is not created. This means
you cannot retrieve error messages from the Result object.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 33 of 95

import arcpy

try:
result = arcpy.GetCount_management("c:/data/rivers.shp")

# Return Geoprocessing specific errors


# (this method is incorrect!)
except arcpy.ExecuteError:
arcpy.AddError(result.getMessages(2))

The above code fails with the message name 'result' is not defined. This is because the Result
object could not be created due to the tool's failure. Since the Result object is not created, a Python
error is raised when trying to use the getMessages method.

Note: A Result object created by calling a geoprocessing service on ArcGIS


Server is created even with a tool failure. A Result object only fails to
be created when a tool runs locally and it raises an error. For more
information about using the result object, see Using tools in Python.

Related topics
Understanding message types and severity

Copyright © 1995-2019 Esri. All rights reserved.

Setting paths to data in Python

Locate topic

Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n
represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in
place of a backslash. Two backslashes can be used instead of one to avoid a syntax error. A string literal
can also be used by placing the letter r before a string containing a backslash so it is interpreted correctly.
Example 1: Valid use of paths in Python

import arcpy

arcpy.GetCount_management("c:/temp/streams.shp")
arcpy.GetCount_management("c:\\temp\\streams.shp")
arcpy.GetCount_management(r"c:\temp\streams.shp")

In the following sample, backslashes are used by mistake, and \t is interpreted as a tab by Python. Get
Count will fail, as the path is interpreted differently than it was intended.
Example 2: Invalid use of paths in Python

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 34 of 95

import arcpy
arcpy.GetCount_management("c:\temp\streams.shp")

# ExecuteError: Failed to execute. Parameters are not valid.


# ERROR 000732: Input Rows: Dataset c: em\streams.shp does not exist or is not support
# Failed to execute (GetCount)
 
Tip: It is possible to have a feature class and a feature dataset with the
same name contained in a geodatabase. In such a case, the feature
class and feature dataset will have the same catalog path. Most tools
work with one or the other. However, for those tools that can work with
either, such as the Copy tool, the data type can be specified to avoid
ambiguity.

Related topics
Paths explained: Absolute, relative, UNC, and URL

Copyright © 1995-2019 Esri. All rights reserved.

Listing tools, toolboxes, and environment settings

Locate topic

Depending on which toolboxes are available, ArcPy might have access to several toolboxes, dozens of
environment settings, and hundreds of tools. ArcPy has several appropriately named functions to return a
list of tools (ListTools), environment settings (ListEnvironments), or toolboxes (ListToolboxes).
Each function has a wild card option and returns a list of name strings that can be looped through. The
example below shows how to access available tools and print out their usage.

import arcpy

# Create a list of the conversion tools


#
tools = arcpy.ListTools("*_conversion")

# Loop through the list and print each tool's usage


#
for tool in tools:
print(arcpy.Usage(tool))

The following sample provides an approach for viewing environment settings in Python.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 35 of 95

import arcpy

environments = arcpy.ListEnvironments()

# Sort the environment list, disregarding capitalization


#
environments.sort(key=str.lower)

for environment in environments:


# As the environment is passed as a variable, use Python's getattr
# to evaluate the environment's value
#
env_value = getattr(arcpy.env, environment)

# Format and print each environment and its current setting


#
print("{0:<30}: {1}".format(environment, env_value))

The following sample provides an approach for viewing current toolboxes in Python.

import arcpy

# Print all current toolboxes


#
for toolbox in arcpy.ListToolboxes():
# Toolboxes are printed in the form of "toolbox_name(toolbox_alias)"
print(toolbox)

Related topics
Create lists of data

Copyright © 1995-2019 Esri. All rights reserved.

Accessing licenses and extensions in Python

Locate topic

Whenever a tool is executed in a script, an ArcGIS license is required. Tools from ArcGIS extensions, such
as the ArcGIS Spatial Analyst extension, require an additional license for that extension. If the necessary
licenses are not available, a tool fails and returns error messages. For example, if you install with an
ArcGIS Desktop Basic license, and you attempt to execute a tool that requires a Desktop Standard or
Desktop Advanced license, the tool will fail.
When using an ArcGIS Desktop Basic or Desktop Standard license, a script should set the product to
Desktop Basic or Desktop Standard. Likewise, when using an Engine or EngineGeoDB license, a script
should set the product to Engine or EngineGeoDB. If a license is not explicitly set, the license will be
initialized based on the highest available license level the first time an ArcPy tool, function, or class is
accessed.
Every tool checks to ensure it has the appropriate license. If it doesn't have what's required, it fails. To
guard against the situation of executing partially through and failing, you can perform a check at the top
of your script and fail immediately.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 36 of 95

Tip: The setting of the product and extensions is only necessary within
stand-alone scripts. If you are running tools from the Python window or
using script tools, the product is already set from within the
application, and the active extensions are based on the Extensions
dialog box.

Desktop, Engine/Server licenses


Product modules are imported prior to the import of arcpy to define the desktop license used by a
script. The CheckProduct function can be used to check the availability of desktop licenses, while the
ProductInfo function reports what the current product license is.

Legacy: The product level should be set by importing the appropriate product
module (arcinfo, arceditor, arcview, arcserver, arcenginegeodb,
or arcengine) prior to importing arcpy. The SetProduct function is a
legacy function and cannot set the product once arcpy has been
imported.

Extension licenses
Licenses for extensions can be retrieved from a license manager and returned once they are no longer
needed. CheckExtension is used to see if a license is available to be checked out for a specific type of
extension, while CheckOutExtension actually retrieves the license. Once the extension license has
been retrieved by the script, extension tools can be executed. Once a script is done using tools from a
particular extension, the CheckInExtension function should be used to return the license to the license
manager so other applications can use it. All checked-out extension licenses and set product licenses
are returned to the license manager when a script completes.
The following example executes some ArcGIS 3D Analyst tools and sets the desktop product license to
ArcGIS Desktop Basic, since an ArcGIS Desktop Advanced license is not required to execute tools from
an extension. The script will fail if the ArcGIS Desktop Basic license is not explicitly set and no ArcGIS
Desktop Advanced license is available, since a desktop license is required to execute extension tools.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 37 of 95

class LicenseError(Exception):
pass

# Set desktop license used to Basic (keyword is arcview)


#
import arcview
import arcpy

try:
if arcpy.CheckExtension("3D") == "Available":
arcpy.CheckOutExtension("3D")
else:
# Raise a custom exception
#
raise LicenseError

arcpy.env.workspace = "D:/GrosMorne"
arcpy.HillShade_3d("WesternBrook", "westbrook_hill", 300)
arcpy.Aspect_3d("WesternBrook", "westbrook_aspect")

except LicenseError:
print("3D Analyst license is unavailable")
except arcpy.ExecuteError:
print(arcpy.GetMessages(2))
finally:
# Check in the ArcGIS 3D Analyst extension
#
arcpy.CheckInExtension("3D")

In the above example, the ArcGIS 3D Analyst extension is checked in under a finally clause, ensuring
that the extension is always checked back in, whether an exception has occurred or not.
A returned value of Failed, Unavailable, or NotLicensed indicates that the extension could not be
successfully checked out.
Below are the extension names and their extension code names:

Extension Extension Code

ArcGIS 3D Analyst extension 3D

ArcGIS Data Interoperability extension for Desktop DataInteroperability

ArcGIS Data Reviewer for Desktop Datareviewer

ArcGIS for Aviation: Airports Airports

ArcGIS for Aviation: Charting Aeronautical

ArcGIS for Maritime: Bathymetry Bathymetry

ArcGIS for Maritime: Charting Nautical

ArcGIS Geostatistical Analyst extension GeoStats

ArcGIS Network Analyst extension Network

ArcGIS Spatial Analyst extension Spatial

ArcGIS Schematics extension Schematics

ArcGIS Tracking Analyst extension Tracking

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 38 of 95

ArcGIS Workflow Manager for Desktop JTX

ArcScan ArcScan

Business Analyst Business

Esri Defense Mapping Defense

Esri Production Mapping Foundation

Esri Roads and Highways Highways

StreetMap StreetMap

Product code names

Product Codes

ArcView (equivalent to an ArcGIS Desktop Basic license)

ArcEditor (equivalent to an ArcGIS Desktop Standard license)

ArcInfo (equivalent to an ArcGIS Desktop Advanced license)

Engine

EngineGeoDB

ArcServer

Licensing functions
Function Explanation

CheckExtension Checks to see if a license is available to be checked out for a


(extension) specific type of extension.

Return
Meaning
Value

Available The requested license is available to be set.

Unavailable The requested license is unavailable to be


set.

NotLicensed The requested license is not valid.

Failed A system failure occurred during the


request.

CheckInExtension Returns the license so other applications can use it.


(extension)
Return
Meaning
Value

NotInitialized No desktop license has been set.

Failed A system failure occurred during the


request.

CheckedIn The license has been returned successfully.

CheckOutExtension Retrieves the license.


(extension)
Return
Meaning
Value

NotInitialized No desktop license has been set.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 39 of 95

Unavailable The requested license is unavailable to be


set.

CheckedOut Successfully set the license.

CheckProduct(code) Checks to see if the requested license is available.

Return Value Meaning

AlreadyInitialized License has already been set in the


script.

Available The requested license is available to be


set.

Unavailable The requested license is unavailable to


be set.

NotLicensed The requested license is not valid.

Failed A system failure occurred during the


request.

ProductInfo() Returns the current product license.

Return
Meaning
Value

NotInitialized No license has been set.

ArcInfo An ArcGIS Desktop Advanced license has


been set.

ArcEditor An ArcGIS Desktop Standard license has


been set.

ArcView An ArcGIS Desktop Basic license has been


set.

ArcServer An ArcGIS Server license has been set.

EngineGeoDB An EngineGeoDB license has been set.

Engine An Engine license has been set.

SetProduct(code) Defines the desktop license.

Return Value Meaning

CheckedOut Successfully set the license.

AlreadyInitialized License has already been set in the


script.

NotLicensed The requested license is not valid.

Failed A system failure occurred during the


request.

Copyright © 1995-2019 Esri. All rights reserved.

Create lists of data

Locate topic

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 40 of 95

One of the foremost tasks in a batch processing script is cataloging the available data so it can iterate
through the data during processing. ArcPy has a number of functions built specifically for creating such
lists.
List functions

Function Description

ListFields(dataset, wild_card, field_type) Returns a list of fields found in the input


value

ListIndexes(dataset, wild_card) Returns a list of attribute indexes found in


the input value

ListDatasets(wild_card, feature_type) Returns the datasets in the current


workspace
ListFeatureClasses(wild_card, feature_type, Returns the feature classes in the current
feature_dataset) workspace

ListFiles(wild_card) Returns the files in the current workspace

ListRasters(wild_card, raster_type) Returns a list of rasters found in the current


workspace

ListTables(wild_card, table_type) Returns a list of tables found in the current


workspace

ListWorkspaces(wild_card, workspace_type) Returns a list of workspaces found in the


current workspace

ListVersions(sde_workspace) Returns a list of versions the connected user


has permission to use

The result of each of these functions is a list, which is a list of values. A list can contain any data type,
such as a string, which can be, for example, a path to a dataset, field, or row from a table. Once the list is
created with the values you want, you can iterate through it in your script to work with each individual
value.
Learn more about listing tools, toolboxes, and environment settings

List function parameters


The parameters of these functions are similar. A few, such as ListFields, require an input dataset
value, since the items the functions are listing reside in a certain object or dataset. Other functions do
not require an input dataset because they list data in the current workspace that are defined in the
environment settings. All functions have a wildcard parameter, which is used to restrict the objects or
datasets listed by name. A wildcard defines a name filter, and all the contents in the newly created list
must pass that filter. For example, you may want to list all the feature classes in a workspace that
start with the letter G. The following example shows how this is done:

import arcpy

# Set the workspace. List all of the feature classes that start with 'G'
arcpy.env.workspace = "D:/St_Johns/data.gdb"
fcs = arcpy.ListFeatureClasses("G*")

The list can also be restricted to match certain data properties, such as only polygon feature classes,
integer fields, or coverage datasets. This is what the type parameter is used for in all functions. In the
next example, the feature classes in a workspace are filtered using a wildcard and a data type, so only
polygon feature classes that start with the letter G are in the resulting list:

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 41 of 95

# Set the workspace. List all of the polygon feature classes that
# start with 'G'
arcpy.env.workspace = "D:/St_Johns/data.gdb"
fcs = arcpy.ListFeatureClasses("G*", "polygon")

Using your list


ArcPy uses a Python list type as the returned type for all its list function results, since lists support the
flexibility required for data access and multiple data types. A for loop is ideal for working with a list
because it can be used to step through the list one item at a time. A for loop iterates through each
item in the list. Below is an example of a for loop used to iterate through the list generated in the
previous example:

# For each feature class in the list of feature classes


for fc in fcs:
# Copy the features from the workspace to a folder
arcpy.CopyFeatures_management(fc, "D:/St_Johns/Shapefiles/" + fc)

Following is another example of how to use an ArcPy list function. The script is used to create raster
pyramids for all rasters that are Tagged Image File Format (TIFF) images in a folder.

# Set the workspace. List all of the TIFF files


arcpy.env.workspace = "D:/St_Johns/images"

# For each raster in the list of rasters


for tiff in arcpy.ListRasters("*", "TIF"):
# Create pyramids
arcpy.BuildPyramids_management(tiff)

A list provides the opportunity to use and manage the results of a list function in a variety of ways.
Lists are a versatile Python type and provide a number of methods (append, count, extend, index,
insert, pop, remove, reverse, and sort) that can be used to manipulate and extract information.
For instance, if you want to know how many feature classes you have in a workspace, you can use
Python's built-in len function to provide that number.

import arcpy

arcpy.env.workspace = "c:/St_Johns/Shapefiles"

fcs = arcpy.ListFeatureClasses()

# Use Python's built-in function len to reveal the number of feature classes
# in the workspace
fcCount = len(fcs)
print(fcCount)
 

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 42 of 95

Tip: A list can easily show its contents. Lists can be manipulated with a
number of methods, including sort, append, and reverse.

>>> import arcpy


>>> arcpy.env.workspace = "c:/data/water.gdb"
>>> fcs = arcpy.ListFeatureClasses()
>>> print(fcs)
['water_pipes', 'water_services', 'water_stations']

>>> fcs.sort(reverse=True)
>>> print(fcs)
['water_stations', 'water_services', 'water_pipes']
 
As lists are an ordered collection, they also permit indexing and
slicing.

>>> print(fcs[0])
water_stations

>>> print(fcs[1:])
['water_services', 'water_pipes']

Searching directories and subdirectories


ArcPy list functions can be used to iterate over a single directory or workspace, but in some cases,
iterating through other subfolders and workspaces is necessary. For files, this can be achieved with
Python's os.walk function which is used to iterate or walk through folders to find additional subfolders
and files. However, os.walk is strictly file based and does not recognize databases and non-file-based
data types that are important in ArcGIS. For instance, os.walk will not see raster datasets or other
contents in a file geodatabase workspace or a feature dataset.
In the arcpy.da module, the Walk function can also be used to iterate through a directory, and can also
look into databases and identify ArcGIS data types.
arcpy.da.Walk function

Walk(top, topdown, Generates data names in a Catalog tree by walking the tree top
onerror, followlinks, down or bottom up. Each directory/workspace in the tree yields
datatype, type) a tuple of three (dirpath, dirnames, filenames).

Note: Unlike the list functions, Walk does not use the workspace
environment to identify its starting workspace. Instead, the first
starting (or top) workspace that Walk traverses is specified in its first
argument, top.

In the following example, the Walk function is used to iterate through a Catalog tree and identifies all
polygon feature classes contained within.
Use Walk function to catalog polygon feature classes.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 43 of 95

import arcpy
import os

workspace = "c:/data"
feature_classes = []
for dirpath, dirnames, datatypes in arcpy.da.Walk(workspace,
datatype="FeatureClass",
type="Polygon"):

# Append all Polygon feature classes to a list for further processing


for datatype in datatypes:
feature_classes.append(os.path.join(dirpath, filename))
 
In some cases, there may be subdirectories that should be avoided when traversing the Catalog tree,
for example, directories of backed-up files. If the topdown argument is True or unspecified, the
workspaces can be modified in-place to avoid any undesired workspaces or to add additional
workspaces as they are created.
Use the Walk function to catalog raster data. Any rasters in a folder named back_up will be ignored.

import arcpy
import os

workspace = "c:/data"
rasters = []

for dirpath, dirnames, filenames in arcpy.da.Walk(


workspace, topdown=True, datatype="RasterDataset"):
# Disregard any folder named 'back_up' in creating list
# of rasters
if "back_up" in dirnames:
dirnames.remove('back_up')
for filename in filenames:
rasters.append(os.path.join(dirpath, filename))

Example: Using arcpy.da.Walk to analyze data


The Walk function (as well as list functions) is commonly used for processing data in bulk. The
following script takes advantage of the arcpy.da.Walk function to analyze all datasets in an SDE
workspace.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 44 of 95

import arcpy
import os

# SDE workspace to be used


admin_workspace = "Database Connections/[email protected]"

analyze_contents = []

for dirpath, workspaces, datatypes in arcpy.da.Walk(


admin_workspace,
followlinks=True,
datatype=['Table', 'FeatureClass', 'RasterDataset']):

# Create full path, and add tables, feature classes, raster datasets
analyze_contents += [
os.path.join(dirpath, datatype) for datatype in datatypes]

# create full path, add the feature datasets of the .sde file
analyze_contents += [
os.path.join(dirpath, workspace) for workspace in workspaces]

# Execute Analyze Datasets on the complete list


arcpy.AnalyzeDatasets_management(admin_workspace,
"SYSTEM",
analyze_contents,
"ANALYZE_BASE",
"ANALYZE_DELTA",
"ANALYZE_ARCHIVE")

Tip: By default, sde connection files are not iterated to save from
unintentional opening of remote databases. To deliberately iterate
through an sde connection file, set the followlinks argument to
True.

Related topics
Listing tools, toolboxes, and environment settings

Copyright © 1995-2019 Esri. All rights reserved.

Working with multivalue inputs

Locate topic

Many geoprocessing tools have input parameters that accept multiple values. When you view the tool's
reference page or its usage in the Python window, whenever you see the parameter enclosed in brackets
[ ], you know it can take a list of values. For example, the Delete Field tool takes a list of fields to delete
and the parameter usage displays as [drop_field, ...]. Some parameters, such as the input_features
parameter of the Union tool, take a list-of-lists. Its usage displays as [[in_features, {Rank}], ...].
Any parameter that accepts a list of values (or a list of list of values) is a multivalue parameter; it accepts
one or more values. There are three ways to specify a multivalue parameter:
1. As a list, where each value is an element in the list

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 45 of 95

2. As a string, where values are separated by semicolons


3. As a ValueTable, where values are stored in a virtual table of rows and columns

Below are examples of each.

As a list
In a script, multivalue inputs can be passed as a list. A list is enclosed in brackets and is a flexible
Python type.
DeleteFields using a Python list for the drop_field parameter

import arcpy

arcpy.env.workspace = 'C:/base/county.gdb'
arcpy.DeleteField_management('roads', ['STREET_NAM', 'LABEL', 'CLASS'])

Union using a Python list for the in_features parameter

import arcpy

arcpy.env.workspace = 'C:/base/data/gdb'
arcpy.Union_analysis([['counties', 2],['parcels', 1]], 'state_landinfo')

As a string
Your script may have to use a multivalue string in some cases, because one may be returned as an
output value of a tool or passed as an input parameter for your script.
DeleteFields using a multivalue string for the drop_field parameter.

import arcpy

arcpy.env.workspace = 'C:/base/county.gdb'
arcpy.DeleteField_management('roads', 'STREET_NAM;LABEL;CLASS')

Union using a multivalue string for the in_features parameter

import arcpy

arcpy.env.workspace = 'C:/base/data/gdb'
arcpy.Union_analysis('counties 2;parcels 1', 'state_landinfo')

With ValueTable
A ValueTable allows you to organize values into a virtual table of rows and columns. You specify the
number of columns when you create a value table. The default is a single column.
DeleteFields using a ValueTable for the drop_field parameter

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 46 of 95

import arcpy

arcpy.env.workspace = 'C:/base/county.gdb'

vt = arcpy.ValueTable()
vt.addRow('STREET_NAM')
vt.addRow('LABEL')
vt.addRow('CLASS')

arcpy.DeleteField_management('roads', vt)

Union using a ValueTable for the in_features parameter

import arcpy

arcpy.env.workspace = 'C:/base/data/gdb'

vt = arcpy.ValueTable(2)
vt.addRow('counties 2')
vt.addRow('parcels 1')

arcpy.Union_analysis(vt, 'state_landinfo')

Related topics
Using the multivalue parameter control

Copyright © 1995-2019 Esri. All rights reserved.

Mapping input fields to output fields

Locate topic

A common geoprocessing task is to merge many datasets into a new or existing dataset to create a single
dataset covering a larger area or a table containing a greater number of records. Often, the attributes, or
fields, are the same for all the inputs that are used in a merge or append operation; sometimes, however,
they do not match, and the relationships between fields of different names and types have to be mapped.
For an example of field mappings, see the Merge tool in the Data Management toolbox; it facilitates this
mapping of relationships so data is placed in the desired output fields with the correct values.

FieldMap
The FieldMap object provides a field definition and a list of input fields from a set of tables or feature
classes that provide its values.
The properties of the FieldMap object include the start and end position of an input text value, so a
new output value can be created using a slice of an input value. If a FieldMap object contains multiple
input fields from the same table or feature class, each record's values are merged using the mergeRule
property. This is a convenient way to join values, such as a street name that is held in one field and a
street type that is held in another, for example, Eureka and Street. The joinDelimiter property of
FieldMap is used if the mergeRule value Join is specified. Any set of characters, such as a space, can
be used as a delimiter. In the above example, this would create a value of Eureka Street.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 47 of 95

Fieldmappings
The FieldMappings object is a collection of FieldMap objects, and it is used as the parameter value for
tools that perform field mapping, such as Merge. The easiest way to work with these objects is to first
create a FieldMappings object, then initialize its FieldMap objects by adding the input feature classes
or tables that are to be combined. Once all inputs are provided, the FieldMappings object will contain
one FieldMap object, or output field, for each unique field name from all the inputs. This list can be
modified by adding new fields, altering the properties and/or contents of an output field, or removing
any unwanted output fields.

Examples
In the following example, a number of feature classes containing U.S. census data will be merged to
form a new feature class. One of the input attributes found in all the inputs is a numeric field, STFID.
This 15-digit value is a unique identifier for all census blocks for the United States. The value can be
broken into four components. The first two digits provide the state code, the next three indicate the
county, the following six identify the census tract, and the last four identify the census block. The value
360899912001006 represents the census block (1006) containing the State University of New York at
Potsdam in upstate New York (36), within census tract 991200 of the county of St. Lawrence (089).
The script sample will merge these feature classes together and also create two new fields, TRACTID
and BLOCKID, because the input data only has the STFID attribute. To do this, the FieldMappings
object is initialized using the addTable method to enter each input. Then the default FieldMappings
object is modified by creating two new FieldMap objects, populating their properties, and adding them
to the FieldMappings object.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 48 of 95

import arcpy
from arcpy import env

env.workspace = "C:/Data/CityBlocks.gdb"
outfc = "C:/Data/CityBlocks.gdb/AllBlocks"

# Each of the input Feature classes has an STFID, which is the


# combination of the Tract ID and Block ID for each block.
# Separate these values out from this field into two new
# fields, TRACTID and BLOCKID.
#

# Create a fieldmappings and two new fieldmaps.


#
fieldmappings = arcpy.FieldMappings()
fldmap_TRACTID = arcpy.FieldMap()
fldmap_BLOCKID = arcpy.FieldMap()

# List all the feature classes in the workspace that start with
# 'block' in their name and are of polygon feature type.
#
fcs = arcpy.ListFeatureClasses("block*", "Polygon")

# Create a value table that will hold the input feature classes to Merge
#
vTab = arcpy.ValueTable()
for fc in fcs:
# Adding a table is the fast way to load all the fields from the
# input into fieldmaps held by the fieldmappings object.
#
fieldmappings.addTable(fc)

# In this example also create two fieldmaps by 'chopping up'


# an input field. Feed the chopped field into the new fieldmaps.
#
fldmap_TRACTID.addInputField(fc, "STFID")
fldmap_BLOCKID.addInputField(fc, "STFID")

# Populate the input value table with feature classes


#
vTab.addRow(fc)

# Set the starting and ending position of the fields going into the
# TractID fieldmap. This is the location in the STFID field where the
# TractID falls.
#
for x in range(0, fldmap_TRACTID.inputFieldCount):
fldmap_TRACTID.setStartTextPosition(x, 5)
fldmap_TRACTID.setEndTextPosition(x, 10)

# Set the Name of the Field output from this field map.
#
fld_TRACTID = fldmap_TRACTID.outputField
fld_TRACTID.name = "TRACTID"
fldmap_TRACTID.outputField = fld_TRACTID

# Set the starting and ending position of the fields going into the
# BlockID fieldmap. This is the location in the STFID field where the

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 49 of 95

The next example shows how to modify a FieldMap object after it has been created using the
addTable method of the FieldMappings object. This is important when the inputs have fields with
different names but logically contain the same values.

import arcpy

outfc = "C:/data/CityData.gdb/AllBlocks"

# Want to merge these two feature classes together. Have a field


# that has the same content but the names are slightly different:
# Blocks1 has TRACT2000 and Blocks2 TRACTCODE. Name the output
# the same as Blocks1.
#
fc1 = "C:/data/CityData.gdb/Blocks1"
fc2 = "C:/data/CityData.gdb/Blocks2"

# Create a new fieldmappings and add the two input feature classes.
#
fieldmappings = arcpy.FieldMappings()
fieldmappings.addTable(fc1)
fieldmappings.addTable(fc2)

# First get the TRACT2000 fieldmap. Then add the TRACTCODE field
# from Blocks2 as an input field. Then replace the fieldmap within
# the fieldmappings object.
#
fieldmap = fieldmappings.getFieldMap(fieldmappings.findFieldMapIndex("TRACT2000"
fieldmap.addInputField(fc2, "TRACTCODE")
fieldmappings.replaceFieldMap(fieldmappings.findFieldMapIndex("TRACT2000"),

# Remove the TRACTCODE fieldmap.


#
fieldmappings.removeFieldMap(fieldmappings.findFieldMapIndex("TRACTCODE"))

# Create a value table that will hold the inputs for Merge.
#
vTab = arcpy.ValueTable()
vTab.addRow(fc1)
vTab.addRow(fc2)

# Run the Merge tool.


#
arcpy.Merge_management(vTab, outfc, fieldmappings)
 
Related topics
FieldMappings
FieldMap
Using the field mapping control

Copyright © 1995-2019 Esri. All rights reserved.

Scheduling a Python script to run at prescribed times

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 50 of 95

Locate topic

How to schedule a Python script to run at prescribed times


The method to schedule a Python script depends on your operating system. The general steps for
Windows operating systems are given below. For more information about scheduled tasks, see the
Windows help. For Unix and Linux systems, see the man entry for cron or crontab.
For more information on running a script or model at a prescribed time, see the blog post Scheduling a
Python script or model to run at a prescribed time

Scheduled Tasks
Steps:
1. Open the Task Scheduler wizard.
l For Windows 7
a. Click the Windows Start menu, click Control Panel > Administrative Tools and
click Task Scheduler.

Note: If Control Panel is in category view, click System


and Security, click Administrative Tools, then click
Task Scheduler.

l For Windows Vista


a. Click the Windows Start menu, click Settings, point to Control Panel, then
click System and Maintenance. Click Administrative Tools and click Schedule
tasks.

l For Windows XP
a. Click the Windows Start menu, point to Control Panel, then double-click
Scheduled Tasks.
b. If the control panel is in category view, click Performance and Maintenance
and click Scheduled Tasks.

l For Windows 2000 and NT


a. Click the Windows Start menu, point to Settings, point to Control Panel, then
click Scheduled Tasks.

2. Double-click Add Scheduled Task (or Create Basic Task).


3. Complete the options on the wizard. These options include when you want the scheduled task
to run, the path to the script you want to run, and any arguments to the script.

Copyright © 1995-2019 Esri. All rights reserved.

Describing data

Locate topic

Geoprocessing tools work with all types of data, such as geodatabase feature classes, shapefiles, rasters,
tables, topologies, and networks. Each piece of data has particular properties that can be accessed and
used to control the flow of a script or used as the parameters of a tool. For example, the output feature
type of the Intersect tool is dependent on the shape type of the data being intersected, that is, point, line,
or polygon. When the Intersect tool runs in a script on a list of input datasets, you must be able to
determine the shape types of the input datasets so the correct output shape type can be set. You can use

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 51 of 95

the Describe function to determine the shape types of all the input datasets.
Using the Describe function, a dataset's properties can be determined and used to make decisions. For
instance, in the following example, the script uses Describe to evaluate the shape type (polyline,
polygon, point, and so on) of input data and determine which geoprocessing tool is appropriate.

import arcpy

inFC = arcpy.GetParameterAsText(0)
outFC = arcpy.GetParameterAsText(1)

# Describe a feature class


#
desc = arcpy.Describe(inFC)

# Get the shape type (Polygon, Polyline) of the feature class


#
type = desc.shapeType

# If the shapeType is Polygon convert the data to polylines


# using the FeatureToLine tool, otherwise just copy the
# data using the CopyFeatures tool.
#
if type == "Polygon":
arcpy.FeatureToLine_management(inFC, outFC)
else:
arcpy.CopyFeatures_management(inFC, outFC)

The Describe function returns a Describe object, with multiple properties, such as data type, fields,
indexes, and many others. Its properties are dynamic, meaning that depending on what data type is
described, different describe properties are available for use.
Describe properties are organized into a series of property groups. Any particular dataset acquires the
properties of at least one of these groups. For instance, if describing a geodatabase feature class, you
could access properties from the GDB FeatureClass, FeatureClass, Table, and Dataset property groups. All
data, regardless of the data type, always acquire the generic Describe Object properties.
Describe Object properties
ArcInfo Workstation Item properties
ArcInfo Workstation Table properties
CAD Drawing Dataset properties
CAD FeatureClass properties
Cadastral Fabric properties
Coverage FeatureClass properties
Coverage properties
Dataset properties
dBASE Table properties
Editor Tracking properties
FeatureClass properties
File properties
Folder properties
GDB FeatureClass properties
GDB Table properties
Geometric Network properties
LAS Dataset properties
Layer properties

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 52 of 95

Map Document properties


Mosaic Dataset properties
Network Analyst Layer properties
Network Dataset properties
Prj File properties
Raster Band properties
Raster Catalog properties
Raster Dataset properties
RecordSet and FeatureSet properties
RelationshipClass properties
RepresentationClass properties
Schematic Dataset properties
Schematic Diagram properties
Schematic Folder properties
SDC FeatureClass properties
Shapefile FeatureClass properties
Table properties
TableView properties
Text File properties
Tin properties
Tool properties
Toolbox properties
Topology properties
VPF Coverage properties
VPF FeatureClass properties
VPF Table properties
Workspace properties

Working with Property sets


Some properties are members of a Property set. For example, the tolerances of a coverage or the
connection properties of a workspace return as Property sets. Property sets have named properties
that can be called from the property set. In the example below, the tolerances of a coverage (fuzzy,
dangle, ticMatch, edit, nodeSnap, weed, grain, and snap) print to the standard output:

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 53 of 95

import arcpy

# Describe a coverage feature class


#
desc = arcpy.Describe("D:/St_Johns/covs/freshwater")

# Create a property set of coverage tolerances


#
covTols = desc.tolerances

# Print each coverage tolerance


#
print(covTols.fuzzy)
print(covTols.dangle)
print(covTols.ticMatch)
print(covTols.edit)
print(covTols.nodeSnap)
print(covTols.weed)
print(covTols.grain)
print(covTols.snap)

Property sets are typically used when the properties of the object being described vary. The connection
properties (server, instance, database, user, and version) of an enterprise geodatabase workspace
vary depending on the type of ArcSDE database that is being used, so it is well suited to a property set
that has no predefined set of values.

Related topics
Describe

Copyright © 1995-2019 Esri. All rights reserved.

Using fields and indexes

Locate topic

When described, feature classes and tables have a fields property that returns a list of field objects, and
an indexes property that returns a list of index objects. Each field or index object has a number of
properties that can be used to explore the object. Alternatively, the ListFields and ListIndexes
functions can be used to create the same lists.
List functions

ListFields(dataset, wild_card, Returns a list of fields found in the input value


field_type)

ListIndexes(dataset, wild_card) Returns a list of attribute indexes found in the input


value

The following example shows how to create a field list and loop through the contents to find a specific
field.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 54 of 95

import arcpy

fc = 'D:/St_Johns/data.gdb/roads'

# Get a list of field objects


fields = arcpy.ListFields(fc, 'Flag')

for field in fields:


# Check the field name, perform a calculation when finding the field 'Flag'
if field.name == 'Flag':
# Set the value for the field and exit loop
arcpy.CalculateField_management(fc, 'Flag', '1')
break
 
The properties of the field and index objects are listed below:
Field properties

Property Explanation

name The name of the field.


aliasName The alias name of the field.
domain The name of the associated domain.
editable True, if the field is editable.
isNullable True, if the field is nullable.
required True, if the field is required.
length The field's length.
type SmallInteger, Integer, Single, Double, String, Date, OID, Geometry, BLOB.

scale The field's scale.


precision The field's precision.
Index properties

Property Explanation

name The name of the index.


isAscending True, if the index sorts in ascending order.
isUnique True, if the index is unique.
fields A list of Field objects. This is the same as using Describe's field property.

Tip: ListFields and ListIndexes can be used to limit the results based on
name and type.

Related topics
ListFields
ListIndexes
Create lists of data

Copyright © 1995-2019 Esri. All rights reserved.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 55 of 95

Using the spatial reference class

Locate topic

Geographic datasets, such as feature classes, coverages, and rasters, have a spatial reference that
defines a dataset's coordinate system, x,y domain, m-domain, and z-domain. Each part of the spatial
reference has a number of properties, especially the coordinate system, which defines what map
projection options are used to define horizontal coordinates. All this information is available from
describing the dataset and accessing its spatial reference property, which is actually another object
containing a number of properties.

import arcpy

# Describe a feature class


#
fc = "D:/St_Johns/data.gdb/roads"
desc = arcpy.Describe(fc)

# Get the spatial reference


#
sr = desc.spatialReference

# Check if the feature class is in projected space


#
if sr.type == "Projected":
arcpy.Copy_management(fc,"D:/St_Johns/data.gdb/roads_UTM")

Creating a spatial reference


It is not often practical to keep all details of a spatial reference inside a Python script. By using a
projection file, factory code, or spatial reference name as an argument to the SpatialReference class,
you can quickly complete the properties of a spatial reference and use the object as input to a
geoprocessing tool. In the following example, the spatial reference is constructed using a factory code
(also known as an authority code) supplied as an input argument.

Tip: For more information on coordinate system names and factory codes,
see geographic_coordinate_systems.pdf and
projected_coordinate_systems.pdf files in the ArcGIS Documentation
folder.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 56 of 95

import arcpy

inputWorkspace = "c:/temp"
outputName = "rivers.shp"

# Get the input workspace, the output name for the new feature class
# and path to an input projection file
#
inputWorkspace = arcpy.GetParameterAsText(0)
outputName = arcpy.GetParameterAsText(1)
factoryCode = arcpy.GetParameterAsText(2)

# Use a code as input to the SpatialReference class


#
sr = arcpy.SpatialReference(factoryCode)

# Use the SpatialReference object to create a new feature class with a


# specific coordinate system
#
arcpy.CreateFeatureclass_management(inputWorkspace, outputName,
"POLYLINE", spatial_reference=sr)

Note: For a full list of properties and methods, see SpatialReference class.

Note: Spatial references are sometimes referred to as Projection Engine


strings. The Projection Engine (PE) is a library of code that all of
ArcGIS uses for defining map projections and transforming from one
projection to another.

Related topics
SpatialReference

Copyright © 1995-2019 Esri. All rights reserved.

Working with feature sets and record sets

Locate topic

FeatureSet objects are lightweight representations of a feature class. They are a special data element
that contains not only schema (geometry type, fields, spatial reference) but also the data, including the
geometry. RecordSet objects are similar but comparable to a table. When used in a script tool, feature
sets and record sets can be used to interactively define features and records.

Note: Server tools communicate using feature sets and record sets, meaning
data must be created using or loaded into these objects when using
server tools.

The FeatureSet and RecordSet classes have the same two methods.
FeatureSet class

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 57 of 95

Property Explanation

load Import a feature class into the FeatureSet object.

save Export to a geodatabase feature class or shapefile.


RecordSet class

Property Explanation

load Import a table into the RecordSet object.

save Export to a geodatabase table or dBASE file.

Creating and using FeatureSet and RecordSet objects


FeatureSet and RecordSet objects can be created in a number of ways depending on the need and
application. The load method can be used to add new features or rows to the object, and the save
method can be used to preserve the features or rows on disk. In addition, the input feature class or
table can also be supplied as an argument to the class. Both FeatureSet and RecordSet objects can
also be used directly as input to a geoprocessing tool.
Create an empty feature set.

import arcpy

# Create an empty FeatureSet object


feature_set = arcpy.FeatureSet()

Construct a feature set from an input feature class.

import arcpy

# Construct a FeatureSet from a feature class


feature_set = arcpy.FeatureSet("c:/base/roads.shp")

GetParameterValue function
If you want to create a feature set or record set with the specific schema of a tool's input, use
GetParameterValue() to create an empty FeatureSet or RecordSet object with the appropriate
schema.

import arcpy

# Add a custom server toolbox


arcpy.ImportToolbox("http://flame7/arcgis/services;BufferByVal", "servertools"

# Get the default input from a tool


in_recordset = arcpy.GetParameterValue("bufferpoints", 0)
 
Using the GetParameter function
When working with script tools, FeatureSet and RecordSet objects can be acquired from the tool
using the GetParameter() function.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 58 of 95

import arcpy

# Get the RecordSet from a script tool


in_recordset = arcpy.GetParameter(0)

Learn more about the GetParameter function

The Result class getInput and getOutput methods


When using a server tool, explicitly ask for its output. When the output is a feature set or record set,
the Result class getOutput() method can be used to return the tool's output in a FeatureSet or
RecordSet object. As well, the Result object's getInput method can be used to get an input
FeatureSet or RecordSet object.

import time
import arcpy

# Add a toolbox from a server


arcpy.ImportToolbox("http://flame7/arcgis/services;GP/BufferByVal",
"servertools")

# Use GetParameterValue to get a featureset object with the default


# schema of the first parameter of the tool 'bufferpoints'
in_featureset = arcpy.GetParameterValue("bufferpoints", 0)

# Load a shapefile into the featureset


in_featureset.load("c:/base/roads.shp")

# Run a server tool named BufferPoints with featureset created above


result = arcpy.BufferPoints_servertools(in_featureset, "5 feet")

# Check the status of the result object every 0.2 seconds until it
# has a value of 4 (succeeded) or greater
while result.status < 4:
time.sleep(0.2)

# Get the output FeatureSet back from the server and save to a
# local geodatabase
out_featureset = result[0]
out_featureset.save("c:/temp/base.gdb/towers_buffer")

Example: Loading data to a feature set using cursors and an in-memory


feature class

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 59 of 95

import arcpy

arcpy.env.overwriteOutput = True

arcpy.ImportToolbox("http://flame7/arcgis/services;BufferByVal",
"servertools")

# List of coordinates
coordinates = [[-117.196717216, 34.046944853],
[-117.186226483, 34.046498438],
[-117.179530271, 34.038016569],
[-117.187454122, 34.039132605],
[-117.177744614, 34.056765964],
[-117.156205131, 34.064466609],
[-117.145491191, 34.068261129],
[-117.170825195, 34.073618099],
[-117.186784501, 34.068149525],
[-117.158325598, 34.03489167]]

# Create an in_memory feature class to initially contain the coordinate pairs


feature_class = arcpy.CreateFeatureclass_management(
"in_memory", "tempfc", "POINT")[0]

# Open an insert cursor


with arcpy.da.InsertCursor(feature_class, ["SHAPE@XY"]) as cursor:
# Iterate through list of coordinates and add to cursor
for (x, y) in coordinates:
cursor.insertRow([(x, y)])

# Create a FeatureSet object and load in_memory feature class


feature_set = arcpy.FeatureSet()
feature_set.load(feature_class)

results = arcpy.BufferPoints_servertools(feature_set)
 
Related topics
A quick tour of using Feature Set and Record Set

Copyright © 1995-2019 Esri. All rights reserved.

Checking for the existence of data

Locate topic

To check for the existence of data in a script, use the Exists function.
Exists function

Exists Tests for the existence of feature classes, tables, datasets, shapefiles, workspaces,
(dataset) layers, and other files in the current workspace at the time of execution. The
function returns a Boolean indicating whether the element exists.

When checking for the existence of geographic data, use the Exists function, since it recognizes catalog
paths. A catalog path is a path name that only ArcGIS recognizes. For example:
D:\Data\Final\Infrastructure.gdb\EastValley\powerlines refers to the powerlines feature class
found in the EastValley feature dataset in the file geodatabase Infrastructure. This is not a valid

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 60 of 95

system path as far as the Windows operating system is concerned, since Infrastructure.gdb (a folder)
does not contain a file named Infrastructure. In short, Windows doesn't know about feature datasets or
feature classes, so you cannot use Python existence functions like os.path.exists. Of course, everything
in ArcGIS knows how to deal with catalog paths. Universal Naming Convention (UNC) paths can also be
used.

import arcpy

arcpy.env.workspace = "d:/St_Johns/data.gdb"
fc = "roads"

# Clip a roads feature class if it exists


#
if arcpy.Exists(fc):
arcpy.Clip_analysis(fc, "urban_area", "urban_roads")

Tip: The Exists function honors the geoprocessing workspace environment


allowing you to just specify the base name.

If the data resides in an enterprise geodatabase, the name must be fully qualified.

import arcpy

arcpy.env.workspace = "Database Connections/Bluestar.sde"


fc = "ORASPATIAL.Rivers"

# Confirm that the feature class exists


#
if arcpy.Exists(fc):
print("Verified {} exists".format(fc))

In scripting, the default behavior for all tools is to not overwrite any output that already exists. This
behavior can be changed by setting the overwriteOutput property to True (arcpy.env.overwriteOutput
= True). Attempting to overwrite when the overwriteOutput is False, causes a tool to fail.

Related topics
Exists
Setting paths to data in Python
Paths explained: Absolute, relative, UNC, and URL

Copyright © 1995-2019 Esri. All rights reserved.

Specifying a query in Python

Locate topic

Structured Query Language (SQL) is a powerful language used to define one or more criteria that can
consist of attributes, operators, and calculations. For example, imagine you have a table of customer data,
and you want to find those customers who spent more than $50,000 with you last year and whose

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 61 of 95

business type is restaurant. You would select the customers with this expression: "Sales > 50000 AND
Business_type = 'Restaurant'".
When a query is specified for an update or search cursor, only the records satisfying that query are
returned. An SQL query represents a subset of the single table queries that can be made against a table in
an SQL database using the SQL SELECT statement. The syntax used to specify the WHERE clause is the
same as that of the underlying database holding the data.
The example below filters the rows of a search cursor to only roads of a specific road class:

import arcpy

fc = "D:/St_Johns/data.gdb/roads"

# Create a search cursor using an SQL expression


#
cursor = arcpy.da.SearchCursor(fc, ("roadclass", "name"), """"roadclass" = 2"""
for row in cursor:
# Print the name of the residential road
#
print(row[1])
 
Tip: In Python, building expressions surrounded with triple quotes is both
easier to read and to understand.

Using AddFieldDelimiters with the SQL expression


The field delimiters used in an SQL expression differ depending on the format of the queried data. For
instance, file geodatabases and shapefiles use double quotes (" "), personal geodatabases use square
brackets ([ ]), and ArcSDE geodatabases don't use field delimiters. The AddFieldDelimiters function
can take away some of the guess work in ensuring that the field delimiters used with your SQL
expression are the correct ones. The following example expands on the above example to add the
proper field delimiters for the SQL expression.

import arcpy

fc = "D:/St_Johns/data.gdb/roads"
fieldname = "roadclass"

# Create field name with the proper delimiters


#
whereclause = """{} = 2""".format(arcpy.AddFieldDelimiters(fc, fieldname))

# Create a search cursor using an SQL expression


#
cursor = arcpy.da.SearchCursor(fc, ("roadclass", "name"), whereclause)

for row in cursor:


# Print the name of the residential road
print(row[1])
 
Related topics

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 62 of 95

Accessing data using cursors

Copyright © 1995-2019 Esri. All rights reserved.

Accessing data using cursors

Locate topic

A cursor is a data access object that can be used to either iterate over the set of rows in a table or insert
new rows into a table. Cursors have three forms: search, insert, and update. Cursors are commonly used
to read existing geometries and write new geometries.
Each type of cursor is created by a corresponding ArcPy function (SearchCursor, InsertCursor, or
UpdateCursor) on a table, table view, feature class, or feature layer. A search cursor can be used to
retrieve rows. An update cursor can be used to positionally update and delete rows, while an insert cursor
is used to insert rows into a table or feature class.
Data access cursor functions (arcpy.da)

Cursor Explanation

arcpy.da.InsertCursor(in_table, field_names) Inserts rows


arcpy.da.SearchCursor(in_table, field_names, {where_clause}, Read-only access
{spatial_reference}, {explode_to_points}, {sql_clause})

arcpy.da.UpdateCursor(in_table, field_names, {where_clause}, Updates or


{spatial_reference}, {explode_to_points}, {sql_clause}) deletes rows

Legacy: A new data access module (arcpy.da) was added in ArcGIS 10.1. The
previously existing cursors (that are still listed under arcpy) are still
functional and valid; however, the new arcpy.da cursors include
significantly faster performance. In most cases, the help documentation
describes the use of the arcpy.da cursors. For more information about
the classic cursor model, see the table below.

Cursor functions (arcpy)

Cursor Explanation

arcpy.InsertCursor(dataset, {spatial_reference}) Inserts rows


arcpy.SearchCursor(dataset, {where_clause}, {spatial_reference}, Read-only access
{fields}, {sort_fields})

arcpy.UpdateCursor(dataset, {where_clause}, {spatial_reference}, Updates or deletes


{fields}, {sort_fields}) rows

Note: Cursors honor layer and table view definition queries and selections.
The cursor object only contains the rows that would be used by any
geoprocessing tool during an operation.

Cursors can only be navigated in a forward direction; they do not support backing up and retrieving rows
that have already been retrieved. If a script needs to make multiple passes over the data, the cursor's
reset method may be called.
Search or update cursors can be iterated with a for loop. The next row can also be accessed by explicitly
using the next method to return the next row. When using the next method on a cursor to retrieve all
rows in a table containing N rows, the script must make N calls to next. A call to next after the last row in
the result set has been retrieved returns a StopIteration exception.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 63 of 95

import arcpy

cursor = arcpy.da.SearchCursor(fc, ['fieldA', 'fieldB'])


for row in cursor:
print(row)

Search and update cursors also support with statements.

import arcpy

with arcpy.da.SearchCursor(fc, ['fieldA', 'fieldB']) as cursor:


for row in cursor:
print(row)

Each row retrieved from a table is returned as a list of field values. The values will be returned in the
same order as provided to the cursor's field_names argument. A cursor's fields property can also be
used to confirm the order of field values.

Cursor object
SearchCursor, UpdateCursor, and InsertCursor create a cursor object that can be used to iterate
through the records. The methods of the cursor object created by the various cursor functions vary
depending on the type of cursor created.
The following chart shows the methods supported by each cursor type:

Cursor type Method Effect on position

arcpy.da.SearchCursor reset() Resets the cursor


to its starting
position
arcpy.da.InsertCursor insertRow() Inserts a row into
the table
arcpy.da.UpdateCursor updateRow() Updates the
current row
deleteRow() Removes the row
from the table
reset() Resets the cursor
to its starting
position

insertRow
An insert cursor is used to create rows and insert them. Once the cursor has been created, the
insertRow method is used to insert a list (or tuple) of values that will make up the new row. Any
field in the table that is not included in the cursor will be assigned the field's default value.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 64 of 95

import arcpy

# Create insert cursor for table


cursor = arcpy.da.InsertCursor("c:/base/data.gdb/roads_lut",
["roadID", "distance"])

# Create 25 new rows. Set the initial row ID and distance values
for i in range(0,25):
cursor.insertRow([i, 100])

updateRow
The updateRow method is used to update the row at the current position of an update cursor. After
returning a row from the cursor object, you can modify the row as needed and call updateRow,
passing in the modified row.

import arcpy

# Create update cursor for feature class


with arcpy.da.UpdateCursor("c:/base/data.gdb/roads",
["roadtype", "distance"]) as cursor:
for row in cursor:
# Update the values in the distance field by multiplying
# the roadtype by 100. Road type is either 1, 2, 3 or 4.
row[1] = row[0] * 100
cursor.updateRow(row)

deleteRow
The deleteRow method is used to delete the row at the current position of an update cursor. After
fetching the row, call deleteRow on the cursor to delete the row.

import arcpy

# Create update cursor for feature class


with arcpy.da.UpdateCursor("c:/base/data.gdb/roads",
["roadtype"]) as cursor:
# Delete all rows that have a roads type of 4
for row in cursor:
if row[0] == 4:
cursor.deleteRow()

Accessing and setting field values


For each cursor, the fields used are supplied by a list (or tuple) of field names. When a row is returned
from the cursor, it is returned as a list of field values that correspond by index position.
In the sample below, state name and population count are accessed by position.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 65 of 95

import arcpy

fc = "c:/base/data.gdb/USA/States"

# Use SearchCursor to access state name and the population count


with arcpy.da.SearchCursor(fc, ['STATE_NAME', 'POP2000']) as cursor:
for row in cursor:
# Access and print the row values by index position.
# state name: row[0]
# population: row[1]
print('{} has a population of {}'.format(row[0], row[1]))

Tip: While all fields can be accessed using an asterisk (*), it is not
generally recommended. The more fields specified, the slower the
cursor will perform. Listing only the fields you are expecting to use will
improve the overall efficiency of the cursor.

Tokens can also be used as shortcuts in place of field names. All tables include an ObjectID field, which
may have many different names depending on the data type. Simple feature classes require a
geometry field, typically (but not always) named Shape. The OID@ token can be used to access the
ObjectID field, and the SHAPE@ token (which returns a geometry object) can be used to access the
geometry field of a feature class without having prior knowledge of the field names.
Search cursor on a multipoint feature class

import arcpy

infc = arcpy.GetParameterAsText(0)

# Enter for loop for each feature


for row in arcpy.da.SearchCursor(infc, ["OID@", "SHAPE@"]):
# Print the current multipoint's ID
print("Feature {}:".format(row[0]))

# For each point in the multipoint feature,


# print the x,y coordinates
for pnt in row[1]:
print("{}, {}".format(pnt.X, pnt.Y))

Additional geometry tokens can be used to access specific geometry information. Accessing the full
geometry is more time-consuming. If you only need specific properties of the geometry, use tokens to
provide shortcuts to access geometry properties. For instance, SHAPE@XY will return a tuple of x,y
coordinates that represent the feature's centroid.

Cursors and locking


Insert and update cursors honor table locks set by ArcGIS applications. Locks prevent multiple
processes from changing the same table at the same time. There are two types of locks, shared and
exclusive, described as follows:
l A shared lock is applied anytime a table or dataset is accessed. Multiple shared locks can exist for a
table, but no exclusive locks are permitted if a shared lock exists. Displaying a feature class and
previewing a table are examples of when a shared lock would be applied.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 66 of 95

l Exclusive locks are applied when changes are made to a table or feature class. Editing and saving a
feature class in a map, changing a table's schema, or using an insert cursor on a feature class in a
Python IDE are examples of when an exclusive lock is applied by ArcGIS.
Update and insert cursors cannot be created for a table or feature class if an exclusive lock exists for
that dataset. The UpdateCursor or InsertCursor function fails because of an exclusive lock on the
dataset. If these functions successfully create a cursor, they apply an exclusive lock on the dataset so
that two scripts cannot create an update or insert cursor on the same dataset.
In Python, the lock persists until the cursor is released. Otherwise, all other applications or scripts
could be unnecessarily prevented from accessing a dataset. A cursor can released by one of the
following:
l Include the cursor inside a with statement, which will guarantee the release of locks regardless of
whether or not the cursor is successfully completed.
l Call reset on the cursor.
l The cursor is successfully completed.
l Explicitly delete the cursor using the Python del statement.
An edit session applies a shared lock to data during the edit session. An exclusive lock is applied when
edits are saved. A dataset is not editable if an exclusive lock already exists.

Cursors and BLOB fields


A binary large object (BLOB) is data stored as a long sequence of binary numbers. ArcGIS stores
annotation and dimensions as BLOBs, and items such as images, multimedia, or bits of code can be
stored in this type of field. You can use a cursor to load or view the contents of a BLOB field.
In Python, BLOB fields can accept strings, bytearray, and memoryviews. When reading BLOB fields, a
memoryview object is returned.

import arcpy
data = open("c:/images/image1.png", "rb").read()
ic = arcpy.da.InsertCursor("c:/data/fgdb.gdb/fc", ['imageblob'])
ic.insertRow([data])

import arcpy
sc = arcpy.da.SearchCursor("c:/data/fgdb.gdb/fc", ["imageblob"])
memview = sc.next()[0]
open("c:/images/image1_copy.png", "wb").write(memview.tobytes())

Related topics
Reading geometries
Writing geometries

Copyright © 1995-2019 Esri. All rights reserved.

Reading geometries

Locate topic

Each feature in a feature class contains a set of points defining the vertices of a polygon or line, or a

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 67 of 95

single coordinate defining a point feature. These points can be accessed with geometry objects (Polygon,
Polyline, PointGeometry, or MultiPoint), which returns them in an array of Point objects.
Features can have multiple parts. The geometry object's partCount property returns the number of parts
for a feature. The getPart method returns an array of point objects for a particular part of the geometry if
an index is specified. If an index is not specified, an array containing an array of point objects for each
geometry part is returned.
PointGeometry features return a single Point object instead of an array of point objects. All other feature
types—polygon, polyline, and multipoint—return an array of point objects, or if the feature has multiple
parts, an array containing multiple arrays of point objects.
If a polygon contains holes, it consists of a number of rings. The array of point objects returned for a
polygon contains the points for the exterior ring and all inner rings. The exterior ring is always returned
first, followed by inner rings, with null point objects as the separator between rings. Whenever a script is
reading coordinates for polygons in a geodatabase or shapefile, it should contain logic for handling inner
rings if this information is required by the script; otherwise, only the exterior ring is read.
A multipart feature is composed of more than one physical part but only references one set of attributes in
the database. For example, in a layer of states, the state of Hawaii could be considered a multipart
feature. Although composed of many islands, it would be recorded in the database as one feature.
A ring is a closed path that defines a two-dimensional area. A valid ring consists of a valid path, such that
the from and to points of the ring have the same x,y coordinates. A clockwise ring is an exterior ring, and
a counterclockwise ring defines an interior ring.
Learn more about writing geometries

Using geometry tokens


Geometry tokens can also be used as shortcuts in place of accessing full geometry objects. Additional
geometry tokens can be used to access specific geometry information. Accessing the full geometry is
more time-consuming. If you only need specific properties of the geometry, use tokens to provide
shortcuts to access geometry properties. For instance, SHAPE@XY returns a tuple of x,y coordinates that
represent the feature's centroid.

Token Explanation

SHAPE@ A geometry object for the feature.


SHAPE@XY A tuple of the feature's centroid x,y coordinates.
SHAPE@TRUECENTROID A tuple of the feature's centroid x,y coordinates. This returns the same
value as SHAPE@XY.

SHAPE@X A double of the feature's x-coordinate.


SHAPE@Y A double of the feature's y-coordinate.
SHAPE@Z A double of the feature's z-coordinate.
SHAPE@M A double of the feature's m-value.
SHAPE@JSON The Esri JSON string representing the geometry.
SHAPE@WKB The well-known binary (WKB) representation for OGC geometry. It
provides a portable representation of a geometry value as a contiguous
stream of bytes.
SHAPE@WKT The well-known text (WKT) representation for OGC geometry. It
provides a portable representation of a geometry value as a text string.
SHAPE@AREA A double of the feature's area.
SHAPE@LENGTH A double of the feature's length.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 68 of 95

Reading point geometries


The examples below use SearchCursor to print the coordinates for all features.
Search cursor on a point feature class

import arcpy

infc = arcpy.GetParameterAsText(0)

# Enter for loop for each feature


for row in arcpy.da.SearchCursor(infc, ["SHAPE@XY"]):
# Print x,y coordinates of each point feature
x, y = row[0]
print("{}, {}".format(x, y))

With the above feature class, the script returns the following information:

2.0 4.0
8.0 10.0
7.0 5.0

Reading multipoint geometries


Search cursor on a multipoint feature class

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 69 of 95

import arcpy

infc = arcpy.GetParameterAsText(0)

# Enter for loop for each feature


for row in arcpy.da.SearchCursor(infc, ["OID@", "SHAPE@"]):
# Print the current multipoint's ID
print("Feature {}:".format(row[0]))

# For each point in the multipoint feature,


# print the x,y coordinates
for pnt in row[1]:
print("{}, {}".format(pnt.X, pnt.Y))

With the feature class above, the script returns the following information:

Feature 0:
3.0 8.0
4.0 4.0
6.0 6.0
Feature 1:
5.0 9.0
8.0 10.0
Feature 2:
9.0 5.0

Reading polyline or polygon geometries


Search cursor on a polygon or line feature class

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 70 of 95

import arcpy

infc = arcpy.GetParameterAsText(0)

# Enter for loop for each feature


for row in arcpy.da.SearchCursor(infc, ["OID@", "SHAPE@"]):
# Print the current polygon or polyline's ID
print("Feature {}:".format(row[0]))
partnum = 0

# Step through each part of the feature


for part in row[1]:
# Print the part number
print("Part {}:".format(partnum))

# Step through each vertex in the feature


for pnt in part:
if pnt:
# Print x,y coordinates of current point
print("{}, {}".format(pnt.X, pnt.Y))
else:
# If pnt is None, this represents an interior ring
print("Interior Ring:")

partnum += 1

With the feature class above, the script returns the information below. Feature 0 is a single-part
polygon, feature 1 is a two-part polygon, and feature 2 is a single-part polygon with an interior ring.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 71 of 95

Feature 0:
Part 0:
3.0 8.0
1.0 8.0
2.0 10.0
3.0 8.0
Feature 1:
Part 0:
5.0 3.0
3.0 3.0
3.0 5.0
5.0 3.0
Part 1:
7.0 5.0
5.0 5.0
5.0 7.0
7.0 5.0
Feature 2:
Part 0:
9.0 11.0
9.0 8.0
6.0 8.0
6.0 11.0
9.0 11.0
Interior Ring:
7.0 10.0
7.0 9.0
8.0 9.0
8.0 10.0
7.0 10.0

Related topics
Accessing data using cursors
Specifying a query in Python
Writing geometries
Using geometry objects with geoprocessing tools

Copyright © 1995-2019 Esri. All rights reserved.

Writing geometries

Locate topic

Using insert and update cursors, scripts can create new features in a feature class or update existing
ones. A script can define a feature by creating a Point object, populating its properties, and placing it in
an Array. That array can then be used to set a feature's geometry using Polygon, Polyline,
PointGeometry, or Multipoint geometry classes.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 72 of 95

import arcpy
fc = "c:/data/gdb.gdb/roads"
cursor = arcpy.da.InsertCursor(fc, ["SHAPE@"])
array = arcpy.Array([arcpy.Point(-77.4349451, 37.5408265),
arcpy.Point(-78.6384349, 35.7780943)])
spatial_reference = arcpy.SpatialReference(4326)
polyline = arcpy.Polyline(array, spatial_reference)

cursor.insertRow([polyline])

As shown above, a single geometry part is defined by an array of points. Likewise, a multipart feature can
be created from an array of arrays of points as shown below using the same cursor.

first_part = arcpy.Array([arcpy.Point(-77.4349451, 37.5408265),


arcpy.Point(-78.6384349, 35.7780943)])
second_part = arcpy.Array([arcpy.Point(-79.7910143, 36.0786785),
arcpy.Point(-80.8546435, 35.2315402)])

array = arcpy.Array([first_part, second_part])


spatial_reference = arcpy.SpatialReference(4326)
multipart_feature = arcpy.Polyline(array, spatial_reference)

cursor.insertRow([multipart_feature])

When writing point features, only a single point object is used to set the geometry of a point feature.
Points can also be created more easily (and efficiently) using the SHAPE@XY token (and SHAPE@M and
SHAPE@Z tokens, as needed).

import arcpy

# fc is a point feature class


fc = "c:/data/gdb.gdb/stops"
cursor = arcpy.da.InsertCursor(fc, ["SHAPE@XY"])
xy = (5997594.4753, 2069901.75682)

cursor.insertRow([xy])

All geometries are validated before they are written to a feature class. Issues such as incorrect ring
orientation and self-intersecting polygons, among others, are corrected when the geometry is simplified
before its insertion.
The following example shows how to read a set of coordinates (defined by coords_list) containing a
series of linear coordinates and use them to create a new feature class.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 73 of 95

# Create a new line feature class using a text file of coordinates.


# Each coordinate entry is semicolon delimited in the format of ID;X;Y
import arcpy
import os

# List of coordinates (ID, X, Y)


coords_list = [[1, -61845879.0968, 45047635.4861],
[1, -3976119.96791, 46073695.0451],
[1, 1154177.8272, -25134838.3511],
[1, -62051091.0086, -26160897.9101],
[2, 17365918.8598, 44431999.7507],
[2, 39939229.1582, 45252847.3979],
[2, 41170500.6291, 27194199.1591],
[2, 17981554.5952, 27809834.8945],
[3, 15519011.6535, 11598093.8619],
[3, 52046731.9547, 13034577.2446],
[3, 52867579.6019, -16105514.2317],
[3, 17160706.948, -16515938.0553]]

# The output feature class to be created


outFC = arcpy.GetParameterAsText(0)

# Get the template feature class


template = arcpy.GetParameterAsText(1)

cur = None
try:
# Create the output feature class
arcpy.CreateFeatureclass_management(os.path.dirname(outFC),
os.path.basename(outFC),
"POLYLINE", template)

# Access spatial reference of template to define spatial


# reference of geometries
spatial_reference = arcpy.Describe(template).spatialReference

# Open an insert cursor for the new feature class


cur = arcpy.da.InsertCursor(outFC, ["SHAPE@"])

# Create an array object needed to create features


array = arcpy.Array()

# Initialize a variable for keeping track of a feature's ID.


ID = -1
for coords in coords_list:
if ID == -1:
ID = coords[0]

# Add the point to the feature's array of points


# If the ID has changed, create a new feature
if ID != coords[0]:
cur.insertRow([arcpy.Polyline(array)])
array.removeAll()
array.add(arcpy.Point(coords[1], coords[2], ID=coords[0]))
ID = coords[0]

# Add the last feature


polyline = arcpy.Polyline(array, spatial_reference)

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 74 of 95

Multipart polygon and polyline features and polygon features with interior rings can be created by creating
an array of arrays and passing that to Polygon and Polyline classes.

Geometry creation from lists of coordinates


Geometry can also be created from a list of coordinates. This approach can provide performance gains,
as it avoids the overhead of creating geometry objects. However, it is limited to only features that are
singlepart, and in the case of polygons, without interior rings. All coordinates should be in the units of
the feature class's spatial reference.
In the example below, a single polygon feature is created from a list of x,y pairs.

import arcpy
import os

coordinates = [(-117.2000424, 34.0555514),


(-117.2000788, 34.0592066),
(-117.1957315, 34.0592309),
(-117.1956951, 34.0556001)]

# Create a feature class with a spatial reference of GCS WGS 1984


result = arcpy.management.CreateFeatureclass(
arcpy.env.scratchGDB,
"esri_square", "POLYGON", spatial_reference=4326)
feature_class = result[0]

# Write feature to new feature class


with arcpy.da.InsertCursor(feature_class, ['SHAPE@']) as cursor:
cursor.insertRow([coordinates])

Related topics
Accessing data using cursors
Specifying a query in Python
Reading geometries
Using geometry objects with geoprocessing tools

Copyright © 1995-2019 Esri. All rights reserved.

Working with NumPy in ArcGIS

Locate topic

Numerical Python (NumPy) is a fundamental package for scientific computing in Python, including support
for a powerful N-dimensional array object. NumPy provides a way to perform complex mathematical
operations and has been part of the ArcGIS software installation since 9.2. For more information, see the
NumPy website .
A Python NumPy array is designed to work with large arrays. There are many existing Python functions
that have been created to process NumPy arrays, the most noted being contained in the SciPy scientific
computing package for Python.

Working with tables and feature data

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 75 of 95

Table and feature classes can be converted to and from NumPy arrays using functions in the data
access (arcpy.da) module.
To convert NumPy arrays to tables and feature classes, the arrays must be structured arrays.
Structured arrays include fields (or structs) that are used to map the data to field in ArcGIS table and
feature classes. For more information on structured arrays, see Structured arrays .
Create a structured NumPy array.

import numpy

arr = numpy.array([(471316.383, 5000448.782), (470402.493, 5000049.216)],


numpy.dtype([('X', '>f8'),('Y', '>f8')]))
 
Once created, a structured NumPy array can be converted to a feature class or table.
Convert a NumPy array to a geodatabase feature class.

import arcpy
import numpy

out_fc = 'C:/data/texas.gdb/fd/pointlocations'

# Create a numpy array with an id field, and a field with a tuple


# of x,y coordinates
arr = numpy.array([(1, (471316.3835861763, 5000448.782036674)),
(2, (470402.49348005146, 5000049.216449278))],
numpy.dtype([('idfield', numpy.int32),('XY', '<f8', 2)]))

# Define a spatial reference for the output feature class


spatial_ref = arcpy.Describe('C:/data/texas.gdb/fd').spatialReference

# Export the numpy array to a feature class using the XY field to


# represent the output point feature
arcpy.da.NumPyArrayToFeatureClass(arr, out_fc, ['XY'], spatial_ref)
 
arcpy.da functions for working with tables and feature data
Functions Explanation
ExtendTable
Join the contents of a NumPy
structured array to a table
based on a common attribute
field.
FeatureClassToNumPyArray
Convert a feature class to a
NumPy structured array.
NumPyArrayToFeatureClass
Convert a NumPy structured
array to a feature class.
NumPyArrayToTable
Convert a NumPy structured
array to a table.
TableToNumPyArray
Convert a table to a NumPy
structured array.

Integer fields in NumPy arrays do not support nulls. If data converted using
FeatureClassToNumPyArray or TableToNumPyArray contains nulls, the rows containing the nulls

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 76 of 95

should either be skipped entirely or masked with a substitute value.


Skip all records that include a null.

arr = arcpy.da.FeatureClassToNumPyArray(fc, fields, skip_nulls=True)

Mask Nones in integer fields with different values using a dictionary.

fields = ['field1', 'field2']


arcpy.da.FeatureClassToNumPyArray(fc, fields, null_value=-9999)

Type conversions
The dtypes of the created array are determined from the field type of the input table or feature
class.

Field type NumPy dtype

Single numpy.float32

Double numpy.float64

SmallInteger numpy.int32

Integer numpy.int32

OID numpy.int32

GUID <U64

String <u1, <u10, and so on

Date <M8[us]

Note: String fields converted to an array will have the same width. For
instance, a string field with a width of 20 will have a dtype of <u20.

Other field types not listed above, including raster and BLOB fields, are not supported. Geometry
fields are also not supported, but multiple geometry properties can be added to the array using the
special tokens listed below.

Token Description

SHAPE@XY The feature's centroid x,y coordinates


SHAPE@TRUECENTROID The feature's true centroid x,y coordinates
SHAPE@X The feature's x-coordinate
SHAPE@Y The feature's y-coordinate
SHAPE@Z The feature's z-coordinate
SHAPE@M The feature's m-value
SHAPE@AREA The feature's area
SHAPE@LENGTH The feature's length

Memory considerations
An array that requires more memory than is available will fail with a MemoryError exception.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 77 of 95

The following are tips to avoid MemoryError exceptions:


l Delete array objects after use; deleting the array will release the memory.
l Use only those fields you need, especially text fields; a text field converted to an array will
consume 4 bytes for every character of width. For instance, a string field with a width of 100 will
consume 400 bytes of memory for each value in the array.

NumPy dtype Number of bytes per value

<U1 4
numpy.int32 4
numpy.float32 4
numpy.float64 8

Note: numpy.nbytes returns a dictionary of dtypes and number of bytes.

Working with rasters


Rasters can be converted to and from NumPy arrays using the ArcPy functions RasterToNumPyArray
and NumPyArrayToRaster. You may want to convert an ArcGIS raster to a NumPy array to do the
following:
l Implement one of the many existing Python functions that can be applied to a NumPy array (for
example, run filters on the data, perform multidimensional analysis, or use optimization routines).
l Develop a custom function by accessing the individual cells within the NumPy array (for example,
to implement neighborhood notation, change individual cell values, or run accumulative operators
on an entire raster).
arcpy functions for working with rasters
Functions Explanation
RasterToNumPyArray
Convert a raster to a NumPy
array.
NumPyArrayToRaster
Convert a NumPy array to a
raster.

A raster is converted to a NumPy array to calculate the percentage of the cell value in the entire raster
row. A new raster is then created.

import arcpy
import numpy

my_array = arcpy.RasterToNumPyArray('C:/data/inRaster')
my_array_sum = my_array.sum(1)
my_array_sum.shape = (my_array.shape[0], 1)
my_array_perc = (my_array * 1.0) / my_array_sum

new_raster = arcpy.NumPyArrayToRaster(my_array_perc)
new_raster.save("C:/output/fgdb.gdb/PercentRaster")

Copyright © 1995-2019 Esri. All rights reserved.

Using geometry objects with geoprocessing tools

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 78 of 95

Locate topic

In many geoprocessing workflows, you may need to run a specific operation using coordinate and
geometry information but don't necessarily want to go through the process of creating a new (temporary)
feature class, populating the feature class with cursors, using the feature class, then deleting the
temporary feature class. Geometry objects can be used instead for both input and output to make
geoprocessing easier. Geometry objects can be created from scratch using Geometry, Multipoint,
PointGeometry, Polygon, or Polyline classes.

Using geometry as input


The following sample creates a polygon geometry object created using a list of x,y coordinates. The
Clip tool is then used to clip a feature class with the polygon geometry object.

import arcpy

# List of coordinates.
coordinates = [
[2365000, 7355000],
[2365000, 7455000],
[2465000, 7455000],
[2465000, 7355000]]

# Create an array with a point object for each coordinate pair


array = arcpy.Array([arcpy.Point(x, y) for x, y in coordinates])

# Create a polygon geometry object using the array object


boundary = arcpy.Polygon(array, arcpy.SpatialReference(2953))

# Use the geometry to clip an input feature class


arcpy.Clip_analysis('c:/data/rivers.shp',
boundary,
'c:/data/rivers_clipped.shp')

Outputting geometry objects


Output geometry objects can be created by setting the output of a geoprocessing tool to an empty
geometry object. When a tool runs when set to an empty geometry object, the tool returns a list of
geometry objects. In the following example, the Copy Features tool is used to return a list of geometry
objects, which can then be looped through to accumulate the total length of all features.

import arcpy

# Run the CopyFeatures tool, setting the output to a geometry object.


# geometries is returned as a list of geometry objects.
#
geometries = arcpy.CopyFeatures_management('c:/temp/outlines.shp', arcpy.Geometry

# Walk through each geometry, totaling the length


#
length = sum([g.length for g in geometries])

print('Total length: {}'.format(length))


 

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 79 of 95

Related topics
Accessing data using cursors
Specifying a query in Python
Reading geometries
Writing geometries

Copyright © 1995-2019 Esri. All rights reserved.

Validating table and field names in Python

Locate topic

Validating table names


Geodatabases use various relational database management systems (RDBMS) to maintain the many
tables that comprise a geodatabase. All tables in a geodatabase must have a valid name, so a
mechanism for checking whether a table name is valid is essential when creating data in a
geodatabase. Using the ValidateTableName() function, a script can determine whether a specific
name is valid to a specific workspace.
The following are table name errors that will be validated:
l The table shares its name with a word reserved by the data source (for example, Table).
l The table contains an invalid character.
l The table has an invalid starting character (for example, using a number as the first character).

Note: The ValidateTableName function does not determine that the


specified name is unique to the specified workspace. The Exists
function can check to see whether the table name is unique for a
given workspace.

ValidateTableName function

Function Explanation

ValidateTableName(name, Takes a table name and a workspace path and returns a


{workspace}) valid table name for the workspace

Specifying the workspace as a parameter allows ArcPy to check all the existing table names and
determine whether there are naming restrictions imposed by the output workspace. If the output
workspace is an RDBMS, it may have reserved words that may not be used in a table name. It may
also have invalid characters that cannot be used in a table or field name. All invalid characters are
replaced with an underscore (_). ValidateTableName returns a string representing a valid table name
that may be the same as the input name if the input name is valid. The example below guarantees that
the new output feature class created by the Copy Features tool has a unique name that is valid in any
geodatabase:

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 80 of 95

"""Move all shapefiles from a folder into a geodatabase"""


import arcpy

# Set the workspace. List all of the shapefiles


arcpy.env.workspace = "d:/St_Johns"
fcs = arcpy.ListFeatureClasses("*")

# Set the workspace to SDE for ValidateTableName


arcpy.env.workspace = "Database Connections/Bluestar.sde"

# For each feature class name


for fc in fcs:
# Validate the output name so it is valid
outfc = arcpy.ValidateTableName(fc)

# Copy the features from the workspace to a geodatabase


arcpy.CopyFeatures_management(fc, outfc)

Validating field names


Each database can have naming restrictions for field names in a table. Objects such as feature classes
or relationship classes are stored as tables in an RDBMS, so these restrictions affect more than just
stand-alone tables. These restrictions may or may not be common among various database systems,
so scripts should check all new field names to ensure that a tool does not fail during execution.
The following are the field name errors that will be validated:
l The field shares its name with a word reserved by the data source (for example, Table).
l The field shares its name with a previously defined field.
l The field contains an invalid character (for example, *).
l The field name exceeds the data source's maximum length for field names.
ValidateFieldName function

Function Explanation

ValidateFieldName(name, Takes a string (field name) and a workspace path and returns a
{workspace}) valid field name based on name restrictions in the output
geodatabase

The example below ensures that a field is added, regardless of the input name, using the
ValidateFieldName function:

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 81 of 95

"""
Create a new numeric field containing the ratio of polygon area to
polygon perimeter. Two arguments, a feature class and field name,
are expected.
"""

# Define a pair of simple exceptions for error handling


class ShapeError(Exception):
pass

class FieldError(Exception):
pass

import arcpy
import os

try:
# Get the input feature class and make sure it contains polygons
input = arcpy.GetParameterAsText(0)
desc = arcpy.Describe(input)
if desc.shapeType.lower() != "polygon":
raise ShapeError

# Get the new field name and validate it


fieldname = arcpy.GetParameterAsText(1)
fieldname = arcpy.ValidateFieldName(fieldname, os.path.dirname(input))

# Make sure shape_length and shape_area fields exist


if len(arcpy.ListFields(input, "Shape_area")) > 0 and \
len(arcpy.ListFields(input, "Shape_length")) > 0:

# Add the new field and calculate the value


#
arcpy.AddField_management(input, fieldname, "double")
arcpy.CalculateField_management(input, fieldname,
"[Shape_area] / [Shape_length]")
else:
raise FieldError

except ShapeError:
print("Input does not contain polygons")

except FieldError:
print("Input does not contain shape area and length fields")

except arcpy.ExecuteError:
print(arcpy.GetMessages(2))
 
Related topics
Specifying a query in Python
Geodatabases
Table basics

Copyright © 1995-2019 Esri. All rights reserved.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 82 of 95

Executing SQL using an EGDB connection

Locate topic

Sometimes when working with tables that are not versioned, it may seem easier to query a table in a
database using Structured Query Language (SQL) rather than using one of the geoprocessing tools. The
ArcSDESQLExecute object supports the execution of most SQL statements and will return the results of
those statements. The object will return a list of lists in the case where the statement returns rows from a
table; for statements that do not return rows, it will return an indication of the success or failure of the
statement (True for success; None for failure). Statements that return a single value from a single row will
return the value in an appropriate type (string, float, and so on).

Caution: l Enterprise geodatabase system tables should not be altered using


anything other than ArcGIS software. Corruption can occur if these
system tables are edited directly using SQL.
l Edits on versioned data performed using SQL should only be done
through versioned views.
l For geodatabases implemented in a relational database
management system (DBMS) using DBMS data types and table
formats, the DBMS's own SQL may be used to work with the
information stored in the database.
l Accessing the information in a geodatabase via SQL allows external
applications to access the tabular data managed by the
geodatabase. These external applications may be nonspatial
database applications or custom spatial applications developed in an
environment other than ArcObjects. Be aware, though, that SQL
access to the geodatabase bypasses geodatabase functionality, such
as topology, networks, terrains, or other class or workspace
extensions.
l It may be possible to use DBMS features such as triggers and
stored procedures to maintain the relationships between tables
needed for certain geodatabase functionality. However, executing
SQL commands against the database without taking this extra
functionality into account—for example, issuing INSERT statements
to add records to a business table—will circumvent geodatabase
functionality and possibly corrupt the relationships between data in
your geodatabase.
l Before attempting to access or modify any enterprise geodatabase
objects, read all enterprise geodatabase documentation about using
SQL against geodatabase objects in the DBMS.

ArcSDESQLExecute properties

Property

transactionAutoCommit The autocommit interval. This can be used to force intermediate


commits after a specified number of features have been modified.
ArcSDESQLExecute methods

Methods

commitTransaction() No DML statements will be committed until the commitTransaction


method is called.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 83 of 95

Note: A commit may also occur when the connection


to the enterprise geodatabase is terminated
(check specific DBMS documentation to see how
each DBMS deals with a disconnect while in a
transaction).

execute Sends the SQL statement to the database via an enterprise geodatabase
(sql_statement) connection. If execute is run outside of a transaction, a commit will
automatically take place once the SQL DML (INSERT, UPDATE, DELETE)
statement has been executed.
rollbackTransaction Roll back any DML operations to the previous commit.
()

startTransaction() To control when your changes are committed to the database, call the
startTransaction method before calling execute. This starts a
transaction, and no DML statements will be committed until the
commitTransaction method is called.

The execute method sends the SQL statement to the database via an enterprise geodatabase connection.
If execute is run outside a transaction, a commit will automatically take place once the SQL DML (INSERT,
UPDATE, DELETE) statement has been executed.
ArcSDESQLExecute supports the geodatabase Transaction model. Transactions are a property of an
enterprise geodatabase connection and bind operations so that an entire set of changes is either recorded
or rejected. For example, if a set of parcels is being updated in a particular order, you can use a
transaction to define the beginning and end of the changes so that all changes are posted together. If a
set of changes can't be successfully inserted, the entire transaction is rejected. All transactions end when
a user disconnects. ArcSDESQLExecute uses the provided enterprise geodatabase API functions to start,
commit, and roll back transactions.
If you want to control when your changes are committed to the database, call the startTransaction
method before calling execute. This starts a transaction, and no DML statements will be committed until
the commitTransaction method is called. A commit may also occur when the connection to the enterprise
geodatabase is terminated (check specific DBMS documentation to see how each DBMS deals with a
disconnect while in a transaction). Within a transaction, it is also possible to roll back any DML operations
to the previous commit.
An autocommit interval property named transactionAutoCommit is available. This can be used to force
intermediate commits after a specified number of features have been modified.
See your specific DBMS SQL Reference guide for help writing SQL statements.

Examples
Execute a list of SQL statements

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 84 of 95

import sys
import arcpy

try:
# Make data path relative
arcpy.env.workspace = sys.path[0]

# Two ways to create the object, which also creates the


# connection to the enterprise geodatabase.
# Using the first method, pass a set of strings containing
# the connection properties:
# <serverName>, <portNumber>, <version>, <userName>, <password>
# arcpy.ArcSDESQLExecute("gpserver3","5151","#","toolbox","toolbox")
# Using the second method pass the path to a valid connection file
egdb_conn = arcpy.ArcSDESQLExecute(r"data\Connection to GPSERVER3.sde"

# Get the SQL statements, separated by ; from a text string.


sql_statement = arcpy.GetParameterAsText(0)
sql_statement_list = sql_statement.split(";")

print("+++++++++++++++++++++++++++++++++++++++++++++\n")

# For each SQL statement passed in, execute it.


for sql in sql_statement_list:
print("Execute SQL Statement: {0}".format(sql))
try:
# Pass the SQL statement to the database.
egdb_return = egdb_conn.execute(sql)
except Exception as err:
print(err)
egdb_return = False

# If the return value is a list (a list of lists), display


# each list as a row from the table being queried.
if isinstance(egdb_return, list):
print("Number of rows returned by query: {0} rows".format(
len(egdb_return)))
for row in egdb_return:
print(row)
print("+++++++++++++++++++++++++++++++++++++++++++++\n")
else:
# If the return value was not a list, the statement was
# most likely a DDL statement. Check its status.
if egdb_return == True:
print("SQL statement: {0} ran successfully.".format(sql))
else:
print("SQL statement: {0} FAILED.".format(sql))
print("+++++++++++++++++++++++++++++++++++++++++++++\n")

except Exception as err:


print(err)
 
Conditional update using a transaction

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 85 of 95

# WARNING - DO NOT USE ON VERSIONED TABLES OR FEATURE CLASSES.


# DO NOT USE ON ANY enterprise geodatabase SYSTEM TABLES.
# DOING SO MAY RESULT IN DATA CORRUPTION.

import sys
import arcpy

try:
# Make data path relative (not relevant unless data is moved
# here and paths modified)
arcpy.env.workspace = sys.path[0]

# Column name:value that should be in the record.


sql_values = {"STREET_NAM": "'EUREKA'"}

# Value that is incorrect if found in the above column.


bad_val = "'EREKA'"

#List of tables to look in for the bad value.


tables = ["streetaddresses_blkA", "streetaddresses_blkB",
"streetaddresses_blkC"]

# Two ways to create the object, which also creates the connection
# to the enterprise geodatabase.
# Using the first method, pass a set of strings containing the
# connection properties:
# <serverName>, <portNumber>, <version>, <userName>, <password>
egdb_conn = arcpy.ArcSDESQLExecute("gpserver3", "5151", "#",
"toolbox", "toolbox")

# Using the second method pass the path to a valid enterprise geodatabase connection f
# arcpy.ArcSDESQLExecute("data\Connection to GPSERVER3.sde")

for tbl in tables:


print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
for col, val in list(sql_values.items()):
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
# Check for the incorrect value in the column for the
# specific rows. If the table contains the incorrect value,
# correct it using the update SQL statement.
print("Analyzing table {0} for bad data: "
"Column:{1} Value: {2}".format(tbl, col, bad_val))
try:
sql = "select OBJECTID,{0} from {1} where {0} = {2}".format
col, tbl, bad_val)
print("Attempt to execute SQL Statement: {0}".format(sql))
egdb_return = egdb_conn.execute(sql)
except Exception as err:
print(err)
egdb_return = False

if isinstance(egdb_return, list):
if len(egdb_return) > 0:
print("Identified {0} rows with incorrect data. Starting "
"transaction for update.".format(len(egdb_return
# Start the transaction
egdb_conn.startTransaction()
print("Transaction started...")

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 86 of 95

Related topics
ArcSDESQLExecute

Copyright © 1995-2019 Esri. All rights reserved.

Extending geoprocessing through Python modules

Locate topic

By utilizing the Python Distribution Utilities (distutils), Python toolboxes and custom toolboxes containing
Models and/or Script Tools can be efficiently distributed to ArcGIS users in the form of Python modules.
The process for building and distributing these toolboxes starts with the creation of the Python module.
The module used in this example will be foo.py.
foo.py
Sample code to create the foo Python module:

import os

def hello():
print('Hello ' + os.getenv('username'))

In order for the module to be built and distributed correctly, a specific directory structure must exist. A
directory named foo must be created to store the foo module. Since distribution requires that the
directory storing the foo module be within a parent directory, a directory named src is created to house
the foo directory and the foo module. The directory structure should be the following:

In order for the foo module to initialize and automatically execute certain code once it has been imported,
it requires an __init__.py file. With the __init__.py in place, users will be able to access the foo module
and import selected definitions.
__init__.py
Sample code to create __init__.py for foo:

from foo import hello

The directory structure should now be the following:

With the files and directory structure in place, the foo module can be imported through import foo, and
foo.hello() can be called and executed. The next step is to build a distribution package for the foo
module so it can be installed into the Python site-packages directory in order to be easily shared. This is
done by writing a setup.py script.
setup.py

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 87 of 95

Sample code to create setup.py:

from distutils.core import setup


setup(name='foo',
version='1.0',
packages=['foo'],
package_dir={'foo': 'foo'},
)

The setup.py file sets the module name and version and points the build utility to the package directory.
The setup.py file should be saved to the src directory. At this point, the directory structure should be the
following:

With the directory structure in place, an installer can be built for the foo module by running one of the
commands below from within the src directory using the corresponding operating system command
prompt. This example is built on the Windows OS.

Note: Make sure that the path to python.exe is set on your system. In the
Windows OS, this can be done by adding the path of your Python
installation to the Path System Variable in the Windows OS
Environment Variables.

Windows:

python setup.py bdist_wininst

Linux:

python setup.py bdist_rpm

The Windows builder creates dist and build directories in the src directory. In the dist directory, foo-
1.0.win32.exe is created. This is an executable that can be distributed in order to install the foo module to
the Python site-packages directory on a Windows machine. As an alternative to running the executable to
install the foo module, the foo directory can also be copied directly from the build/lib directory into the
Python site-packages directory. If there are user restrictions in place that prohibit running an executable,
copying the foo directory from the build/lib directory to the site-packages directory will produce the
same effect as installing it through the executable. Once the foo module is installed or copied into the site-
packages directory, the structure should be the following:

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 88 of 95

This process can be further implemented to extend geoprocessing functionality by adding custom
toolboxes and/or Python toolboxes directly to the ArcGIS system toolboxes. As a system toolbox, it is
readily accessible in the list of system toolboxes within ArcGIS and can have ArcPy wrappers created for
extending ArcPy as well. In addition, this allows the custom toolbox module to take advantage of the well-
established methodology that ArcGIS system toolboxes have for message distribution, language-based
help, and response to localized settings. ArcGIS Desktop will search within the Python site-packages
location to see if a directory named esri exists within each module. The esri directory contains the custom
toolboxes along with their associated help files. The following is the directory structure for the English
language:

Custom toolboxes (.tbx and .pyt) are placed in the esri/toolboxes directory along with any supporting
scripts if using script tools. The esri/help/gp directory is where the toolbox and tool metadata (.xml) for
custom toolboxes and tools are stored. The naming convention for the toolbox is <toolbox
alias>_toolbox.xml and the naming convention for each tool is <toolname>_<toolbox alias>.xml. The
esri/help/gp/messages directory is where any geoprocessing message (.xml) files are placed. These
message files are used within the Python toolboxes for messages that need to be internationalized. The
toolbox and tool labels categories override files are located in the esri/help/gp/toolboxes directory.
Through the creation of a new Python toolbox named SamplePythonToolbox, the entire process of
extending geoprocessing through Python modules can be demonstrated. For additional information on
creating and working with Python toolboxes, see Creating a new Python toolbox.

Note: It is important to set an alias on the Python toolbox that will be used in
this process.

SamplePythonToolbox.pyt
Sample code to create a Python toolbox:

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 89 of 95

import arcpy
import os
import foo

class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Toolbox"
self.alias = "SampleToolbox"

# List of tool classes associated with this toolbox


self.tools = [SampleTool]

class SampleTool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Sample Tool"
self.description = ""
self.canRunInBackground = False

def getParameterInfo(self):
"""Define parameter definitions"""
params = None
return params

def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True

def updateParameters(self, parameters):


"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return

def updateMessages(self, parameters):


"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return

def execute(self, parameters, messages):


"""The source code of the tool."""
messages.AddMessage(os.getenv("username") + " welcome to the sample tool"
foo.hello()
return
 
In the SamplePythonToolbox.pyt, the foo module has been imported and the execute method of the
SampleTool class has called the hello function from the foo module. This is an effective way of
distributing custom Python code as a module and exposing its functionality through ArcGIS geoprocessing
tools. Once the SamplePythonToolbox.pyt is created and the side-panel help has been configured for the
toolbox through the metadata edited in the Item Description context menu or a custom compiled help file
(.chm) has been created, it and its accompanying .xml files must be copied over from the directory where
it was created. Using ArcCatalog or the Catalog window, copy the files into the esri/toolboxes directory

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 90 of 95

that exists in the distribution structure. The esri directory and file layout should be the following:

The new directory structure for the distribution should be the following:

In order to reflect these changes in our distribution, the setup.py file must be edited.
The new setup.py
Sample code to include setup.py directory changes:

from distutils.core import setup


setup(name='foo',
version='1.0',
packages=['foo'],
package_dir={'foo': 'foo'},
package_data={'foo': ['esri/toolboxes/*.*']},
)

The new setup.py differs from the original by one line where the additional data found within the esri
directory is added to the package. Now when the builder for the foo module is executed and installed, the
following directory structure will be created in the Python site-packages directory:

Using ArcGIS Desktop and the Python Distribution Utilities (Distutils), it is possible to build and install a
package that extends geoprocessing with custom tools in custom toolboxes that can be viewed and
executed from within the ArcGIS system toolboxes. For English language distributions, this is all that is
needed. The Internationalization topic expands on the process of extending geoprocessing to utilize the
same methodology used by Esri to package the module for distribution in languages other than English.

Related topics

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 91 of 95

Internationalization of Python modules

Copyright © 1995-2019 Esri. All rights reserved.

Internationalization of Python modules

Locate topic

When distributing geoprocessing toolboxes with Python modules, the modules can be customized to
support all the languages supported by ArcGIS. The help and support files for these supported languages
are stored in the help directory. The following shows the help directory structure, if being created for all
10 languages, with English as the default:

The locale setting of the operating system is used to determine which directory is searched initially. The
top-level gp directory is used for the English language and is the default when the file being searched is
not found within one of the language-specific directories. The messages directory contains the .xml file of

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 92 of 95

localizable strings used within the Python toolbox and Python script tools, while the toolboxes directory is
used to override the localizable labels for binary toolboxes (custom toolboxes containing model and script
tools).
The gp directory stores the .xml files for the side-panel help in the toolbox and the tool. These .xml files
are generated from the toolbox's metadata edited in the Item Description context menu by using the
createtoolboxsupportfiles function below. The command works on any toolbox.

Note: Make sure that an alias is set on the toolbox before running the
command. The alias is needed to generate the side-panel help files.

arcpy.gp.createtoolboxsupportfiles(<path to .tbx or .pyt>)

This command will generate all the toolbox support files found within the esri folder structure described
above. The esri directory is created in the same location as the toolbox pointed to in the input path for the
command. The newly generated esri directory structure should be

The side-panel help files are placed into the esri/help/gp directory, the localizable labels file is placed in
the esri/help/gp/toolboxes directory, and the ArcPy wrapper for the toolbox is created in the
esri/arcpy directory. Additionally, the messages directory needs to be created in the esri/help/gp
directory to make the error messages used in the script tools or Python toolboxes localizable and, in case
it has not been done yet, the toolboxes directory that stores the toolbox and any supporting Python
scripts must be copied into the existing distribution structure. With the messages directory created and
the toolboxes directory copied into the esri directory, the structure should be

With the localized properties of the toolboxes and tools in place through the creation of the language-
specific .xml files under esri/help/gp and esri/help/gp/toolboxes, one additional .xml file is needed
to store the localized error messages used in the script tools or Python toolboxes. Within the
esri/help/messages directory, create a new .xml file named messages.xml.
messages.xml

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 93 of 95

The following is sample code to create messages.xml.

<Messages>
<Message><ID>unique_string</ID><Description>%1 welcome to the sample tool</Description></Me
</Messages>
 
To reflect this change, the execute method from the SamplePythonToolbox.pyt from Extending
geoprocessing through Python modules needs to be edited to use the AddIDMessage method instead of
AddMessage. The new execute method should be
Python toolbox execute method
The following is sample code to edit the execute method in the SamplePythonToolbox.pyt.

def execute(self, parameters, messages):


"""The source code of the tool."""
messages.AddIDMessage('informative', 'unique_string', os.getenv('username'
foo.hello()
return
 
The AddIDMessage method provides an effective way of accessing the external messages stored in the
messages.xml file in the esri/help/messages directory. In this case, it uses the message marked with
the unique_string ID. The message can be any string. The Python ID messages take either an integer or a
string; the integers reference Esri messages, and the strings should be used by third-party developers or
users. Since it is easier to make strings unique, one suggestion is to set the message ID with a company
name.
With these changes in place, the new distribution directory structure should be

To reflect these changes, setup.py needs to be edited. The new setup.py for localization should be
New setup.py for localization
The following is sample code for setup.py to include localization directories.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 94 of 95

from distutils.core import setup


setup(name='foo',
version='1.0',
packages=['foo'],
package_dir={'foo': 'foo'},
package_data={'foo': ['esri/toolboxes/*.*', 'esri/arcpy/*.*', 'esri/help/gp/*.*'
'esri/help/gp/messages/*.*', 'esri/help/gp/toolboxes/*.*']},
)
 
The .xml files can now be edited into any language for toolbox and module support and copied into the
respective language directory as outlined above. If the language files are being distributed for Spanish
along with English, the directory structure should be

For the Spanish localization distribution changes to be implemented, the setup.py needs to be edited. The
new setup.py that includes the Spanish localization should be
New setup.py for Spanish localization
The following is sample code for setup.py to include Spanish localization directories.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 95 of 95

from distutils.core import setup


setup(name='foo',
version='1.0',
packages=['foo'],
package_dir={'foo': 'foo'},
package_data={'foo': ['esri/toolboxes/*.*', 'esri/arcpy/*.*',
'esri/help/gp/*.*', 'esri/help/gp/messages/*.*',
'esri/help/gp/toolboxes/*.*', 'esri/help/es/gp/*.*',
'esri/help/es/gp/messages/*.*', 'esri/help/es/gp/toolboxes/*.*']},
)
 
Following this process, it is possible to build and distribute a single installable package that will support
multiple languages and respond to the locale setting of the operating system in a straightforward .xml-
based approach. By extending geoprocessing through Python modules, all 10 languages that are
supported in ArcGIS can be distributed without the need to create toolboxes and tools for each language.

Related topics
Extending geoprocessing through Python modules

Copyright © 1995-2019 Esri. All rights reserved.

file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024

You might also like