Prueba 4
Prueba 4
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.
Related topics
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 2 of 95
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 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 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
Locate topic
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.
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 4 of 95
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 5 of 95
if arcpy.env.cellSize != 30:
arcpy.env.cellSize = 30
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")
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
Related topics
What is Python?
Essential Python vocabulary
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
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:
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:
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.
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"
# 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:
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.
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
arcpy.CheckOutExtension("spatial")
arcpy.CheckOutExtension("spatial")
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 10 of 95
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?
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"
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"
# 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]
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"
import arcpy
in_features = "c:/temp/rivers.shp"
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.
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")
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
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.
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
# 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
dem = "c:/dems/k_ne_g"
# 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)
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
# Use GetParameterValue to get a featureset object with the default schema of the
# first parameter of the tool 'bufferpoints'
#
inFeatureSet = arcpy.GetParameterValue("bufferpoints", 0)
# 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
# Use Python's urllib module's urlretrieve method to copy the image locally
#
urllib.urlretrieve(mapimage, "c:/base/road_buffer.jpg")
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.
# 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
# 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
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
Related topics
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 20 of 95
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
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
Classes can be used repeatedly; in the following example, two unique point objects are created by using
the Point class.
import arcpy
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.
import arcpy
inputWorkspace = "c:/temp"
outputName = "rivers.shp"
Related topics
Using tools in Python
Using functions 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.
import arcpy
arcpy.env.workspace = "c:/data"
import arcpy
arcpy.env.spatialGrid1 = float(grid_index) / 2
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"
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.
import arcpy
inputFC = arcpy.GetParameterAsText(0)
clipFC = arcpy.GetParameterAsText(1)
outputFC = arcpy.GetParameterAsText(2)
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 24 of 95
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
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
Related topics
Setting environments in the Python window
env
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
Severity Description
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
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"
# Print the last message - ending and elapsed times for tool
print(arcpy.GetMessage(arcpy.GetMessageCount - 1))
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 27 of 95
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"
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
featset = arcpy.FeatureSet()
featset.load("//flames/gpqa/coredata/global/redlands/control.shp")
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")
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.
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)
except:
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Return python error messages for use in script tool or Python window
arcpy.AddError(pymsg)
arcpy.AddError(msgs)
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 32 of 95
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>
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")
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.
Related topics
Understanding message types and severity
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")
Related topics
Paths explained: Absolute, relative, UNC, and URL
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
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()
The following sample provides an approach for viewing current toolboxes in Python.
import arcpy
Related topics
Create lists of data
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.
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
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:
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 38 of 95
ArcScan ArcScan
StreetMap StreetMap
Product Codes
Engine
EngineGeoDB
ArcServer
Licensing functions
Function Explanation
Return
Meaning
Value
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 39 of 95
Return
Meaning
Value
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
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
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")
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.
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.
>>> 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']
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"):
import arcpy
import os
workspace = "c:/data"
rasters = []
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 44 of 95
import arcpy
import os
analyze_contents = []
# 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]
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
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
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'])
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')
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)
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
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"
# 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)
# 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"
# 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"),
# Create a value table that will hold the inputs for Merge.
#
vTab = arcpy.ValueTable()
vTab.addRow(fc1)
vTab.addRow(fc2)
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 50 of 95
Locate topic
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.
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.
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)
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
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 53 of 95
import arcpy
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
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
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'
Property Explanation
Property Explanation
Tip: ListFields and ListIndexes can be used to limit the results based on
name and type.
Related topics
ListFields
ListIndexes
Create lists of data
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 55 of 95
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
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)
Note: For a full list of properties and methods, see SpatialReference class.
Related topics
SpatialReference
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
Property Explanation
import arcpy
import arcpy
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
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 58 of 95
import arcpy
import time
import arcpy
# 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")
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]]
results = arcpy.BufferPoints_servertools(feature_set)
Related topics
A quick tour of using Feature Set and Record Set
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"
If the data resides in an enterprise geodatabase, the name must be fully qualified.
import arcpy
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
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"
import arcpy
fc = "D:/St_Johns/data.gdb/roads"
fieldname = "roadclass"
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 62 of 95
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
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 Explanation
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
import arcpy
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:
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 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
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
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"
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)
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.
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.
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
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
Token Explanation
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 68 of 95
import arcpy
infc = arcpy.GetParameterAsText(0)
With the above feature class, the script returns the following information:
2.0 4.0
8.0 10.0
7.0 5.0
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)
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
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)
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
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.
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
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
cur = None
try:
# Create the output feature class
arcpy.CreateFeatureclass_management(os.path.dirname(outFC),
os.path.basename(outFC),
"POLYLINE", template)
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.
import arcpy
import os
Related topics
Accessing data using cursors
Specifying a query in Python
Reading geometries
Using geometry objects with geoprocessing tools
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.
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
import arcpy
import numpy
out_fc = 'C:/data/texas.gdb/fd/pointlocations'
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
Type conversions
The dtypes of the created array are determined from the field type of the input table or feature
class.
Single numpy.float32
Double numpy.float64
SmallInteger numpy.int32
Integer numpy.int32
OID numpy.int32
GUID <U64
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
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
<U1 4
numpy.int32 4
numpy.float32 4
numpy.float64 8
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")
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.
import arcpy
# List of coordinates.
coordinates = [
[2365000, 7355000],
[2365000, 7455000],
[2465000, 7455000],
[2465000, 7355000]]
import arcpy
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
Locate topic
ValidateTableName function
Function Explanation
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
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.
"""
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
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
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 82 of 95
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).
ArcSDESQLExecute properties
Property
Methods
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 83 of 95
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]
print("+++++++++++++++++++++++++++++++++++++++++++++\n")
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024
What is Python? Page 85 of 95
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]
# 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")
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
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:
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
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:
Linux:
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"
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
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:
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
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.
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
<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.
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
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
Related topics
Extending geoprocessing through Python modules
file:///C:/Users/agea1/AppData/Local/Temp/arc3AED/~hh58BB.htm 23-06-2024