def delete_cwd_dir(argv=None): """Deletes cost-weighted distance directory and CWD rasters """ if argv is None: argv = sys.argv # Get parameters from ArcGIS tool dialog projectDir = argv[1] cwdBaseDir = os.path.join(projectDir, "datapass\\cwd") try: if os.path.exists(cwdBaseDir): arcpy.Delete_management(cwdBaseDir) except Exception: try: if os.path.exists(cwdBaseDir): shutil.rmtree(cwdBaseDir) except Exception: arcpy.AddError("Unable to delete cwd directory. One of the rasters " "might have been open in ArcMap.\n You may " 'need to re-start ArcMap to release the file lock.') for msg in range(0, arcpy.GetMessageCount() - 1): if arcpy.GetSeverity(msg) == 2: arcpy.AddReturnMessage(msg) print(arcpy.AddReturnMessage(msg)) exit(0) return
def createDBConnectionFile(instance, database_type, database, account_authentication, dbms_admin, dbms_admin_pwd): # Local variables instance_temp = instance.replace("\\", "_") instance_temp = instance_temp.replace("/", "_") instance_temp = instance_temp.replace(":", "_") Conn_File_NameT = instance_temp + "_" + database + "_" + dbms_admin if os.environ.get("TEMP") == None: temp = "c:\\temp" else: temp = os.environ.get("TEMP") if os.environ.get("TMP") == None: temp = "/usr/tmp" else: temp = os.environ.get("TMP") Connection_File_Name = Conn_File_NameT + ".sde" Connection_File_Name_full_path = temp + os.sep + Conn_File_NameT + ".sde" # Check for the .sde file and delete it if present arcpy.env.overwriteOutput = True if os.path.exists(Connection_File_Name_full_path): os.remove(Connection_File_Name_full_path) try: arcpy.AddMessage("Creating Database Connection File...") # Process: Create Database Connection File... # Usage: out_file_location, out_file_name, DBMS_TYPE, instnace, account_authentication, username, password, database, save_username_password(must be true) arcpy.CreateDatabaseConnection_management( out_folder_path=temp, out_name=Connection_File_Name, database_platform=database_type, instance=instance, database=database, account_authentication=account_authentication, username=dbms_admin, password=dbms_admin_pwd, save_user_pass="******") for i in range(arcpy.GetMessageCount()): if "000565" in arcpy.GetMessage( i): # Check if database connection was successful arcpy.AddReturnMessage(i) arcpy.AddMessage("++++++++++++++++++") arcpy.AddMessage("Exiting!!") arcpy.AddMessage("++++++++++++++++++") sys.exit(3) else: arcpy.AddReturnMessage(i) arcpy.AddMessage("++++++++++++++++++") except: for i in range(arcpy.GetMessageCount()): arcpy.AddReturnMessage(i) connection = Connection_File_Name_full_path return connection
def createUserConnectionFiles(instance, database_type, database, account_authentication, role, dbuser_pwd, out_folder_path): # Local variables if role == 'sde': dbuser_name = 'SDE' else: dbuser_name = database.upper() + '_' + role.upper() # if dbuser_pwd != '#': # dbuser_pwd = database.lower() + '_' + role.upper() + '_' + str(datetime.datetime.now().year) # arcpy.AddMessage(dbuser_pwd) instance_temp = instance.replace("\\", "_") instance_temp = instance_temp.replace("/", "_") instance_temp = instance_temp.replace(":", "_") Conn_File_NameT = instance_temp + "." + database + "." + dbuser_name Connection_File_Name = Conn_File_NameT + ".sde" Connection_File_Name_full_path = out_folder_path + os.sep + Conn_File_NameT + ".sde" # Check for the .sde file and delete it if present arcpy.env.overwriteOutput = True if os.path.exists(Connection_File_Name_full_path): os.remove(Connection_File_Name_full_path) try: arcpy.AddMessage("Creating Database Connection File...") # Process: Create Database Connection File... # Usage: out_file_location, out_file_name, DBMS_TYPE, instnace, account_authentication, username, password, database, save_username_password(must be true) arcpy.CreateDatabaseConnection_management( out_folder_path=out_folder_path, out_name=Connection_File_Name, database_platform=database_type, instance=instance, database=database, account_authentication=account_authentication, username=dbuser_name, password=dbuser_pwd, save_user_pass="******") for i in range(arcpy.GetMessageCount()): if "000565" in arcpy.GetMessage( i): # Check if database connection was successful arcpy.AddReturnMessage(i) arcpy.AddMessage("++++++++++++++++++") arcpy.AddMessage("Exiting!!") arcpy.AddMessage("++++++++++++++++++") sys.exit(3) else: arcpy.AddReturnMessage(i) arcpy.AddMessage("++++++++++++++++++") except: for i in range(arcpy.GetMessageCount()): arcpy.AddReturnMessage(i) return Connection_File_Name_full_path
def createDBRole(connection, role): try: arcpy.AddMessage('Creating database role ' + role) arcpy.CreateRole_management(input_database=connection, grant_revoke='GRANT', role=role, user_name='') for i in range(arcpy.GetMessageCount()): arcpy.AddReturnMessage(i) arcpy.AddMessage("++++++++++++++++++") except: for i in range(arcpy.GetMessageCount()): arcpy.AddReturnMessage(i)
def exit_with_geoproc_error(filename): """Handle geoprocessor errors and provide details to user""" tb = sys.exc_info()[2] # get the traceback object # tbinfo contains the error's line number and the code tbinfo = traceback.format_tb(tb)[0] line = tbinfo.split(", ")[1] arcpy.AddError("Geoprocessing error on **" + line + "** of " + filename + " :") for msg in range(0, arcpy.GetMessageCount() - 1): if arcpy.GetSeverity(msg) == 2: arcpy.AddReturnMessage(msg) print(arcpy.AddReturnMessage(msg)) exit(0)
def logPreviousToolMessages(): i = 0 msgCount = arcpy.GetMessageCount() while i < msgCount: msg = arcpy.GetMessage(i) arcpy.AddReturnMessage(i) i += 1
def createDBRoleSQL(instance, database, dbms_admin, dbms_admin_pwd, role): try: arcpy.AddMessage('Creating database role ' + role) sql = gc_sql_utils.createRole.format(database=database, role=role) executeSQL(sql, instance, dbms_admin, dbms_admin_pwd) arcpy.AddMessage("++++++++++++++++++") except: for i in range(arcpy.GetMessageCount()): arcpy.AddReturnMessage(i)
def createDBUser(database, connection, dbuser_pwd, role): # if dbuser_pwd != '': # dbuser_pwd = database.lower() + '_' + role.upper() + '_' + str(datetime.datetime.now().year) # arcpy.AddWarning('No password specified. Setting the password to: ' + dbuser_pwd) try: dbuser = (database + '_' + role).upper() role = 'R_SDE_' + role.upper() arcpy.AddMessage('Creating database user ' + dbuser) arcpy.CreateDatabaseUser_management( input_database=connection, user_authentication_type='DATABASE_USER', user_name=dbuser, user_password=dbuser_pwd, role=role, tablespace_name='') for i in range(arcpy.GetMessageCount()): arcpy.AddReturnMessage(i) arcpy.AddMessage("++++++++++++++++++") except: for i in range(arcpy.GetMessageCount()): arcpy.AddReturnMessage(i)
def createSDE(database_type, instance, database, account_authentication, dbms_admin, dbms_admin_pwd, schema_type, gdb_admin, gdb_admin_pwd, tablespace, license): # Get the current product license product_license = arcpy.ProductInfo() # Checks required license level if product_license.upper() == "ARCVIEW" or product_license.upper( ) == 'ENGINE': print( "\n" + product_license + " license found!" + " Creating an enterprise geodatabase requires an ArcGIS for Desktop Standard or Advanced, ArcGIS Engine with the Geodatabase Update extension, or ArcGIS for Server license." ) sys.exit("Re-authorize ArcGIS before creating enterprise geodatabase.") else: print("\n" + product_license + " license available! Continuing to create...") arcpy.AddMessage("++++++++++++++++++") try: arcpy.AddMessage("Creating enterprise geodatabase...") arcpy.CreateEnterpriseGeodatabase_management( database_platform=database_type, instance_name=instance, database_name=database, account_authentication=account_authentication, database_admin=dbms_admin, database_admin_password=dbms_admin_pwd, sde_schema=schema_type, gdb_admin_name=gdb_admin, gdb_admin_password=gdb_admin_pwd, tablespace_name=tablespace, authorization_file=license) for i in range(arcpy.GetMessageCount()): arcpy.AddReturnMessage(i) arcpy.AddMessage("++++++++++++++++++") except: for i in range(arcpy.GetMessageCount()): arcpy.AddReturnMessage(i)
print "Creating egdb Database Connection File..." # Process: Create egdb Database Connection File... # Usage: out_file_location, out_file_name, DBMS_TYPE, instance, database, account_authentication, username, password, save_username_password(must be true) arcpy.CreateDatabaseConnection_management( out_folder_path=Connection_File_Out_Folder, out_name=Connection_File_Name, database_platform=database_type, instance=instance, database=database, account_authentication=account_authentication, username=username, password=password, save_user_pass="******") for i in range(arcpy.GetMessageCount()): if "000565" in arcpy.GetMessage( i): #Check if database connection was successful arcpy.AddReturnMessage(i) arcpy.AddMessage("Exiting!!") sys.exit(3) else: arcpy.AddReturnMessage(i) #Check if no value entered for option except SystemExit as e: if e.code == 2: parser.usage = "" print "\n" parser.print_help() parser.exit(2)
def connect(database, server="<default server>", username="******", password="******", version="SDE.DEFAULT"): # Check if value entered for option try: #Usage parameters for spatial database connection to upgrade service = "sde:sqlserver:" + server account_authentication = 'DATABASE_AUTH' version = version.upper() database = database.lower() # Check if direct connection if service.find(":") <> -1: #This is direct connect ServiceConnFileName = service.replace(":", "") ServiceConnFileName = ServiceConnFileName.replace(";", "") ServiceConnFileName = ServiceConnFileName.replace("=", "") ServiceConnFileName = ServiceConnFileName.replace("/", "") ServiceConnFileName = ServiceConnFileName.replace("\\", "") else: arcpy.AddMessage("\n+++++++++") arcpy.AddMessage("Exiting!!") arcpy.AddMessage("+++++++++") sys.exit( "\nSyntax for a direct connection in the Service parameter is required for geodatabase upgrade." ) # Local variables Conn_File_NameT = server + "_" + ServiceConnFileName + "_" + database + "_" + username if os.environ.get("TEMP") == None: temp = "c:\\temp" else: temp = os.environ.get("TEMP") if os.environ.get("TMP") == None: temp = "/usr/tmp" else: temp = os.environ.get("TMP") Connection_File_Name = temp + os.sep + Conn_File_NameT + ".sde" if os.path.isfile(Connection_File_Name): return Connection_File_Name # Check for the .sde file and delete it if present arcpy.env.overwriteOutput = True # Variables defined within the script; other variable options commented out at the end of the line saveUserInfo = "SAVE_USERNAME" #DO_NOT_SAVE_USERNAME saveVersionInfo = "SAVE_VERSION" #DO_NOT_SAVE_VERSION print "\nCreating ArcSDE Connection File...\n" # Process: Create ArcSDE Connection File... # Usage: out_folder_path, out_name, server, service, database, account_authentication, username, password, save_username_password, version, save_version_info print temp print Conn_File_NameT print server print service print database print account_authentication print username print password print saveUserInfo print version print saveVersionInfo arcpy.CreateArcSDEConnectionFile_management(temp, Conn_File_NameT, server, service, database, account_authentication, username, password, saveUserInfo, version, saveVersionInfo) for i in range(arcpy.GetMessageCount()): if "000565" in arcpy.GetMessage( i): #Check if database connection was successful arcpy.AddReturnMessage(i) arcpy.AddMessage("\n+++++++++") arcpy.AddMessage("Exiting!!") arcpy.AddMessage("+++++++++\n") sys.exit(3) else: arcpy.AddReturnMessage(i) arcpy.AddMessage("+++++++++\n") return Connection_File_Name #Check if no value entered for option except SystemExit as e: print e.code return
outFocalStatistics = FocalStatistics(outNFRaster, neighborhood, "MEDIAN", "DATA") outFocalStatistics.save(fsMedRaster) #Process: Copy Raster to create an 8bit tif. # The input image has a Min-max range of 0-255 but NoData is -32868 and therefore defaulted to 16bit in a GRID. # Using copy Raster does not change the data range but converts to TIF and assigns NoData value to 256, therefore is an 8bit. arcpy.AddMessage("Creating Filtered 8bit TIF image ...") arcpy.CopyRaster_management(fsMedRaster, outFRaster, "", "", "", "NONE", "NONE", "8_BIT_UNSIGNED") except arcpy.ExecuteError: #Return Geoprocessing tool specific errors line, filename, err = trace() arcpy.AddError("Geoprocessing error on " + line + " of " + filename + " :") for msg in range(0, arcpy.GetMessageCount()): if arcpy.GetSeverity(msg) == 2: arcpy.AddReturnMessage(msg) except: #Returns Python and non-tool errors line, filename, err = trace() arcpy.AddError("Python error on " + line + " of " + filename) arcpy.AddError(err) finally: # Process: Delete intermediate files if arcpy.Exists(inRastC): arcpy.Delete_management(inRastC, "") if arcpy.Exists(scImage1): arcpy.Delete_management(scImage1, "") if arcpy.Exists(fsMedRaster): arcpy.Delete_management(fsMedRaster, "") arcpy.AddMessage("Intermediate files deleted!")
def GPMsg(sev=None, msg=None, msgType=None): """Send a message to the geoprocessor,"python-print", or both Geoprocessing messages displayed with methods like "arcpy.AddMessage" may be visible in ArcGIS or in tty python output, but when running the script within IDE environments like IDLE or Wing, invisible, or display garbled. This method allows you to specify to send a message to python-print, just the geoprocessor, or to both places. The syntax also allows for a little less typing than the gp messaging methods it calls. dependencies GPModeThing arguments sev - severity code / message option "Message","Warning","Error","Return","Time","Gpmessages" (only the first letter is required) msg - text message to display A special syntax for msg is used to support arcpy.AddIDMessage(). (Spaces are required between each argument!) ID <MessageID> {AddArgument1} {AddArgument2} For example, to do this: arcpy.AddIDMessage("Error", 12, outFeatureClass) You can use this syntax with GPMsg: GPMsg("Error","ID %s %s" % (12,outFeatureClass)) If a message argument contains a space, you can use | to separate the second argument so it will parse correctly: GPMsg("Error","ID %s %s|%s" % (328,"Input dataset",outFeatureClass)) (Please only use error numbers documented in the ArcGIS help!) msgType - Where to send the message. If this argument is given the destination will stay the same until GPMode is used or the argument is given again. "gp" Geoprocessor (default) (arcpy or 9.x gp object) "print" Python print "both" Both places "off" Nothing prints anywhere (use with care) None Use current value of GPMode() examples GPMode("print") # change default output to python-print GPMsg("This is a message") # default output, print ONLY GPMsg("t","The time is now","gp") # output to ArcGIS ONLY GPMsg() # print arcpy.AddMessages(0) GP messages to ARCGIS only GPMsg("w","ID 345","both") # use arcpy.AddIDMessage, output to gp,print GPMode("off") # no messages printed Output: This is a message 10:40:05 The time is now Executing: CopyFeatures poly_inout E:\work\poly_inout_CopyFeatures.shp # 0 0 0 Start Time: Wed Apr 07 11:11:58 2010 Executed (CopyFeatures) successfully. End Time: Wed Apr 07 11:11:58 2010 (Elapsed Time: 0.00 seconds) WARNING 000345: Input must be a workspace """ # support shorthand usage: GPMsg("message") and GPMsg() if sev != None and msg == None: # GPMsg("message") -> GPMsg("","message") sev, msg = None, sev elif sev == None and msg == None: # GPMsg() -> GPMsg("Message",arcpy.GetMessages(0)) sev, msg = "g", None if not msgType: msgType = GPMode() # use current value of GPMode else: msgType = GPMode(msgType) # set GPMode (and remember for next GPMsg) if msgType == "off": # Do not print anything! (like AML "&messages &off &all") return # decode severity to a code 0 thru 5: # sev isev description # 0 message # "w" 1 warning # "e" 2 error # "r" 3 returnmessage # "t" 4 message with clock time & sec since last check # "g" 5 return arcpy.GetMessages(0) dictSev = {"w": 1, "e": 2, "r": 3, "t": 4, "g": 5} try: sev = str(sev).lower()[:1] # "Warning" -> "w" isev = dictSev[sev] except: isev = 0 # support arcpy.AddIDMessage IDMessage = False # assume this isn't an id message try: # Usage: "ID <msgID> {|} {arg1} {|} {arg2}" lstMsg = msg.split() if lstMsg[0].lower() != "id": raise try: MessageID = int(lstMsg[1]) if MessageID <= 0 or MessageID > 99999: raise except: GPMsg("w", "GPMsg: Invalid message ID: %s" % MessageID) raise xmsg = " ".join(lstMsg[2:]) if xmsg.find("|") > -1: lstMsg = xmsg.split("|") else: lstMsg = xmsg.split() IDMessage = True # capture AddArgument1, AddArgument2 try: IDArg1, IDArg2 = "", "" IDArg1 = lstMsg[0] IDArg2 = lstMsg[1] except: pass except: pass # send our message if msgType.lower() in ["gp", "both"]: # send message to geoprocessor if isev == 0: arcpy.AddMessage(msg) elif isev == 1: if not IDMessage: arcpy.AddWarning(msg) else: arcpy.AddIDMessage("Warning", MessageID, IDArg1, IDArg2) elif isev == 2: if not IDMessage: arcpy.AddError(msg) else: arcpy.AddIDMessage("Error", MessageID, IDArg1, IDArg2) elif isev == 3: arcpy.AddReturnMessage(int(msg)) elif isev == 4: curTime = time.strftime("%H:%M:%S ", time.localtime()) elpTime = timeDiff() arcpy.AddMessage("%s %.2f %s" % (curTime, elpTime, msg)) elif isev == 5: arcpy.AddMessage(arcpy.GetMessages(0)) if msgType.lower() in ["print", "both"]: # python-print messages SevLabel = ["", "WARNING", "ERROR"] if isev == 0: print msg elif isev in [1, 2]: if not IDMessage: print("%s: %s" % (SevLabel[isev], msg)) else: print("%s %06d: %s" % (SevLabel[isev], MessageID, lstMsg)) elif isev == 3: print(arcpy.GetMessage(int(msg))) elif isev == 4: curTime = time.strftime("%H:%M:%S ", time.localtime()) elpTime = timeDiff() print("%s %.2f %s" % (curTime, elpTime, msg)) elif isev == 5: msg = arcpy.GetMessages(0) if len(msg) > 0: print(msg)
# define the enterprise geodatabase workspace env.workspace = r'C:\Data\OSM\Mxds\NewOSMDEV.sde' # get the feature set (first parameter) to extract the AOI envelope aoi_featureset = arcpy.GetParameter(0) inputName = arcpy.GetParameterAsText(1) validatedTableName = arcpy.ValidateTableName(inputName, env.workspace) nameOfTargetDataset = arcpy.os.path.join(env.workspace, validatedTableName) nameOfPointFeatureClass = arcpy.os.path.join(env.workspace, validatedTableName, validatedTableName + r'_osm_pt') nameOfLineFeatureClass = arcpy.os.path.join(env.workspace, validatedTableName, validatedTableName + r'_osm_ln') nameOfPolygonFeatureClass = arcpy.os.path.join( env.workspace, validatedTableName, validatedTableName + r'_osm_ply') # request the data from the OSM server and store it in the target feature dataset arcpy.OSMGPDownload_osmtools(r'http://www.openstreetmap.org', aoi_featureset, 'DO_NOT_INCLUDE_REFERENCES', nameOfTargetDataset, nameOfPointFeatureClass, nameOfLineFeatureClass, nameOfPolygonFeatureClass) # Return the resulting messages as script tool output messages # x = 0 while x < arcpy.GetMessageCount(): arcpy.AddReturnMessage(x) x = x + 1
def RotateFeatureClass(inputFC, outputFC, angle=0, pivot_point=None): """Rotate Feature Class inputFC Input features outputFC Output feature class angle Angle to rotate, in degrees pivot_point X,Y coordinates (as space-separated string) Default is lower-left of inputFC As the output feature class no longer has a "real" xy locations, after rotation, it no coordinate system defined. """ def RotateXY(x, y, xc=0, yc=0, angle=0, units="DEGREES"): """Rotate an xy cooordinate about a specified origin x,y xy coordinates xc,yc center of rotation angle angle units "DEGREES" (default) or "RADIANS" """ x = x - xc y = y - yc # make angle clockwise (like Rotate_management) angle = angle * -1 if units == "DEGREES": angle = math.radians(angle) xr = (x * math.cos(angle)) - (y * math.sin(angle)) + xc yr = (x * math.sin(angle)) + (y * math.cos(angle)) + yc return xr, yr # temp names for cleanup env_file = None lyrFC, lyrTmp = [None] * 2 # layers tmpFC = None # temp dataset try: # process parameters try: xcen, ycen = [float(xy) for xy in pivot_point.split()] pivot_point = xcen, ycen except: # if pivot point was not specified, get it from # the lower-left corner of the feature class ext = arcpy.Describe(inputFC).extent xcen, ycen = ext.XMin, ext.YMin pivot_point = xcen, ycen angle = float(angle) # set up environment env_file = arcpy.CreateScratchName("xxenv", ".xml", "file", os.environ["TEMP"]) arcpy.gp.SaveSettings(env_file) WKS = env.workspace if not WKS: if os.path.dirname(outputFC): WKS = os.path.dirname(outputFC) else: WKS = os.path.dirname(arcpy.Describe(inputFC).catalogPath) env.workspace = env.scratchWorkspace = WKS # Disable any GP environment clips arcpy.ClearEnvironment("extent") # get feature class properties lyrFC = 'lyrFC' arcpy.MakeFeatureLayer_management(inputFC, lyrFC) dFC = arcpy.Describe(lyrFC) shpField = dFC.shapeFieldName shpType = dFC.shapeType # create temp feature class tmpFC = arcpy.CreateScratchName("xxfc", "", "featureclass") # Create Feature Class using inputFC as template (so will have "Grid" field) arcpy.CreateFeatureclass_management(os.path.dirname(tmpFC), os.path.basename(tmpFC), shpType, inputFC) lyrTmp = 'lyrTmp' arcpy.MakeFeatureLayer_management(tmpFC, lyrTmp) ## WORKAROUND: removed below because it was creating a schema lock until Pro/arcpy exited ## set up grid field #gridField = "Grid" #arcpy.AddField_management(lyrTmp, gridField, "TEXT") #arcpy.DeleteField_management(lyrTmp, 'ID') # rotate the feature class coordinates for each feature, and each feature part # open read and write cursors updateFields = ['SHAPE@', 'Grid'] arcpy.AddMessage('Rotating temporary dataset') parts = arcpy.Array() rings = arcpy.Array() ring = arcpy.Array() with arcpy.da.SearchCursor(lyrFC, updateFields) as inRows,\ arcpy.da.InsertCursor(lyrTmp, updateFields) as outRows: for inRow in inRows: shp = inRow[0] # SHAPE p = 0 for part in shp: for pnt in part: if pnt: x, y = RotateXY(pnt.X, pnt.Y, xcen, ycen, angle) ring.add(arcpy.Point(x, y, pnt.ID)) else: # if we have a ring, save it if len(ring) > 0: rings.add(ring) ring.removeAll() # we have our last ring, add it rings.add(ring) ring.removeAll() # if only one, remove nesting if len(rings) == 1: rings = rings.getObject(0) parts.add(rings) rings.removeAll() p += 1 # if only one, remove nesting if len(parts) == 1: parts = parts.getObject(0) if dFC.shapeType == "Polyline": shp = arcpy.Polyline(parts) else: shp = arcpy.Polygon(parts) parts.removeAll() gridValue = inRow[1] # GRID string outRows.insertRow([shp, gridValue]) # write row to output arcpy.AddMessage('Merging temporary, rotated dataset with output') env.qualifiedFieldNames = False arcpy.Merge_management(lyrTmp, outputFC) except MsgError as xmsg: arcpy.AddError(str(xmsg)) except arcpy.ExecuteError: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo.strip()) arcpy.AddError(arcpy.GetMessages()) numMsg = arcpy.GetMessageCount() for i in range(0, numMsg): arcpy.AddReturnMessage(i) except Exception as xmsg: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo + str(xmsg)) finally: # reset environment if env_file: arcpy.gp.LoadSettings(env_file) # Clean up temp files for f in [lyrFC, lyrTmp, tmpFC, env_file]: try: if f and arcpy.Exists(f): arcpy.Delete_management(f) except: pass # return pivot point try: pivot_point = "{0} {1}".format(*pivot_point) except: pivot_point = None return pivot_point
def RotateFeatureClass(inputFC, outputFC, angle=0, pivot_point=None): """Rotate Feature Class inputFC Input features outputFC Output feature class angle Angle to rotate, in degrees pivot_point X,Y coordinates (as space-separated string) Default is lower-left of inputFC As the output feature class no longer has a "real" xy locations, after rotation, it no coordinate system defined. """ def RotateXY(x, y, xc=0, yc=0, angle=0, units="DEGREES"): """Rotate an xy cooordinate about a specified origin x,y xy coordinates xc,yc center of rotation angle angle units "DEGREES" (default) or "RADIANS" """ import math x = x - xc y = y - yc # make angle clockwise (like Rotate_management) angle = angle * -1 if units == "DEGREES": angle = math.radians(angle) xr = (x * math.cos(angle)) - (y * math.sin(angle)) + xc yr = (x * math.sin(angle)) + (y * math.cos(angle)) + yc return xr, yr # temp names for cleanup env_file = None lyrFC, lyrTmp, lyrOut = [None] * 3 # layers tmpFC = None # temp dataset Row, Rows, oRow, oRows = [None] * 4 # cursors try: # process parameters try: xcen, ycen = [float(xy) for xy in pivot_point.split()] pivot_point = xcen, ycen except: # if pivot point was not specified, get it from # the lower-left corner of the feature class ext = arcpy.Describe(inputFC).extent xcen, ycen = ext.XMin, ext.YMin pivot_point = xcen, ycen angle = float(angle) # set up environment env_file = arcpy.CreateScratchName("xxenv",".xml","file", os.environ["TEMP"]) arcpy.SaveSettings(env_file) # Disable any GP environment clips or project on the fly arcpy.ClearEnvironment("extent") arcpy.ClearEnvironment("outputCoordinateSystem") WKS = env.workspace if not WKS: if os.path.dirname(outputFC): WKS = os.path.dirname(outputFC) else: WKS = os.path.dirname( arcpy.Describe(inputFC).catalogPath) env.workspace = env.scratchWorkspace = WKS # Disable GP environment clips or project on the fly arcpy.ClearEnvironment("extent") arcpy.ClearEnvironment("outputCoordinateSystem") # get feature class properties lyrFC = "lyrFC" arcpy.MakeFeatureLayer_management(inputFC, lyrFC) dFC = arcpy.Describe(lyrFC) shpField = dFC.shapeFieldName shpType = dFC.shapeType FID = dFC.OIDFieldName # create temp feature class tmpFC = arcpy.CreateScratchName("xxfc","","featureclass") arcpy.CreateFeatureclass_management(os.path.dirname(tmpFC), os.path.basename(tmpFC), shpType) lyrTmp = "lyrTmp" arcpy.MakeFeatureLayer_management(tmpFC, lyrTmp) # set up id field (used to join later) TFID = "XXXX_FID" arcpy.AddField_management(lyrTmp, TFID, "LONG") arcpy.DeleteField_management(lyrTmp, "ID") # rotate the feature class coordinates # only points, polylines, and polygons are supported # open read and write cursors Rows = arcpy.SearchCursor(lyrFC, "", "", "%s;%s" % (shpField,FID)) oRows = arcpy.InsertCursor(lyrTmp) if shpType == "Point": for Row in Rows: shp = Row.getValue(shpField) pnt = shp.getPart() pnt.X, pnt.Y = RotateXY(pnt.X,pnt.Y,xcen,ycen,angle) oRow = oRows.newRow() oRow.setValue(shpField, pnt) oRow.setValue(TFID,Row.getValue(FID)) oRows.insertRow(oRow) elif shpType in ["Polyline","Polygon"]: parts = arcpy.Array() rings = arcpy.Array() ring = arcpy.Array() for Row in Rows: shp = Row.getValue(shpField) p = 0 for part in shp: for pnt in part: if pnt: x, y = RotateXY(pnt.X, pnt.Y, xcen, ycen, angle) ring.add(arcpy.Point(x, y, pnt.ID)) else: # if we have a ring, save it if len(ring) > 0: rings.add(ring) ring.removeAll() # we have our last ring, add it rings.add(ring) ring.removeAll() # if only one, remove nesting if len(rings) == 1: rings = rings.getObject(0) parts.add(rings) rings.removeAll() p += 1 # if only one, remove nesting if len(parts) == 1: parts = parts.getObject(0) if dFC.shapeType == "Polyline": shp = arcpy.Polyline(parts) else: shp = arcpy.Polygon(parts) parts.removeAll() oRow = oRows.newRow() oRow.setValue(shpField, shp) oRow.setValue(TFID,Row.getValue(FID)) oRows.insertRow(oRow) else: #raise Exception, "Shape type {0} is not supported".format(shpType) #UPDATE raise Exception("Shape type {0} is not supported".format(shpType)) del oRow, oRows # close write cursor (ensure buffer written) oRow, oRows = None, None # restore variables for cleanup # join attributes, and copy to output arcpy.AddJoin_management(lyrTmp, TFID, lyrFC, FID) env.qualifiedFieldNames = False arcpy.Merge_management(lyrTmp, outputFC) lyrOut = "lyrOut" arcpy.MakeFeatureLayer_management(outputFC, lyrOut) # drop temp fields 2,3 (TFID, FID) fnames = [f.name for f in arcpy.ListFields(lyrOut)] dropList = ";".join(fnames[2:4]) arcpy.DeleteField_management(lyrOut, dropList) #except MsgError, xmsg: #UPDATE except MsgError as xmsg: arcpy.AddError(str(xmsg)) except arcpy.ExecuteError: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo.strip()) arcpy.AddError(arcpy.GetMessages()) numMsg = arcpy.GetMessageCount() for i in range(0, numMsg): arcpy.AddReturnMessage(i) #except Exception, xmsg: #UPDATE except Exception as xmsg: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo + str(xmsg)) finally: # reset environment if env_file: arcpy.LoadSettings(env_file) # Clean up temp files for f in [lyrFC, lyrTmp, lyrOut, tmpFC, env_file]: try: if f: arcpy.Delete_management(f) except: pass # delete cursors try: for c in [Row, Rows, oRow, oRows]: del c except: pass # return pivot point try: pivot_point = "{0} {1}".format(*pivot_point) except: pivot_point = None return pivot_point
def sde_connect(self, database, server="<default server>", username="", password="", version="SDE.DEFAULT"): # Check if value entered for option try: # usage parameters for spatial database connection to upgrade server = server.lower() version = version.upper() database = database.lower() service = "sde:sqlserver:" + server account_authentication = 'OPERATING_SYSTEM_AUTH' # check if direct connection if service.find(":") != -1: # this is direct connect sde_conn_file_name = service.replace(":", "_") sde_conn_file_name = sde_conn_file_name.replace(";", "") sde_conn_file_name = sde_conn_file_name.replace("=", "") sde_conn_file_name = sde_conn_file_name.replace("/", "") sde_conn_file_name = sde_conn_file_name.replace("\\", "") else: arcpy.AddMessage("\n+++++++++") arcpy.AddMessage("Exiting!!") arcpy.AddMessage("+++++++++") sys.exit("\nSyntax for a direct connection in the Service parameter is required for geodatabase upgrade.") # local variables sde_conn_file_name = sde_conn_file_name + "_" + database + "_" + version.split('.')[-1].lower() sde_conn_file_path = self.app_files_path + os.sep + sde_conn_file_name + ".sde" if os.path.isfile(sde_conn_file_path): return sde_conn_file_path # Check for the .sde file and delete it if present arcpy.env.overwriteOutput=True # Variables defined within the script; other variable options commented out at the end of the line save_user_info = "" save_version_info = "" print("Creating ArcSDE Connection File...") print(self.app_files_path) print(sde_conn_file_name) print(server) print(service) print(database) print(account_authentication) print(username) print(password) print(save_user_info) print(version) print(save_version_info) arcpy.CreateArcSDEConnectionFile_management(self.app_files_path, sde_conn_file_name, server, service, database, account_authentication, username, password, save_user_info, version, save_version_info) for i in range(arcpy.GetMessageCount()): if "000565" in arcpy.GetMessage(i): # check if database connection was successful arcpy.AddReturnMessage(i) arcpy.AddMessage("\n+++++++++") arcpy.AddMessage("Exiting!!") arcpy.AddMessage("+++++++++\n") sys.exit(3) else: arcpy.AddReturnMessage(i) arcpy.AddMessage("+++++++++\n") return sde_conn_file_path # check if no value entered for option except SystemExit as e: print e.code return