├── commonSQL ├── README.md ├── simpleFindAndReplace ├── CreateUniqueID ├── SplitOnCharacters ├── ConcatFields ├── MakeRelativePaths.py ├── Contour_Indexing ├── JoinFields2hyperlink.js ├── DisconnectReconnectUsers.py ├── FindDuplicates ├── dissolve.py ├── License.txt ├── compareFieldsReturnHighest ├── EditAttribues ├── ExportMXD2Adobe.py ├── DetachReAttach.py ├── directoryPDFindexing ├── ExportDataDrivenPagesToPDf.py ├── Label Expressions ├── TruncateAndAppendGeodatabase.py └── ReconcileAndPostVersionedEdits.py /commonSQL: -------------------------------------------------------------------------------- 1 | ## Not in many values 2 | "MNLEGDIST" NOT IN ('20B','43A','18B','19A','9A','16B') 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ArcGIS-Scripting 2 | ================ 3 | 4 | ArcGIS Scripting 5 | 6 | 7 | This repository is for the sharing of common and not so common ArcGIS scripts... 8 | 9 | -------------------------------------------------------------------------------- /simpleFindAndReplace: -------------------------------------------------------------------------------- 1 | def ReClass(name): 2 | try: 3 | newname = name.replace("CR-","County Road ") 4 | return newname 5 | except: 6 | pass 7 | 8 | ## ReClass() 9 | -------------------------------------------------------------------------------- /CreateUniqueID: -------------------------------------------------------------------------------- 1 | #create a unique ID for each record in an attribute table 2 | #Paste function definition into Pre-Logic Script Code 3 | 4 | rec= 0 5 | def autoIncrement(): 6 | global rec 7 | pStart = 1 8 | pInterval = 1 9 | if (rec ==0): 10 | rec=pStart 11 | else: 12 | rec +=pInterval 13 | return rec 14 | 15 | #paste the function into small box below Pre-Logic Script Code 16 | 17 | autoIncrement() 18 | -------------------------------------------------------------------------------- /SplitOnCharacters: -------------------------------------------------------------------------------- 1 | ##Dataset contains spatial join of street intersections, deliminated by "&" 2 | ##Parse Street intersection into two fields 3 | 4 | 5 | ## Return everything after '&' 6 | 7 | def ReClass(streets): 8 | try: 9 | rest = streets.split('&', 1)[1] 10 | return rest 11 | except: 12 | pass ## do not return single items it is taken care of with before function 13 | 14 | ## Return everything before '&' 15 | 16 | def ReClass(streets): 17 | rest = streets.split('&', 1)[0] 18 | return rest 19 | -------------------------------------------------------------------------------- /ConcatFields: -------------------------------------------------------------------------------- 1 | ## This script concatinates two fields, one string and one float into a new string field 2 | ## that complies with the streetlights table in the local govt. information model 3 | 4 | def ConcatFields(type, watt): 5 | watt = int(watt) 6 | stringWatt = str(watt) 7 | if type == "HPS": 8 | return stringWatt + " Watts High Pressure Sodium" 9 | if type == "MH": 10 | return stringWatt + " Watts Metal Halide" 11 | if type == "MV": 12 | return stringWatt + " Watts Mercury Vapor" 13 | else: 14 | return "Unknown" 15 | 16 | ##Run 17 | ConcatFields( !gs_lamp_ty!, !gs_old_wat!) 18 | -------------------------------------------------------------------------------- /MakeRelativePaths.py: -------------------------------------------------------------------------------- 1 | import arcpy, os 2 | 3 | #walk through all subdirectories and change mxd to store relative paths 4 | 5 | for root, dirs, files in os.walk(r"Q:\Geodata\shape"): 6 | for f in files: 7 | if f.endswith(".mxd"): 8 | filepath = root + '\\' + f 9 | print filepath 10 | try: 11 | mxd = arcpy.mapping.MapDocument(filepath) 12 | #set relative paths property 13 | mxd.relativePaths = True 14 | mxd.save() 15 | except: 16 | print filepath + ' failed' 17 | pass 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Contour_Indexing: -------------------------------------------------------------------------------- 1 | #### This code takes elevations and determines if they are 2' or 10' intervals 2 | #### Example Dataset: Elevation | Contour Index | 3 | #### 462 | NULL | 4 | #### 468 | NULL | 5 | #### 460 | NULL | 6 | #### 466 | NULL | 7 | 8 | #### RETURNS: 9 | #### 462 | 2 | 10 | #### 468 | 2 | 11 | #### 460 | 10 | 12 | #### 466 | 2 | 13 | 14 | 15 | #Pre-Logic Script Code 16 | def Reclass( index): 17 | if index % 10 ==0: 18 | return 10 19 | else: 20 | return 2 21 | 22 | #ELEVINDEX = 23 | Reclass(!Elevation!) 24 | -------------------------------------------------------------------------------- /JoinFields2hyperlink.js: -------------------------------------------------------------------------------- 1 | //hyperlink JavaScript with ArcGIS 2 | 3 | //example data 4 | 5 | //ObjectID //Path //Attachment 6 | //001 //C://users/gis/ //1094.pdf 7 | //002 //C://users/gis/ //1095.pdf 8 | //003 //C://users/gis/ //1096.pdf 9 | //004 //C://users/gis/ //1099.pdf 10 | //005 //C://users/gis/ //1456.pdf 11 | //006 //C://users/gis/ //2354-1.pdf 12 | 13 | // Layer Properties/Display tab 14 | // "Support Hyperlinks using field: Script-> Edit -> Parser: JScript 15 | 16 | function OpenLink ( [Path] , [Attachment] ) 17 | { 18 | var objShell = new ActiveXObject("Shell.Application"); 19 | var path = [Path] + [Attachment] ; 20 | objShell.ShellExecute(path, "", "", "open", 1); 21 | } 22 | -------------------------------------------------------------------------------- /DisconnectReconnectUsers.py: -------------------------------------------------------------------------------- 1 | import arcpy 2 | 3 | # Many ArcGIS SDE maintenence tasks cannot be performed while users are connected to DB 4 | # This script will disconnect users and reconnect them after you run maintenence tasks 5 | # One could just comment out the AcceptConnections method to do maintenence through catalog 6 | # then just run the accepting connections method once they are finished. 7 | 8 | #block new connections to the database. 9 | arcpy.AcceptConnections("Database Connections\your.sde", False) 10 | print 'Refusing Connections' 11 | 12 | #disconnect all users from the database. 13 | arcpy.DisconnectUser("Database Connections\your.sde", "ALL") 14 | print 'Disconnected all users' 15 | 16 | # perform server maintenence here! 17 | 18 | #Allow the database to begin accepting connections again 19 | arcpy.AcceptConnections("Database Connections\your.sde", True) 20 | print "Accepting connections" 21 | 22 | -------------------------------------------------------------------------------- /FindDuplicates: -------------------------------------------------------------------------------- 1 | ## I used this script to determine if features share a common attribute 2 | ## Field Calculator 3 | 4 | # This returns duplicates 5 | 6 | uniqueList = [] 7 | def isDuplicate(inValue): 8 | if inValue in uniqueList: 9 | return 1 10 | else: 11 | uniqueList.append(inValue) 12 | return 0 13 | 14 | 15 | # This finds duplicates and gives count 16 | 17 | uniqueList = [] 18 | i = 0 19 | def isDuplicate(inValue): 20 | global i 21 | if inValue in uniqueList: 22 | i += 1 23 | return i 24 | else: 25 | uniqueList.append(inValue) 26 | return 0 27 | 28 | # This finds duplicates and gives count through dictionary 29 | 30 | UniqueDict = {} 31 | def isDuplicateIndex(inValue): 32 | UniqueDict.setdefault(inValue,0) 33 | UniqueDict[inValue] += 1 34 | return UniqueDict[inValue] 35 | 36 | # Dictionary and list methods called respectively: 37 | 38 | isDuplicateIndex( !YOUR_FIELD! ) or isDuplicate(!YOUR_FIELD!) 39 | -------------------------------------------------------------------------------- /dissolve.py: -------------------------------------------------------------------------------- 1 | # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script 2 | # The following inputs are layers or table views: "2012generalresults" 3 | # Run inside mxd with the following fields: MNLEGDIS, MNSENDIST, CONGDIST, MCDNAME, COUNTYFIPS 4 | arcpy.Dissolve_management(in_features="2012generalresults", out_feature_class="C:/Users/ccantey/Desktop/Mapbox Studio/combinedElection2012/2012mnhouseresults.shp", dissolve_field="MNLEGDIST", statistics_fields="USPRSR SUM;USPRSDFL SUM;USPRSLIB SUM;USPRSSWP SUM;USPRSCP SUM;USPRSCG SUM;USPRSGP SUM;USPRSGR SUM;USPRSSL SUM;USPRSJP SUM;USPRSWI SUM;USPRSTOTAL SUM;USSENIP SUM;USSENR SUM;USSENDFL SUM;USSENGR SUM;USSENMOP SUM;USSENWI SUM;USSENTOTAL SUM;USREPIP SUM;USREPR SUM;USREPDFL SUM;USREPWI SUM;USREPTOTAL SUM;MNSENIP SUM;MNSENR SUM;MNSENDFL SUM;MNSENWI SUM;MNSENTOTAL SUM;MNLEGIP SUM;MNLEGR SUM;MNLEGDFL SUM;MNLEGWI SUM;MNLEGTOTAL SUM", multi_part="MULTI_PART", unsplit_lines="DISSOLVE_LINES") 5 | -------------------------------------------------------------------------------- /License.txt: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /compareFieldsReturnHighest: -------------------------------------------------------------------------------- 1 | ## Compare many (unlimited/non strict number) of fields 2 | ## Return the name of the field that holds the highest value 3 | 4 | # A function that takes unlimited number of key:value pairs and returns the key with highest value 5 | 6 | def classifyWinner(**kwargs): 7 | highest = max(kwargs.values()) 8 | winner = [k for k,v in kwargs.items() if v == highest] 9 | if len(winner) == 1: 10 | return winner[0] 11 | else: 12 | return 'TIE' 13 | 14 | ## run president 15 | classifyWinner( DFL = !USPRSDFL! , R = !USPRSR! , LIB = !USPRSLIB!, SWP = !USPRSSWP!, CP = !USPRSCP!, CG = !USPRSCG!, GP = !USPRSGP!, GR = !USPRSGR!, SL = !USPRSSL!, JP = !USPRSJP!, WI = !USPRSWI!) 16 | 17 | ## run US senate - in current dataset there was a fudge up in data - all US SenateDFL are highest - i must have done a shotty field calculator by accident 18 | classifyWinner( DFL = !USSENDFL! , R = !USSENR! , GR = !USSENGR! ,MOP = !USSENMOP! , WI = !USSENWI!) 19 | 20 | ## run US house 21 | classifyWinner( DFL = !USREPDFL! , R = !USREPR! , IR = !USREPIP! , WI = !USREPWI! ) 22 | 23 | ## run MN Senate 24 | classifyWinner( DFL = !MNSENDFL! , R = !MNSENR! , IP = !MNSENIP! , WI = !MNSENWI! ) 25 | 26 | ## run MN house 27 | classifyWinner( DFL = !MNLEGDFL! , R = !MNLEgR! , IP = !MNLEGIP! , WI = !MNLEGWI! ) 28 | -------------------------------------------------------------------------------- /EditAttribues: -------------------------------------------------------------------------------- 1 | #This field calculator checks the winner and returns a net win result 2 | def reclass(a, b, c): 3 | if a == 'DFL': 4 | total = b-c 5 | return total 6 | else: 7 | return 0 8 | 9 | reclass( !MNSENWIN!, !MNSENDFL!, !MNSENR!) 10 | 11 | #This field calculator associates strings with zoning codes into field 12 | #Pre-Logic Script Code 13 | 14 | def Reclass(zoneCode): 15 | if zoneCode == "A-O": 16 | return "Agriculture - Open Space" 17 | 18 | if zoneCode == "B-1": 19 | return "Neighborhood Business" 20 | 21 | if zoneCode == "R-2": 22 | return "Single Family and 2 Family Residential" 23 | 24 | if zoneCode == "R-3": 25 | return "Medium Density Residential" 26 | 27 | #So on so forth 28 | 29 | else: 30 | return "NULL" 31 | 32 | #ZONEDESC = 33 | Reclass(!ZONECLASS!) 34 | 35 | 36 | #This field calculator determines the string length of an attribute and return the appropriate attribute (prepends zeros) 37 | def reclass(district): 38 | length = len(district) 39 | if length < 2: 40 | return "0" + district 41 | else: 42 | return district 43 | 44 | # HouseDistrict = 45 | reclass( !MNLEGDIST! ) 46 | 47 | #This field calculator determines a pct of something - in this case race:nonewhite 48 | def reclass(pop, white): 49 | if pop == 0: 50 | return 0 51 | else: 52 | pct = (pop - white)*100 /pop 53 | return pct 54 | 55 | 56 | # PctNonWhite = 57 | reclass( !populaiton!, !white!) 58 | -------------------------------------------------------------------------------- /ExportMXD2Adobe.py: -------------------------------------------------------------------------------- 1 | # Export batch .mxds to pdf, ai, jpeg, png, emf, eps, svg, bmp, tiff, gif 2 | 3 | # To use this script, all you have to do is set your workspace variables (line 12-13). 4 | # The script will export all .mxds in the directory to Illustrator, pdf, or any of the other listed formats. 5 | 6 | # This script has hung up on very large mxd files... Usually those with large raster datasets 7 | 8 | import arcpy, os 9 | 10 | # Set OverWrite if files already exist 11 | arcpy.OverWriteOutput = 1 12 | 13 | # Set workspace variables 14 | ws = arcpy.env.workspace = r"K:\01992-020\GIS\Maps" 15 | outDir = r"C:\Users\ccantey\Desktop\Test" 16 | 17 | #Select all .mxd's 18 | mapList = arcpy.ListFiles("*.mxd") 19 | 20 | # Export all mxds to new format 21 | for m in mapList: 22 | print m 23 | # Set any parameters as variables here, pass to arcpy.mapping.ExportToPDF(mxd, outDir + r'/' + str(m)), dataframe, colorspace) 24 | ## data_frame = 'PAGE_LAYOUT' 25 | ## resolution = "300" 26 | ## image_quality = "NORMAL" 27 | ## colorspace = "RGB" 28 | ## compress_vectors = "True" 29 | ## image_compression = "DEFLATE" 30 | ## picture_symbol = 'RASTERIZE_BITMAP' 31 | ## convert_markers = "False" 32 | ## embed_fonts = "True" 33 | ## layers_attributes = "NONE" 34 | ## georef_info = "False" 35 | 36 | mxd = arcpy.mapping.MapDocument(os.path.join(ws,m)) 37 | arcpy.mapping.ExportToAI(mxd, outDir + r'/' + str(m)) #.ExportToPDF, .ExportToAI, etc., give it the same name as mxd 38 | del mxd 39 | -------------------------------------------------------------------------------- /DetachReAttach.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import arcpy 3 | import os 4 | import sys 5 | 6 | input = r"Database Connections\your.sde\pictures featureclass" 7 | inputField = "NAME" 8 | matchTable = r"C:\Users\\Desktop\matchtable.csv" 9 | matchField = "NAME" 10 | pathField = r"picture Location" 11 | rootdir = r"C:\Root Directory\A-Z pictures\picture" 12 | #get subdirectories 13 | subdirectories = [x[0] for x in os.walk(rootdir)] 14 | 15 | for folders in subdirectories[1:]: 16 | print folders 17 | try: 18 | # create a new Match Table csv file 19 | writer = csv.writer(open(matchTable, "wb"), delimiter=",") 20 | 21 | # write a header row (the table will have two columns: ParcelID and Picture) 22 | writer.writerow([matchField, pathField]) 23 | 24 | # iterate through each picture in the directory and write a row to the table 25 | for file in os.listdir(folders): 26 | if str(file).find(".pdf") > -1: 27 | writer.writerow([str(file).replace(".pdf", ""), file]) 28 | 29 | # the input feature class must first be GDB attachments enabled 30 | # arcpy.EnableAttachments_management(input) 31 | 32 | # use the match table with the Remove Attachments tool 33 | arcpy.RemoveAttachments_management(input, inputField, matchTable, matchField, pathField) 34 | 35 | # use the match table with the Add Attachments tool 36 | arcpy.AddAttachments_management(input, inputField, matchTable, matchField, pathField, folders) 37 | print "Finished Attaching Documents in " + folders 38 | 39 | except: 40 | print arcpy.GetMessages(2) 41 | -------------------------------------------------------------------------------- /directoryPDFindexing: -------------------------------------------------------------------------------- 1 | # This code takes pdf files and determines if they are which numerical directory they reside in 2 | 3 | #Prelogic script 4 | 5 | directory = "S:\EngBB\Maps & Drawings\A-Z drawings\Adrawings" 6 | def Reclass( name): 7 | adraw = name[2:] 8 | # if there are more than one file (example: 'A-954-1') 9 | if adraw.endswith('-1'): 10 | adraw = adraw[:-2] 11 | try: 12 | if int(adraw) <= 99: 13 | return directory + "\\0001 thru 0099" 14 | elif int(adraw) <= 199: 15 | return directory + "\\0100 thru 0199" 16 | elif int(adraw) <= 299: 17 | return directory + "\\0200 thru 0299" 18 | elif int(adraw) <= 399: 19 | return directory + "\\0300 thru 0399" 20 | elif int(adraw) <= 499: 21 | return directory + "\\0400 thru 0499" 22 | elif int(adraw) <= 599: 23 | return directory + "\\0500 thru 0599" 24 | elif int(adraw) <= 699: 25 | return directory + "\\0600 thru 0699" 26 | elif int(adraw) <= 799: 27 | return directory + "\\0700 thru 0799" 28 | elif int(adraw) <= 899: 29 | return directory + "\\0800 thru 0899" 30 | elif int(adraw) <= 999: 31 | return directory + "\\0900 thru 0999" 32 | elif int(adraw) <= 1099: 33 | return directory + "\\1000 thru 1099" 34 | elif int(adraw) <= 1199: 35 | return directory + "\\1100 thru 1199" 36 | elif int(adraw) <= 1299: 37 | return directory + "\\1200 thru 1299" 38 | elif int(adraw) <= 1399: 39 | return directory + "\\1300 thru 1399" 40 | elif int(adraw) <= 1499: 41 | return directory + "\\1400 thru 1499" 42 | elif int(adraw) <= 1599: 43 | return directory + "\\1500 thru 1599" 44 | elif int(adraw) <= 1699: 45 | return directory + "\\1600 thru 1699" 46 | elif int(adraw) <= 1799: 47 | return directory + "\\1700 thru 1799" 48 | elif int(adraw) <= 1899: 49 | return directory + "\\1800 thru 1899" 50 | elif int(adraw) <= 1999: 51 | return directory + "\\1900 thru 1999" 52 | elif int(adraw) <= 2099: 53 | return directory + "\\2000 thru 2099" 54 | elif int(adraw) <= 2199: 55 | return directory + "\\2100 thru 2199" 56 | elif int(adraw) <= 2299: 57 | return directory + "\\2200 thru 2299" 58 | elif int(adraw) <= 2399: 59 | return directory + "\\2300 thru 2399" 60 | elif int(adraw) <= 2499: 61 | return directory + "\\2400 thru 2499" 62 | except: 63 | pass 64 | 65 | #Given 'Path' is the field we want to edit 66 | #Path = 67 | Reclass(!Name!) 68 | 69 | -------------------------------------------------------------------------------- /ExportDataDrivenPagesToPDf.py: -------------------------------------------------------------------------------- 1 | '''This script reads ArcGIS data driven pages, determines whether or not it should have landscape or portrait orientation 2 | and exports it to a PDF''' 3 | 4 | import arcpy 5 | import re 6 | from arcpy import env 7 | import os.path 8 | env.workspace = "q:\\Geodata\\shape\\vtds\\vtd2015" 9 | 10 | sCur = arcpy.SearchCursor("q:\\Geodata\\shape\\vtds\\vtd2015\\vtd2015general.shp") 11 | 12 | # Fetch each feature from the cursor and examine the extent properties 13 | 14 | for row in sCur: 15 | #clean bad characters out of fields 16 | #Duplicate pct names, append county name and district for down the road processing 17 | ceanName = re.sub('[^\w\-_\. ]', '_', row.PCTNAME) + " +"+ row.COUNTYNAME + " +" + row.MNLEGDIST 18 | 19 | geom = row.shape 20 | ext = geom.extent 21 | 22 | xlength = ext.XMax - ext.XMin 23 | ylength = ext.YMax - ext.YMin 24 | 25 | 26 | if xlength > ylength: 27 | print"x>y, map should be landscape" 28 | 29 | #skip if the file already exists - this is a long running script so breaks happen and we have to start over 30 | if os.path.isfile(r"D:\\DDP Test\\Landscape\\" + str(ceanName) + ".pdf"): 31 | print str(ceanName) + ".pdf exists" 32 | else: 33 | print str(ceanName) + ".pdf DOES NOT exist" 34 | 35 | mxd = arcpy.mapping.MapDocument(r"q:\\Geodata\\projects\\Projects2016\\WebPrecinctMaps\\Precincts2015_10222015_landscape.mxd") 36 | pageID = mxd.dataDrivenPages.getPageIDFromName(str(row.PCTNAME)) 37 | mxd.dataDrivenPages.currentPageID = pageID 38 | print "Exporting landscape page {0} of {1}".format(str(mxd.dataDrivenPages.currentPageID), str(mxd.dataDrivenPages.pageCount)) 39 | print str(row.PCTNAME) + ".pdf" 40 | print 41 | arcpy.mapping.ExportToPDF(mxd, r"D:\\DDP Test\\Landscape\\" + str(ceanName) + ".pdf",resolution=150) 42 | 43 | del mxd 44 | 45 | else: 46 | print"x 4 digits 115 | def FindLabel ( [SOME_NUMERIC_FIELD] ): 116 | return "{:,}".format(int( [SOME_NUMERIC_FIELD] )) 117 | -------------------------------------------------------------------------------- /TruncateAndAppendGeodatabase.py: -------------------------------------------------------------------------------- 1 | import arcpy 2 | import os 3 | 4 | ##This program appends (copies) feature classes from another agencies geodatabase 5 | ##into our agency's geodatabase. Must first truncate data, then append. 6 | ##This program assumes matching schema. Workaround would be to use field_mapping parameter. 7 | ##This program uses desktop copies of gdb's for proof of concept 8 | ##This program calls the Append_management method 10 times. A loop using ListFeatureClasses() method would work 9 | 10 | 11 | ##Read Water Database 12 | arcpy.env.workspace = "C:\Users\ccantey\Desktop\Local Government.gdb\WaterDistribution" ##works 13 | 14 | datasets = arcpy.ListDatasets(feature_type='feature') 15 | datasets = [''] + datasets if datasets is not None else [] 16 | 17 | ##Truncate all feature classes in current water distributin feature dataset 18 | try: 19 | for ds in datasets: 20 | for fc in arcpy.ListFeatureClasses(feature_dataset=ds): 21 | path = os.path.join(arcpy.env.workspace, ds, fc) 22 | ## Print all the feature classes 23 | print path, " truncated" 24 | arcpy.TruncateTable_management(path) 25 | except: 26 | print "didnt't work" 27 | print arcpy.GetMessages() 28 | 29 | 30 | # Set local variables 31 | inLocation = "C:\Users\ccantey\Desktop\Water_GISDATA\WaterSystem.mdb\Water_Distribution_Network" 32 | outLocation = "C:\Users\ccantey\Desktop\Local Government.gdb" 33 | schemaType = "NO_TEST" 34 | fieldMappings = "" 35 | subtype = "" 36 | 37 | print "" 38 | 39 | try: 40 | # Process: Append the feature classes into the empty feature class 41 | wLateralLine = [inLocation + "\wLateralLine"] 42 | arcpy.Append_management(wLateralLine, outLocation + "\wLateralLine", schemaType, fieldMappings, subtype) 43 | print "pass wLateralLine" 44 | 45 | # Process: Append the feature classes into the empty feature class 46 | wControlValve = [inLocation + "\wControlValve"] 47 | arcpy.Append_management(wControlValve, outLocation + "\wControlValve", schemaType, fieldMappings, subtype) 48 | print "pass wControlValve" 49 | 50 | # Process: Append the feature classes into the empty feature class 51 | wBreaks = [inLocation + "\wBreaks"] 52 | arcpy.Append_management(wBreaks, outLocation + "\wBreaks", schemaType, fieldMappings, subtype) 53 | print "pass wBreaks" 54 | 55 | # Process: Append the feature classes into the empty feature class 56 | wPressurizedMain = [inLocation + "\wPressurizedMain"] 57 | arcpy.Append_management(wControlValve, outLocation + "\wPressurizedMain", schemaType, fieldMappings, subtype) 58 | print "pass wPressurizedMain" 59 | 60 | # Process: Append the feature classes into the empty feature class 61 | wFitting = [inLocation + "\wFitting"] 62 | arcpy.Append_management(wFitting, outLocation + "\wFitting", schemaType, fieldMappings, subtype) 63 | print "pass wFitting" 64 | 65 | # Process: Append the feature classes into the empty feature class 66 | wHydrant = [inLocation + "\wHydrant"] 67 | arcpy.Append_management(wHydrant, outLocation + "\wHydrant", schemaType, fieldMappings, subtype) 68 | print "pass wHydrant" 69 | 70 | # Process: Append the feature classes into the empty feature class 71 | wManhole = [inLocation + "\wManhole"] 72 | arcpy.Append_management(wManhole, outLocation + "\wManhole", schemaType, fieldMappings, subtype) 73 | print "pass wManhole" 74 | 75 | # Process: Append the feature classes into the empty feature class 76 | wNetworkStructure = [inLocation + "\wNetworkStructure"] 77 | arcpy.Append_management(wNetworkStructure, outLocation + "\wNetworkStructure", schemaType, fieldMappings, subtype) 78 | print "pass wNetworkStructure" 79 | 80 | # Process: Append the feature classes into the empty feature class 81 | wSystemValve = [inLocation + "\wSystemValve"] 82 | arcpy.Append_management(wSystemValve, outLocation + "\wSystemValve", schemaType, fieldMappings, subtype) 83 | print "pass wSystemValve" 84 | 85 | # Process: Append the feature classes into the empty feature class 86 | Water_Distribution_Network_Junctions = [inLocation + "\Water_Distribution_Network_Junctions"] 87 | arcpy.Append_management(Water_Distribution_Network_Junctions, outLocation + "\Water_Distribution_Network_Junctions", schemaType, fieldMappings, subtype) 88 | print "pass Water_Distribution_Network_Junctions" 89 | 90 | except: 91 | # If an error occurred while running a tool print the messages 92 | print arcpy.GetMessages() 93 | 94 | -------------------------------------------------------------------------------- /ReconcileAndPostVersionedEdits.py: -------------------------------------------------------------------------------- 1 | import arcpy, time, smtplib, random 2 | 3 | 4 | # get a list of connected users. 5 | userList = arcpy.ListUsers("Database Connections/###.sde") 6 | 7 | # get a list of usernames of users currently connected and make email addresses 8 | emailList = [user.Name for user in arcpy.ListUsers("Database Connections/###.sde")] 9 | filteredEmail = [] 10 | for users in emailList: 11 | try: 12 | #print users.split('\\',1)[1].split('"',1)[0] + "@###.org" 13 | if users.split('\\',1)[1].split('"',1)[0] == 'ARCGIS': 14 | #do not mail to 'ARCGIS' user (web services) 15 | pass 16 | else: 17 | filteredEmail = users.split('\\',1)[1].split('"',1)[0] + "@####.org" 18 | except: 19 | #do not mail to 'DBO' user (me) 20 | pass 21 | 22 | print filteredEmail 23 | # take the email list and use it to send an email to connected users. 24 | SERVER = "Your mail server" 25 | FROM = "SDE Admin " 26 | TO = filteredEmail 27 | SUBJECT = "Maintenance is about to be performed" 28 | MSG = "Auto generated Message.\n\rGIS: Server maintenance will be performed in 5 minutes, please save all edits and maps. \nReconciling and posting all edited versions of ####.sde. \n\nPlease log off of all ArcGIS applications." 29 | 30 | # Prepare actual message 31 | MESSAGE = """\ 32 | From: %s 33 | To: %s 34 | Subject: %s 35 | 36 | %s 37 | """ % (FROM, ", ".join(TO), SUBJECT, MSG) 38 | 39 | # Send the mail if filteredEmail 40 | try: 41 | server = smtplib.SMTP(SERVER) 42 | server.sendmail(FROM, TO, MESSAGE) 43 | server.quit() 44 | except: 45 | pass 46 | 47 | 48 | try: 49 | #Weekly synchronization of County parcels 50 | arcpy.SynchronizeChanges_management("GIS Servers/gis on #### (user)/GeoData/####y_GeoData.GeoDataServer","DBO.####sParcels","Database Connections/####.sde","FROM_GEODATABASE1_TO_2","IN_FAVOR_OF_GDB1","BY_OBJECT","DO_NOT_RECONCILE") 51 | print 'Synchronized parcels from County' 52 | 53 | #block new connections to the database. 54 | arcpy.AcceptConnections('Database Connections/###.sde', False) 55 | 56 | # wait 10 minutes 57 | time.sleep(300) 58 | 59 | #disconnect all users from the database. 60 | arcpy.DisconnectUser('Database Connections/###.sde', "ALL") 61 | 62 | #reconcile users to QC 63 | arcpy.ReconcileVersions_management("Database Connections/###.sde","ALL_VERSIONS","DBO.QC","DBO.Chris;DBO.Joe;DBO.Kraig;DBO.Marc;DBO.Adam","LOCK_ACQUIRED","NO_ABORT","BY_OBJECT","FAVOR_EDIT_VERSION","POST","KEEP_VERSION","#") 64 | print 'reconciled & posted users to QC' 65 | 66 | #reconcile QC to DEFAULT 67 | arcpy.ReconcileVersions_management("Database Connections/###.sde","ALL_VERSIONS","dbo.DEFAULT","DBO.QC","LOCK_ACQUIRED","NO_ABORT","BY_OBJECT","FAVOR_TARGET_VERSION","POST","KEEP_VERSION","c:/temp/reconcilelog.txt") 68 | print 'reconciled & posted QC to DEFAULT' 69 | 70 | #compress database 71 | arcpy.Compress_management('Database Connections/###.sde') 72 | print 'DB compressed' 73 | 74 | #Allow the database to begin accepting connections again 75 | arcpy.AcceptConnections('Database Connections/###.sde', True) 76 | 77 | 78 | # Email GIS Admin when task is accomplished. 79 | SERVER = "Your mail server" 80 | FROM = "SDE Admin " 81 | TO = "SDE Admin " 82 | SUBJECT = "Maintenance was performed" 83 | MSG = "Auto generated Message.\n\rGIS: Server maintenance was performed. \nReconciled and posted all edited versions of ####.sde. \n\nPlease delete the log file located in C-Temp folder ." 84 | 85 | # Prepare actual message 86 | MESSAGE = """\ 87 | From: %s 88 | To: %s 89 | Subject: %s 90 | 91 | %s 92 | """ % (FROM, ", ".join(TO), SUBJECT, MSG) 93 | 94 | # Send the mail if script is successful 95 | try: 96 | server = smtplib.SMTP(SERVER) 97 | server.sendmail(FROM, TO, MESSAGE) 98 | server.quit() 99 | except: 100 | pass 101 | except: 102 | # Email GIS Admin if task fails. 103 | SERVER = "Your mail server " 104 | FROM = "SDE Admin " 105 | TO = "SDE Admin " 106 | SUBJECT = "An error occured." 107 | MSG = "Auto generated Message.\n\rGIS: Server maintenance was NOT performed. \nAn error occured while reconciling and posting edited versions of OS@###.sde. \n\nThis most likely occured because this sript does not overwrite the previous reconcil log. Please delete the log file located in C-Temp folder ." 108 | 109 | # Prepare actual message 110 | MESSAGE = """\ 111 | From: %s 112 | To: %s 113 | Subject: %s 114 | 115 | %s 116 | """ % (FROM, ", ".join(TO), SUBJECT, MSG) 117 | 118 | # Send the mail if script is successful 119 | try: 120 | server = smtplib.SMTP(SERVER) 121 | server.sendmail(FROM, TO, MESSAGE) 122 | server.quit() 123 | except: 124 | pass 125 | 126 | --------------------------------------------------------------------------------