├── Download_Zipped_File_From_FTP.py ├── GPXtoPolyline.py ├── LICENSE ├── LogResults_CaptureErrors_Template.py ├── PointFeatureClassfromCSV.py ├── Polygon_Centroid_To_Point_Layer.py ├── README.md ├── SDE_to_FileGDB_Replica.py ├── enterprise_geodatabase_maintenance_tasks.py ├── export_layers_to_file_geodatabase_and_excel.py ├── print_errors.py └── update_replica_schema.py /Download_Zipped_File_From_FTP.py: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------------------------------- 2 | # Name: Download Zipped File from FTP Site 3 | # 4 | # Author: Patrick McKinney, Cumberland County GIS (pmckinney@ccpa.net or pnmcartography@gmail.com) 5 | # 6 | # Created on: 01/2018 7 | # 8 | # Updated on: 12/7/2018 9 | # 10 | # Description: This is a template script for downloading a file from an FTP site 11 | # to a local or network drive. Results and error messages are written to a text file. 12 | # 13 | # Disclaimer: CUMBERLAND COUNTY ASSUMES NO LIABILITY ARISING FROM USE OF THESE MAPS OR DATA. THE MAPS AND DATA ARE PROVIDED WITHOUT 14 | # WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 15 | # FITNESS FOR A PARTICULAR PURPOSE. 16 | # Furthermore, Cumberland County assumes no liability for any errors, omissions, or inaccuracies in the information provided regardless 17 | # of the cause of such, or for any decision made, action taken, or action not taken by the user in reliance upon any maps or data provided 18 | # herein. The user assumes the risk that the information may not be accurate. 19 | # --------------------------------------------------------------------------- 20 | 21 | # Import modules 22 | import sys, os, datetime, time, zipfile, ftplib 23 | 24 | # Writes messages to a text file 25 | def message(message): 26 | time_stamp = time.strftime("%b %d %Y %H:%M:%S") 27 | placeholder = '\n{} {}\n'.format(time_stamp,message) 28 | return placeholder 29 | # end message() 30 | 31 | try: 32 | # Get current date and time 33 | currentTime = datetime.datetime.now() 34 | # Format date as Year-Month-Day (2017-01-17 35 | dateToday = currentTime.strftime("%Y-%m-%d") 36 | 37 | # container for messages for log file 38 | log_text = '' 39 | # path and name of text file to store log messages 40 | # sample: r'C:\Scripts\File Transfer\Download Geodatabase Results {}.txt'.format(dateToday) 41 | log_file = '' 42 | 43 | # Variables 44 | # ftp server 45 | ftp_server = "" 46 | # user name for FTP 47 | username = '' 48 | # password for FTP 49 | password = '' 50 | # location to save file 51 | # change this to the directory you want to save the file to 52 | # sample: r'C:\GIS Data\' 53 | localDir = '' 54 | # zipped file on FTP you are downloading 55 | zippedFileToDownload = 'Name_Of_File.zip' 56 | 57 | # Download file from FTP site 58 | # open ftp connection 59 | ftp = ftplib.FTP(ftp_server) 60 | print 'Established FTP connection' 61 | log_text += message('Established FTP connection') 62 | # login to ftp 63 | ftp.login(username, password) 64 | print 'Logged into FTP' 65 | log_text += message('Logged into FTP') 66 | # change directory to desired directory 67 | ftp.cwd('SomeDirectory') 68 | # get current ftp directory 69 | ftpDir = ftp.pwd() 70 | print 'Changed directories to {}'.format(ftpDir) 71 | log_text += message('Changed directories to {}'.format(ftpDir)) 72 | # get list of files in current FTP directory 73 | filesInFtpDir = ftp.nlst() 74 | print 'Created list of files in {}'.format(ftpDir) 75 | log_text += message('Created list of files in {}'.format(ftpDir)) 76 | # check if file is in list 77 | if zippedFileToDownload in filesInFtpDir: 78 | # download zipped file on ftp to local directory 79 | with open(os.path.join(localDir, zippedFileToDownload), 'wb') as local_file: 80 | ftp.retrbinary('RETR ' + zippedFileToDownload, local_file.write) 81 | print 'Downloaded file to {}'.format(localDir) 82 | log_text += message('Downloaded file to {}'.format(localDir)) 83 | else: # if file is not in list 84 | print 'The file: {}, was not found in {}'.format(zippedFileToDownload, ftpDir) 85 | log_text += message('The file: {}, was not found in {}'.format(zippedFileToDownload, ftpDir)) 86 | # close ftp connection 87 | ftp.close() 88 | print 'Closed FTP connection' 89 | log_text += message('Closed FTP connection') 90 | 91 | # Unzip zipped file 92 | # get listing of files in local directory 93 | filesInLocalDir = os.listdir(localDir) 94 | # check if regional geodatabase is in directory 95 | if zippedFileToDownload in filesInLocalDir: 96 | # file object for zip file 97 | localZipFile = os.path.join(localDir, zippedFileToDownload) 98 | # verify file is a zipped file 99 | if zipfile.is_zipfile(localZipFile): 100 | # create zip file object 101 | with zipfile.ZipFile(localZipFile) as z: 102 | # unzip file to local directory 103 | z.extractall(localDir) 104 | print 'Completed unzipping file' 105 | log_text += message('Completed unzipping file') 106 | else: # file is not a zip file 107 | print 'The file: {}, is not a zipped file'.format(zippedFileToDownload) 108 | log_text += message('The file: {}, is not a zipped file'.format(zippedFileToDownload)) 109 | else: # file was not found on local directory. 110 | print 'The file: {}, was not found in {}'.format(zippedFileToDownload, localDir) 111 | log_text += message('The file: {}, was not found in {}'.format(zippedFileToDownload, localDir)) 112 | # If an error occurs running geoprocessing tool(s) capture error and write message 113 | # handle error outside of Python system 114 | except EnvironmentError as e: 115 | tbE = sys.exc_info()[2] 116 | # add the line number the error occured to the log message 117 | log_text += "\nFailed at Line {}\n".format(tbE.tb_lineno) 118 | print 'Failed at Line {}\n'.format(tbE.tb_lineno) 119 | # add the error message to the log message 120 | log_text += "\nError: {}\n".format(str(e)) 121 | print 'Error: {}\n'.format(str(e)) 122 | # handle exception error 123 | except Exception as e: 124 | # Store information about the error 125 | tbE = sys.exc_info()[2] 126 | # add the line number the error occured to the log message 127 | log_text += "\nFailed at Line {}\n".format(tbE.tb_lineno) 128 | print 'Failed at Line {}\n'.format(tbE.tb_lineno) 129 | # add the error message to the log message 130 | log_text += "\nError: {}\n".format(e.message) 131 | print 'Error: {}\n'.format(e.message) 132 | finally: 133 | # write message to log file 134 | try: 135 | with open(log_file, 'w') as f: 136 | f.write(str(log_text)) 137 | except: 138 | pass -------------------------------------------------------------------------------- /GPXtoPolyline.py: -------------------------------------------------------------------------------- 1 | # Name: gpx_to_polyline.py 2 | # Description: Converts GPX file into a polyline feature 3 | # Feature class can be a shapefile or geodatabase feature class 4 | # Created by: Patrick McKinney, Cumberland County GIS 5 | # Contact: pnmcartography@gmail.com 6 | # "Telling the stories of our world through the power of maps" 7 | 8 | # Import system models 9 | import arcpy, sys 10 | 11 | try: 12 | # Define parameter variables for use in ArcGIS toolbox script 13 | inputGPX = arcpy.GetParameterAsText(0) 14 | outputFeatureClass = arcpy.GetParameterAsText(1) 15 | 16 | # Convert the GPX file into in_memory features 17 | arcpy.GPXtoFeatures_conversion(inputGPX, 'in_memory\gpx_layer') 18 | 19 | # Add message that GPX file has been succesfully converted to layer in Geoprocessing window 20 | arcpy.AddMessage("GPX file converted to feature class") 21 | 22 | # Convert the tracks into lines. 23 | arcpy.PointsToLine_management('in_memory\gpx_layer', outputFeatureClass) 24 | 25 | # Add message that Polyline feature has been created in Geoprocessing window 26 | arcpy.AddMessage("GPX file converted to polyline feature class") 27 | 28 | # If an error occurs running geoprocessing tool(s) capture error and write message 29 | # handle error outside of Python system 30 | except EnvironmentError as e: 31 | tbE = sys.exc_info()[2] 32 | # Write the error message to tool's dialog window 33 | arcpy.AddError("Failed at Line {}\n".format(tbE.tb_lineno)) 34 | arcpy.AddError("Error: {}".format(str(e))) 35 | # handle exception error 36 | except Exception as e: 37 | # Store information about the error 38 | tbE = sys.exc_info()[2] 39 | # Write the error message to tool's dialog window 40 | arcpy.AddError("Failed at Line {}\n".format(tbE.tb_lineno)) 41 | arcpy.AddErro("Error: {}".format(e.message)) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /LogResults_CaptureErrors_Template.py: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------------------------------- 2 | # Name: Template ArcPy Script for Writing Messages to Text File 3 | # 4 | # Author: Patrick McKinney, Cumberland County GIS (pmckinney@ccpa.net or pnmcartography@gmail.com) 5 | # 6 | # Created on: 01/06/2017 7 | # 8 | # Updated on: 9/17/2019 9 | # 10 | # Description: This is a template script for running ArcGIS geoprocessing tool(s). 11 | # It is ideally suited for scripts that run as Windows scheduled tasks. 12 | # The script writes success or error messages in a text file. 13 | # You must update the path and name of the text file. 14 | # The ArcPy geoprocessing code goes in at line 39. 15 | # 16 | # Disclaimer: CUMBERLAND COUNTY ASSUMES NO LIABILITY ARISING FROM USE OF THESE MAPS OR DATA. THE MAPS AND DATA ARE PROVIDED WITHOUT 17 | # WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 18 | # FITNESS FOR A PARTICULAR PURPOSE. 19 | # Furthermore, Cumberland County assumes no liability for any errors, omissions, or inaccuracies in the information provided regardless 20 | # of the cause of such, or for any decision made, action taken, or action not taken by the user in reliance upon any maps or data provided 21 | # herein. The user assumes the risk that the information may not be accurate. 22 | # --------------------------------------------------------------------------- 23 | 24 | # Import system modules 25 | import arcpy, sys, time, datetime 26 | 27 | # Run geoprocessing tool. 28 | # If there is an error with the tool, it will break and run the code within the except statement 29 | try: 30 | # Time stamp variables 31 | current_time = datetime.datetime.now() 32 | # Date formatted as month-day-year (1-1-2017) 33 | date_today = current_time.strftime("%m-%d-%Y") 34 | # Date formated as month-day-year-hours-minutes-seconds 35 | date_today_time = current_time.strftime("%m-%d-%Y-%H-%M-%S") 36 | 37 | # Create text file for logging results of script 38 | # Update file path with your parameters 39 | # Each time the script runs, it creates a new text file with the date1 variable as part of the file name 40 | # The example would be GeoprocessingReport_1-1-2017 41 | log_file = r'C:\GIS\Results\GeoprocessingReport_{}.txt'.format(date_today) 42 | 43 | # variable to store messages for log file. Messages written in finally statement at end of script 44 | log_message = '' 45 | 46 | # Get the start time of the geoprocessing tool(s) 47 | start_time = time.clock() 48 | 49 | # Put ArcPy geoprocessing code within this section 50 | result # = arcpy command with appropriate parameters 51 | 52 | # write result messages to log 53 | # delay writing results until geoprocessing tool gets the completed code 54 | while result.status < 4: 55 | time.sleep(0.2) 56 | # store tool result message in a variable 57 | result_value = result.getMessages() 58 | # add the tool's message to the log file message 59 | log_message += "completed {}\n".format(str(result_value)) 60 | 61 | # Get the end time of the geoprocessing tool(s) 62 | finish_time = time.clock() 63 | # Get the total time to run the geoprocessing tool(s) 64 | elapsed_time = finish_time - start_time 65 | # total time in minutes 66 | elapsed_time_minutes = round((elapsed_time / 60), 2) 67 | 68 | # add a more human readable message to log message 69 | log_message += "\nSuccessfully ran the geoprocessing tool in {} seconds on {}\n".format(str(elapsed_time), date_today) 70 | # If an error occurs running geoprocessing tool(s) capture error and write message 71 | # handle error outside of Python system 72 | except EnvironmentError as e: 73 | tbE = sys.exc_info()[2] 74 | # add the line number the error occured to the log message 75 | log_message += "\nFailed at Line {}\n".format(tbE.tb_lineno) 76 | # add the error message to the log message 77 | log_message += "\nError: {}\n".format(str(e)) 78 | # handle exception error 79 | except Exception as e: 80 | # Store information about the error 81 | tbE = sys.exc_info()[2] 82 | # add the line number the error occured to the log message 83 | log_message += "\nFailed at Line {}\n".format(tbE.tb_lineno) 84 | # add the error message to the log message 85 | log_message += "\nError: {}\n".format(e.message) 86 | finally: 87 | # write message to log file 88 | try: 89 | with open(log_file, 'w') as f: 90 | f.write(str(log_message)) 91 | except: 92 | pass -------------------------------------------------------------------------------- /PointFeatureClassfromCSV.py: -------------------------------------------------------------------------------- 1 | # Name: Create Point Feature Class from CSV File 2 | # Description: Create a feature class from a CSV file containing latitude, longitude, 3 | # and attributes for a layer. Script creates a empty feature class, add fields to 4 | # the feature class, and then loops through a CSV file to add records to the feature class 5 | # Created by: Patrick McKinney, Cumberland County GIS 6 | # Contact: pnmcartography@gmail.com 7 | # "Telling the stories of our world through the power of maps" 8 | # Updated on: 12/7/2018 9 | ############################################################################################## 10 | 11 | # Import the arcpy module and set the current workspace 12 | import arcpy, sys 13 | 14 | try: 15 | arcpy.env.workspace = r"enter file path within quotes" 16 | 17 | # Create a variable to hold the spatial reference for the feature class 18 | # Place WKID (well-know ID) within () 19 | # Geographic Coordinate System reference: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Geographic_coordinate_systems/02r300000105000000/ 20 | # Projected Coordinate System reference: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Projected_coordinate_systems/02r3000000vt000000/ 21 | sr = arcpy.SpatialReference() 22 | 23 | # Create a new feature class 24 | # Options for "GEOMETRY TYPE" are "POINT", "MULTIPOINT", "POLYGON", or "POLYLINE" 25 | # This script is developed to create a Point feature class 26 | arcpy.CreateFeatureclass_management(arcpy.env.workspace, "Name of Feature Class", "GEOMETRY TYPE", spatial_reference = sr) 27 | 28 | # Add a Field to the feature class 29 | # Repeat this code block for as many fields are as needed 30 | # Field types can be "TEXT", "FLOAT", "DOUbLE", "SHORT", "LONG", "DATE", "BLOB", "RASTER", or "GUID" 31 | arcpy.AddField_management("Name of Feature Class", "Field Name", "Field Type") 32 | 33 | 34 | # Create a list holding field names from Feature Class 35 | iflds = ["SHAPE@XY", "Field Name", "Field Name"] 36 | 37 | # Create an arcpy.da.InsertCursor for Feature Class 38 | # iflds is the fields to edit through the insert cursor 39 | iCur = arcpy.da.InsertCursor("Name of Feature Class", iflds) 40 | 41 | # Open CSV file containing information to create feature class from. 42 | # Loop through each record in CSV file and add information into Feature Class. 43 | # Loop uses "if count > 1" because it is assumed the first row in the CSV file 44 | # will contain the field titles 45 | count = 1 46 | 47 | # Make sure to place the corresponding number for each field from the CSV file within the [] 48 | for ln in open(r"File path to csv file", 'r').readlines(): 49 | lnstrip = ln.strip() 50 | if count > 1: 51 | dataList = ln.split(",") 52 | # Number in array containing Latitude 53 | lat = dataList[1] 54 | # Number in array containing longitude 55 | lon = dataList[2] 56 | # Create variables for each field in CSV file. Use corresponding array number from CSV file 57 | var = dataList[0] 58 | # float() is used to convert string to a numberic field 59 | # include all variables from above, seperated by commas 60 | ivals = [(float(lon), float(lat)), var] 61 | iCur.insertRow(ivals) 62 | count += 1 63 | 64 | # Delete the cursor to close the cursor and release the exclusive lock 65 | del iCur 66 | 67 | print "Script completed" 68 | # If an error occurs running geoprocessing tool(s) capture error and write message 69 | # handle error outside of Python system 70 | except EnvironmentError as e: 71 | tbE = sys.exc_info()[2] 72 | # Print the line number the error occured 73 | print("Failed at Line {}\n".format(tbE.tb_lineno)) 74 | # Print the error message 75 | print("Error: {}".format(str(e))) 76 | # handle exception error 77 | except Exception as e: 78 | # Store information about the error 79 | tbE = sys.exc_info()[2] 80 | # Print the line number the error occured 81 | print("Failed at Line {}\n".format(tbE.tb_lineno)) 82 | # Print the error message 83 | print("Error: {}".format(e.message)) -------------------------------------------------------------------------------- /Polygon_Centroid_To_Point_Layer.py: -------------------------------------------------------------------------------- 1 | # --------------------------------------------------------------------------- 2 | # Name: Create Point Feature Class from Polygon Feature Class 3 | # 4 | # Description: This script allows you to create a point feature class from 5 | # a polygon feature class using the centroid of the polygon 6 | # feature class. This mimics the behavior of the Feature To Point 7 | # geoprocessing tool (http://pro.arcgis.com/en/pro-app/tool-reference/data-management/feature-to-point.htm). 8 | # As this tool requires a ArcGIS Desktop Advanced license, this 9 | # script provides a work around for lower license installs of ArcGIS Desktop. 10 | # 11 | # Author: Patrick McKinney, Cumberland County GIS 12 | # 13 | # Created on: 7/23/2018 14 | # 15 | # Updated on: 12/7/2018 16 | # 17 | # Disclaimer: CUMBERLAND COUNTY ASSUMES NO LIABILITY ARISING FROM USE OF THESE MAPS OR DATA. THE MAPS AND DATA ARE PROVIDED WITHOUT 18 | # WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 19 | # FITNESS FOR A PARTICULAR PURPOSE. 20 | # Furthermore, Cumberland County assumes no liability for any errors, omissions, or inaccuracies in the information provided regardless 21 | # of the cause of such, or for any decision made, action taken, or action not taken by the user in reliance upon any maps or data provided 22 | # herein. The user assumes the risk that the information may not be accurate. 23 | # --------------------------------------------------------------------------- 24 | 25 | # Import system modules 26 | import arcpy, sys, time, datetime, os 27 | 28 | # Run geoprocessing tool. 29 | # If there is an error with the tool, it will break and run the code within the except statement 30 | try: 31 | # Time stamp variables 32 | current_time = datetime.datetime.now() 33 | # Date formatted as month-day-year (1-1-2017) 34 | date_today = current_time.strftime("%m-%d-%Y") 35 | # Date formated as month-day-year-hours-minutes-seconds 36 | date_today_time = current_time.strftime("%m-%d-%Y-%H-%M-%S") 37 | 38 | # If you want to overwrite an existing feature class, uncomment this line 39 | # arcpy.env.overwriteOutput = True 40 | 41 | # Create text file for logging results of script 42 | # Update file path with your parameters 43 | # Each time the script runs, it creates a new text file with the date_today variable as part of the file name 44 | # The example would be Polygon_To_Point_FC_1-1-2017.txt 45 | log_file = r'C:\GIS\Results\Polygon_To_Point_FC_{}.txt'.format(date_today) 46 | # variable to store messages for log file. Messages written in finally statement at end of script 47 | log_msg = '' 48 | # Get the start time of the geoprocessing tool(s) 49 | start_time = time.clock() 50 | 51 | # 1. Copy data for features from polygon layer to a list 52 | # list to contain data for each record 53 | features_list = [] 54 | # Polygon Layer 55 | # update to your polygon layer 56 | polygon_layer = r'C:\GIS\Geodata.gdb\Polygon_Layer' 57 | # fields from polygon layer 58 | # include any fields from polygon layer you want within the point layer 59 | # 'SHAPE@TRUECENTROID' gives us the x,y coordinates to use for the point layer 60 | polygon_fields = ['SHAPE@TRUECENTROID', 'NAME', 'FACILITY_ID', 'ADDRESS'] 61 | 62 | # Create a Search Cursor to loop through the polygon feature class and copy 63 | # each record to the features_list variable 64 | with arcpy.da.SearchCursor(polygon_layer,polygon_fields) as cursor: 65 | for row in cursor: 66 | # append item to features_list 67 | featuresList.append([row[0],row[1],row[2],row[3]]) 68 | # end for 69 | # end with 70 | 71 | # write messages to text file 72 | # update message as desired 73 | log_msg += 'Completed copying features from polygon layer to list container\n' 74 | 75 | # 2. Create a shell feature class for point layer 76 | # name of feature class 77 | fc_name = 'Point_Layer' 78 | # location of feature class 79 | output_location = r'C:\GIS\Geodata.gdb' 80 | # projected or geographic coordinate system for feature class 81 | sr = arcpy.SpatialReference(0000) 82 | 83 | # create feature class 84 | arcpy.CreateFeatureclass_management(output_location,fc_name,'POINT',spatial_reference=sr) 85 | # add message 86 | # update message as desired 87 | log_msg += '\nCreated empty feature class for Points Layer\n' 88 | 89 | # 3. Add fields to Point layer 90 | # These fields should match the fields from the polygon_fields variable with the 91 | # exception of the 'SHAPE@TRUECENTROID' field 92 | # point layer created in step #2 93 | point_layer = os.path.join(output_location,fc_name) 94 | 95 | # Create PIN field 96 | arcpy.AddField_management(point_layer,'NAME','TEXT') 97 | # add message 98 | log_msg += '\nAdded NAME field\n' 99 | 100 | # Create location field 101 | arcpy.AddField_management(addPts,'FACILITY_ID','SHORT') 102 | # add message 103 | log_msg += '\nAdded FACILITY_ID field\n' 104 | 105 | # create City field 106 | arcpy.AddField_management(addPts,'ADDRESS','TEXT') 107 | # add message 108 | log_msg += '\nAdded ADDRESS field\n' 109 | 110 | # 4. Loop through features_list and add records to Point layer 111 | # Point layer fields 112 | # 'SHAPE@XY' defines where the point is located 113 | # the other fields should match what was created in step #3 and the fields from the polygon layer 114 | point_fields = ['SHAPE@XY', 'NAME', 'FACILITY_ID', 'ADDRESS'] 115 | 116 | # Create an Insert Cursor on the Point layer and add records from features_list 117 | with arcpy.da.InsertCursor(point_layer,point_fields) as cursor: 118 | for record in features_list: 119 | cursor.insertRow(record) 120 | # end for 121 | # end with 122 | 123 | # Get the end time of the geoprocessing tool(s) 124 | finish_time = time.clock() 125 | # Get the total time to run the geoprocessing tool(s) 126 | elapsed_time_seconds = finish_time - start_time 127 | # convert elapsed time to minutes 128 | elapsed_time_minutes = round((elapsed_time_seconds / 60),2) 129 | 130 | # add message 131 | log_msg += '\nCompleted adding records to points layer\n' 132 | log_msg += '\nCompleted script in {} seconds on {}'.format(elapsed_time_seconds,date_today) 133 | # of if you want minutes, use this line instead 134 | log_msg += '\nCompleted script in {} minutes on {}'.format(elapsed_time_minutes,date_today) 135 | # If an error occurs running geoprocessing tool(s) capture error and write message 136 | # handle error outside of Python system 137 | except EnvironmentError as e: 138 | tbE = sys.exc_info()[2] 139 | # add the line number the error occured to the log message 140 | log_msg += "\nFailed at Line {}\n".format(tbE.tb_lineno) 141 | # add the error message to the log message 142 | log_msg += "\nError: {}\n".format(str(e)) 143 | # handle exception error 144 | except Exception as e: 145 | # Store information about the error 146 | tbE = sys.exc_info()[2] 147 | # add the line number the error occured to the log message 148 | log_msg += "\nFailed at Line {}\n".format(tbE.tb_lineno) 149 | # add the error message to the log message 150 | log_msg += "\nError: {}\n".format(e.message) 151 | finally: 152 | try: 153 | # delete cursor 154 | del cursor 155 | except: 156 | pass 157 | # write message to log file 158 | try: 159 | with open(log_file, 'w') as f: 160 | f.write(str(log_msg)) 161 | except: 162 | print 'an error occured writing results to text file' -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ArcPy 2 | This repository contains sample Python scripts developed for Esri's ArcGIS Desktop using the ArcPy site package, and Python 2.7. 3 | 4 | If you are looking for sample scripts written for ArcGIS Pro (Python 3), please visit my [Esri-Arcpy-Python repository](https://github.com/pmacMaps/esri-arcpy-python). 5 | 6 | I also have a [repository of sample scripts](https://github.com/pmacMaps/ago-admin-scripts) for administering ArcGIS Online (Python 3). 7 | -------------------------------------------------------------------------------- /SDE_to_FileGDB_Replica.py: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------------------------------------------------------------------------------------------------------- 2 | # Name: Run Replication from SDE Enterprise Geodatabase to File Geodatabase 3 | # 4 | # Author: Patrick McKinney, Cumberland County GIS (pmckinney@ccpa.net or pnmcartography@gmail.com) 5 | # 6 | # Created on: 05/12/2016 7 | # 8 | # Updated on: 12/7/2018 9 | # 10 | # Description: Synchronizes updates between a parent and child replica geodatabase in favor of the parent. 11 | # The parent geodatabase is a SDE enterprise geodatabase. The child is a file geodatabase 12 | # The script can be added as a windows scheduled task to automate replication updates on a weekly basis, for example. 13 | # 14 | # Note: Originally developed by Cumberland County GIS to replicate data to various departments. 15 | # You must update the following paramaters: 16 | # 1. file path to the log file that reports whether the tool ran successfully or unsuccessfully. 17 | # 2. SDE connection to parent geodatabase 18 | # 3. file path to the child file geodatabase 19 | # 4. name of the replication you are performing synchronize changes on 20 | # 21 | # Disclaimer: CUMBERLAND COUNTY ASSUMES NO LIABILITY ARISING FROM USE OF THESE MAPS OR DATA. THE MAPS AND DATA ARE PROVIDED WITHOUT 22 | # WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 23 | # FITNESS FOR A PARTICULAR PURPOSE. 24 | # Furthermore, Cumberland County assumes no liability for any errors, omissions, or inaccuracies in the information provided regardless 25 | # of the cause of such, or for any decision made, action taken, or action not taken by the user in reliance upon any maps or data provided 26 | # herein. The user assumes the risk that the information may not be accurate. 27 | # --------------------------------------------------------------------------------------------------------------------------------------------------- 28 | 29 | # Import system modules 30 | import arcpy, sys, time, datetime 31 | 32 | # Try to run Replication 33 | try: 34 | # Time stamp variables 35 | currentTime = datetime.datetime.now() 36 | # Date formatted as month-day-year (1-1-2017) 37 | dateToday = currentTime.strftime("%m-%d-%Y") 38 | # Date formated as month-day-year-hours-minutes-seconds 39 | dateTodayTime = currentTime.strftime("%m-%d-%Y-%H-%M-%S") 40 | 41 | # Create text file for logging results of script 42 | # Update file path with your parameters 43 | # Each time the script runs, it creates a new text file with the date1 variable as part of the file name 44 | # The example would be GeoprocessingReport_1-1-2017 45 | logFile = r'C:\GIS\Results\GeoprocessingReport_{}.txt'.format(dateToday) 46 | 47 | # variable to store messages for log file. Messages written in finally statement at end of script 48 | logMsg = '' 49 | 50 | # get time stamp for start of tool 51 | starttime = time.clock() 52 | 53 | # SDE is parent geodatabase in replication 54 | # Change this to your SDE connection 55 | sde = r"SDE Connection" 56 | # Child file geodatabase in replication 57 | # Change this to your file geodatabase 58 | child_gdb = r"\\path\to\file.gdb" 59 | 60 | # Process: Synchronize Changes 61 | # Replicates data from parent to child geodatabase 62 | # update the name of the replication 63 | result = arcpy.SynchronizeChanges_management(sde, "Name of Replication", child_gdb, "FROM_GEODATABASE1_TO_2", "IN_FAVOR_OF_GDB1", "BY_OBJECT", "DO_NOT_RECONCILE") 64 | 65 | # Get the end time of the geoprocessing tool(s) 66 | finishtime = time.clock() 67 | # Get the total time to run the geoprocessing tool(s) 68 | elapsedtime = finishtime - starttime 69 | 70 | # write result messages to log 71 | # delay writing results until geoprocessing tool gets the completed code 72 | while result.status < 4: 73 | time.sleep(0.2) 74 | # store tool result message in a variable 75 | resultValue = result.getMessages() 76 | # add the tool's message to the log message 77 | logMsg += "completed {}\n".format(str(resultValue)) 78 | # add a more human readable message to log message 79 | logMsg += "\nSuccessfully ran replication from {} to {} in {} seconds on {}\n".format(sde, child_gdb, str(elapsedtime), dateToday) 80 | # If an error occurs running geoprocessing tool(s) capture error and write message 81 | # handle error outside of Python system 82 | except EnvironmentError as e: 83 | tbE = sys.exc_info()[2] 84 | # add the line number the error occured to the log message 85 | logMsg += "\nFailed at Line {}\n".format(tbE.tb_lineno) 86 | # add the error message to the log message 87 | logMsg += "\nError: {}\n".format(str(e)) 88 | # handle exception error 89 | except Exception as e: 90 | # Store information about the error 91 | tbE = sys.exc_info()[2] 92 | # add the line number the error occured to the log message 93 | logMsg += "\nFailed at Line {}\n".format(tbE.tb_lineno) 94 | # add the error message to the log message 95 | logMsg += "\nError: {}\n".format(e.message) 96 | finally: 97 | # write message to log file 98 | try: 99 | with open(logFile, 'w') as f: 100 | f.write(str(logMsg)) 101 | except: 102 | pass -------------------------------------------------------------------------------- /enterprise_geodatabase_maintenance_tasks.py: -------------------------------------------------------------------------------- 1 | # Performs 'Analyze Datasets' > 'Rebuild Indexes' > 'Compress' 2 | # > 'Analyze Datasets' > 'Rebuild Indexes' geoprocessing tools 3 | # on an enterprise (sde) geodatabase 4 | # connections to the database are closed, and all users are disconnected 5 | # before running tools. database connections are opened at the end 6 | 7 | # import modules 8 | import arcpy 9 | import os 10 | import sys 11 | import datetime 12 | import time 13 | 14 | # capture the date the script is being run 15 | date_today = datetime.date.today() 16 | # convert date format to month-day-year (1-1-2020) 17 | formatted_date_today = date_today.strftime("%m-%d-%Y") 18 | # placeholder for messages for text file 19 | log_message = '' 20 | # text file to write messages to 21 | # TODO: update path 22 | log_file = r'C:\GIS\Results\Database_Maint_Report_{}.txt'.format(date_today) 23 | 24 | try: 25 | # database connection 26 | # TODO: update path for sde connection 27 | dbase = r"SDE Connection" 28 | # set workspace to geodatabase 29 | arcpy.env.workspace = dbase 30 | # get list of all: 31 | # > feature classes 32 | feature_classes = arcpy.ListFeatureClasses() 33 | # > tables 34 | tables = arcpy.ListTables() 35 | # list of data to run tools on 36 | data_list = feature_classes + tables 37 | # Next, for feature datasets get all of the datasets and featureclasses 38 | # from the list and add them to the master list. 39 | for dataset in arcpy.ListDatasets("", "Feature"): 40 | arcpy.env.workspace = os.path.join(dbase, dataset) 41 | data_list += arcpy.ListFeatureClasses() + arcpy.ListDatasets() 42 | # add message 43 | log_message += '{} : Created list of feature classes and tables in geodatabase\n'.format(time.strftime('%I:%M%p')) 44 | 45 | # close database from accepting connections 46 | arcpy.AcceptConnections(dbase, False) 47 | # remove existing users 48 | arcpy.DisconnectUser(dbase, 'ALL') 49 | # add message 50 | log_message += '\n{} : Disconnected users and closed connections to the geodatabase\n'.format(time.strftime('%I:%M%p')) 51 | 52 | # run analyze datasets 53 | arcpy.AnalyzeDatasets_management(dbase, 'SYSTEM', data_list, 'ANALYZE_BASE', 'ANALYZE_DELTA', 'ANALYZE_ARCHIVE') 54 | # add message 55 | log_message += '\n{} : Ran "Analyze Datasets" tool\n'.format(time.strftime('%I:%M%p')) 56 | 57 | # run rebuild indexes 58 | arcpy.RebuildIndexes_management(dbase, 'SYSTEM', data_list, 'ALL') 59 | # add message 60 | log_message += '\n{} : Ran "Rebuild Indexes" tool\n'.format(time.strftime('%I:%M%p')) 61 | 62 | # run compress 63 | arcpy.Compress_management(dbase) 64 | # add message 65 | log_message += '\n{} : Ran "Compress" tool\n'.format(time.strftime('%I:%M%p')) 66 | 67 | # run analyze datasets 68 | arcpy.AnalyzeDatasets_management(dbase, 'SYSTEM', data_list, 'ANALYZE_BASE', 'ANALYZE_DELTA', 'ANALYZE_ARCHIVE') 69 | # add message 70 | log_message += '\n{} : Ran "Analyze Datasets" tool\n'.format(time.strftime('%I:%M%p')) 71 | 72 | # run rebuild indexes 73 | arcpy.RebuildIndexes_management(dbase, 'SYSTEM', data_list, 'ALL') 74 | # add message 75 | log_message += '\n{} : Ran "Rebuild Indexes" tool\n'.format(time.strftime('%I:%M%p')) 76 | 77 | # allow database to accept connections 78 | arcpy.AcceptConnections(dbase, True) 79 | # If an error occurs running geoprocessing tool(s) capture error and write message 80 | except (Exception, EnvironmentError) as e: 81 | tbE = sys.exc_info()[2] 82 | # Write the line number the error occured to the log file 83 | log_message += "\nFailed at Line {}\n".format(tbE.tb_lineno) 84 | # Write the error message to the log file 85 | log_message += "Error: {}".format(str(e)) 86 | finally: 87 | # write message to log file 88 | try: 89 | # allow database to accept connections 90 | arcpy.AcceptConnections(dbase, True) 91 | # add message 92 | log_message += '\n{} : Opened connections to the geodatabase\n'.format(time.strftime('%I:%M%p')) 93 | # write messages to text file 94 | with open(log_file, 'w') as f: 95 | f.write(str(log_message)) 96 | except: 97 | pass -------------------------------------------------------------------------------- /export_layers_to_file_geodatabase_and_excel.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # Name: Export Layers to File Geodatabase and Microsoft Excel 3 | # 4 | # Purpose: Creates a new directory using the current date. A file geodatabase 5 | # is created in this new directory. A list of feature classes are exported to this 6 | # file geodatabase. The feature classes have field values calculated. 7 | # After field calculations, the layers in the file geodatabase are exported 8 | # to Microsoft Excel format in the newly created directory. 9 | # 10 | # Author: Patrick McKinney, Cumberland County, PA 11 | # 12 | # Created: 4/4/2019 13 | # 14 | # Updated: 4/18/2019 15 | # 16 | # Disclaimer: CUMBERLAND COUNTY ASSUMES NO LIABILITY ARISING FROM USE OF THESE MAPS OR DATA. THE MAPS AND DATA ARE PROVIDED WITHOUT 17 | # WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 18 | # FITNESS FOR A PARTICULAR PURPOSE. 19 | # Furthermore, Cumberland County assumes no liability for any errors, omissions, or inaccuracies in the information provided regardless 20 | # of the cause of such, or for any decision made, action taken, or action not taken by the user in reliance upon any maps or data provided 21 | # herein. The user assumes the risk that the information may not be accurate. 22 | #------------------------------------------------------------------------------- 23 | 24 | import arcpy, datetime, sys, os 25 | 26 | try: 27 | # Time stamp variables 28 | currentTime = datetime.datetime.now() 29 | # Date formatted as month-day-year (1-1-2017) 30 | dateToday = currentTime.strftime("%m-%d-%Y") 31 | # date for file geodatabase name 32 | dateGdb = currentTime.strftime("%m%d%Y") 33 | 34 | # Create text file for logging results of script 35 | # update this variable 36 | log_file = r'[path]\[to]\[location]\Report File Name {}.txt'.format(dateToday) 37 | # variable to store messages for log file. Messages written in finally statement at end of script 38 | logMsg = '' 39 | 40 | # sde database connection 41 | # update this variable 42 | sde = r'Database Connections\[SDE Database Name].sde' 43 | # layers 44 | # update this variable 45 | layers = [[os.path.join(sde, r'Name of Layer'), 'Name of Layer'], [os.path.join(sde, r'Name of Layer'), 'Name of Layer'], [os.path.join(sde, r'Name of Layer'), 'Name of Layer']] 46 | 47 | # 1. create new directory 48 | # parent directory 49 | # update this variable 50 | parent_dir = r'[path]\[to]\[location]' 51 | # output directory 52 | out_dir = r'{}\{}'.format(parent_dir,dateGdb) 53 | # create sub-directory with current date 54 | os.mkdir(out_dir) 55 | # add message 56 | logMsg += '\nCreated directory "{}" in {}\n'.format(dateGdb,out_dir) 57 | 58 | # 2. create file geodatabase 59 | # parameters 60 | # update this variable 61 | out_gdb_name = r'Name_of_Geodatabase_{}'.format(dateGdb) 62 | out_gdb = os.path.join(out_dir, '{}.gdb'.format(out_gdb_name)) 63 | # geoprocessing 64 | arcpy.CreateFileGDB_management(out_dir,out_gdb_name,'10.0') 65 | # add message 66 | logMsg += '\nCreated file geodatabase "{}" in directory "{}"\n'.format(out_gdb_name, out_dir) 67 | 68 | # 3. Export layers to file geodatabase 69 | for fc in layers: 70 | # export feature class 71 | arcpy.FeatureClassToFeatureClass_conversion(fc[0],out_gdb,fc[1]) 72 | # add message 73 | logMsg += '\nCopied {} layer to {}\n'.format(fc[1],out_gdb) 74 | # end for 75 | 76 | # 4. update Latitude Longitude fields in feature classes 77 | # export feature class to excel 78 | # set workspace for listing function 79 | arcpy.env.workspace = out_gdb 80 | # create list of feature classes in file geodatabase 81 | datasets = arcpy.ListFeatureClasses() 82 | # fields for update 83 | # update this variable 84 | # these are examples 85 | fc_fields = ['SHAPE@XY', 'LON', 'LAT'] 86 | # loop through feature classes 87 | for fc in datasets: 88 | # create update cursor 89 | with arcpy.da.UpdateCursor(fc, fc_fields) as cursor: 90 | for row in cursor: 91 | # longitude 92 | row[1] = row[0][0] 93 | # latitude 94 | row[2] = row[0][1] 95 | # update record 96 | cursor.updateRow(row) 97 | # end for 98 | # update your message 99 | logMsg += '\nCompleted updating Latitude and Longitude records for "{}" layer\n'.format(fc) 100 | # end cursor 101 | # convert to Excel 102 | arcpy.TableToExcel_conversion(fc,os.path.join(out_dir,'{}.xls'.format(fc)),"ALIAS") 103 | # add message 104 | logMsg += '\nExported {} layer to Microsof Excel format\n'.format(fc) 105 | # end for 106 | # If an error occurs running geoprocessing tool(s) capture error and write message 107 | # handle error outside of Python system 108 | except EnvironmentError as e: 109 | tbE = sys.exc_info()[2] 110 | # add the line number the error occured to the log message 111 | logMsg += "\nFailed at Line {}\n".format(tbE.tb_lineno) 112 | # add the error message to the log message 113 | logMsg += "\nError: {}\n".format(str(e)) 114 | # handle exception error 115 | except Exception as e: 116 | # Store information about the error 117 | tbE = sys.exc_info()[2] 118 | # add the line number the error occured to the log message 119 | logMsg += "\nFailed at Line {}\n".format(tbE.tb_lineno) 120 | # add the error message to the log message 121 | logMsg += "\nError: {}\n".format(e.message) 122 | finally: 123 | try: 124 | if cursor: 125 | del cursor 126 | except: 127 | pass 128 | # write message to log file 129 | try: 130 | with open(log_file, 'w') as f: 131 | f.write(str(logMsg)) 132 | except: 133 | pass -------------------------------------------------------------------------------- /print_errors.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # Name: Print Errors Helper Module 3 | # 4 | # Purpose: Writes error messages that are returned from function. 5 | # Messages can be written to log file or printed in the console. 6 | # 7 | # Author: Patrick McKinney, Cumberland County, Pennsylvania 8 | # 9 | # Created: 08/22/2019 10 | # Copyright: (c) pmckinney 2019 11 | # Disclaimer: CUMBERLAND COUNTY ASSUMES NO LIABILITY ARISING FROM USE OF THESE MAPS OR DATA. THE MAPS AND DATA ARE PROVIDED WITHOUT 12 | # WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 13 | # FITNESS FOR A PARTICULAR PURPOSE. 14 | # Furthermore, Cumberland County assumes no liability for any errors, omissions, or inaccuracies in the information provided regardless 15 | # of the cause of such, or for any decision made, action taken, or action not taken by the user in reliance upon any maps or data provided 16 | # herein. The user assumes the risk that the information may not be accurate. 17 | #------------------------------------------------------------------------------- 18 | 19 | import sys 20 | import linecache 21 | 22 | # Function to handle errors 23 | def print_exception(error): 24 | exc_type, exc_obj, tb = sys.exc_info() 25 | f = tb.tb_frame 26 | lineno = tb.tb_lineno 27 | filename = f.f_code.co_filename 28 | linecache.checkcache(filename) 29 | line = linecache.getline(filename, lineno, f.f_globals) 30 | # add message 31 | message = '\nError: {}\nFILE: {}, LINE: {}\n\n\t "{}": {}'.format(error, filename, lineno, line.strip(), exc_obj) 32 | # return to variable 33 | return message 34 | # end PrintException -------------------------------------------------------------------------------- /update_replica_schema.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------ 2 | # Name: Update Schema for Child Replication Geodatabases 3 | # 4 | # Purpose: Exports replication schema from parent enterprise geodatabase, 5 | # and compares changes with child geodatabases. Imports changes 6 | # into child geodatabases. 7 | # 8 | # Data schemas change from time to time. Use this script to help 9 | # automate incorporating those changes into child geodatabases 10 | # particpating in parent-to-child replication. 11 | # 12 | # Author: Patrick McKinney, Cumberland County GIS 13 | # 14 | # Created: 5/11/2021 15 | # 16 | # Updated: 5/27/2021 17 | # 18 | # Copyright: (c) Cumberland County 2021 19 | # 20 | # Disclaimer: CUMBERLAND COUNTY ASSUMES NO LIABILITY ARISING FROM USE OF THESE MAPS OR DATA. THE MAPS AND DATA ARE PROVIDED WITHOUT 21 | # WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 22 | # FITNESS FOR A PARTICULAR PURPOSE. 23 | # Furthermore, Cumberland County assumes no liability for any errors, omissions, or inaccuracies in the information provided regardless 24 | # of the cause of such, or for any decision made, action taken, or action not taken by the user in reliance upon any maps or data provided 25 | # herein. The user assumes the risk that the information may not be accurate. 26 | #----------------------------------------------------------------- 27 | 28 | # note the imported "print_errors" helper module that is located within this "ArcPy" repo 29 | # Import system modules 30 | import arcpy 31 | import os 32 | import sys 33 | import time 34 | import datetime 35 | import print_errors 36 | 37 | try: 38 | # Get the start time of the geoprocessing tool(s) 39 | start_time = time.clock() 40 | 41 | # Time stamp variables 42 | date_today = datetime.date.today() 43 | # Date formatted as month-day-year (1-1-2017) 44 | # used in creating log file 45 | formatted_date_today = date_today.strftime("%m-%d-%Y") 46 | # date formatted as MonthDayYear (01012017) 47 | # used in creating directory to store schema xml files in 48 | folder_formatted_date_today = date_today.strftime("%m%d%Y") 49 | 50 | # variable to store messages for log file. Messages written in finally statement at end of script 51 | log_message = '' 52 | # Create text file for logging results of script 53 | log_file = r'\Path\To\Directory\Update Schema Report {}.txt'.format(formatted_date_today) 54 | 55 | # root directory for schema change files 56 | # each time this script is run, a sub-directory with the current date will be created 57 | # replication compare xml files will be created in sub-directory 58 | base_dir = r'\Path\To\Directory' 59 | # directory to store schema change files 60 | out_dir = os.path.join(base_dir, folder_formatted_date_today) 61 | # create directory 62 | os.mkdir(out_dir) 63 | # add message 64 | log_message += 'Created output directory for schema changes at {}\n'.format(out_dir) 65 | 66 | # parent enterprise geodatabase in replication 67 | sde_ccgis = r"\Path\To\SDE Connection File\geodatabase.sde" 68 | 69 | # list of dictionaries containing data for each replica you want to update schema for 70 | # name = human friendly name for replica; used in log file messages 71 | # geodatabase = path to the child geodatabase participating in replica 72 | # child_output = output xml file generated when comparing parent geodatabase to child geodatabase 73 | # replica_changes = output xml file that is imported into child geodatabase to bring in schema changes from parent geodatabase 74 | replication_data = [ 75 | { 76 | "name": "Planning Department", 77 | "geodatabase": r"\Path\To\Geodatabase\Geodata.gdb", 78 | "replica": "SDE.Planning_Replica", 79 | "child_output": r"{}\planning_schema_export.xml".format(out_dir), 80 | "replica_changes": r"{}\planning_schema_changes.xml".format(out_dir) 81 | }, 82 | { 83 | "name": "Public Works", 84 | "geodatabase": r"\Path\To\Geodatabase\Geodata.gdb", 85 | "replica": "SDE.PublicWorks_Replica", 86 | "child_output": r"{}\public_works_schema_export.xml".format(out_dir), 87 | "replica_changes": r"{}\public_works_schema_changes.xml".format(out_dir) 88 | } 89 | ] 90 | 91 | # loop through list of replications and update schema 92 | for replica in replication_data: 93 | try: 94 | # add message 95 | log_message += '\nRunning schema update process for {}\n'.format(replica["name"]) 96 | # export schema from parent geodatabase 97 | arcpy.ExportReplicaSchema_management(sde_ccgis, replica["child_output"], replica["replica"]) 98 | # add message 99 | log_message += '\n\tExported schema for CCGIS geodatabase\n' 100 | # create compare file between parent and child 101 | arcpy.CompareReplicaSchema_management(replica["geodatabase"], replica["child_output"], replica["replica_changes"]) 102 | # add message 103 | log_message += '\n\tCompared changes to child geodatabase\n' 104 | # import schema compare file into child geodatabase 105 | arcpy.ImportReplicaSchema_management(replica["geodatabase"], replica["replica_changes"]) 106 | # add message 107 | log_message += '\n\tImported changes into child geodatabase\n' 108 | except EnvironmentError as e: 109 | log_message += '\nError running {} replication\n'.format(replica["name"]) 110 | log_message += print_errors.print_exception(e) 111 | except Exception as e: 112 | log_message += '\nError running {} replication\n'.format(replica["name"]) 113 | log_message += print_errors.print_exception(e) 114 | # end for loop 115 | 116 | # Get the end time of the geoprocessing tool(s) 117 | finish_time = time.clock() 118 | # Get the total time to run the geoprocessing tool(s) 119 | elapsed_time = finish_time - start_time 120 | # total time in minutes 121 | elapsed_time_minutes = round((elapsed_time / 60), 2) 122 | 123 | # Write message to a log file 124 | log_message += "\nSuccessfully updated replication schemas for departments in {}-minutes on {}\n".format(elapsed_time_minutes,formatted_date_today) 125 | # If an error occurs running geoprocessing tool(s) capture error and write message 126 | # handle error outside of Python system 127 | except EnvironmentError as e: 128 | tbE = sys.exc_info()[2] 129 | # Write the line number the error occured to the log file 130 | log_message += "\nFailed at Line {}\n".format(tbE.tb_lineno) 131 | # Write the error message to the log file 132 | log_message += "Error: {}".format(str(e)) 133 | except Exception as e: 134 | # If an error occurred, write line number and error message to log 135 | tb = sys.exc_info()[2] 136 | log_message += "\nFailed at Line {}\n".format(tb.tb_lineno) 137 | log_message += "Error: {}".format(e) 138 | finally: 139 | # write message to log file 140 | try: 141 | with open(log_file, 'w') as f: 142 | f.write(str(log_message)) 143 | except: 144 | pass --------------------------------------------------------------------------------