您的位置:首页 > 编程语言 > Python开发

Exercise: Use Python in ArcGIS Desktop 10

2012-10-10 21:03 501 查看
http://training.esri.com/Courses/PythonDesktop10_0/player.cfm?



Exercise: Use Python in ArcGIS Desktop 10



Print

This exercise is designed to introduce you to some of the common ways of using Python with ArcGIS 10. During this exercise, you will write several Python scripts to automate GIS tasks and increase your productivity. You will learn how to use your scripts in
the Python window and Field Calculator in ArcMap, as well as in PythonWin, a widely used third-party Python integrated development environment (IDE).


Estimated completion time: 45 minutes


Step 1: Download the data

To complete the exercise, you need to download
the data. If you have already downloaded and installed the data, continue to the next step.

Can't find the data you downloaded?


Step 2: Verify a setting and open the map document

Before you begin working in ArcMap, you will ensure that the option to hide file extensions is turned off.

Start ArcCatalog.

From the Customize menu, choose ArcCatalog Options.

On the General tab, make sure Hide file extensions is unchecked.
View
result


Click OK.

On the Standard toolbar, click the Launch ArcMap button

.

After the ArcMap window opens, close ArcCatalog.

In the ArcMap – Getting Started dialog box, under Existing Maps, click Browse for more.

Browse to your C:\Student\PythonDesktop10_0 folder, or the folder containing your data.

Click the Westerville map document and click Open.

The map shows an area within the city of Westerville, Ohio. Notice that the table of contents displays several layers for the city.
View
result


You will use these layers in upcoming steps as you create your Python scripts.


Step 3: Buffer schools using the Python window

In this step, you will use the Python window to create buffer polygons around the schools. City planners will use these polygons when making land-use decisions in the areas near schools.

On the Standard toolbar, click the Python window button

.
View
result


Note: The Python window can also be opened from the Geoprocessing menu.

The Python window is divided into two sections:

The left section, which currently displays the primary prompt (>>>), is where you enter your Python script.

The section on the right displays syntax, help, and execution messages.

Click the title bar of the Python window and drag it the bottom of the interface, docking it below the map.



View
result


First, you will enter code into the Python window to set the current workspace environment.

In your Python window, type:

arcpy.en


The syntax for the Python statement appears in a drop-down list. This list of choices is called code completion. Code completion
allows you to complete your code faster by choosing options from a drop-down list, rather than typing. In addition to allowing you to work faster, this also reduces errors in your code.

Press the Tab key on your keyboard to accept the env value in the list.

The env class stores the ArcGIS environment settings used for geoprocessing.

Next, you will set the value of the workspace, which is an environment setting.

After arcpy.env, type:

.w


Press the Tab key to add workspace to your line of Python code.

Verify that your code now looks like this:

arcpy.env.workspace


To assign the path to your data, type:

= "C:/Student/PythonDesktop10_0/Data/Westerville.gdb"


Note: If your course data is not in the C:\Student\PythonDesktop10_0 folder, type the path to the location where you downloaded the
data instead.

When you have finished setting your workspace, press Enter to move to a new prompt.

In this line of code, you have accessed the workspace geoprocessing environment setting and set its value to the Westerville geodatabase. The ArcPy site package contains the Python libraries and modules which enable you to access many ArcGIS functions from
within Python.

Next, you will run the Buffer geoprocessing tool using Python.

At the prompt in the Python window, type:

arcpy.Bu


Press your Tab key to choose Buffer_analysis from the drop-down list.

Type a left parenthesis to continue your line of code.
View
result


Notice that the syntax for the Buffer tool displays in the help section of the Python window, and that the code completion provides a list of layers corresponding to the in_features.

In the drop-down list, choose the Schools layer and press your Tab key.

Tip: You can also use the up/down arrow keys on your keyboard to choose the Schools layer from the list.

Type a comma (,)
and observe that the next argument for the Buffer tool (out_feature_class) is highlighted in the help and syntax section.
View
result


For out_feature_class, type "Buffer_1000",
including the quotation marks.
View
result


Type another comma (,)
and then type "1000
feet" for the buffer_distance_or_field value, followed by a right parenthesis ).

Verify that your code now looks like this:



Note: Depending on the width or your Python window, your code may wrap to the next line.

Notice that the help for the Buffer tool is no longer displayed because you have finished adding all of the arguments and provided a closing parenthesis.

How does the Buffer tool know where to save the Buffer_1000 output feature class?

Answer

Press Enter on your keyboard to run the Buffer tool.


I
received an error.


The buffer will take a few moments to execute. After it is finished, a new Buffer_1000 layer is added to your map.
View
result


In the Python window, notice that the help and syntax section displays the status of the Buffer command, as well as the start and finish times.

Click the X in the upper right corner of the Python window to close it.

Close ArcMap without saving your changes.


Step 4: Buffer schools using PythonWin

ArcPy can also be accessed outside of ArcGIS Desktop in any Python integrated development environment (IDE). In this step, you will see how the Buffer tool can be accessed from within the PythonWin IDE.

Open Windows Explorer.

Navigate to C:\Python26\ArcGIS10\Lib\site-packages\pythonwin.


Can't
find PythonWin?


Double-click Pythonwin.exe.

From the File menu, choose New.

In the New dialog box, choose Python Script and click OK.
View
result


From the File menu, choose Save As.

Save your script in your ..\PythonDesktop10_0 folder and name your script SchoolBuffer.py.

From the Window menu, choose Tile.
View
result


In the Interactive Window at the bottom, type:

import arcpy


This loads ArcPy into memory and allows you to access classes and functions with drop-down lists similar to the Python window in ArcMap.

In the SchoolBuffer scripting window on the top, type:

arcpy.en


The drop-down list opens as shown below.



With env highlighted in the list, press the Tab key on your keyboard.

To highlight workspace in the drop-down list, type:

.w


View
result


Press the Tab key.

Verify that your code now looks like this:

arcpy.env.workspace


Set the workspace pathname to complete your code:

= "C:/Student/PythonDesktop10_0/Data/Westerville.gdb"


Note: If your data is not in the C:\Student\PythonDesktop10_0 folder, change the pathname in your code to the location where you
downloaded the data.

Press Enter to finish your first line of code.
View
result


On the next line, type:

arcpy.Bu


Select Buffer_analysis from the drop-down list and press your Tab key.

Note: Remember that Python is case sensitive. If you type a lower-case "b", the drop-down list will not highlight Buffer_analysis.

View
result


Type a left parenthesis (, which displays the syntax for the Buffer_analysis tool.
View
result


This syntax is similar to what you saw in the help and syntax section of the Python window in ArcMap.

For in_features, type:

"Schools",


Note: Remember to add the quotes around the word Schools,
followed by a comma to end the in_features argument.

For out_feature_class, type:

"Buffer_500",


For buffer_distance, type:

"500 feet"


Finish your code statement with a right parenthesis ).
View
result


Prior to running your script, insert import arcpy as the first line in your script.
View
result


Tip: Your script would run without this line because you previously imported arcpy in the Interactive Window. However, as a best
practice, always include the necessary import statements as part of your Python script. Running your scripts outside of PythonWin
in other environments will often require the import statement as part of the script.

Click the Save button

,
then click the Run button

to
execute your script.

Click OK on the Run Script dialog box.

The script takes a few moments to run. If it finishes without error, the following message displays on the status bar in the bottom left corner of PythonWin.



When the script is finished, confirm that you do not have any error messages in the Interactive Window.


I
received an error in the Interactive Window.


Close PythonWin.


Step 5: Create a calculation expression using Python

In this step, you will use Python in the Field Calculator to programmatically change attribute values.

Open the Westerville.mxd map document that you used earlier in this exercise.

Right-click the Streets layer and choose Open Attribute Table.

Widen the table so you can see all the field names.

Notice that some streets have a value the TYPE field of dr, while others have DR.
These should all use capital letters for consistency.

Right-click the TYPE field and choose Field Calculator.

The Field Calculator opens.

At the top of the Field Calculator, notice that you have a choice of either VB Script or Python.

Click the button next to Python, as shown below.



Under Fields, double-click TYPE.

Notice that !TYPE! appears in the window at the bottom of the Field Calculator. When referencing field names in the Field Calculator using Python, the field is enclosed by exclamation points.

Complete the code as follows:

!TYPE!.replace("dr", "DR")


This Python code will use the replace function to replace all occurrences of dr with DR.

Click OK.

After the calculation has completed, examine the TYPE field in the attribute table.

Notice that the values of dr have been changed to DR.

Close the attribute table.


Step 6: Create a multiline calculation expression

In this step, you will create a Python expression in the Field Calculator that is several lines long. This expression will create an attribute value that can be used for labeling the schools.

Open the Schools attribute table.

At the top of the attribute table window, click the Table Options button

and
choose Add Field.

In the Add Field dialog box, do the following:

For Field Name, type MAP_LABEL.

For Type, choose Text.

Click OK.

Scroll to the end of the table so you can see your new MAP_LABEL field.

Now you will create an expression to combine the attribute values from the NAME and TYPE fields, and to abbreviate the school type as well. For example, if the value for TYPE is HIGH, your calculation will change it to HS, for High School.

Open the Field Calculator for the MAP_LABEL field.

Remind me how

Set the Parser to Python.
View
result


Check the box next to Show Codeblock.
View
result


Notice that the bottom of the Field Calculator is now divided into two boxes:

the Pre-Logic Script Code, and

your MAP_LABEL attribute.

Simple field calculator expressions, like the one you created in the previous step, are entered directly into the Expression text box. More complex expressions, such as multiline scripts and those that have looping or branching, are entered in the Codeblock
boxes.

You will load a Python script that so formatted specifically for use in the Field Calculator.

Click Load.

Browse to your ..\PythonDesktop10_0 folder, click the Schools.cal file,
and click Open.

Examine the newly added code at the bottom of the Field Calculator:

label( !NAME!, !TYPE! )


For each school, values from the NAME and TYPE attributes are read and passed to a function named label.

Now examine the first line of code under Pre-Logic Script Code:

def label(name, type):


A function named label is created (or defined)
with the def statement. The label function
reads the NAME and TYPE attribute values and holds them in two new variables: name and type.

Examine the next line of Python code:

if type == "HIGH":


This line compares the attribute value held in the type variable to a text string, HIGH.
Also, notice that this line is indented two spaces and ends with a colon (:). The colon tells Python to execute the next line(s) if the condition is true.

Examine the next line of code, which is indented below the previous if statement.

return name + " HS"


Lines that are indented at this same level will be executed if the value of the type variable is equal to HIGH.

The return statement will combine the value in the name variable
with the text string HS. This combined text string will be entered as the new value in the MAP_LABEL field.

If the statement is false (e.g., type does not equal HIGH),
the next condition will be evaluated:

elif type == "MIDDLE":


The elif statement ("else if") will check whether the type variable is equal to MIDDLE.
Notice the elif statement is indented to the same level as the first if statement.

Using your knowledge of Python and the previous code example, add the necessary code that will check if the type variable is equal
to ELEMENTARY. If it is, return the school's name concatenated to the text string ELEM.

Note: Remember, Python enforces indentation as part of its syntax. In the Field Calculator, use two or four spaces to define each
logical level.

View code

After you have entered your new code, click OK.


I
received an error.


Examine your new calculated values in the MAP_LABEL attribute field.
View
result


Close the attribute table.

Minimize ArcMap.


Step 7: Edit a script to accept user input

In this step, you will see how you can make your Python script accept your input rather than using hard-coded values.

Open PythonWin.

From the File menu, choose Open and browse to your ..\PythonDesktop10_0 folder.

Open the Buffer_HardCoded.py script.

At the top of the script, read the comments describing the author and purpose.

Read the comments describing the three variables in this script: inFCs, outWS,
and dist.

Notice that the values for these variables are already set within the script. For example, the variable which stores the buffer distance is set to a value of 1000 in the script. If you wanted to run the script with a different buffer distance, you would have
to edit the script each time you wished to use a different distance.

Although the script will run with these hard-coded values, it is not very flexible. Before you convert this script to a script tool, you will remove the hard-coded values and replace them with a Python function that will allow you to provide your own input.

From the File menu, choose Save As.

Save your script in your ..\PythonDesktop10_0 folder with the name Buffer_multiple.py.

Locate the following code in your script:

inFCs = "C:/Student/PythonDesktop10_0/Data/Shapefiles/Schools.shp"


Delete the pathname (and the quotes) and replace it with:

arcpy.GetParameterAsText(0)


Verify that your line of code looks like this:

inFCs = arcpy.GetParameterAsText(0)


The GetParameterAsText function will allow you to type an input value that will be used by the script.
The value you enter will be stored in the inFCs variable.

Using the same technique, make the following changes to the outWS and dist variables:

outWS = arcpy.GetParameterAsText(1)
dist = arcpy.GetParameterAsText(2)


Notice that the GetParameterAsText value for inFCs is
0 and increments up to a value of 2 for the dist variable. This is the order in which your input
values will be assigned in your Python script (i.e., inFCs is the first input value, followed by outWS,
and then dist). This function is referred to as being zero-based,
meaning the first input value, will be item 0.

Save your Buffer_multiple.py script.

Now you are ready create a script tool from your modified script.

Close PythonWin.


Step 8: Create a script tool

In this step, you will create a tool in ArcToolbox from your Python script. Once a script is part of ArcToolbox, it behaves like any other tool. This means you can run the script from a dialog box, from the Python window, or from a model.

Restore ArcMap.

Before you can add a script tool, you will need to create a toolbox to store the script.

Open the Catalog window and navigate to your ..\PythonDesktop10_0 folder.

Right-click the Data folder and choose New > Toolbox.

A new toolbox is created in your Data folder, as shown below.



Right-click Toolbox and choose Properties.

In the Toolbox Properties dialog box, enter Westerville for both the Name and Label properties.
View
result


Click OK.

Next, you will add your script as a tool in your new toolbox.

Right-click the Westerville toolbox, choose Add > Script.

The Add Script wizard opens.

The first panel asks for the script tool's Name, Label, and Description. The Name is used to execute the script tool from the Command Line window or from another script. The Label is the display name for the script, and will determine how it appears in the
ArcToolbox window.

The following rules apply to the Name and Label properties:

The Name cannot contain spaces or underscores.

Labels may contain spaces or other special characters.

In the Add Script wizard, set the following:

Name: BufferMultiple

Label: Buffer Multiple

Description: Buffer multiple feature classes

View
result


Click Next.

Click the Browse button

.

Navigate to your ..\PythonDesktop10_0 folder, select Buffer_multiple.py,
and click Open.

Click Next.

Now you will enter the three script arguments for the inFCs, outWS,
and dist variables that you coded in a previous step.

On this panel, do the following:

For the first argument, click in the first empty field under Display Name and type Feature classes to buffer.

Under Data Type, click in the first empty row and choose Feature Layer from the drop-down list.

Under Parameter Properties, click in the Value column for MultiValue and choose Yes from the drop-down list.

View
result


By setting the MultiValue property to Yes, you are enabling your script to accept multiple feature classes as input.

The input feature classes will be associated with the arcpy.GetParameterAsText(0) function, which
will set the value of the inFCs variable. The inFCs variable
will store the list of feature classes.

For the second argument, specify the following:

Display Name: Output location

Data Type: Workspace or Feature Dataset

Under Parameter Properties, for Environment: Current Workspace [workspace]

Note: You can move the vertical divider to the left of Display Name to view the entire contents of the column.

View
result


The Output location will be associated with the arcpy.GetParameterAsText(1) function, which will set the value of the outFC variable.

For the last argument (the buffer distance), set the following:

Display Name: Distance

Data Type: Double

Under Parameter Properties, for Filter: Range

In the Range dialog box that opens, set the following:

Minimum Value: 500

Maximum Value: 1500

Click OK.
View
result


By setting a range filter, you are restricting the buffer distance to a set of acceptable values for your application, in this case, values between 500 and 1500 feet.

Verify that your Add Script dialog box matches the following graphic:



Click Finish.

Open the Catalog window and, if necessary, expand your Westerville toolbox.
View
result


Your new Script tool named Buffer Multiple is now available in your toolbox.


Step 9: Run your script tool

In this step, you will run your new Buffer Multiple script tool.

In your Westerville toolbox, double-click the Buffer Multiple script tool.

For Feature classes to buffer, click the down arrow and choose Schools.
View
result


Note: Your script tool can support multiple input feature classes. However, for this example, you will only buffer the Schools feature
class.

For Output location, browse to ..\PythonDesktop10_0\Data\Westerville.gdb and click Add.
View
result


For Distance, type 500.

Click OK to run the Buffer Multiple tool.

When the process has finished, close the status window.

Open the Catalog window.

Navigate to and expand your ..\PythonDesktop10_0\Data\Westerville.gdb geodatabase.

Notice it contains a new feature class named Schools_buffer.

This new feature class was created when you ran your script tool. Your Python code named the output feature class with the name of the layer (in this case,Schools),
followed by _buffer.

Drag the Schools_buffer feature class onto your map.


Step 10: Associate map layers with different source data

All of the layers in your map document, with the exception of the newly created Schools_buffer layer, reference shapefiles. Imagine that you have migrated all of these shapefiles to a file geodatabase. In this step, you will use Python to change the source
of the layers in your map from shapefiles to their equivalent geodatabase feature classes. You will then save a copy of your map document with the layers that point to the new geodatabase feature classes.

Open the layer properties for the Streets layer.

Click the Source tab.

What is the workspace path for the streets data?

Answer

Close Layer Properties.

Using Python, you will set the source workspace for each layer from the Shapefiles folder to the Westerville geodatabase in your ..\PythonDesktop10_0\Data folder.

Open the Python window.

Remind me how

In the Python window, enter the following line of code:

mxd = arcpy.mapping.MapDocument("CURRENT")


Press Enter.

Note: If you receive an error message, reenter the line of code again, making sure it is exactly as shown in above.

You are setting a variable named mxd equal to the map document in which you are currently working.
This map document is referenced by the CURRENT keyword.

Next, you will use the replaceWorkspaces function. This function has four required arguments and one
optional argument.

Old workspace path

Old workspace type

New workspace path

New workspace type

Validate (optional)

In your map document, the old workspace will reference the shapefiles folder and the new workspace will be your Westerville geodatabase.

In the Python window, type:

mxd.rep


From the drop-down list, choose replaceWorkspaces and press your Tab key.

Verify that your Python window matches the following code:

>>> mxd = arcpy.mapping.MapDocument("CURRENT")
>>> mxd.replaceWorkspaces


Type a left parenthesis and notice that the usage for the replaceWorkspaces appears in the help portion
of the Python window.
View
result


For the first argument, the old_workspace_path, type:

"C:/Student/PythonDesktop10_0/Data/Shapefiles"


Type a comma, then type the second argument (old_workspace_type):

"SHAPEFILE_WORKSPACE"


Note: Depending on the width or your Python window, your code may wrap to the next line.

Type a comma, then type the new_workspace_path:

"C:/Student/PythonDesktop10_0/Data/Westerville.gdb"


For the final argument, type a comma, then type the new_workspace_type:

"FILEGDB_WORKSPACE"


Note: The optional argument, Validate, checks to see if the new_workspace_path is
a valid workspace. If it is not, the workspace is not replaced. You will not enter a value for the validate argument.

Type a right parenthesis ) to
finish your line of code.
View
result


Press Enter to execute the replaceWorkspaces function.

Open the layer properties for the Streets layer.

Do you see that the path has changed? The data source now points to the Westerville geodatabase.

You can also use the Python window to save your map document. You will save your current map with another name, leaving the existing map document unchanged.

In the Python window, type:

mxd.saveACopy("C:/Student/PythonDesktop10_0/Westerville_New.mxd")


Press Enter.

You have saved your map as a new .mxd file.

Close ArcMap without saving your changes.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: