Changeset ff99eae in flex_extract.git for python/tools.py
- Timestamp:
- Jun 1, 2018, 8:34:59 PM (6 years ago)
- Branches:
- master, ctbto, dev
- Children:
- e1228f3
- Parents:
- ccab809
- File:
-
- 1 moved
Legend:
- Unmodified
- Added
- Removed
-
python/tools.py
r991df6a rff99eae 2 2 # -*- coding: utf-8 -*- 3 3 #************************************************************************ 4 # T ODOAP5 # - check my error6 # - check normal exit7 # - check get ListAsString4 # ToDo AP 5 # - check my_error 6 # - check normal_exit 7 # - check get_list_as_string 8 8 # - seperate args and control interpretation 9 9 #************************************************************************ … … 15 15 # @Change History: 16 16 # October 2014 - Anne Fouilloux (University of Oslo) 17 # - created functions silent remove and product (taken from ECMWF)17 # - created functions silent_remove and product (taken from ECMWF) 18 18 # 19 19 # November 2015 - Leopold Haimberger (University of Vienna) 20 # - created functions: interpret_args_and_control, clean up21 # my error, normalexit, init128, toparamId20 # - created functions: interpret_args_and_control, clean_up 21 # my_error, normal_exit, init128, to_param_id 22 22 # 23 23 # April 2018 - Anne Philipp (University of Vienna): 24 24 # - applied PEP8 style guide 25 25 # - added documentation 26 # - moved all functions from file Flexpart Tools to this file Tools27 # - added function get ListAsString26 # - moved all functions from file Flexparttools to this file tools 27 # - added function get_list_as_string 28 28 # 29 29 # @License: … … 39 39 # @Module Content: 40 40 # - interpret_args_and_control 41 # - clean up42 # - my error43 # - normal exit41 # - clean_up 42 # - my_error 43 # - normal_exit 44 44 # - product 45 # - silent remove45 # - silent_remove 46 46 # - init128 47 # - to paramId48 # - get ListAsString47 # - to_param_id 48 # - get_list_as_string 49 49 # 50 50 #******************************************************************************* … … 57 57 import sys 58 58 import glob 59 import inspect 60 import subprocess 59 61 import traceback 60 from numpy import *61 from gribapi import *62 62 from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter 63 import numpy as np 63 64 64 65 # software specific class from flex_extract … … 123 124 parser.add_argument("--flexpart_root_scripts", dest="flexpart_root_scripts", 124 125 help="FLEXPART root directory (to find grib2flexpart \ 125 and COMMAND file)\n \Normally ECMWFDATA resides in \126 and COMMAND file)\n Normally ECMWFDATA resides in \ 126 127 the scripts directory of the FLEXPART distribution") 127 128 128 # this is only used by prepare FLEXPART.py to rerun a postprocessing step129 # this is only used by prepare_flexpart.py to rerun a postprocessing step 129 130 parser.add_argument("--ppid", dest="ppid", 130 131 help="Specify parent process id for \ 131 rerun of prepare FLEXPART")132 rerun of prepare_flexpart") 132 133 133 134 # arguments for job submission to ECMWF, only needed by submit.py … … 152 153 except IOError: 153 154 try: 154 c = ControlFile(localpythonpath + args.controlfile) 155 except: 156 print('Could not read CONTROL file "' + args.controlfile + '"') 157 print('Either it does not exist or its syntax is wrong.') 158 print('Try "' + sys.argv[0].split('/')[-1] + 159 ' -h" to print usage information') 155 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath( 156 inspect.getfile(inspect.currentframe()))) 157 c = ControlFile(LOCAL_PYTHON_PATH + args.controlfile) 158 except IOError: 159 print 'Could not read CONTROL file "' + args.controlfile + '"' 160 print 'Either it does not exist or its syntax is wrong.' 161 print 'Try "' + sys.argv[0].split('/')[-1] + \ 162 ' -h" to print usage information' 160 163 exit(1) 161 164 162 165 # check for having at least a starting date 163 166 if args.start_date is None and getattr(c, 'start_date') is None: 164 print ('start_date specified neither in command line nor \165 in CONTROL file ' + args.controlfile )166 print ('Try "' + sys.argv[0].split('/')[-1] +167 ' -h" to print usage information' )167 print 'start_date specified neither in command line nor \ 168 in CONTROL file ' + args.controlfile 169 print 'Try "' + sys.argv[0].split('/')[-1] + \ 170 ' -h" to print usage information' 168 171 exit(1) 169 172 … … 206 209 l = args.area.split('/') 207 210 if afloat: 208 for i in range(len(l)):209 l[i] = str(int(float(l[i]) * 1000))211 for i, item in enumerate(l): 212 item = str(int(float(item) * 1000)) 210 213 c.upper, c.left, c.lower, c.right = l 211 214 … … 218 221 if 'to' in args.step.lower(): 219 222 if 'by' in args.step.lower(): 220 ilist = arange(int(l[0]), int(l[2]) + 1, int(l[4]))223 ilist = np.arange(int(l[0]), int(l[2]) + 1, int(l[4])) 221 224 c.step = ['{:0>3}'.format(i) for i in ilist] 222 225 else: 223 my error(None, args.step + ':\n' +224 'please use "by" as well if "to" is used')226 my_error(None, args.step + ':\n' + 227 'please use "by" as well if "to" is used') 225 228 else: 226 229 c.step = l … … 239 242 240 243 241 def clean up(c):244 def clean_up(c): 242 245 ''' 243 246 @Description: … … 263 266 ''' 264 267 265 print ("cleanup")268 print "clean_up" 266 269 267 270 cleanlist = glob.glob(c.inputdir + "/*") 268 271 for cl in cleanlist: 269 272 if c.prefix not in cl: 270 silent remove(cl)273 silent_remove(cl) 271 274 if c.ecapi is False and (c.ectrans == '1' or c.ecstorage == '1'): 272 silent remove(cl)273 274 print ("Done")275 silent_remove(cl) 276 277 print "Done" 275 278 276 279 return 277 280 278 281 279 def my error(c, message='ERROR'):282 def my_error(c, message='ERROR'): 280 283 ''' 281 284 @Description: … … 303 306 <nothing> 304 307 ''' 305 # uncomment if user wants email notification directly from python 306 #try: 307 #target = c.mailfail 308 #except AttributeError: 309 #target = os.getenv('USER') 310 311 #if(type(target) is not list): 312 #target = [target] 313 314 print(message) 315 316 # uncomment if user wants email notification directly from python 317 #for t in target: 318 #p = subprocess.Popen(['mail','-s ECMWFDATA v7.0 ERROR', os.path.expandvars(t)], 319 # stdin = subprocess.PIPE, stdout = subprocess.PIPE, 320 # stderr = subprocess.PIPE, bufsize = 1) 321 #tr = '\n'.join(traceback.format_stack()) 322 #pout = p.communicate(input = message+'\n\n'+tr)[0] 323 #print 'Email sent to '+os.path.expandvars(t) # +' '+pout.decode() 308 309 print message 310 311 # comment if user does not want email notification directly from python 312 try: 313 target = [] 314 target.extend(c.mailfail) 315 except AttributeError: 316 target = [] 317 target.extend(os.getenv('USER')) 318 319 for t in target: 320 p = subprocess.Popen(['mail', '-s ECMWFDATA v7.0 ERROR', 321 os.path.expandvars(t)], 322 stdin=subprocess.PIPE, 323 stdout=subprocess.PIPE, 324 stderr=subprocess.PIPE, 325 bufsize=1) 326 tr = '\n'.join(traceback.format_stack()) 327 pout = p.communicate(input=message + '\n\n' + tr)[0] 328 print 'Email sent to ' + os.path.expandvars(t) + ' ' + pout.decode() 324 329 325 330 exit(1) … … 328 333 329 334 330 def normal exit(c, message='Done!'):335 def normal_exit(c, message='Done!'): 331 336 ''' 332 337 @Description: … … 354 359 355 360 ''' 356 # Uncomment if user wants notification directly from python357 #try: 358 #target = c.mailops359 #if(type(target) is not list):360 #target = [target]361 #for t in target:362 #p = subprocess.Popen(['mail','-s ECMWFDATA v7.0 normal exit',363 # os.path.expandvars(t)],364 # stdin = subprocess.PIPE,365 # stdout =subprocess.PIPE,366 # stderr = subprocess.PIPE, bufsize = 1)367 #pout = p.communicate(input = message+'\n\n')[0]368 #print pout.decode()369 #except:370 #pass371 372 print(message)361 print message 362 363 # comment if user does not want notification directly from python 364 try: 365 target = [] 366 target.extend(c.mailops) 367 for t in target: 368 p = subprocess.Popen(['mail', '-s ECMWFDATA v7.0 normal exit', 369 os.path.expandvars(t)], 370 stdin=subprocess.PIPE, 371 stdout=subprocess.PIPE, 372 stderr=subprocess.PIPE, 373 bufsize=1) 374 pout = p.communicate(input=message+'\n\n')[0] 375 print 'Email sent to ' + os.path.expandvars(t) + ' ' + pout.decode() 376 finally: 377 pass 373 378 374 379 return … … 411 416 412 417 413 def silent remove(filename):418 def silent_remove(filename): 414 419 ''' 415 420 @Description: … … 435 440 436 441 437 def init128(f n):442 def init128(filepath): 438 443 ''' 439 444 @Description: … … 441 446 442 447 @Input: 443 f n: string448 filepath: string 444 449 Path to file of ECMWF grib table number 128. 445 450 … … 451 456 ''' 452 457 table128 = dict() 453 with open(f n) as f:458 with open(filepath) as f: 454 459 fdata = f.read().split('\n') 455 460 for data in fdata: … … 460 465 461 466 462 def to paramId(pars, table):467 def to_param_id(pars, table): 463 468 ''' 464 469 @Description: … … 486 491 ipar = [] 487 492 for par in cpar: 488 found = False489 493 for k, v in table.iteritems(): 490 494 if par == k or par == v: 491 495 ipar.append(int(k)) 492 found = True493 496 break 494 if found is False:495 print ('Warning: par ' + par + ' not found in table 128')497 else: 498 print 'Warning: par ' + par + ' not found in table 128' 496 499 497 500 return ipar 498 501 499 def get ListAsString(listObj):502 def get_list_as_string(list_obj, concatenate_sign=', '): 500 503 ''' 501 504 @Description: … … 503 506 504 507 @Input: 505 list Obj: list508 list_obj: list 506 509 A list with arbitrary content. 507 510 508 @Return: 509 strOfList: string 511 concatenate_sign: string, optional 512 A string which is used to concatenate the single 513 list elements. Default value is ", ". 514 515 @Return: 516 str_of_list: string 510 517 The content of the list as a single string. 511 518 ''' 512 519 513 str OfList = ", ".join( str(l) for l in listObj)514 515 return str OfList520 str_of_list = concatenate_sign.join(str(l) for l in list_obj) 521 522 return str_of_list
Note: See TracChangeset
for help on using the changeset viewer.