ArcGis and Python (3 ): Your first script

If you have read the two previous articles   ArcGis and Python: Before your first steps and
  ArcGis and Python: getting started , you are
ready to get started.

There are two things you need to learn: the Python language and how to
use the ArcGis Python geoprocessing library. As for Python, tutorials abound. But
do not forget that you will only need some basics of the language. You will
basically string together already existing ArcGis tools.

Here, we will discuss a first script example and its integration in your
personal toolbox. We will, still, use the Clip tool of a layer. Let’s
say we want to adapt the Clip tool so that it, automatically,
split all layers in a workspace (directory, geodatabase), storing the results
in another workspace.

We could make a model with Model Builder using a data input iterator. And
besides that’s probably what you would do now if you’re just starting with
Python. So let’s see how to do the same thing with Python.

As example we will use PyScripter, but in this case, you do not
even need IDE. A text editor can do the trick. On the other hand be aware that with
Python, the lines indentation is part of the syntax and that typing a code line
at the beginning of the line or after one or two tabs does not mean the same
thing.

An IDE will automatically position you where it is needed.

Launch your IDE or open your text editor.

You will type your unavoidable line

arcpy import

without which Python does not know ArcGis processes at all.

You will add a second, called the os module that provides
quick access to the basic tools of the operating system. Some managing methods for
the file names of the os module will be used in this script.

import os  

The script will have two parts:

  • the first one where you will
    define input and output data
  • the second where you will perform
    the processing

Definition of input and output data

This part has a double interest. Of course for the processes execution it
is necessary that the tool knows on data has to work. But also because to run
the script as a toolbox tool it will be necessary to create the parameter
window that will be displayed when launching the tool. It will then resume, one
by one, the definitions of our script to create an input field in the window. Therefore,
you have to run your lines of code to find yourself at last in  the process.

We will use 4 input / output variables

  • the workspace where the layers to
    be cut are located
  • the layer that will be used to
    cut the others
  • the workspace where to put the
    resulting cut layers
  • the tolerance to be used by the
    Cutting tool

Enter the following  code lines:

# Workspace Input: Type WORKSPACE
arcpy.env.workspace = arcpy.GetParameterAsText (0)

#Class of entities used to cut Type FEATURECLASS
clipFeatures = arcpy.GetParameterAsText ( 1)

# Output Workspace :
Type WORKSPACE
outWorkspace = arcpy.GetParameterAsText (2)

# XY Tolerance of Cut Tool : DOUBLE Type
clusterTolerance = arcpy.GetParameterAsText (3)

The GetParameterAsText function retrieves the script input
parameters. If you want to run it on the command line (in a command window) you
will use a command such as the following:

python.exe “patrameter1”
“parameter2” “parameter3” Number

If, as we will see later, you use a tool from the toolbox, you will have
to match the order of the fields of the dialog window with the order defined in
the script variables: the first field of the dialogue window should be the
input work space, the second the cutting layer, etc.

In our four definitions, the first is a definition of an ArcGis
variable, this is the current workspace, while the other three are variables
specific to this script.

The body of the script: the process

Before starting to enter the code lines of the process itself, we are
going to enter a weird statement. We will simply type

try :

At the end of our process, we will return the complementary instruction
of this one: except

They are not mandatory. If you do not enter them, the script will work
without any problem except … when there is a problem. If an error occurs
during processing and you do not have these instructions, you will have a lovely
window “ArcGis has encountered an error and must be closed … “.
On the other hand, if you have mi try / except, if an error occurs in the body
of the processing, instead of crashing the system, the script will execute the
instructions found  in the except
paragraph (usually displaying an error message and an explanation).

The first instruction that we will enter corresponds to the creation of
the layers list present in the input workspace and that it will be necessary to
cut.

fcs = arcpy.ListFeatureClasses ()  

Note that the lines do not start at the beginning of the line. The
indent tells Python that this command is inside the try command .

The fcs variable will contain the list of layers to be cut. The ListFeatureClasses
statement generates the list of feature classes for the current workspace. Remember,
we defined it in the first instruction of the script, the parameter 0.

Now that we have the list of layers to process, we will put a loop-like
statement so that the processing is repeated on each layer of the list

for fc in fcs:

In this loop we will cut an input layer and create an output layer. Before
we cut it out, we need to handle some things we’ve done so far on ArcGis,
either on the commands or toolbox tools. For example, if our input workspace is
a geodatabase and we define our output space as a directory, the output layers
will be shapefiles. No problem, except that shapefile names are much more
restrictive than those in the geodatabase. We may have names that are too long
or with dots or dashes. In a script, it’s up to us to handle this type of
problem. Rest assured. It’s not complicated, but you have to do it.

Just retrieve the function ValidateTableName which
transforms the input names into the correct output names, while ensuring that
there are no repeated output names.

featureClassName = arcpy.ValidateTableName (fc, outWorkspace)
outFeatureClass = os.path.join (outWorkspace, featureClassName)

Now we are going to cut the input layer with the cutting layer. But if
the cutting layer is in the input workspace, we do not want to cut it! We put a
test to make the cutting provided that the name of the layer to be cut is
different from that which cuts:

if fc! = os.path.basename (clipFeatures):

This function just gets the name of the file, without the path, because
in our input list we only have the names without path.
Then the cutting function:

arcpy.Clip_analysis ( fc, clipFeatures, outFeatureClass, clusterTolerance)

It’s over for the processing.

Now, we must inform what to do in case of error:

except Exception as err:
arcpy.AddError (err)
print err

Since the script can be run by a toolbox tool or all by itself, we have two error displays. AddError will add the error message in the result window of the toolbos tool. Print will display the error in the command window if the script is executed by itself.

Note the indentation of except . It is at the same level
as try .

Save your file. It is ready to switch to the Toolbox.

Adding the script in the toolbox

In the Toolbox, load a personal toolbox (here My Scripts ).
Right click on the toolbox and select Add-> Script  

The first window allows you to define the Name of the tool (without spaces or special characters) and the label that will appear in the toolbox display (with spaces and special characters if you want).

The second window allows to link with our script.  

The last window is the one that
requires the most work. You will define the input parameters of the tool
window.

For each parameter of the script (we have four) it will be needed one
line. In the Name column, type the text that you want to see next
to the input field in the dialog window.

In the Data Type column you must specify the type of data to enter in the dialog box field.

For the first parameter of the
script (parameter 0) we indicate ” Workspace input
and the data type ” Workspace “.

Here is the screenshot with all the definitions for our script.  

The order of the lines is very
important. The first line will be the first parameter defined in the script,
parameter 0. The second line will be ai = u second parameter, parameter 1. And
so on.

When finished, close the Add Script window. You can now run it as any
other tool, by double clicking in the Toolbox.

You find the four parameters to
enter.

Not only do you have a new tool that can run from the toolbox but you
can include it in a Model Builder template.

Si cet article vous a intéressé et que vous pensez qu'il pourrait bénéficier à d'autres personnes, n'hésitez pas à le partager sur vos réseaux sociaux en utilisant les boutons ci-dessous. Votre partage est apprécié !

Leave a Reply

Your email address will not be published. Required fields are marked *