下面是ArcGIS9.2帮助中对如何使用Python和GP操作交互的说明。
另外可参考Mars的自语的《ArcGIS 9.2 笔记(5):Georocessing与Python》
http://www.cnblogs.com/maweifeng/archive/2007/01/10/616329.html
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
The Script1 window will open. Script1 is the default name of your script.
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.
#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.
Refer to your Python reference material for more information about the tools in these modules.
#Create the geoprocessor object
gp = arcgisscripting.create()
This script will have the following arguments so it can be used in a generic fashion:
Refer to the Clip tool in the Analysis toolbox for detailed information on how Clip works.
#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.
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.
#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.
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.
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.
##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.