#! /usr/bin/env python # # Just type: # # ./get_LiNox.py -h # # 27 Aug 2013 - P. Le Sager - V0 # import os import sys import glob import re import time import argparse def total_linox(file): '''Return total LiNOx in "Tg N" from one log file''' # open file f=open(file,'r') r1='dynamics step from.*(\d{4}/\d{2}/\d{2} *\d+:\d+)' r2='global.*lightning emission *: *(\d+\.\d+) *Tg\[N\]/a' r3='--> second half : \d{4}/\d{2}/\d{2} *\d+:\d+ - (\d{4}/\d{2}/\d{2} *\d+:\d+)' total=0. line='abc' while line !='': line=f.readline() match=re.search(r1,line) if match: date1=match.group(1) while line !='': line=f.readline() emiss=re.search(r2,line) if emiss: while line !='': line=f.readline() half=re.search(r3,line) if half: date1_p=time.mktime(time.strptime(date1,"%Y/%m/%d %H:%M")) date2_p=time.mktime(time.strptime(half.group(1),"%Y/%m/%d %H:%M")) delta_sec = date2_p-date1_p total+=float(emiss.group(1))*delta_sec/(365.*24*60*60) break break return total ############################################################################################ # MAIN : process all the files in specific directory # ############################################################################################ if __name__ == "__main__": # --- Options: DIR and MASK parser = argparse.ArgumentParser(description='Compute Lightning NOx emissions total.') parser.add_argument('-d', '--dir', default=os.getcwd(), help='directory with log files to process. Default=current working dir.') parser.add_argument('-m', '--mask', default='*.out', help='mask to find the log files. Default="*.out"') args = parser.parse_args() directory = args.dir mask = args.mask # --- Get list of files print "" print "Looking for files in %s directory" % directory print "" try: os.chdir(directory) except: print "Cannot switch to %s directory" % directory sys.exit(1) files=glob.glob(os.path.join(directory,mask)) if not files: print "No '%s' files in %s" % (mask, directory) sys.exit(0) # --- Proceed summ=0. for f in files: month=total_linox(f) print os.path.basename(f), month, 'Tg [N]' summ+=month print "" print 'Total: %s Tg[N]' % summ