Python Commenting Help

المشرف العام

Administrator
طاقم الإدارة
I needed to properly comment some code I was just wondering if I had commented all of it correctly? I'm new to programming and was doing this for practice.

#This function will assign the proper projection of the infile to the outfile.def projection_fix(infile, outfile, sr):#This code creates a describe object for the infile. The sr1 variable will allow me to get the spatial reference of the dataset/infile. desc1 = arcpy.Describe(infile) sr1 = desc1.spatialReference#This code changes the spatial reference of the infile. The if else statement will change the coordinate system if the spatial reference of the infile does not match the spatial reference defined in the variable sr. #The copy features management will copy the features in the infile to the outfile if infile has the proper spatial reference if sr1.Name != sr.Name: arcpy.Project_management(infile, outfile, sr) else: arcpy.CopyFeatures_management(infile, outfile) return Nonedef start_end_peak(af_file):# This will set a search cursor to move through the af_file and extract the values for the year month and date and put it into a list cur = arcpy.SearchCursor(af_file) dList = [] for c in cur: val = c.YYYYMMDD dList.append(val)#I am deleting the c and cur variables to release the locks on the file. del c, cur#This will sort the dates in the list dataset created above. dList.sort() singleD = list(set(dList))#unsure output = [] output.append(int(dList[0])) output.append(int(dList[-1]))#unsure x = 0 d1 = 0 for d in singleD: y = dList.count(d) if y > x: x = y d1 = d output.append(int(d1)) output.append(x) return output#The goal of this function is to extract the data for the different burn scars and analyze the data to find the tip 4 burn scars within a certain area. def top5burns(inscars):#This creates a search cursor to go through the inscars file and uses a for loop to extract the area of the different burned scars and then copies it into a list cur = arcpy.SearchCursor(inscars) scarSizes = [] for c in cur: scarSizes.append(c.Area) del c, cur#This sorts the different scaresizes or the areas in the list created above. scarSizes.sort()#This will print out a statement if there were less then 5 fire events. if len(scarSizes) < 5: print 'There were only {x} fire event in this fire season'.format(x = len(scarSizes)) sub_scars = scarSizes else: sub_scars = scarSizes[-5:]#this creates a list and a cursor to search the different sub_names = [] for s in sub_scars: cur = arcpy.SearchCursor(inscars, '"Area" = '+str(repr(s)))#this for loop uses the cursor to put the names of the fires in a list for c in cur: sub_names.append(c.Fire_Name) del c, cur#this will return the different burn scar sizes and their names return [sub_scars,sub_names]#this prints an error message to the rfiledef printing(mess, rfile): arcpy.AddMessage(mess) print mess rfile.write(mess) return None#This function will define how the errors are handled in the code. def error_print(pymsg,arcmsg,logfile): #this is defining the function of the print statement """adds error message to Python screen, ArcGIS system and the logfile""" #This adds python and arcpy error messages to arcgis script and prints it to the logfile for i in ([pymsg,arcmsg]): print i arcpy.AddError(i) print >> logfile, i#this allows me to ingest the entire module for arcpy,os,shutil, traceback,and sys import arcpy, sys, traceback, os, shutil#This creates an exception class providing the dataset path has not be set class NoDataPath(Exception): pass#This creats an exception class providing there is no data present in a dataset class NoData(Exception): passtry: #this sets the different work paths that we will use to copy or save our data to. inpath = 'C:/oshfile/mid/project_data/' outpath = 'C:/oshfile/mid/solution/' reportpath = 'C:/oshfile/mid/report/' #This helps you overwrite files so you're not constantly redeleting data that has been updated arcpy.env.overwriteOutput = True #This if statement checks to see if a directory exists and if not makes a new directory and prints the error message in a logfile. if not os.path.exists(reportpath): os.mkdir(reportpath) logfile = open(reportpath+'error_log.txt','a') print >> logfile, 'starting the log for project error' print 'Starting the log file for project error at {reportpath}error_log.txt'.format(reportpath = reportpath) #this if else statement checks to see if data folder has a proper data path and if it doesn't it rasise an error if it does it prints that directory path if not os.path.exists(inpath): raise NoDataPath else: print 'Data folder at {inpath} is confirmed.'.format(inpath=inpath) # this deltes the directory in the outpath variable if os.path.exists(outpath): shutil.rmtree(outpath, ignore_errors=True) #this method creates a directory for the outpath os.mkdir(outpath) #this sets the workpath environment to the directory saved within the outpath variable arcpy.env.workspace = outpath #the variable for year creates a prompt asking the user to type in an integer for the year for analysis between 2001 and 2010. year = int(raw_input('Please type in the year for analysis between 2001 and 2010: ')) #the variables link to the different shapefiles that will be used in the for loop which is used to print an error message to the log file if there is missing data in the data sources/variables. inaffile = str(year)+'_af.shp' inscarfile = str(year)+'perimeters.shp' stations = 'RAWS_stations.shp' weather = 'RAWS_weather_data.dbf' ecosys = 'wwf_terr_ecos.shp' for f in ([inaffile,inscarfile,stations,weather,ecosys]): if not os.path.exists(inpath+f): print >> logfile, 'Missing file {f}'.format(f = f) raise NoData #the actual geospatial processing begins here #this creates a text file rep_file = 'fire_analysis_'+str(year)+'.txt' # if os.path.exists(reportpath+rep_file): os.remove(reportpath+rep_file) #this opens the file rfile = open(reportpath+rep_file, 'a') report_title = '*'*50+'\nFire season analysis for year {year}.\n'.format(year = year)+'*'*50+'\n\n' #this prints out the information for the fire season analysis printing(report_title, rfile) #this creates a describe object and allows me to set the spatial reference desc = arcpy.Describe(inpath+inscarfile) sr = desc.spatialReference # this for loop sets the projection for the infile and then copies the updated data into the new outfile shapefile. Then it copies it copies the data in weather database from the table in the infile to the outfile for f in ([inaffile,stations,ecosys]): infile = inpath+f outfile = outpath+f projection_fix(infile, outfile, sr) arcpy.CopyFeatures_management(inpath+inscarfile, outpath+inscarfile) arcpy.CopyRows_management(inpath+weather, outpath+weather) #These variables reveal the different time frames for fire activity thought the year seasonDates = start_end_peak(outpath+inaffile) sStart = 'Fires were detected as early as {mm}/{dd}/{year}.\n'.format(mm = str(seasonDates[0])[4:6], dd = str(seasonDates[0])[-2:], year = str(seasonDates[0])[0:4]) sEnd = 'Fires continued burning as late as {mm}/{dd}/{year}.\n'.format(mm = str(seasonDates[1])[4:6], dd = str(seasonDates[1])[-2:], year = str(seasonDates[1])[0:4]) sPeak = 'Fire occurrence peaked on {mm}/{dd}/{year} with {x} fire detections.\n'.format(mm = str(seasonDates[2])[4:6], dd = str(seasonDates[2])[-2:], year = str(seasonDates[2])[0:4], x =seasonDates[3] ) #this will print out the different fire characteristics present in the file subtseason = 'Fire characteristcs for the entire season:\n\n' printing(subtseason, rfile) #this will print out the times during the year where fire events start, end, and peak. for s in ([sStart,sEnd,sPeak]): printing('\t'+s, rfile) #this will create a variable that can count the number of large fire events during this fire sesason using get count. x = int((arcpy.GetCount_management(outpath+inscarfile)).getOutput(0)) scarinfo = 'There were the total of {x} large fire events during this fire season.\n'.format(x = x) #this will print out the data for the burn scars and will tab the data printing('\t'+scarinfo, rfile) #calculate total area burned in ha (conversion factor * 0.0001) cur = arcpy.SearchCursor(outpath+inscarfile, fields='Area') tot = 0.0 for c in cur: tot = tot+c.Area del c, cur ba_ha = round(tot*0.0001, 3) bainfo = 'A total of {ba_ha} hectares were burned.\n'.format(ba_ha = ba_ha) #this reads the file and prints out total area that was burned in hectored. The data is tabbed. printing('\t'+bainfo,rfile) #This variable uses the clip function so one can figure out what part of the ecosystem has been burned. burned_ecosys = arcpy.Clip_analysis(outpath+ecosys,outpath+inscarfile, outpath+'burned_ecosys.shp') # the new clip shapefile that has the data for burned parts of the ecosystem now has a search cursor cur = arcpy.SearchCursor(burned_ecosys) #this is an empty list created for the burned ecosystem data eList = [] #This appends the data into the list using the cursor that was created earlier for c in cur: eList.append(c.ECO_NAME) #these deletes the c and cur variables to release the locks on the file del c, cur #remove duplicates from the List to preserve only unique names eSet = set(eList) #This function calculates a new field in the burned ecosystem shapefile and it will add the information for the burned areas in hectares in the new field arcpy.CalculateField_management(burned_ecosys, 'AREA', '!shape.area@hectares!', "PYTHON") #this for loop will use an expression to filter through the search cursor to query data about total area burned in the different ecosystems in the file. outText = '' for e in eSet: expr = '"ECO_NAME" = \''+e+'\'' #these variables use the an expression to query specific data using the search cursor subcur = arcpy.SearchCursor(burned_ecosys, expr) tot = 0 for c in subcur: tot = tot + c.AREA #this will delete any locks on the file created by the cursor and rounds the total area del c, subcur tot_ha = round(tot, 3) #this variable will print the total area in hectores that were burned in the different ecosystems outText = outText+'\tA total of {tot_ha} burned in {e}.\n'.format(tot_ha = tot_ha, e=e) #this prints out the total area that was defined in the outTest variable above printing(outText,rfile) #these variables will allow me to find the top 5 fire events along with their sizes via the for loop output = top5burns(outpath+inscarfile) sizes = output[0] names = output[1] mess = '\tThe 5 largest fire events of this fire season were:\n' for i in range(len(sizes)): size = round(sizes*0.0001, 3) name = names mess = mess+'\t\t{name} which burned {size} ha\n'.format(name=name,size=size) #this will print out the names of the 5 largest fire events along with their sizes. printing(mess,rfile)# This exception will be printed if there is no path directory found except NoDataPath: print 'Data folder could not be found at {inpath}.\nPlease make sure data exists.\n'.format(inpath=inpath)#This excpeption will print if there are data sources that are missing and prompts the user to check the logfile for the specific error. except NoData: print 'One or more sources of data needed to run this analysis are missing.\nPlease refer to the log for missing file names.\n'#this will show the multiple error exceptions except: # Below I will get the traceback object and get the message strings for python and the arcpy tool tbList = sys.exc_info() tb = tbList[2] tbval = tbList[1] tbinfo = traceback.format_tb(tb)[0] pymsg = 'Python Error:\n\tError type:\n\t'+str(tbval)+'\n\tError:\n\t'+tbinfo apErr = arcpy.GetMessages(2) arcpymsg = 'ArcPy Error:\n\t'+apErr+'\n' #this prints out the different error messages error_print(pymsg,arcpymsg,logfile)#This print statement lets you know the error messages have been processed and to check the repot file for the errors. printing('Completed code execusion. Please check the repot file .', rfile)#This closes the obect file rfile.close()# This closes the logfile logfile.close()

أكثر...
 
أعلى