ArcGIS9.2中使用Python和GP交互
2007-06-15 21:54 flyingfish 阅读(2399) 评论(0) 编辑 收藏 举报下面是ArcGIS9.2帮助中对如何使用Python和GP操作交互的说明。
另外可参考Mars的自语的《ArcGIS 9.2 笔记(5):Georocessing与Python》
http://www.cnblogs.com/maweifeng/archive/2007/01/10/616329.html
Creating a new Python script module
About creating a new Python script module
To retain Python code, Python files (.py extension) can be created. These files are ASCII files that contain Python statements.
Learn more about executing and debugging Python
How to create a new Python script module
- In PythonWin, click the File menu and click New. Accept the default option of Python Script and click OK.
The Script1 window will open. Script1 is the default name of your script.
- Click the Maximize button on the Script1 window.
- Click the File menu and click Save As. Name the script multi_clip and save it in a folder of your choice.
Modules should follow the same naming rules as variables. They must start with a letter and can be followed by any number of letters, digits, or underscores. Module names become variable names when they are imported, so to avoid syntax errors, they should not use reserved words such as while or if. Scripts should always have a .py extension, as this is required when importing a script module. It also defines Python as the executing application for your script.
- At the top of your script add the following lines:
#Import modules import arcgisscripting, sys, os
This imports the system, operating system, and arcgisscripting modules to the script. The arcgisscripting module has already been discussed, but the other two are new.
- The sys module refers to the Python system and will be used to access user-specified inputs.
- The os module provides easy access to the most fundamental tools of the operating system. Some of the os module's file name manipulation tools are used in this script.
Refer to your Python reference material for more information about the tools in these modules.
- Add the following code to declare the geoprocessor object:
#Create the geoprocessor object gp = arcgisscripting.create()
This script will have the following arguments so it can be used in a generic fashion:
- An input workspace defining the set of feature classes to process
- A feature class to be used by the Clip tool as the area to be clipped from an input feature class
- An output workspace where the results of the Clip tool will be written
- A cluster tolerance that will be used by the Clip tool
Refer to the Clip tool in the Analysis toolbox for detailed information on how Clip works.
- Add the following code to your script to define and set variables based on the user-defined values passed to the script at execution:
#Set the input workspace gp.workspace = sys.argv[1] #Set the clip featureclass clipFeatures = sys.argv[2] #Set the output workspace outWorkspace = sys.argv[3] #Set the cluster tolerance clusterTolerance = sys.argv[4]
The passed-in arguments are attributes of the sys module and can be sliced to extract the argument you want. The first value of argv, argv[0], is the name of the script. You can apply the same slicing tools used on strings to the argv attribute, so sys.argv[1:] will return the entire list of argument values.
- Add the following error-handling statement and geoprocessor call to the script window:
try: #Get a list of the featureclasses in the input folder fcs = gp.ListFeatureClasses()
Python enforces indentation of code after certain statements as a construct of the language. The try statement defines the beginning of a block of code that will be handled by its associated exception handler, or except statement. All code within this block must be indented. Python uses try/except blocks to handle unexpected errors during execution. Exception handlers define what the program should do when an exception is raised by the system or by the script itself. In this case, you are only concerned about an error occurring with the geoprocessor, so a try block is started just before you start to use the object. It is good practice to use exception handling in any script using the geoprocessor so its error messages can be propagated back to the user. This also allows the script to exit gracefully and return informative messages instead of simply causing a system error.
The geoprocessor's ListFeatureClasses method returns an enumeration of feature class names in the current workspace. The workspace defines the location of your data and where all new data will be created unless a full path is specified. The workspace has already been set to the first argument's value.
- Add the following code to get the first value of the enumeration:
#Loop through the list of feature classes fcs.Reset() fc = fcs.Next()
An enumeration is a list that has an undefined number of items. It should always be reset before the first item is extracted so you can get the first item in the list. You want to get the first item before you start looping through its contents, as you will use it as the conditional value for continuing a loop.
- Add the following code:
while fc: #Validate the new feature class name for the output workspace. outFeatureClass = outWorkspace + "/" + gp.ValidateTableName(fc, outWorkspace) #Clip each feature class in the list with the clip feature class. #Do not clip the clipFeatures, it may be in the same workspace. if str(fc) != str(os.path.split(clipFeatures)[1]): gp.Clip(fc, clipFeatures, outFeatureClass, clusterTolerance) fc = fcs.Next()
When there are no more names in the enumeration, a null or empty string will be returned. Python will evaluate this as false, which will cause the while loop to exit. The next value from the enumeration must be retrieved before the end of the indented block so it is evaluated correctly at the start of the loop. The ValidateTableName method is used to ensure the output name is valid for the output workspace. Certain characters, such as periods or dashes, are not allowed in geodatabases, so this method will return a name with valid characters in place of invalid ones. It will also return a unique name so no existing data is overwritten.
The os module's path object is used to manipulate the clip feature classes path, so only the feature class name is evaluated in an expression, not the entire path. The Clip tool is accessed as a method of the geoproccessor, using the various string variables as parameter values.
- Add the following lines to complete the script:
except: gp.AddMessage(gp.GetMessages(2)) print gp.GetMessages(2)
The except statement is required by the earlier try statement; otherwise, a syntax error will occur. If an error occurs during execution, the code within the except block will be executed. In this case, any message with a severity value of 2, indicating an error, will be added to the geoprocessor in case the script is used as the source of a tool. All error messages are also printed to the standard output in case the script is run outside a tool.
- Save the script by clicking the Save button on the Standard toolbar.
- Add the following comments to the top of your script:
##Script Name: Clip Multiple Feature Classes ##Description: Clips one or more shapefiles ##from a folder and places the clipped ##feature classes into a geodatabase. ##Created By: Insert name here. ##Date: Insert date here.
The script completed above is used to learn more about using Python, with Executing and debugging Python, and Setting breakpoints using Python.
Tips
- When naming variables, remember that Python is case sensitive, so "GP" is not the same as "gp". The names of the geoprocessor's methods and properties (including tool and environment setting names) are not case sensitive.
- Python automatically removes an object from memory when it is no longer referenced in a program. When a script completes, all memory allocated for objects is released and any open files are closed. The del statement can be used to delete an object so its memory is deallocated during a script's execution.
- Many geoprocessing scripts are not generic in nature and have no arguments. They use defined dataset names and parameter values and may not require the sys module. Import modules only as needed to avoid unnecessary memory use.
- Statements that end with a colon indicate the beginning of indented code. Python does not use braces, brackets, or semicolons to indicate the beginning or end of a block of code. Instead Python, uses the indentation of the block to define its boundaries. This results in code that is easy to read and write.