Changeset ff99eae in flex_extract.git for python/tools.py


Ignore:
Timestamp:
Jun 1, 2018, 8:34:59 PM (6 years ago)
Author:
Anne Philipp <anne.philipp@…>
Branches:
master, ctbto, dev
Children:
e1228f3
Parents:
ccab809
Message:

completed application of pep8 style guide and pylint investigations. added documentation almost everywhere

File:
1 moved

Legend:

Unmodified
Added
Removed
  • python/tools.py

    r991df6a rff99eae  
    22# -*- coding: utf-8 -*-
    33#************************************************************************
    4 # TODO AP
    5 # - check myerror
    6 # - check normalexit
    7 # - check getListAsString
     4# ToDo AP
     5# - check my_error
     6# - check normal_exit
     7# - check get_list_as_string
    88# - seperate args and control interpretation
    99#************************************************************************
     
    1515# @Change History:
    1616#    October 2014 - Anne Fouilloux (University of Oslo)
    17 #        - created functions silentremove and product (taken from ECMWF)
     17#        - created functions silent_remove and product (taken from ECMWF)
    1818#
    1919#    November 2015 - Leopold Haimberger (University of Vienna)
    20 #        - created functions: interpret_args_and_control, cleanup
    21 #          myerror, normalexit, init128, toparamId
     20#        - created functions: interpret_args_and_control, clean_up
     21#          my_error, normal_exit, init128, to_param_id
    2222#
    2323#    April 2018 - Anne Philipp (University of Vienna):
    2424#        - applied PEP8 style guide
    2525#        - added documentation
    26 #        - moved all functions from file FlexpartTools to this file Tools
    27 #        - added function getListAsString
     26#        - moved all functions from file Flexparttools to this file tools
     27#        - added function get_list_as_string
    2828#
    2929# @License:
     
    3939# @Module Content:
    4040#    - interpret_args_and_control
    41 #    - cleanup
    42 #    - myerror
    43 #    - normalexit
     41#    - clean_up
     42#    - my_error
     43#    - normal_exit
    4444#    - product
    45 #    - silentremove
     45#    - silent_remove
    4646#    - init128
    47 #    - toparamId
    48 #    - getListAsString
     47#    - to_param_id
     48#    - get_list_as_string
    4949#
    5050#*******************************************************************************
     
    5757import sys
    5858import glob
     59import inspect
     60import subprocess
    5961import traceback
    60 from numpy import *
    61 from gribapi import *
    6262from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
     63import numpy as np
    6364
    6465# software specific class from flex_extract
     
    123124    parser.add_argument("--flexpart_root_scripts", dest="flexpart_root_scripts",
    124125                        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 \
    126127                        the scripts directory of the FLEXPART distribution")
    127128
    128     # this is only used by prepareFLEXPART.py to rerun a postprocessing step
     129    # this is only used by prepare_flexpart.py to rerun a postprocessing step
    129130    parser.add_argument("--ppid", dest="ppid",
    130131                        help="Specify parent process id for \
    131                         rerun of prepareFLEXPART")
     132                        rerun of prepare_flexpart")
    132133
    133134    # arguments for job submission to ECMWF, only needed by submit.py
     
    152153    except IOError:
    153154        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'
    160163            exit(1)
    161164
    162165    # check for having at least a starting date
    163166    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'
    168171        exit(1)
    169172
     
    206209        l = args.area.split('/')
    207210        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))
    210213        c.upper, c.left, c.lower, c.right = l
    211214
     
    218221        if 'to' in args.step.lower():
    219222            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]))
    221224                c.step = ['{:0>3}'.format(i) for i in ilist]
    222225            else:
    223                 myerror(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')
    225228        else:
    226229            c.step = l
     
    239242
    240243
    241 def cleanup(c):
     244def clean_up(c):
    242245    '''
    243246    @Description:
     
    263266    '''
    264267
    265     print("cleanup")
     268    print "clean_up"
    266269
    267270    cleanlist = glob.glob(c.inputdir + "/*")
    268271    for cl in cleanlist:
    269272        if c.prefix not in cl:
    270             silentremove(cl)
     273            silent_remove(cl)
    271274        if c.ecapi is False and (c.ectrans == '1' or c.ecstorage == '1'):
    272             silentremove(cl)
    273 
    274     print("Done")
     275            silent_remove(cl)
     276
     277    print "Done"
    275278
    276279    return
    277280
    278281
    279 def myerror(c, message='ERROR'):
     282def my_error(c, message='ERROR'):
    280283    '''
    281284    @Description:
     
    303306        <nothing>
    304307    '''
    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()
    324329
    325330    exit(1)
     
    328333
    329334
    330 def normalexit(c, message='Done!'):
     335def normal_exit(c, message='Done!'):
    331336    '''
    332337    @Description:
     
    354359
    355360    '''
    356     # Uncomment if user wants notification directly from python
    357     #try:
    358         #target = c.mailops
    359         #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         #pass
    371 
    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
    373378
    374379    return
     
    411416
    412417
    413 def silentremove(filename):
     418def silent_remove(filename):
    414419    '''
    415420    @Description:
     
    435440
    436441
    437 def init128(fn):
     442def init128(filepath):
    438443    '''
    439444    @Description:
     
    441446
    442447    @Input:
    443         fn: string
     448        filepath: string
    444449            Path to file of ECMWF grib table number 128.
    445450
     
    451456    '''
    452457    table128 = dict()
    453     with open(fn) as f:
     458    with open(filepath) as f:
    454459        fdata = f.read().split('\n')
    455460    for data in fdata:
     
    460465
    461466
    462 def toparamId(pars, table):
     467def to_param_id(pars, table):
    463468    '''
    464469    @Description:
     
    486491    ipar = []
    487492    for par in cpar:
    488         found = False
    489493        for k, v in table.iteritems():
    490494            if par == k or par == v:
    491495                ipar.append(int(k))
    492                 found = True
    493496                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'
    496499
    497500    return ipar
    498501
    499 def getListAsString(listObj):
     502def get_list_as_string(list_obj, concatenate_sign=', '):
    500503    '''
    501504    @Description:
     
    503506
    504507    @Input:
    505         listObj: list
     508        list_obj: list
    506509            A list with arbitrary content.
    507510
    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
    510517            The content of the list as a single string.
    511518    '''
    512519
    513     strOfList = ", ".join( str(l) for l in listObj)
    514 
    515     return strOfList
     520    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.
hosted by ZAMG