Advertisement
lightxx

UE3

Dec 4th, 2012
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.00 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. #==============================================================================
  4. #title           :heuberger_buffer.py
  5. #description     :Creates 10 buffers for a given input file ranging from 1000
  6. #                 to 10000 meters in steps of 1000 meters.
  7. #author          :Thomas Heuberger
  8. #date            :2012-12-03
  9. #version         :
  10. #usage           :python heuberger_buffer.py --help
  11. #usage           :heuberger_buffer.py --shapefile c:\temp\Center_0.shp\center_0.shp --outputdirectory c:\temp\test --refresharea
  12. #notes           :
  13. #python_version  :2.7.3
  14. #arcgis_version  :10.1 build 3143
  15. #==============================================================================
  16.  
  17. import arcpy
  18. import argparse
  19. import os.path
  20. import datetime
  21. import sys
  22.  
  23. # set up the command line argument parser
  24. parser = argparse.ArgumentParser(description="Creates 10 buffers for a given input file ranging from 1000 to 10000 meters in steps of 1000 meters.")
  25. 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")
  26. 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")
  27. parser.add_argument('-out', '--outputdirectory', help="Sets the directory used for the buffer files. Uses the current directory if not specified")
  28. # parse the command line arguments
  29. args = parser.parse_args()
  30.  
  31. # the fully qualified path of the current .py file
  32. workingDir = os.path.abspath(os.path.dirname(__file__))
  33.  
  34. # If the input shapefile was specified, use it. if not use default 'Center_0.shp\center_0.shp'
  35. shapeFile = args.shapefile if args.shapefile else workingDir + '\\' + 'Center_0.shp\\center_0.shp'
  36.  
  37. # List of file extensions
  38. ext = ["dbf", "prj", "sbn", "sbx", "shp", "shp.xml", "shx"]
  39.  
  40. ### PREFLIGHT CHECKS
  41.  
  42. # Check if the input Shapefile exists. Abort if not.
  43. if not os.path.isfile(shapeFile):
  44.     sys.exit("\r\nShapefile \"{}\" not found. \r\n Run {} --help for help. Aborting...".format(shapeFile, os.path.basename(__file__)))
  45.  
  46. # If an output directory was specified, check if it exists. Abort if not.
  47. if args.outputdirectory and not os.path.exists(args.outputdirectory):
  48.     sys.exit("\r\nSpecified output directory \"{}\" not found. \r\n Aborting...".format(args.outputdirectory))
  49. elif args.outputdirectory:
  50.     outputDir = args.outputdirectory
  51. else:
  52.     outputDir = workingDir + '\\' + 'bufferShapefiles'
  53.     # try to create the ouput directory for the buffer files.
  54.     if not os.path.exists(outputDir):
  55.         try:
  56.             os.makedirs(outputDir)
  57.         except:
  58.             sys.exit("Error creating output directory. Aborting...")
  59.  
  60. # Set the Workspace
  61. arcpy.env.workspace = outputDir
  62. # overwrite existing files aka delete existing ones. disabled in favor of Python's os.remove(). see below
  63. #arcpy.env.overwriteOutput = True
  64.    
  65. msg = "\r\nShapefile found, start buffering!"
  66. print msg
  67. print "=" * len(msg)
  68. print "\r\n" * 2
  69.  
  70. # create a range from 1000 to 10000 with steps of 1000
  71. try:
  72.     for x in xrange(1000, 11000, 1000):
  73.         # The File for the current buffer, ie. buffer_1000.shp
  74.         bufferFile =  outputDir + '\\' + "buffer_{}.shp".format(x)
  75.        
  76.         # a little housekeeping. check for existing files and remove. do this for every extension.
  77.         # see the ext list above for the list of extensions.
  78.         # I'm specifially not using wildcard matching here to prevent the deletion of the ueber-important buffer_1000.readme!!! file
  79.         for extension in ext:
  80.                 thisFile = outputDir + '\\' + "buffer_{}.{}".format(x, extension)
  81.                 if os.path.isfile(thisFile):
  82.                     os.remove(thisFile)
  83.        
  84.         timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S %f")
  85.         # Create the buffer
  86.         arcpy.Buffer_analysis(shapeFile, bufferFile, "{} Meters".format(x))
  87.            
  88.         # If the script was invoked with the --refresharea parameter, trigger an update of the Shape_Area field
  89.         if args.refresharea:
  90.             # Update the Shape_Area
  91.             arcpy.CalculateField_management(bufferFile, "Shape_Area", "float('!shape.area@squaremeters!')", "PYTHON")
  92.        
  93.         # There is just one row in each buffer file, so print will only get called once per Shapefile            
  94.         with arcpy.da.SearchCursor(bufferFile, ("SHAPE@AREA")) as cursor:
  95.             for row in cursor:
  96.                 print "File {} processed {} - Area: {} m2.".format("buffer_{}".format(x), timestamp, "{0:.2f}".format(row[0]))            
  97. except:
  98.     exMessage = ""
  99.     # Iterate through the collecion of traceback messages (if present) and compose the error message shown to the user
  100.     for ex in sys.exc_info():
  101.         try:
  102.             exMessage = exMessage + str(ex.message) + "\r\n"                              
  103.         except:
  104.             # current traceback has no ex.message attribute. pass
  105.             pass
  106.     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