Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- #==============================================================================
- #title :heuberger_buffer.py
- #description :Creates 10 buffers for a given input file ranging from 1000
- # to 10000 meters in steps of 1000 meters.
- #author :Thomas Heuberger
- #date :2012-12-03
- #version :
- #usage :python heuberger_buffer.py --help
- #usage :heuberger_buffer.py --shapefile c:\temp\Center_0.shp\center_0.shp --outputdirectory c:\temp\test --refresharea
- #notes :
- #python_version :2.7.3
- #arcgis_version :10.1 build 3143
- #==============================================================================
- import arcpy
- import argparse
- import os.path
- import datetime
- import sys
- # set up the command line argument parser
- parser = argparse.ArgumentParser(description="Creates 10 buffers for a given input file ranging from 1000 to 10000 meters in steps of 1000 meters.")
- parser.add_argument('-shp', '--shapefile', help="The input Shapefile. If not specified, Center_0.shp\center_0.shp from the directory where the .py resides is used. You must specify the full qualified path to a valid .shp file, not just a directory name")
- parser.add_argument('-ra', '--refresharea', help="Triggers the recalculation of the Shape_Area field so that the correct value is shown in ArcMap. Regardles of this setting the output of the script is always correct", action="store_true")
- parser.add_argument('-out', '--outputdirectory', help="Sets the directory used for the buffer files. Uses the current directory if not specified")
- # parse the command line arguments
- args = parser.parse_args()
- # the fully qualified path of the current .py file
- workingDir = os.path.abspath(os.path.dirname(__file__))
- # If the input shapefile was specified, use it. if not use default 'Center_0.shp\center_0.shp'
- shapeFile = args.shapefile if args.shapefile else workingDir + '\\' + 'Center_0.shp\\center_0.shp'
- # List of file extensions
- ext = ["dbf", "prj", "sbn", "sbx", "shp", "shp.xml", "shx"]
- ### PREFLIGHT CHECKS
- # Check if the input Shapefile exists. Abort if not.
- if not os.path.isfile(shapeFile):
- sys.exit("\r\nShapefile \"{}\" not found. \r\n Run {} --help for help. Aborting...".format(shapeFile, os.path.basename(__file__)))
- # If an output directory was specified, check if it exists. Abort if not.
- if args.outputdirectory and not os.path.exists(args.outputdirectory):
- sys.exit("\r\nSpecified output directory \"{}\" not found. \r\n Aborting...".format(args.outputdirectory))
- elif args.outputdirectory:
- outputDir = args.outputdirectory
- else:
- outputDir = workingDir + '\\' + 'bufferShapefiles'
- # try to create the ouput directory for the buffer files.
- if not os.path.exists(outputDir):
- try:
- os.makedirs(outputDir)
- except:
- sys.exit("Error creating output directory. Aborting...")
- # Set the Workspace
- arcpy.env.workspace = outputDir
- # overwrite existing files aka delete existing ones. disabled in favor of Python's os.remove(). see below
- #arcpy.env.overwriteOutput = True
- msg = "\r\nShapefile found, start buffering!"
- print msg
- print "=" * len(msg)
- print "\r\n" * 2
- # create a range from 1000 to 10000 with steps of 1000
- try:
- for x in xrange(1000, 11000, 1000):
- # The File for the current buffer, ie. buffer_1000.shp
- bufferFile = outputDir + '\\' + "buffer_{}.shp".format(x)
- # a little housekeeping. check for existing files and remove. do this for every extension.
- # see the ext list above for the list of extensions.
- # I'm specifially not using wildcard matching here to prevent the deletion of the ueber-important buffer_1000.readme!!! file
- for extension in ext:
- thisFile = outputDir + '\\' + "buffer_{}.{}".format(x, extension)
- if os.path.isfile(thisFile):
- os.remove(thisFile)
- timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S %f")
- # Create the buffer
- arcpy.Buffer_analysis(shapeFile, bufferFile, "{} Meters".format(x))
- # If the script was invoked with the --refresharea parameter, trigger an update of the Shape_Area field
- if args.refresharea:
- # Update the Shape_Area
- arcpy.CalculateField_management(bufferFile, "Shape_Area", "float('!shape.area@squaremeters!')", "PYTHON")
- # There is just one row in each buffer file, so print will only get called once per Shapefile
- with arcpy.da.SearchCursor(bufferFile, ("SHAPE@AREA")) as cursor:
- for row in cursor:
- print "File {} processed {} - Area: {} m2.".format("buffer_{}".format(x), timestamp, "{0:.2f}".format(row[0]))
- except:
- exMessage = ""
- # Iterate through the collecion of traceback messages (if present) and compose the error message shown to the user
- for ex in sys.exc_info():
- try:
- exMessage = exMessage + str(ex.message) + "\r\n"
- except:
- # current traceback has no ex.message attribute. pass
- pass
- sys.exit("\r\nError processing the buffer Shapefiles. \r\n The error was {} \r\n Aborting ...".format(exMessage))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement