Package firetools :: Module RunConfig
[hide private]
[frames] | no frames]

Source Code for Module firetools.RunConfig

 1  """Run a Script including logging and error trapping 
 2           
 3          At the command prompt run this script with the target script as the  
 4          first argument. As in this example (but use absolute paths)  
 5           
 6          >> python.exe RunConfig.py Configfile.py 
 7           
 8          Initially, this module sets up a console stream log.   
 9          Then a call to Run() will execute a script including:    
10                  1. set up a log file based on the input script (path_LOG.txt)  
11                  2. execute the script [path] within a try-except block 
12                  3. print and write log for any exception before quitting 
13   
14  """ 
15   
16  import sys, os, time 
17  import traceback, logging, logging.handlers 
18   
19  ## Setup Root logger 
20  log = logging.getLogger() 
21  log.setLevel(logging.DEBUG) 
22  formatter=logging.Formatter("%(asctime)s:%(name)s:%(message)s",datefmt="%H:%M:%S") 
23   
24  ## Console stream log handler        
25  ch = logging.StreamHandler() 
26  ch.setLevel(logging.DEBUG) 
27  ch.setFormatter(formatter) 
28  log.addHandler(ch) 
29   
30 -def AddLogFile(logfile):
31 """Add a logging file handler""" 32 fh=logging.handlers.RotatingFileHandler(logfile,maxBytes=pow(10,4),backupCount=3) 33 formatter = logging.Formatter("%(asctime)s:%(name)s:%(message)s") 34 fh.setFormatter(formatter) 35 fh.setLevel(logging.DEBUG) 36 log.addHandler(fh) 37 log.info("\n")
38
39 -def FormatTrace():
40 """trace the current error and format the message""" 41 etype,val,tb = sys.exc_info() 42 trace = traceback.extract_tb(tb) 43 emsg = '\n' 44 for (path,line,mod,text) in trace: 45 relpath = (os.path.basename(path).ljust(20)+' ('+str(line)+'): ') 46 emsg += relpath + text + '\n' 47 48 emsg += 'VALUE: '.ljust(20)+ str(val) +'\n' 49 emsg += 'TYPE: '.ljust(20) + str(etype) +'\n' 50 return emsg
51
52 -def Run(script):
53 """Run a script with logging and debugging""" 54 log = logging.getLogger('RunScript'.ljust(10)) 55 AddLogFile(script[:-3]+'_LOG.txt') 56 57 log.info(os.path.basename(script)) 58 try: 59 execfile(script) 60 log.info('Completed Successfully') 61 except: 62 log.info(FormatTrace()) 63 64 log.info("\n")
65 66 if __name__ == '__main__': 67 68 ## Run a script 69 script = sys.argv[1] 70 Run(script) 71