0% found this document useful (0 votes)
7 views

Lec 3

Uploaded by

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

Lec 3

Uploaded by

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

GIS Programming

Moffat Magondu
Introduction to Geoprocessing Using Python

• Modules, or code libraries that can be called by a script to increase


its programming potential, are either built into Python or are created
by third parties and added later to Python.
• Most of these are written in Python, but a number of them are also
written in other programming languages and then “wrapped” in
Python to make them available within Python scripts.
• Modules are also used to make other programs available to Python,
such as the tools built in Microsoft Word.
• The ArcPy module is a wrapper module used to interact with the
ArcGIS tools, which are then executed by ArcGIS in its internal code
format, and a code base that allows for additional control of
geospatial analyses and map production.
Introduction to Geoprocessing Using Python

• ArcPy is used to control the tools in ArcToolbox, but the tools have
not been rewritten in Python; instead, we are able to use the ArcGIS
tools using ArcPy.
• ArcPy also gives us the ability to control ArcGIS Map Documents(
MXDs) and the objects that MXDs include: legends, titles, images,
layers, and the map view itself.
• ArcPy also has tools that are not available in ArcToolbox. The most
powerful of these are the data cursors.
• The ability to control geospatial analyses using ArcPy allows for the
integration of ArcGIS tools into workflows that contain other
powerful Python modules.
• Python’s “glue language” abilities increase the usefulness of ArcGIS
by reducing the need to treat geospatial data in a special manner.
Introduction to Geoprocessing Using Python

Assignment 1:
1. Install python in your computer or check if it is already installed if
you have installed ArcGIS 10….
2. Read and write short notes on
i. How Python executes a script: What is python interpreter, where is it
located, how does the interpreter work, Which Python interpreter should
be used, How does the computer know where the interpreter is etc.
ii. Python folder structure: Where modules reside,
iii. Integrated Development Environments (IDEs): What are they ?, discuss
the most common ones IDLE, Python WIN and Aptana Studio 3.
iv. There are many other IDEs, both commercial and free, available for coding
in Python. In the end, each GIS analyst must choose the tool that makes
them feel productive and comfortable. look for one more that interest you
discuss its advantages.
Introduction to Geoprocessing Using Python

• ArcPy Site Package:


• The geoprocessing functionality of ArcGIS can be accessed through Python
using the ArcPy site package.
• A site package in Python is like a library of functions that add functionality to
Python. The site package works very much like a module, but a package
contains multiple modules as well as functions and classes.
• ArcPy is organized in modules, functions, tools, and classes.
• Importing ArcPy
• Working with ArcPy starts with importing the site package. A typical
geoprocessing script therefore starts with the following line of code:
import arcpy

• Once you import ArcPy, you can run all the geoprocessing tools found in the
standard toolboxes installed with ArcGIS.
Introduction to Geoprocessing Using Python

• Importing ArcPy
• ArcPy contains many modules, including two specialized ones: a map
automation module (arcpy.mapping) and a map algebra module (arcpy.sa).
• To import these modules, you can use the following syntax:
import arcpy.mapping

• Once you import ArcPy or one of its specialized modules, you can start using
its modules, functions, and classes.
• One of the first tasks typically is to set the current workspace. For example,
here is how you would set the current workspace to C:\Data:
import arcpy
arcpy.env.workspace = "C:/Data"
Introduction to Geoprocessing Using Python

• Importing ArcPy
• Often you may not need to use the entire module.
• You can use the from-import statement to import only a portion of a module.
The following code imports just the env class. Instead of accessing
environments using arcpy.env, you can simplify it to env.
from arcpy import env
env.workspace = "C:/Data"

• You can further control the importing of modules by giving a module or part
of a module a custom name using the from-import-as statement as follows:
from arcpy import env as myenv
myenv.workspace = "C:/Data"
Introduction to Geoprocessing Using Python

• Using GP Tools
• When working with geoprocessing tools in Python, the tools are referred to
by name.
• This does not correspond exactly to the tool label, which is how the tool
appears in ArcToolbox.
• A tool name is generally very similar to the tool label but contains no spaces.
For example, the name of the Add Field tool in the Data Management
toolbox is AddField.
• In addition to using the tool name rather than the tool label, a reference to a
particular tool also requires the toolbox alias. It is because multiple tools in
different toolboxes can share the same name.
• The easiest way to call a tool is to call its corresponding function.
• All tools are available as functions in ArcPy.
• An ArcPy function is a defined bit of functionality that does a specifc task.
The syntax for calling a tool by its function is as follows:
Introduction to Geoprocessing Using Python

• Using GP Tools
• An ArcPy function is a defined bit of functionality that does a specifc task.
• The syntax for calling a tool by its function is as follows:

arcpy.<toolname_toolboxalias>(<para
meters>)
• For example, the following code runs the Clip tool:
import arcpy
arcpy.env.workspace = "C:/Data"
arcpy.Clip_analysis(“kenya_rivers.shp",
“kiambu.shp", “Kiambu_rivers.shp")
• A key aspect of running geoprocessing tools is to get the syntax right for the
parameters.
Introduction to Geoprocessing Using Python

• Using GP Tools
• Every geoprocessing tool has parameters, required and optional, that provide
the tool with the information it needs for execution.
• Common parameters are input datasets, output datasets, and keywords that
control the execution of the tool. The documentation of each tool describes
its parameters and properties.
• Listing required parameters first makes it easy to simply leave out the
optional parameters when they are not needed.
• Sometimes, however, some of the optional parameters need to be set.
• Because parameters need to be specified in the order that they are listed in
the tool syntax, it can mean that some optional parameters may need to be
skipped.
• Consider, for example, the syntax of the Buffer tool:
Buffer_analysis (in_features, out_feature_class,
buffer_distance_or_
field,{line_side},{line_end_type},{dissolve_option},
{dissolve_field})
Introduction to Geoprocessing Using Python
• Using GP Tools
• A code example of the Buffer tool is as follows:
import arcpy
arcpy.env.workspace = "C:/Data/study.gdb"
arcpy.Buffer_analysis("roads", "buffer",
"100 METERS")
• Using this example, how would you specify the optional dissolve_option
parameter and skip the other optional parameters that follow the required
parameters? It can be accomplished in different ways, as follows:
• By setting the optional parameters using an empty string ("") or the
number sign ("#")
• By specifying by name the parameter that needs to be set, bypassing all
others
Introduction to Geoprocessing Using Python

• Using GP Tools
• In the above examples, the parameters of the tool use the actual file name
(for example, “roads”).
• This means the file names are hard-coded. That is, the parameters are not
set as variables, but use the values directly.
• Although this syntax is correct and works fine, it is often more useful to make
your code flexible by using variables for parameters instead of using file
names.
• First, create a variable and assign it a value. Then you can use the variable as
a parameter. These variable values are passed to the tool.
• For example, in the case of the Clip tool, it would look like this:
import arcpy
arcpy.env.workspace = "C:/Data"
infc = “kenya_rivers.shp"
clipfc = “kiambu.shp"
outfc = “Kiambu_rivers.shp"
arcpy.Clip_analysis(infc, clipfc, outfc)
Introduction to Geoprocessing Using Python

• Using GP Tools
• The next is to have the values of the variables provided by a user or another
tool, which means the actual file names would no longer appear in the script.
• For example, the following code runs the Copy tool, and the input and
output feature classes are obtained from user input using the
GetParameterAsText function:

import arcpy
infc = arcpy.GetParameterAsText(0)
outfc = arcpy.GetParameterAsText(1)
arcpy.Copy_management(infc, outfc)

• Setting tool parameters based on user input is commonly used for script
tools. Working with variables in this way gives you more flexibility and makes
much of your code reusable.
Introduction to Geoprocessing Using Python

• Using GP Tools
• ArcPy returns the output of a tool as a result object.
• When the output of a tool is a new or updated feature class, the result object
includes the path to the dataset.
• For other tools, however, the result object can consist of a string, a number,
or a Boolean value.
• For example, in the following code, a geoprocessing tool is run and the
output is returned as a result object:

import arcpy
arcpy.env.workspace = "C:/Data"
mycount =
arcpy.GetCount_management(“rivers.shp")
print mycount

• This code displays the string representation of the result object. For
example:3153
Introduction to Geoprocessing Using Python

• Using GP Tools
• When the output of a tool consists of a feature class, the result object
includes the path to the dataset.
• For example, the following code runs the Clip tool:
import arcpy
arcpy.env.workspace = "C:/Data"
myresult = arcpy.analysis.Clip(“kenya_rivers.shp",
“kiambu.shp", “Kiambu_rivers.shp")

print myresult

C:/Data/Kiambu_rivers.shp
• Running the code displays the string representation of the path to the output
dataset:

• The result object can be used as an input to another function.


Introduction to Geoprocessing Using Python

• Using GP Tools
• For example, in the following code, a feature class is buffered using the
Buffer tool.
• The output polygon feature class is returned as an object and the object is
used as the input to the Get Count tool, as follows:
import arcpy
arcpy.env.workspace = "C:/Data/trial.gdb"
buffer = arcpy.Buffer_analysis(“road", “road_buf",
"100 METERS")
count = arcpy.GetCount_management(buffer)
print count
• Although many tools have only a single output, some tools have multiple
outputs.
• The getOutput method of the result object can be used to obtain a specifc
output by using an index number.
Introduction to Geoprocessing Using Python

• Using GP Tools
• A more generic way to get a geoprocessing result follows:
import arcpy
arcpy.env.workspace = "C:/Data/study.gdb"
buffer = arcpy.Buffer_analysis(“road",
“road_buf", "100 METERS")
count =
arcpy.GetCount_management(buffer).getOutput(
0)
print str(count)

• This means that you can create a series of geoprocessing operations, just as
in ModelBuilder, and only the final desired output is returned back to the
application that called the script.
Introduction to Geoprocessing Using Python

• Working with Third-Party Toolboxes


• When the ArcPy site package is imported into Python, all the system
toolboxes are available.
• When custom tools are created and stored in a custom toolbox, these tools
can be accessed in Python only by importing the custom toolbox.
• So even if a custom toolbox has been added to ArcToolbox in ArcMap or
ArcCatalog, Python is not aware of this toolbox until it has been imported.
• This is accomplished using the ImportToolbox function. The following code
illustrates how to import a toolbox:

import arcpy
arcpy.ImportToolbox("C:/Data/sample
tools.tbx")
Introduction to Geoprocessing Using Python

• Using Environment Settings


• Environment settings are exposed as properties of the env class.
• These properties can be used to retrieve the current values or to set them.
Each property has a name and a label.
• The labels are displayed on the Environment Settings dialog box in ArcGIS,
but Python works with names only.
• The env class also has many other properties. A complete list can be found in
the ArcPy documentation.
• Some important properties include the extent, the output coordinate system,
the scratch workspace, and the XY domain.
• Some properties are specific either to feature classes or to raster datasets.
For example, cell size, compression, and mask are used for raster datasets
only.
• The following code sets the cell size to 30:
Introduction to Geoprocessing Using Python

• Using Environment Settings


• The following code sets the cell size to 30:
import arcpy
from arcpy import env
env.cellSize = 30

• The properties of the env class not only specify environments, but can also
be used to retrieve their current values.
• For example, the following code retrieves the current settings for the XY
tolerance:
import arcpy
from arcpy import env
print env.XYTolerance
Introduction to Geoprocessing Using Python

• Using Environment Settings


• To get a complete list of properties, you can use the ArcPy ListEnvironments
function:
import arcpy
print arcpy.ListEnvironments()

• The default value of the overwriteOutput property is False. The following


code sets the value to True:
import arcpy
from arcpy import env
env.overwriteOutput = True
Introduction to Geoprocessing Using Python

• Working with Licenses


• Licenses for extensions can be retrieved for use in a script and returned once
they are no longer needed.
• This is similar to checking out licenses from within ArcMap or ArcCatalog
using the Customize > Extensions option.
• The CheckExtension function is used to check whether a license is available to
be checked out. For example:
import arcpy
arcpy.CheckExtension("spatial")

• The CheckExtension function returns a string and can have one of four
possible values:
• Available—requested license is available to be set.
• Unavailable—requested license is unavailable to be set.
• NotLicensed—requested license is not valid.
• Failed—system failure occurred during license request.
Introduction to Geoprocessing Using Python
• Working with Licenses
• Once the availability of a license is determined, the CheckOutExtension
function can be used to actually obtain the license.
• Once a script runs the tools that required the particular license, the
CheckInExtension function can be used to return the license to the license
manager.
• For example, the following code first checks the availability of a license for
ArcGIS 3D Analyst, and if the license is available, a license is obtained and
then returned after the tool is finished running:
Introduction to Geoprocessing Using Python
• Working with Licenses
• The CheckOutExtension function returns a string, and there are three
possible return values: (1) NotInitialized, (2) Unavailable, and(3) CheckedOut.

• Typically, you would use the CheckExtension function to first determine the
availability of the license before using the CheckOutExtension function.

• The CheckInExtension function returns a string, and there are three possible
return values: (1) NotInitialized,(2) Failed, and (3) CheckedIn.

You might also like