Book Image

Programming ArcGIS with Python Cookbook, Second Edition

By : Donald Eric Pimpler, Eric Pimpler
Book Image

Programming ArcGIS with Python Cookbook, Second Edition

By: Donald Eric Pimpler, Eric Pimpler

Overview of this book

Table of Contents (22 chapters)
Programming ArcGIS with Python Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

ArcGIS is an industry-standard geographic information system from Esri.

This book will show you how to use the Python programming language to create geoprocessing scripts, tools, and shortcuts for the ArcGIS for Desktop environment.

It will make you a more effective and efficient GIS professional by showing you how to use the Python programming language with ArcGIS for Desktop to automate geoprocessing tasks, manage map documents and layers, find and fix broken data links, edit data in feature classes and tables, and much more.

Programming ArcGIS with Python Cookbook Second Edition, starts by covering fundamental Python programming concepts in an ArcGIS for Desktop context. Using a how-to instruction style, you'll then learn how to use Python to automate common important ArcGIS geoprocessing tasks.

In this book, you will also cover specific ArcGIS scripting topics that will help save you time and effort when working with ArcGIS. Topics include managing map document files, automating map production and printing, finding and fixing broken data sources, creating custom geoprocessing tools, and working with feature classes and tables, among others.

In Programming ArcGIS with Python Cookbook Second Edition, you'll learn how to write geoprocessing scripts using a pragmatic approach designed around accomplishing specific tasks in a cookbook style format.

What this book covers

Chapter 1, Fundamentals of the Python Language for ArcGIS, will cover many of the basic language constructs found in Python. Initially, you'll learn how to create new Python scripts or edit existing scripts. From there, you'll get into language features, such as adding comments to your code, variables, and the built-in typing systems that makes coding with Python easy and compact. Furthermore, we'll look at the various built-in data types that Python offers, such as strings, numbers, lists, and dictionaries. In addition to this, we'll cover statements, including decision support and looping structures for making decisions in your code, and/or looping through a code block multiple times.

Chapter 2, Managing Map Documents and Layers, will use the ArcPy mapping module to manage map document and layer files. You will learn how to add and remove geographic layers from map document files, insert layers into data frames, and move layers around within the map document. You will also learn how to update layer properties and symbology.

Chapter 3, Finding and Fixing Broken Data Links, will teach you how to generate a list of broken data sources in a map document file and apply various ArcPy mapping functions to fix these data sources. You will learn how to automate the process of fixing data sources across many map documents.

Chapter 4, Automating Map Production and Printing, will teach you how to automate the process of creating production-quality maps. These maps can then be printed, exported to image file formats, or exported to PDF files for inclusion in map books.

Chapter 5, Executing Geoprocessing Tools from Scripts, will teach you how to write scripts that access and run geoprocessing tools provided by ArcGIS.

Chapter 6, Creating Custom Geoprocessing Tools, will teach you how to create custom geoprocessing tools that can be added to ArcGIS and shared with other users. Custom geoprocessing tools are attached to a Python script that processes or analyzes geographic data in some way.

Chapter 7, Querying and Selecting Data, will teach you how to execute the Select by Attribute and Select by Location geoprocessing tools from a script to select features and records. You will learn how to construct queries that supply an optional where clause for the Select by Attribute tool. The use of feature layers and table views as temporary datasets will also be covered.

Chapter 8, Using the ArcPy Data Access Module with Feature Classes and Tables, will teach you how to create geoprocessing scripts that select, insert, or update data from geographic data layers and tables. With the new ArcGIS 10.1 Data Access module, geoprocessing scripts can create in-memory tables of data, called cursors, from feature classes and tables. You will learn how to create various types of cursors, including search, insert, and update.

Chapter 9, Listing and Describing GIS Data, will teach you how to obtain descriptive information about geographic datasets through the use of the ArcPy Describe function. As the first step in a multistep process, geoprocessing scripts frequently require that a list of geographic data be generated followed by various geoprocessing operations that can be run against these datasets.

Chapter 10, Customizing the ArcGIS Interface with Add-ins, will teach you how to customize the ArcGIS interface through the creation of Python add-ins. Add-ins provide a way of adding user interface items to ArcGIS for Desktop through a modular code base designed to perform specific actions. Interface components can include buttons, tools, toolbars, menus, combo boxes, tool palettes, and application extensions. Add-ins are created using Python scripts and an XML file that define how the user interface should appear.

Chapter 11, Error Handling and Troubleshooting, will teach you how to gracefully handle errors and exceptions as they occur while a geoprocessing script is executing. ArcPy and Python errors can be trapped with the Python try/except structure and handled accordingly.

Chapter 12, Using Python for Advanced ArcGIS, covers the use of the ArcGIS REST API with Python to access services exposed by ArcGIS Server and ArcGIS Online. You will learn how to make HTTP requests and parse the responses, export maps, query map services, perform geocoding, and more. Also covered in this chapter are some miscellaneous topics related to ArcPy FieldMap and FieldMappings, as well as working with ValueTables.

Chapter 13, Using Python with ArcGIS Pro, covers some distinctions between the new ArcGIS Pro environment and ArcGIS for Desktop related to Python and, in particular, the Python Window for writing and executing code.

Appendix A, Automating Python Scripts, will teach you how to schedule geoprocessing scripts to run at a prescribed time. Many geoprocessing scripts take a long time to fully execute and need to be scheduled to run during nonworking hours on a regular basis. You will learn how to create batch files containing geoprocessing scripts and execute these at a prescribed time.

Appendix B, Five Python Recipes Every GIS Programmer Should Know, will teach you how to write scripts that perform various general purpose tasks with Python. Tasks, such as reading and writing delimited text files, sending e-mails, interacting with FTP servers, creating ZIP files, and reading and writing JSON and XML files, are common. Every GIS programmer should know how to write Python scripts that incorporate these functionalities.

What you need for this book

To complete the exercises in this book, you will need to have installed ArcGIS for Desktop 10.3 at either the Basic, Standard, or Advanced license level. Installing ArcGIS for Desktop 10.3 will also install Python 2.7 along with the IDLE Python code editor. The text is also appropriate for users working with ArcGIS for Desktop 10.2 or 10.1. Chapter 13, Using Python with ArcGIS Pro, requires ArcGIS Pro version 1.0.

Who this book is for

Programming ArcGIS with Python Cookbook, Second Edition, is written for GIS professionals who wish to revolutionize their ArcGIS workflow with Python. Whether you are new to ArcGIS or a seasoned professional, you almost certainly spend time each day performing various geoprocessing tasks. This book will teach you how to use the Python programming language to automate these geoprocessing tasks and make you a more efficient and effective GIS professional.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text are shown as follows: "we have loaded the ListFeatureClasses.py script with IDLE."

A block of code is set as follows:

   import arcpy
   fc = "c:/ArcpyBook/data/TravisCounty/TravisCounty.shp"
   # Fetch each feature from the cursor and examine the extent # properties and spatial reference
   for row in arcpy.da.SearchCursor(fc, ["SHAPE@"]):
     # get the extent of the county boundary
     ext = row[0].extent
     # print out the bounding coordinates and spatial reference
     print("XMin: " + ext.XMin)
     print("XMax: " + ext.XMax)
     print("YMin: " + ext.YMin)
     print("YMax: " + ext.YMax)
     print("Spatial Reference: " + ext.spatialReference.name)

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

   import arcpy
   fc = "c:/data/city.gdb/streets"
   # For each row print the Object ID field, and use the SHAPE@AREA
   # token to access geometry properties
   with arcpy.da.SearchCursor(fc, ("OID@", "SHAPE@AREA")) as cursor:
     for row in cursor:
       print("Feature {0} has an area of {1}".format(row[0], row[1]))

Any command-line input or output is written as follows:

[<map layer u'City of Austin Bldg Permits'>, <map layer u'Hospitals'>, <map layer u'Schools'>, <map layer u'Streams'>, <map layer u'Streets'>, <map layer u'Streams_Buff'>, <map layer u'Floodplains'>, <map layeru'2000 Census Tracts'>, <map layer u'City Limits'>, <map layer u'Travis County'>]

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "go to Start | All Programs | ArcGIS | Python 2.7 | IDLE".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.