Select to view content in your preferred language

Batch Clip Process

2980
5
05-09-2013 06:00 AM
OsmanSABAN
Emerging Contributor
Hi all,

I am using below code to clip numbers of feature from Dan Patterson;

#BatchClipFCs.py
#
#Author
#  Dan Patterson
#  Dept of Geography and Environmental Studies
#  Carleton University, Ottawa, Canada
Dan_Patterson@carleton.ca
#
#Purpose
#  Batch clips feature classes (eg shapefiles) in a project
#  and writes them to a folder.
#  Many batch clip examples exist, this is compiled for demonstration
#  purpose for a class
#
#Properties (right-click on the tool and specify the following)
#General
#  Name   BatchClipFCs
#  Label  Batch Clip Feature Classes
#  Desc   Batch clip feature classes (eg shapefiles) and saves
#         them to a folder.
#
#Source  BatchClipFCs.py
#
#Parameter list
#                                                Parameter Properties
#           Display Name          Data type      Type      Direction  MultiValue
#  argv[1]  Feature(s) to clip    Feature Layer  Required  Input      Yes
#  argv[2]  Polygon clip layer    Feature Layer  Required  Input      No
#  argv[3]  Append to output      String         Optional  Input      No
#           filename
#  argv[4]  Output folder         Folder         Required  Input      No
#--------------------------------------------------------------------
#Import the standard modules
#  Get a list of feature classes (shapefiles)
#  Get the clip feature class
#  Get the optional text to append to the filename output filename
#  Get the output folder

# Usage: BatchClipFCs <Input_Features> <ClipWith> <optional_text> <Output_Workspace>
# ---------------------------------------------------------------------------
#
# Import system modules, Create the Geoprocessor object and
# Load required toolboxes...
#
import sys, string, os, win32com.client
gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1")
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Analysis Tools.tbx")
#gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
#
# Script arguments...
FCsToClip = gp.GetParameterAsText(0)    #a list of features
fcs = string.split(FCsToClip, ";")      #split into a list
#
clipWith = sys.argv[2]                  #clip layer
desc = gp.Describe(clipWith)
clipWithType = desc.ShapeType
#
addToName = sys.argv[3]                 #optional text to append to output name
if(addToName == "#"):
  addToName = ""
#
outputFolder = sys.argv[4]              #a folder
#
gp.Addmessage("\n" + "Batch Clip Feature layers" + "\n" )
#
if (clipWithType == "Polygon"):
  for fc in fcs:
    try:
      fc=fc.replace("'","")             #check if a layers name has been changed
      desc = gp.Describe(fc)
      fcDataType = desc.DataType
      gp.AddMessage("Data type = " + fcDataType)
      if(fcDataType == "FeatureClass"): # Feature class on disk
        theName = str(os.path.split(fc)[1])
        outFile = outputFolder + "\\" + theName + addToName + ".shp"
      else:                             # Feature layer
        FullName = desc.CatalogPath
        theName = (os.path.split(FullName)[1]).replace(".shp","")
        theName = str(fc).replace(" ","_")
        outFile = outputFolder + "\\" + theName + addToName + ".shp"
        gp.AddMessage("Output file from layer " + outFile)
      #
      gp.AddMessage("Clipping " + str(fcDataType) + ": " + fc + " Saving to: " + outFile + "\n")
      try:
        gp.Clip_analysis(fc, clipWith, outFile, "")
      except:
        gp.AddMessage("Could not clip " + fc + " with " + clipWith + " to " + outFile)
    except:
      gp.AddMessage("cannot describe" + fc)
else:
  gp.AddMessage (clipWith + " is not a polygon layer, clipping terminated" )
#



but every single time when I run this code got this message:
"<type 'expestations.ImportError'>: No Module named win32com.client
Failed to execute (Script)

see attached file.

Can you please help me to solve this problem?

Thank you and much appreciated
Tags (2)
0 Kudos
5 Replies
markdenil
Frequent Contributor
gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1")
is a bit of an antique.
What version of Arc are you running this on?

Version 9 should import arcgisscripting and then
gp = arcgisscripting.create()

or in version 9.3 you can use
gp = arcgisscripting.create(9.3)

arcgisscripting will still work in version 10.x, but in 10.x the arcpy module is available,
and has a lot more features.
so..
import arcpy
then use arcpy where you had earlier used gp.

Watch out for syntax changes in later versions (arcpy tool syntax is CaseSensitive!),
and sometimes different objects are returned than came back using earlier geoprocessors.

(I expect you will have better results clipping features from a geodataset,
rather than directly from poor Dan Patterson; it sounds painful for him!)
0 Kudos
OsmanSABAN
Emerging Contributor
Hey Mark,

Thank you for your reply. I understand what you mean but i dont know how to implement that into my code. I am using Arc 10 right now. Can you please help me to solve this issue?

Thank you
0 Kudos
ThaiTruong
Deactivated User
Like Mark suggested, you can create the geoprocessor object by import arcgisscripting module to instantiate the geoprocessor object.

So, Replace:
import sys, string, os, win32com.client
gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1")


With:

import sys, string, os, arcgisscripting
gp = arcgisscripting.create()


If you want to use the new Arcpy module, you've got more work to do.  You've got to modify the code as below:

#BatchClipFCs.py
#
#Author
# Dan Patterson
# Dept of Geography and Environmental Studies
# Carleton University, Ottawa, Canada
# Dan_Patterson@carleton.ca
#
#Purpose
# Batch clips feature classes (eg shapefiles) in a project
# and writes them to a folder.
# Many batch clip examples exist, this is compiled for demonstration
# purpose for a class
#
#Properties (right-click on the tool and specify the following)
#General
# Name BatchClipFCs
# Label Batch Clip Feature Classes
# Desc Batch clip feature classes (eg shapefiles) and saves
# them to a folder.
#
#Source BatchClipFCs.py
#
#Parameter list
# Parameter Properties
# Display Name Data type Type Direction MultiValue
# argv[1] Feature(s) to clip Feature Layer Required Input Yes
# argv[2] Polygon clip layer Feature Layer Required Input No
# argv[3] Append to output String Optional Input No
# filename
# argv[4] Output folder Folder Required Input No
#--------------------------------------------------------------------
#Import the standard modules
# Get a list of feature classes (shapefiles)
# Get the clip feature class
# Get the optional text to append to the filename output filename
# Get the output folder

# Usage: BatchClipFCs <Input_Features> <ClipWith> <optional_text> <Output_Workspace>
# ---------------------------------------------------------------------------
#
# Import system modules, Create the Geoprocessor object and
# Load required toolboxes...
#
import sys, string, os, arcpy

#
# Script arguments...
FCsToClip = arcpy.GetParameterAsText(0) #a list of features
fcs = string.split(FCsToClip, ";") #split into a list
#
clipWith = arcpy.GetParameterAsText(1) #clip layer
desc = arcpy.Describe(clipWith)
clipWithType = desc.ShapeType
#
addToName = arcpy.GetParameterAsText(2) #optional text to append to output name
if(addToName == "#"):
    addToName = ""
#
outputFolder = arcpy.GetParameterAsText(3) #a folder
#
arcpy.AddMessage("\n" + "Batch Clip Feature layers" + "\n" )
#
if (clipWithType == "Polygon"):
    for fc in fcs:
        try:
            fc=fc.replace("'","") #check if a layers name has been changed
            desc = arcpy.Describe(fc)
            fcDataType = desc.DataType
            arcpy.AddMessage("Data type = " + fcDataType)
            if(fcDataType == "FeatureClass"): # Feature class on disk
                theName = str(os.path.split(fc)[1])
                outFile = outputFolder + "\\" + theName + addToName + ".shp"
            else: # Feature layer
                FullName = desc.CatalogPath
                theName = (os.path.split(FullName)[1]).replace(".shp","")
                theName = str(fc).replace(" ","_")
                outFile = outputFolder + "\\" + theName + addToName + ".shp"
            arcpy.AddMessage("Output file from layer " + outFile)
            #
            arcpy.AddMessage("Clipping " + str(fcDataType) + ": " + fc + " Saving to: " + outFile + "\n")
            try:
                arcpy.Clip_analysis(fc, clipWith, outFile, "")
            except:
                arcpy.AddMessage("Could not clip " + fc + " with " + clipWith + " to " + outFile)
        except:
            arcpy.AddMessage("cannot describe" + fc)
else:
    arcpy.AddMessage (clipWith + " is not a polygon layer, clipping terminated" )
#


Hope that you get the idea!

Cheer...
0 Kudos
OsmanSABAN
Emerging Contributor
Hi Thai,

Thank you too for your help. i tried to work around your code suggestion and run the code. it runs with no problem but returns nothing, no error and no clipped data at specified location.

any idea?

Thanks,
0 Kudos
markdenil
Frequent Contributor
I take it you have confirmed that any of the input FCs to be clipped
can actually be clipped with the clip FC, and return a result.
To wit: they actually intersect, and you have confirmed that by trying it manually?

Also:
Try printing the members of the list fcs
print "the input list"
for f in fcs:
    print f

and print the value of ClipWith
and print the vale of outputFolder

That will confirm that you are correctly passing in the parameters.
0 Kudos