Creating a new Python script

To retain Python code, you create Python files (.py). These files are ASCII files that contain Python statements. The steps below assume you're using the PythonWin application, as described in Writing_Python_scripts.

Steps:
  1. In PythonWin, click the File menu and click New. Accept the default option of Python Script and click OK.
  2. The Script1 window opens. Script1 is the default name of your script.

  3. Click the Maximize button on the Script1 window.
  4. Click the File menu and click Save As. Name the script multi_clip.py and save it in a folder of your choice.
  5. Add the following lines at the top of your script:
  6. # Import ArcPy site-package and os modules
    #
    import arcpy 
    import os
    

    This imports the ArcPy site-package and operating system module os to the script. The os module provides easy access to the most fundamental tools of the operating system. Some of the os module's file name manipulation methods are used in this script.

    This script will have the following four arguments so it can be used generically:

    • 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
    • An XY 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.

  7. Add the following code to your script to define and set variables based on the user-defined values passed to the script at execution:
  8. # Set the input workspace
    #
    arcpy.env.workspace = arcpy.GetParameterAsText(0)
    
    # Set the clip featureclass
    #
    clipFeatures = arcpy.GetParameterAsText(1)
    
    # Set the output workspace
    #
    outWorkspace = arcpy.GetParameterAsText(2)
    
    # Set the XY tolerance
    #
    clusterTolerance = arcpy.GetParameterAsText(3)
    
  9. Add the following error-handling statement and ArcPy's ListFeatureClasses() function to the script window:
  10. try:
        # Get a list of the featureclasses in the input folder
        #
        fcs = arcpy.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. 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 ListFeatureClasses() function returns a Python list 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. A Python list is a versatile object. A for loop is used to walk through each feature class contained in the list.

  11. Add the following code:
  12.     for fc in fcs:   
            # Validate the new feature class name for the output workspace.
            #
            featureClassName = arcpy.ValidateTableName(fc, outWorkspace)
            outFeatureClass = os.path.join(outWorkspace, featureClassName)
            
            # 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 fc <> os.path.basename(clipFeatures):
                arcpy.Clip_analysis(fc, clipFeatures, outFeatureClass, 
                                    clusterTolerance)
    

    When there are no more names in the list, the for loop ends. The ValidateTableName() function 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 returns a name with valid characters in place of invalid ones. It also returns a unique name so no existing data is overwritten.

    The os.path's basename method is used to manipulate the clip feature class's path, so only the feature class name is evaluated in an expression, not the entire path. The Clip tool is accessed as an ArcPy function, using the various string variables as parameter values.

  13. Add the following lines to complete the script:
  14. except:
        arcpy.AddMessage(arcpy.GetMessages(2))
        print arcpy.GetMessages(2)
    

    The except statement is required by the earlier try statement; otherwise, a syntax error occurs. If an error occurs during execution, the code within the except block is executed. Any messages with a severity value of 2, indicating an error, are added in case the script is run from a script tool. All error messages are also printed to the standard output in case the script is run outside a tool.

  15. Add the following comments to the top of your script:
  16. # 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.
    
  17. Save the script by clicking the Save button on the PythonWin's toolbar.
  18. The script completed above is used to learn more about using Python with Executing and debugging Python and Setting breakpoints using Python.

    NoteNote:

    When naming variables, remember that Python is case sensitive, so clipFeatures is not the same as ClipFeatures.

    NoteNote:

    GetParameterAsText() is used to receive arguments. If a script uses defined dataset names and parameter values, it may not need to use the GetParameterAsText() function.

    NoteNote:

    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. Python instead uses the indentation of the block to define its boundaries. This results in code that is easy to read and write.

The completed 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.

# Import ArcPy site-package and os modules
#
import arcpy 
import os

# Set the input workspace
#
arcpy.env.workspace = arcpy.GetParameterAsText(0)

# Set the clip featureclass
#
clipFeatures = arcpy.GetParameterAsText(1)

# Set the output workspace
#
outWorkspace = arcpy.GetParameterAsText(2)

# Set the XY tolerance
#
clusterTolerance = arcpy.GetParameterAsText(3)

try:
    # Get a list of the featureclasses in the input folder
    #
    fcs = arcpy.ListFeatureClasses()

    for fc in fcs:   
        # Validate the new feature class name for the output workspace.
        #
        featureClassName = arcpy.ValidateTableName(fc, outWorkspace)
        outFeatureClass = os.path.join(outWorkspace, featureClassName)
        
        # 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 fc <> os.path.basename(clipFeatures):
            arcpy.Clip_analysis(fc, clipFeatures, outFeatureClass, 
                                clusterTolerance)

except:
    arcpy.AddMessage(arcpy.GetMessages(2))
    print arcpy.GetMessages(2)

Related Topics


12/15/2011