Changeset 2fb99de in flex_extract.git for python


Ignore:
Timestamp:
Sep 20, 2018, 11:56:37 AM (6 years ago)
Author:
Anne Philipp <anne.philipp@…>
Branches:
master, ctbto, dev
Children:
5d42acd
Parents:
3232589
Message:

introduced config with path definitions and changed py files accordingly; Installation works; some tests were added for tarball making; Problems in submission to ecgate

Location:
python
Files:
68 added
1 deleted
12 edited
1 moved

Legend:

Unmodified
Added
Removed
  • python/ControlFile.py

    r54a8a01 r2fb99de  
    5353# ------------------------------------------------------------------------------
    5454import os
     55import re
    5556import sys
    5657import inspect
     58
     59import _config
    5760
    5861# ------------------------------------------------------------------------------
     
    110113        self.stream = None
    111114        self.number = 'OFF'
    112         self.expver = None
     115        self.expver = '1'
    113116        self.grid = None
    114117        self.area = ''
     
    142145        self.inputdir = '../work'
    143146        self.outputdir = self.inputdir
    144         self.ecmwfdatadir = None
    145         self.exedir = None
     147        self.ecmwfdatadir = _config.PATH_FLEXEXTRACT_DIR
     148        self.exedir = _config.PATH_FORTRAN_SRC
    146149        self.flexpart_root_scripts = None
    147         self.makefile = None
     150        self.makefile = 'Makefile.gfortran'
    148151        self.destination = None
    149152        self.gateway = None
     
    152155        self.install_target = None
    153156        self.debug = 0
     157        self.request = 0
     158
     159        self.logicals = ['gauss', 'omega', 'omegadiff', 'eta', 'etadiff',
     160                         'dpdeta', 'cwc', 'wrf', 'grib2flexpart', 'ecstorage',
     161                         'ectrans', 'debug', 'request']
    154162
    155163        self.__read_controlfile__()
     
    172180
    173181        # read whole CONTROL file
    174         with open(self.controlfile) as f:
     182        with open(os.path.join(_config.PATH_CONTROLFILES,
     183                               self.controlfile)) as f:
    175184            fdata = f.read().split('\n')
    176185
     
    222231                pass
    223232
    224         # script directory
    225         self.ecmwfdatadir = os.path.dirname(os.path.abspath(inspect.getfile(
    226             inspect.currentframe()))) + '/../'
    227 
    228         # Fortran source directory
    229         self.exedir = self.ecmwfdatadir + 'src/'
    230 
    231233        return
    232234
     
    310312        return
    311313
    312     def check_conditions(self):
     314    def check_conditions(self, queue):
    313315        '''
    314316        @Description:
     
    321323                Description see class documentation.
    322324
     325            queue: string
     326                Name of the queue if submitted to the ECMWF servers.
     327                Used to check if ecuid, ecgid, gateway and destination
     328                are set correctly and are not empty.
     329
    323330        @Return:
    324331            <nothing>
     
    330337        # otherwise program is not allowed to run
    331338        if self.start_date is None:
    332             print 'start_date specified neither in command line nor ' + \
    333                   'in CONTROL file ' +  self.controlfile
    334             print 'Try "' + sys.argv[0].split('/')[-1] + \
    335                   ' -h" to print usage information'
     339            print('start_date specified neither in command line nor \
     340                   in CONTROL file ' +  self.controlfile)
     341            print('Try "' + sys.argv[0].split('/')[-1] +
     342                  ' -h" to print usage information')
    336343            sys.exit(1)
    337344
     
    341348
    342349        # assure consistency of levelist and level
    343         if self.levelist is None:
    344             if self.level is None:
    345                 print 'Warning: neither levelist nor level ' + \
    346                       'specified in CONTROL file'
    347                 sys.exit(1)
     350        if self.levelist is None and self.level is None:
     351            print('Warning: neither levelist nor level \
     352                               specified in CONTROL file')
     353            sys.exit(1)
     354        elif self.levelist is None and self.level:
     355            self.levelist = '1/to/' + self.level
     356        elif (self.levelist and self.level is None) or \
     357             (self.levelist[-1] != self.level[-1]):
     358            self.level = self.levelist.split('/')[-1]
     359        else:
     360            pass
     361
     362        # if area was provided (only from commandline)
     363        # decompose area into its 4 components
     364        if self.area:
     365            components = self.area.split('/')
     366            # convert float to integer coordinates
     367            if '.' in self.area:
     368                components = [str(int(float(item) * 1000))
     369                              for i, item in enumerate(components)]
     370            self.upper, self.left, self.lower, self.right = components
     371
     372        # prepare step list if "/" signs are found
     373        if '/' in self.step:
     374            steps = self.step.split('/')
     375            if 'to' in self.step.lower() and 'by' in self.step.lower():
     376                ilist = np.arange(int(steps[0]),
     377                                  int(steps[2]) + 1,
     378                                  int(steps[4]))
     379                self.step = ['{:0>3}'.format(i) for i in ilist]
     380            elif 'to' in self.step.lower() and 'by' not in self.step.lower():
     381                my_error(self.mailfail, self.step + ':\n' +
     382                         'if "to" is used in steps parameter, \
     383                         please use "by" as well')
    348384            else:
    349                 self.levelist = '1/to/' + self.level
    350         else:
    351             if 'to' in self.levelist.lower():
    352                 self.level = self.levelist.split('/')[2]
    353             else:
    354                 self.level = self.levelist.split('/')[-1]
    355 
    356         # if area was provided at command line
    357         # decompse area into its 4 components
    358         if self.area:
    359             afloat = '.' in self.area
    360             l = self.area.split('/')
    361             if afloat:
    362                 for i, item in enumerate(l):
    363                     item = str(int(float(item) * 1000))
    364             self.upper, self.left, self.lower, self.right = l
    365 
    366         # prepare step for correct usage
    367         if '/' in self.step:
    368             l = self.step.split('/')
    369             if 'to' in self.step.lower():
    370                 if 'by' in self.step.lower():
    371                     ilist = np.arange(int(l[0]), int(l[2]) + 1, int(l[4]))
    372                     self.step = ['{:0>3}'.format(i) for i in ilist]
    373                 else:
    374                     my_error(self.mailfail, self.step + ':\n' +
    375                              'if "to" is used, please use "by" as well')
    376             else:
    377                 self.step = l
     385                self.step = steps
    378386
    379387        # if maxstep wasn't provided
     
    407415                self.mailops = [self.mailops]
    408416
    409         if not self.gateway or not self.destination or \
     417        if queue in ['ecgate', 'cca'] and \
     418           not self.gateway or not self.destination or \
    410419           not self.ecuid or not self.ecgid:
    411             print '\nEnvironment variables GATWAY, DESTINATION, ECUID and ' + \
    412                   'ECGID were not set properly!'
    413             print 'Please check for excistence of file "ECMWF_ENV" in the ' + \
    414                   'python directory!'
     420            print('\nEnvironment variables GATEWAY, DESTINATION, ECUID and \
     421                   ECGID were not set properly!')
     422            print('Please check for existence of file "ECMWF_ENV" in the \
     423                   python directory!')
    415424            sys.exit(1)
     425
     426        if self.request != 0:
     427            marsfile = os.path.join(_config.PATH_RUN_DIR,
     428                                    _config.FILE_MARS_REQUESTS)
     429            if os.path.isfile(marsfile):
     430                os.remove(marsfile)
     431
     432        # check all logical variables for data type
     433        # if its a string change to integer
     434        for var in self.logicals:
     435            if not isinstance(getattr(self, var), int):
     436                setattr(self, var, int(getattr(self, var)))
    416437
    417438        return
     
    434455        if self.install_target and \
    435456           self.install_target not in ['local', 'ecgate', 'cca']:
    436             print 'ERROR: unknown or missing installation target '
    437             print 'target: ', self.install_target
    438             print 'please specify correct installation target \
    439                    (local | ecgate | cca)'
    440             print 'use -h or --help for help'
     457            print('ERROR: unknown or missing installation target ')
     458            print('target: ', self.install_target)
     459            print('please specify correct installation target ' +
     460                  '(local | ecgate | cca)')
     461            print('use -h or --help for help')
    441462            sys.exit(1)
    442463
     
    444465            if not self.ecgid or not self.ecuid or \
    445466               not self.gateway or not self.destination:
    446                 print 'Please enter your ECMWF user id and group id as well as \
    447                        the \nname of the local gateway and the ectrans \
    448                        destination '
    449                 print 'with command line options --ecuid --ecgid \
    450                        --gateway --destination'
    451                 print 'Try "' + sys.argv[0].split('/')[-1] + \
    452                       ' -h" to print usage information'
    453                 print 'Please consult ecaccess documentation or ECMWF user \
    454                        support for further details'
     467                print('Please enter your ECMWF user id and group id as well ' +
     468                      'as the \nname of the local gateway and the ectrans ' +
     469                      'destination ')
     470                print('with command line options --ecuid --ecgid \
     471                       --gateway --destination')
     472                print('Try "' + sys.argv[0].split('/')[-1] + \
     473                      ' -h" to print usage information')
     474                print('Please consult ecaccess documentation or ECMWF user \
     475                       support for further details')
    455476                sys.exit(1)
    456477
     
    459480            else:
    460481                self.flexpart_root_scripts = self.flexpart_root_scripts
    461         else:
     482        else: # local
    462483            if not self.flexpart_root_scripts:
    463                 self.flexpart_root_scripts = '../'
    464 
    465         if not self.makefile:
    466             self.makefile = 'Makefile.gfortran'
     484                self.flexpart_root_scripts = _config.PATH_FLEXEXTRACT_DIR
    467485
    468486        return
  • python/EcFlexpart.py

    rdda0e9d r2fb99de  
    102102
    103103# software specific classes and modules from flex_extract
     104import _config
    104105from GribTools import GribTools
    105106from tools import init128, to_param_id, silent_remove, product, my_error
     
    204205        self.accuracy = c.accuracy
    205206        self.level = c.level
    206 
    207         if c.levelist:
    208             self.levelist = c.levelist
    209         else:
    210             self.levelist = '1/to/' + c.level
    211 
     207        self.expver = c.expver
    212208        # for gaussian grid retrieval
    213209        self.glevelist = '1/to/' + c.level
     
    217213        else:
    218214            self.gaussian = ''
    219 
    220         if hasattr(c, 'expver') and c.expver:
    221             self.expver = c.expver
    222         else:
    223             self.expver = '1'
    224 
    225         if hasattr(c, 'number') and c.number:
    226             self.number = c.number
    227         else:
    228             self.number = '0'
    229215
    230216        if 'N' in c.grid:  # Gaussian output grid
     
    250236        # 4) Download also data for WRF
    251237
    252 
    253238        # Different grids need different retrievals
    254239        # SH = Spherical Harmonics, GG = Gaussian Grid,
     
    274259            self.params['OG__ML'] = ['T/Q', 'ML', self.levelist, self.grid]
    275260
    276             if c.gauss == '0' and c.eta == '1':
     261            #if c.gauss == '0' and c.eta == '1':
     262            if not c.gauss and c.eta:
    277263                # the simplest case
    278264                self.params['OG__ML'][0] += '/U/V/77'
    279             elif c.gauss == '0' and c.eta == '0':
     265            #elif c.gauss == '0' and c.eta == '0':
     266            elif not c.gauss and not c.eta:
    280267            # this is not recommended (inaccurate)
    281268                self.params['OG__ML'][0] += '/U/V'
    282             elif c.gauss == '1' and c.eta == '0':
     269            #elif c.gauss == '1' and c.eta == '0':
     270            elif c.gauss and not c.eta:
    283271                # this is needed for data before 2008, or for reanalysis data
    284272                self.params['GG__SL'] = ['Q', 'ML', '1', \
     
    286274                self.params['SH__ML'] = ['U/V/D', 'ML', self.glevelist, 'OFF']
    287275            else:
    288                 print 'Warning: This is a very costly parameter combination, \
    289                        use only for debugging!'
     276                print('Warning: This is a very costly parameter combination, \
     277                      use only for debugging!')
    290278                self.params['GG__SL'] = ['Q', 'ML', '1', \
    291279                                         '{}'.format((int(self.resol) + 1) / 2)]
     
    293281                                         '{}'.format((int(self.resol) + 1) / 2)]
    294282
    295             if hasattr(c, 'omega') and c.omega == '1':
     283            if c.omega:
    296284                self.params['OG__ML'][0] += '/W'
    297285
    298286            # add cloud water content if necessary
    299             if hasattr(c, 'cwc') and c.cwc == '1':
     287            if c.cwc:
    300288                self.params['OG__ML'][0] += '/CLWC/CIWC'
    301289
    302290            # add vorticity and geopotential height for WRF if necessary
    303             if hasattr(c, 'wrf') and c.wrf == '1':
     291            if c.wrf:
    304292                self.params['OG__ML'][0] += '/Z/VO'
    305293                if '/D' not in self.params['OG__ML'][0]:
     
    367355            f.write('&NAMGEN\n')
    368356            f.write(',\n  '.join(['maxl = ' + str(maxl), 'maxb = ' + str(maxb),
    369                                   'mlevel = ' + self.level,
    370                                   'mlevelist = ' + '"' + self.levelist + '"',
    371                                   'mnauf = ' + self.resol,
     357                                  'mlevel = ' + str(self.level),
     358                                  'mlevelist = ' + '"' + str(self.levelist)
     359                                                 + '"',
     360                                  'mnauf = ' + str(self.resol),
    372361                                  'metapar = ' + '77',
    373362                                  'rlo0 = ' + str(area[1]),
     
    375364                                  'rla0 = ' + str(area[2]),
    376365                                  'rla1 = ' + str(area[0]),
    377                                   'momega = ' + c.omega,
    378                                   'momegadiff = ' + c.omegadiff,
    379                                   'mgauss = ' + c.gauss,
    380                                   'msmooth = ' + c.smooth,
    381                                   'meta = ' + c.eta,
    382                                   'metadiff = ' + c.etadiff,
    383                                   'mdpdeta = ' + c.dpdeta]))
     366                                  'momega = ' + str(c.omega),
     367                                  'momegadiff = ' + str(c.omegadiff),
     368                                  'mgauss = ' + str(c.gauss),
     369                                  'msmooth = ' + str(c.smooth),
     370                                  'meta = ' + str(c.eta),
     371                                  'metadiff = ' + str(c.etadiff),
     372                                  'mdpdeta = ' + str(c.dpdeta)]))
    384373
    385374            f.write('\n/\n')
     
    387376        return
    388377
    389     def retrieve(self, server, dates, inputdir='.'):
     378    def retrieve(self, server, dates, request, inputdir='.'):
    390379        '''
    391380        @Description:
     
    437426                    pass
    438427                if pk == 'OG_OROLSM__SL':
    439                     if oro is False:
     428                    if not oro:
    440429                        mfstream = 'OPER'
    441430                        mftype = 'AN'
     
    457446
    458447    # ------  on demand path  --------------------------------------------------
    459                 if self.basetime is None:
     448                if not self.basetime:
    460449                    MR = MarsRetrieval(self.server,
    461450                                       marsclass=self.marsclass,
     
    477466                                       param=pv[0])
    478467
    479                     MR.display_info()
    480                     MR.data_retrieve()
     468                    if request == 0:
     469                        MR.display_info()
     470                        MR.data_retrieve()
     471                    elif request == 1:
     472                        MR.print_info()
     473                    elif request == 2:
     474                        MR.print_info()
     475                        MR.display_info()
     476                        MR.data_retrieve()
     477                    else:
     478                        print('Failure')
    481479    # ------  operational path  ------------------------------------------------
    482480                else:
     
    566564
    567565                            MR.display_info()
     566
    568567                            MR.data_retrieve()
    569568                        # --------------  non flux data ------------------------
     
    662661                            MR.data_retrieve()
    663662
    664         print "MARS retrieve done... "
     663        if request == 0 or request == 2:
     664            print('MARS retrieve done ... ')
     665        elif request == 1:
     666            print('MARS request printed ...')
    665667
    666668        return
     
    702704        '''
    703705
    704         print '\n\nPostprocessing:\n Format: {}\n'.format(c.format)
    705 
    706         if c.ecapi is False:
     706        print('\n\nPostprocessing:\n Format: {}\n'.format(c.format))
     707
     708        if not c.ecapi:
    707709            print('ecstorage: {}\n ecfsdir: {}\n'.
    708710                  format(c.ecstorage, c.ecfsdir))
    709             if not hasattr(c, 'gateway'):
    710                 c.gateway = os.getenv('GATEWAY')
    711             if not hasattr(c, 'destination'):
    712                 c.destination = os.getenv('DESTINATION')
     711            #if not hasattr(c, 'gateway'):
     712            #    c.gateway = os.getenv('GATEWAY')
     713            #if not hasattr(c, 'destination'):
     714            #    c.destination = os.getenv('DESTINATION')
    713715            print('ectrans: {}\n gateway: {}\n destination: {}\n '
    714716                  .format(c.ectrans, c.gateway, c.destination))
    715717
    716         print 'Output filelist: \n'
    717         print self.outputfilelist
     718        print('Output filelist: \n')
     719        print(self.outputfilelist)
    718720
    719721        if c.format.lower() == 'grib2':
     
    724726                p = subprocess.check_call(['mv', ofile + '_2', ofile])
    725727
    726         if int(c.ectrans) == 1 and c.ecapi is False:
     728        if c.ectrans and not c.ecapi:
    727729            for ofile in self.outputfilelist:
    728730                p = subprocess.check_call(['ectrans', '-overwrite', '-gateway',
     
    731733                #print('ectrans:', p)
    732734
    733         if int(c.ecstorage) == 1 and c.ecapi is False:
     735        if c.ecstorage and not c.ecapi:
    734736            for ofile in self.outputfilelist:
    735737                p = subprocess.check_call(['ecp', '-o', ofile,
     
    742744        # prepare environment for the grib2flexpart run
    743745        # to convert grib to flexpart binary
    744         if c.grib2flexpart == '1':
     746        if c.grib2flexpart:
    745747
    746748            # generate AVAILABLE file
     
    858860
    859861        index_keys = ["date", "time", "step"]
    860         indexfile = c.inputdir + "/date_time_stepRange.idx"
     862        indexfile = os.path.join(c.inputdir, _config.FILE_GRIB_INDEX)
    861863        silent_remove(indexfile)
    862864        grib = GribTools(inputfiles.files)
     
    868870        for key in index_keys:
    869871            index_vals.append(grib_index_get(iid, key))
    870             print index_vals[-1]
     872            print(index_vals[-1])
    871873            # index_vals looks for example like:
    872874            # index_vals[0]: ('20171106', '20171107', '20171108') ; date
     
    878880
    879881        for prod in product(*index_vals):
     882            # e.g. prod = ('20170505', '0', '12')
     883            #             (  date    ,time, step)
     884            # per date e.g. time = 0, 1200
     885            # per time e.g. step = 3, 6, 9, 12
    880886            # flag for Fortran program CONVERT2 and file merging
    881887            convertFlag = False
    882             print 'current prod: ', prod
     888            print('current prod: ', prod)
    883889            # e.g. prod = ('20170505', '0', '12')
    884890            #             (  date    ,time, step)
     
    902908                # they are just valid for a single product
    903909                for k, f in fdict.iteritems():
    904                     silent_remove(c.inputdir + "/fort." + k)
    905                     fdict[k] = open(c.inputdir + '/fort.' + k, 'w')
     910                    fortfile = os.path.join(c.inputdir, 'fort.' + k)
     911                    silent_remove(fortfile)
     912                    fdict[k] = open(fortfile, 'w')
    906913
    907914                cdate = str(grib_get(gid, 'date'))
     
    931938                    if timestamp < slimit or timestamp > elimit:
    932939                        continue
     940            else:
     941                pass
    933942
    934943            try:
    935                 if c.wrf == '1':
    936                     if 'olddate' not in locals():
    937                         fwrf = open(c.outputdir + '/WRF' + cdate +
    938                                     '.{:0>2}'.format(time) + '.000.grb2', 'w')
     944                if c.wrf:
     945                    if 'olddate' not in locals() or cdate != olddate:
     946                        fwrf = open(os.path.join(c.outputdir,
     947                                    'WRF' + cdate + '.{:0>2}'.format(time) +
     948                                    '.000.grb2'), 'w')
    939949                        olddate = cdate[:]
    940                     else:
    941                         if cdate != olddate:
    942                             fwrf = open(c.outputdir + '/WRF' + cdate +
    943                                         '.{:0>2}'.format(time) + '.000.grb2',
    944                                         'w')
    945                             olddate = cdate[:]
    946950            except AttributeError:
    947951                pass
    948952
    949             # helper variable to remember which fields are already used.
     953            # helper variable to remember which fields were already used.
    950954            savedfields = []
    951955            while 1:
     
    958962                # Specific humidity (Q.grb) is used as a template only
    959963                # so we need the first we "meet"
    960                     with open(c.inputdir + '/fort.18', 'w') as fout:
     964                    with open(os.path.join(c.inputdir, 'fort.18'), 'w') as fout:
    961965                        grib_write(gid, fout)
    962966                elif paramId == 131 or paramId == 132:
     
    971975                    grib_write(gid, fdict['13'])
    972976                elif  paramId in [129, 138, 155] and levtype == 'hybrid' \
    973                         and c.wrf == '1':
     977                        and c.wrf:
    974978                    pass
    975979                elif paramId == 246 or paramId == 247:
     
    991995                        savedfields.append(paramId)
    992996                    else:
    993                         print 'duplicate ' + str(paramId) + ' not written'
     997                        print('duplicate ' + str(paramId) + ' not written')
    994998
    995999                try:
    996                     if c.wrf == '1':
    997                         if levtype == 'hybrid': # model layer
    998                             if paramId in [129, 130, 131, 132, 133, 138, 155]:
    999                                 grib_write(gid, fwrf)
    1000                         else: # sfc layer
    1001                             if paramId in wrfpars:
    1002                                 grib_write(gid, fwrf)
     1000                    if c.wrf:
     1001                        # model layer
     1002                        if levtype == 'hybrid' and \
     1003                           paramId in [129, 130, 131, 132, 133, 138, 155]:
     1004                            grib_write(gid, fwrf)
     1005                        # sfc layer
     1006                        elif paramId in wrfpars:
     1007                            grib_write(gid, fwrf)
    10031008                except AttributeError:
    10041009                    pass
     
    10141019                pwd = os.getcwd()
    10151020                os.chdir(c.inputdir)
    1016                 if os.stat('fort.21').st_size == 0 and int(c.eta) == 1:
    1017                     print 'Parameter 77 (etadot) is missing, most likely it is \
    1018                            not available for this type or date/time\n'
    1019                     print 'Check parameters CLASS, TYPE, STREAM, START_DATE\n'
     1021                if os.stat('fort.21').st_size == 0 and c.eta:
     1022                    print('Parameter 77 (etadot) is missing, most likely it is \
     1023                           not available for this type or date/time\n')
     1024                    print('Check parameters CLASS, TYPE, STREAM, START_DATE\n')
    10201025                    my_error(c.mailfail, 'fort.21 is empty while parameter eta \
    10211026                             is set to 1 in CONTROL file')
     
    10231028                # create the corresponding output file fort.15
    10241029                # (generated by CONVERT2) + fort.16 (paramId 167 and 168)
    1025                 p = subprocess.check_call(
    1026                     [os.path.expandvars(os.path.expanduser(c.exedir)) +
    1027                      '/CONVERT2'], shell=True)
     1030                p = subprocess.check_call([os.path.join(c.exedir, 'CONVERT2')],
     1031                                          shell=True)
    10281032                os.chdir(pwd)
    10291033
    10301034                # create final output filename, e.g. EN13040500 (ENYYMMDDHH)
    1031                 fnout = c.inputdir + '/' + c.prefix
     1035                fnout = os.path.join(c.inputdir, c.prefix)
    10321036                if c.maxstep > 12:
    10331037                    suffix = cdate[2:8] + '.{:0>2}'.format(time/100) + \
     
    10361040                    suffix = cdateH[2:10]
    10371041                fnout += suffix
    1038                 print "outputfile = " + fnout
     1042                print("outputfile = " + fnout)
    10391043                self.outputfilelist.append(fnout) # needed for final processing
    10401044
     
    10441048                    c.inputdir + '/OG_OROLSM__SL.*.' + c.ppid + '*')[0])
    10451049                fluxfile = 'flux' + cdate[0:2] + suffix
    1046                 if c.cwc != '1':
     1050                if not c.cwc:
    10471051                    flist = ['fort.15', fluxfile, 'fort.16', orolsm]
    10481052                else:
     
    10511055                with open(fnout, 'wb') as fout:
    10521056                    for f in flist:
     1057                        shutil.copyfileobj(open(os.path.join(c.inputdir, f),
     1058                                                'rb'), fout)
     1059
     1060                if c.omega:
     1061                    with open(os.path.join(c.outputdir, 'OMEGA'), 'wb') as fout:
    10531062                        shutil.copyfileobj(
    1054                             open(c.inputdir + '/' + f, 'rb'), fout)
    1055 
    1056                 if c.omega == '1':
    1057                     with open(c.outputdir + '/OMEGA', 'wb') as fout:
    1058                         shutil.copyfileobj(
    1059                             open(c.inputdir + '/fort.25', 'rb'), fout)
    1060 
    1061         if hasattr(c, 'wrf') and c.wrf == '1':
     1063                            open(os.path.join(c.inputdir, 'fort.25'),
     1064                                 'rb'), fout)
     1065            else:
     1066                pass
     1067
     1068        if c.wrf:
    10621069            fwrf.close()
    10631070
     
    11021109        pars = to_param_id(self.params['OG_acc_SL'][0], table128)
    11031110        index_keys = ["date", "time", "step"]
    1104         indexfile = c.inputdir + "/date_time_stepRange.idx"
     1111        indexfile = os.path.join(c.inputdir, _config.FILE_GRIB_INDEX)
    11051112        silent_remove(indexfile)
    11061113        grib = GribTools(inputfiles.files)
     
    11121119        for key in index_keys:
    11131120            key_vals = grib_index_get(iid, key)
    1114             print key_vals
     1121            print(key_vals)
    11151122            # have to sort the steps for disaggregation,
    11161123            # therefore convert to int first
     
    11331140            stepsdict[str(p)] = []
    11341141
    1135         print 'maxstep: ', c.maxstep
     1142        print('maxstep: ', c.maxstep)
    11361143
    11371144        for prod in product(*index_vals):
     
    11401147            # per date e.g. time = 0, 1200
    11411148            # per time e.g. step = 3, 6, 9, 12
     1149            print('current prod: ', prod)
    11421150            for i in range(len(index_keys)):
    11431151                grib_index_select(iid, index_keys[i], prod[i])
    11441152
     1153            # get first id from current product
    11451154            gid = grib_new_from_index(iid)
     1155
     1156            # if there is data for this product combination
     1157            # prepare some date and time parameter before reading the data
    11461158            if gid is not None:
    11471159                cdate = grib_get(gid, 'date')
     
    11611173
    11621174            if c.maxstep > 12:
    1163                 fnout = c.inputdir + '/flux' + \
    1164                     sdate.strftime('%Y%m%d') + '.{:0>2}'.format(time/100) + \
    1165                     '.{:0>3}'.format(step-2*int(c.dtime))
    1166                 gnout = c.inputdir + '/flux' + \
    1167                     sdate.strftime('%Y%m%d') + '.{:0>2}'.format(time/100) + \
    1168                     '.{:0>3}'.format(step-int(c.dtime))
    1169                 hnout = c.inputdir + '/flux' + \
    1170                     sdate.strftime('%Y%m%d') + '.{:0>2}'.format(time/100) + \
    1171                     '.{:0>3}'.format(step)
    1172                 g = open(gnout, 'w')
    1173                 h = open(hnout, 'w')
     1175                fnout = os.path.join(c.inputdir, 'flux' +
     1176                                     sdate.strftime('%Y%m%d') +
     1177                                     '.{:0>2}'.format(time/100) +
     1178                                     '.{:0>3}'.format(step-2*int(c.dtime)))
     1179                gnout = os.path.join(c.inputdir, 'flux' +
     1180                                     sdate.strftime('%Y%m%d') +
     1181                                     '.{:0>2}'.format(time/100) +
     1182                                     '.{:0>3}'.format(step-int(c.dtime)))
     1183                hnout = os.path.join(c.inputdir, 'flux' +
     1184                                     sdate.strftime('%Y%m%d') +
     1185                                     '.{:0>2}'.format(time/100) +
     1186                                     '.{:0>3}'.format(step))
    11741187            else:
    1175                 fnout = c.inputdir + '/flux' + fdate.strftime('%Y%m%d%H')
    1176                 gnout = c.inputdir + '/flux' + (fdate +
    1177                                                 timedelta(hours=int(c.dtime))
    1178                                                ).strftime('%Y%m%d%H')
    1179                 hnout = c.inputdir + '/flux' + sdates.strftime('%Y%m%d%H')
    1180                 g = open(gnout, 'w')
    1181                 h = open(hnout, 'w')
    1182 
    1183             print "outputfile = " + fnout
    1184             f = open(fnout, 'w')
     1188                fnout = os.path.join(c.inputdir, 'flux' +
     1189                                     fdate.strftime('%Y%m%d%H'))
     1190                gnout = os.path.join(c.inputdir, 'flux' +
     1191                                     (fdate + timedelta(hours=int(c.dtime))).
     1192                                     strftime('%Y%m%d%H'))
     1193                hnout = os.path.join(c.inputdir, 'flux' +
     1194                                     sdates.strftime('%Y%m%d%H'))
     1195
     1196            print("outputfile = " + fnout)
     1197            f_handle = open(fnout, 'w')
     1198            g_handle = open(gnout, 'w')
     1199            h_handle = open(hnout, 'w')
    11851200
    11861201            # read message for message and store relevant data fields
     
    12431258                            grib_set(gid, 'date', fdate.year*10000 +
    12441259                                     fdate.month*100+fdate.day)
    1245                         grib_write(gid, f)
     1260                        grib_write(gid, f_handle)
    12461261
    12471262                        if c.basetime is not None:
     
    12701285                                     truedatetime.month * 100 +
    12711286                                     truedatetime.day)
    1272                             grib_write(gid, h)
     1287                            grib_write(gid, h_handle)
    12731288
    12741289                            #values = (svdp[1]+svdp[2])/2.
     
    12851300                                     truedatetime.day)
    12861301                            grib_set_values(gid, values)
    1287                             grib_write(gid, g)
     1302                            grib_write(gid, g_handle)
    12881303
    12891304                    grib_release(gid)
     
    12911306                    gid = grib_new_from_index(iid)
    12921307
    1293             f.close()
    1294             g.close()
    1295             h.close()
     1308            f_handle.close()
     1309            g_handle.close()
     1310            h_handle.close()
    12961311
    12971312        grib_index_release(iid)
  • python/GribTools.py

    r54a8a01 r2fb99de  
    297297                Grib index id.
    298298        '''
    299         print "... index will be done"
     299        print("... index will be done")
    300300        iid = None
    301301
    302302        if os.path.exists(index_file):
    303303            iid = grib_index_read(index_file)
    304             print "Use existing index file: %s " % (index_file)
     304            print("Use existing index file: %s " % (index_file))
    305305        else:
    306306            for filename in self.filenames:
    307                 print "Inputfile: %s " % (filename)
     307                print("Inputfile: %s " % (filename))
    308308                if iid is None:
    309309                    iid = grib_index_new_from_file(filename, index_keys)
     
    314314                grib_index_write(iid, index_file)
    315315
    316         print '... index done'
     316        print('... index done')
    317317
    318318        return iid
  • python/MarsRetrieval.py

    r54a8a01 r2fb99de  
    6565import os
    6666
     67import _config
    6768# ------------------------------------------------------------------------------
    6869# CLASS
     
    310311        '''
    311312        @Description:
    312             Prints all class attributes and their values.
     313            Prints all class attributes and their values to the
     314            standard output.
    313315
    314316        @Input:
     
    328330                pass
    329331            else:
    330                 print item[0] + ': ' + str(item[1])
     332                print(item[0] + ': ' + str(item[1]))
     333
     334        return
     335
     336
     337    def print_info(self):
     338        '''
     339        @Description:
     340            Prints all mars requests to an extra file for debugging and
     341            information.
     342
     343        @Input:
     344            self: instance of MarsRetrieval
     345                For description see class documentation.
     346
     347        @Return:
     348            <nothing>
     349        '''
     350        # Get all class attributes and their values as a dictionary
     351        attrs = vars(self)
     352
     353        # open a file to store all requests to
     354        with open(os.path.join(_config.PATH_RUN_DIR,
     355                               _config.FILE_MARS_REQUESTS), 'a') as f:
     356            f.write('mars\n')
     357            # iterate through all attributes and print them
     358            # with their corresponding values
     359            for item in attrs.items():
     360                if item[0] in 'server':
     361                    pass
     362                else:
     363                    f.write(item[0] + ': ' + str(item[1]) + '\n')
     364            f.write('\n\n')
    331365
    332366        return
     
    371405                self.server.execute(s, target)
    372406            except:
    373                 print 'MARS Request failed, \
    374                     have you already registered at apps.ecmwf.int?'
     407                print('MARS Request failed, \
     408                      have you already registered at apps.ecmwf.int?')
    375409                raise IOError
    376410            if os.stat(target).st_size == 0:
    377                 print 'MARS Request returned no data - please check request'
     411                print('MARS Request returned no data - please check request')
    378412                raise IOError
    379413        # MARS request via extra process in shell
     
    384418                                 stderr=subprocess.PIPE, bufsize=1)
    385419            pout = p.communicate(input=s)[0]
    386             print pout.decode()
     420            print(pout.decode())
    387421
    388422            if 'Some errors reported' in pout.decode():
    389                 print 'MARS Request failed - please check request'
     423                print('MARS Request failed - please check request')
    390424                raise IOError
    391425
    392426            if os.stat(target).st_size == 0:
    393                 print 'MARS Request returned no data - please check request'
     427                print('MARS Request returned no data - please check request')
    394428                raise IOError
    395429
  • python/_config.py

    r222aa11 r2fb99de  
    2828_VERSION_STR = '7.1'
    2929
    30 # add path to pythonpath
     30# ------------------------------------------------------------------------------
     31# FILENAMES
     32# ------------------------------------------------------------------------------
     33
     34FLEXEXTRACT_DIRNAME = 'flex_extract_v' + _VERSION_STR
     35FILE_MARS_REQUESTS = 'mars_requests.dat'
     36FORTRAN_EXECUTABLE = 'CONVERT2'
     37FILE_USER_ENVVARS = 'ECMWF_ENV'
     38TEMPFILE_INSTALL_COMPILEJOB = 'compilejob.temp'
     39FILE_INSTALL_COMPILEJOB = 'compilejob.ksh'
     40TEMPFILE_INSTALL_JOB = 'job.temp.o'
     41TEMPFILE_JOB = 'job.temp'
     42FILE_JOB_OD = 'job.ksh'
     43FILE_JOB_OP = 'jopoper.ksh'
     44FILE_NAMELIST = 'fort.4'
     45FILE_GRIB_INDEX = 'date_time_stepRange.idx'
     46
     47# ------------------------------------------------------------------------------
     48#  PATHES
     49# ------------------------------------------------------------------------------
     50
     51# path to the flex_extract directory
     52PATH_FLEXEXTRACT_DIR = os.path.normpath(os.path.dirname(os.path.abspath(
     53    inspect.getfile(inspect.currentframe()))) + '/../')
     54
     55# path to the local python source files
    3156PATH_LOCAL_PYTHON = os.path.dirname(os.path.abspath(
    3257    inspect.getfile(inspect.currentframe())))
     58PATH_RELATIVE_PYTHON = os.path.relpath(PATH_LOCAL_PYTHON, PATH_FLEXEXTRACT_DIR)
     59# add path to pythonpath
    3360if PATH_LOCAL_PYTHON not in sys.path:
    3461    sys.path.append(PATH_LOCAL_PYTHON)
    3562
    36 PATH_FLEXEXTRACT_DIR = os.path.normpath(os.path.dirname(os.path.abspath(
    37     inspect.getfile(inspect.currentframe()))) + '/../')
     63# path to the templates
     64PATH_TEMPLATES = os.path.join(PATH_FLEXEXTRACT_DIR, '_templates')
     65PATH_RELATIVE_TEMPLATES = os.path.relpath(PATH_TEMPLATES, PATH_FLEXEXTRACT_DIR)
    3866
    39 PATH_TEMPLATES = os.path.join(PATH_FLEXEXTRACT_DIR + os.path.sep +
    40                               '_templates')
     67# path to the environment parameter file
     68PATH_ECMWF_ENV = os.path.join(PATH_LOCAL_PYTHON, FILE_USER_ENVVARS)
     69PATH_RELATIVE_ECMWF_ENV = os.path.relpath(PATH_ECMWF_ENV, PATH_FLEXEXTRACT_DIR)
    4170
    4271# path to gribtable
    43 PATH_GRIBTABLE = os.path.join(PATH_TEMPLATES + os.path.sep +
    44                               'ecmwf_grib1_table_128')
     72PATH_GRIBTABLE = os.path.join(PATH_TEMPLATES, 'ecmwf_grib1_table_128')
    4573
    46 PATH_RUN_DIR = os.path.join(PATH_FLEXEXTRACT_DIR + os.path.sep +
    47                                 'run')
     74# path to run directory
     75PATH_RUN_DIR = os.path.join(PATH_FLEXEXTRACT_DIR, 'run')
     76PATH_RELATIVE_RUN_DIR = os.path.relpath(PATH_RUN_DIR, PATH_FLEXEXTRACT_DIR)
    4877
    49 PATH_CONTROLFILES = os.path.join(PATH_RUN_DIR + os.path.sep +
    50                                 'control')
     78# path to directory where all control files are stored
     79PATH_CONTROLFILES = os.path.join(PATH_RUN_DIR, 'control')
     80PATH_RELATIVE_CONTROLFILES = os.path.relpath(PATH_CONTROLFILES, PATH_FLEXEXTRACT_DIR)
     81
     82# path to directory where all job scripts are stored
     83PATH_JOBSCRIPTS = os.path.join(PATH_RUN_DIR, 'jobscripts')
     84PATH_RELATIVE_JOBSCRIPTS = os.path.relpath(PATH_JOBSCRIPTS, PATH_FLEXEXTRACT_DIR)
     85
     86# path to the fortran executable and the source code
     87PATH_FORTRAN_SRC = os.path.join(PATH_FLEXEXTRACT_DIR, 'src')
     88PATH_RELATIVE_FORTRAN_SRC = os.path.relpath(PATH_FORTRAN_SRC, PATH_FLEXEXTRACT_DIR)
     89
     90# path to the python testing directory
     91PATH_TEST_DIR = os.path.join(PATH_LOCAL_PYTHON, 'pythontest')
     92
  • python/get_mars_data.py

    r54a8a01 r2fb99de  
    5757
    5858# software specific classes and modules from flex_extract
     59import _config
    5960from tools import my_error, normal_exit, get_cmdline_arguments, read_ecenv
    6061from EcFlexpart import EcFlexpart
    6162from UioFiles import UioFiles
    62 
    63 # add path to pythonpath so that python finds its buddies
    64 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath(
    65     inspect.getfile(inspect.currentframe())))
    66 if LOCAL_PYTHON_PATH not in sys.path:
    67     sys.path.append(LOCAL_PYTHON_PATH)
    68 
    6963# ------------------------------------------------------------------------------
    7064# FUNCTION
     
    8983        c = ControlFile(args.controlfile)
    9084    except IOError:
    91         try:
    92             c = ControlFile(LOCAL_PYTHON_PATH + args.controlfile)
    93         except IOError:
    94             print 'Could not read CONTROL file "' + args.controlfile + '"'
    95             print 'Either it does not exist or its syntax is wrong.'
    96             print 'Try "' + sys.argv[0].split('/')[-1] + \
    97                   ' -h" to print usage information'
    98             sys.exit(1)
    99 
    100     env_parameter = read_ecenv(c.ecmwfdatadir + 'python/ECMWF_ENV')
     85        print('Could not read CONTROL file "' + args.controlfile + '"')
     86        print('Either it does not exist or its syntax is wrong.')
     87        print('Try "' + sys.argv[0].split('/')[-1] + \
     88              ' -h" to print usage information')
     89        sys.exit(1)
     90
     91    env_parameter = read_ecenv(_config.PATH_ECMWF_ENV)
    10192    c.assign_args_to_control(args, env_parameter)
    10293    c.assign_envs_to_control(env_parameter)
    103     c.check_conditions()
     94    c.check_conditions(args.queue)
    10495
    10596    get_mars_data(c)
     
    137128        os.makedirs(c.inputdir)
    138129
    139     print "Retrieving EC data!"
    140     print "start date %s " % (c.start_date)
    141     print "end date %s " % (c.end_date)
     130    if c.request == 0 or c.request == 2:
     131        print("Retrieving EC data!")
     132    elif c.request == 1:
     133        print("Printing mars requests!")
     134
     135    print("start date %s " % (c.start_date))
     136    print("end date %s " % (c.end_date))
    142137
    143138    if ecapi:
     
    147142
    148143    c.ecapi = ecapi
    149     print 'ecapi: ', c.ecapi
     144    print('Using ECMWF WebAPI: ' + str(c.ecapi))
    150145
    151146    # basetime geht rückwärts
     
    192187
    193188    # --------------  flux data ------------------------------------------------
    194     print 'removing old flux content of ' + c.inputdir
    195     tobecleaned = UioFiles(c.inputdir,
    196                            '*_acc_*.' + str(os.getppid()) + '.*.grb')
    197     tobecleaned.delete_files()
     189    if c.request == 0 or c.request == 2:
     190        print('... removing old flux content of ' + c.inputdir)
     191        tobecleaned = UioFiles(c.inputdir,
     192                               '*_acc_*.' + str(os.getppid()) + '.*.grb')
     193        tobecleaned.delete_files()
    198194
    199195    # if forecast for maximum one day (upto 24h) are to be retrieved,
     
    213209
    214210    # --------------  non flux data --------------------------------------------
    215     print 'removing old non flux content of ' + c.inputdir
    216     tobecleaned = UioFiles(c.inputdir,
    217                            '*__*.' + str(os.getppid()) + '.*.grb')
    218     tobecleaned.delete_files()
     211    if c.request == 0 or c.request == 2:
     212        print('... removing old non flux content of ' + c.inputdir)
     213        tobecleaned = UioFiles(c.inputdir,
     214                               '*__*.' + str(os.getppid()) + '.*.grb')
     215        tobecleaned.delete_files()
    219216
    220217    do_retrievement(c, server, start, end, datechunk, fluxes=False)
     
    280277                    end.strftime("%Y%m%d")
    281278
    282         print "retrieve " + dates + " in dir " + c.inputdir
     279        print("... retrieve " + dates + " in dir " + c.inputdir)
    283280
    284281        try:
    285             flexpart.retrieve(server, dates, c.inputdir)
     282            flexpart.retrieve(server, dates, c.request, c.inputdir)
    286283        except IOError:
    287284            my_error(c.mailfail, 'MARS request failed')
  • python/install.py

    r222aa11 r2fb99de  
    1212#        - added documentation
    1313#        - moved install_args_and_control in here
     14#        - splitted code in smaller functions
     15#        - delete convert build files in here instead of compile job script
     16#        - changed static path names to Variables from config file
    1417#
    1518# @License:
     
    3437#    - install_via_gateway
    3538#    - mk_tarball
     39#    - un_tarball
    3640#    - mk_env_vars
    3741#    - mk_compilejob
     
    4751import os
    4852import sys
     53import glob
    4954import subprocess
    5055import inspect
     
    5257
    5358# software specific classes and modules from flex_extract
     59import _config
    5460from ControlFile import ControlFile
    5561from UioFiles import UioFiles
    5662from tools import make_dir, put_file_to_ecserver, submit_job_to_ecserver
    57 
    58 # add path to pythonpath so that python finds its buddies
    59 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath(
    60     inspect.getfile(inspect.currentframe())))
    61 if LOCAL_PYTHON_PATH not in sys.path:
    62     sys.path.append(LOCAL_PYTHON_PATH)
    63 
    64 _VERSION_STR = '7.1'
    6563
    6664# ------------------------------------------------------------------------------
     
    8078    '''
    8179
    82     os.chdir(LOCAL_PYTHON_PATH)
     80    #os.chdir(_config.PATH_LOCAL_PYTHON)
     81
    8382    args = get_install_cmdline_arguments()
    8483
     
    8685        c = ControlFile(args.controlfile)
    8786    except IOError:
    88         print 'Could not read CONTROL file "' + args.controlfile + '"'
    89         print 'Either it does not exist or its syntax is wrong.'
    90         print 'Try "' + sys.argv[0].split('/')[-1] + \
    91               ' -h" to print usage information'
     87        print('Could not read CONTROL file "' + args.controlfile + '"')
     88        print('Either it does not exist or its syntax is wrong.')
     89        print('Try "' + sys.argv[0].split('/')[-1] +
     90              ' -h" to print usage information')
    9291        exit(1)
    9392
     
    134133                        servers (to find grib2flexpart and COMMAND file)\n\
    135134                        Normally flex_extract resides in the scripts directory \
    136                         of the FLEXPART distribution, thus the:")
     135                        of the FLEXPART distribution.")
    137136
    138137    # arguments for job submission to ECMWF, only needed by submit.py
     
    171170        <nothing>
    172171    '''
    173 
    174     ecd = c.ecmwfdatadir
    175     tarball_name = 'flex_extract_v' + _VERSION_STR + '.tar'
    176     target_dir = 'flex_extract_v' + _VERSION_STR
    177     fortran_executable = 'CONVERT2'
     172    import tarfile
     173
     174    ecd = _config.PATH_FLEXEXTRACT_DIR
     175    tarball_name = _config.FLEXEXTRACT_DIRNAME + '.tar'
     176    tar_file = os.path.join(ecd, tarball_name)
     177
     178    target_dirname = _config.FLEXEXTRACT_DIRNAME
     179    fortran_executable = _config.FORTRAN_EXECUTABLE
    178180
    179181    if c.install_target.lower() != 'local': # ecgate or cca
    180182
    181         mk_compilejob(ecd + 'python/compilejob.temp', c.makefile,
    182                       c.install_target, c.ecuid, c.ecgid,
     183        mk_compilejob(c.makefile, c.install_target, c.ecuid, c.ecgid,
    183184                      c.flexpart_root_scripts)
    184185
    185         mk_job_template(ecd + 'python/job.temp.o', c.ecuid, c.ecgid, c.gateway,
     186        mk_job_template(c.ecuid, c.ecgid, c.gateway,
    186187                        c.destination, c.flexpart_root_scripts)
    187188
    188         mk_env_vars(ecd, c.ecuid, c.ecgid, c.gateway, c.destination)
    189 
    190         #os.chdir('/')
    191 
    192         mk_tarball(ecd, tarball_name)
     189        mk_env_vars(c.ecuid, c.ecgid, c.gateway, c.destination)
     190
     191        mk_tarball(tar_file)
    193192
    194193        put_file_to_ecserver(ecd, tarball_name, c.install_target,
    195194                             c.ecuid, c.ecgid)
    196195
    197         submit_job_to_ecserver(ecd + '/python/', c.install_target,
    198                                'compilejob.ksh')
    199 
    200         print 'job compilation script has been submitted to ecgate for ' + \
    201               'installation in ' + c.flexpart_root_scripts + \
    202                '/' + target_dir
    203         print 'You should get an email with subject "flexcompile" within ' + \
    204               'the next few minutes!'
     196        submit_job_to_ecserver(c.install_target,
     197                               os.path.join(_config.PATH_RELATIVE_JOBSCRIPTS,
     198                                            _config.FILE_INSTALL_COMPILEJOB))
     199
     200        print('job compilation script has been submitted to ecgate for ' +
     201              'installation in ' + c.flexpart_root_scripts +
     202               '/' + target_dirname)
     203        print('You should get an email with subject "flexcompile" within ' +
     204              'the next few minutes!')
    205205
    206206    else: #local
    207         if not c.flexpart_root_scripts or c.flexpart_root_scripts == '../':
    208             print 'WARNING: FLEXPART_ROOT_SCRIPTS has not been specified'
    209             print 'There will be only the compilation of ' + \
    210                   ' in ' + ecd + '/src'
    211             os.chdir(ecd + '/src')
     207        if c.flexpart_root_scripts == _config.PATH_FLEXEXTRACT_DIR :
     208            print('WARNING: FLEXPART_ROOT_SCRIPTS has not been specified')
     209            print('flex_extract will be installed in here by compiling the ' +
     210                  'Fortran source in ' + _config.PATH_FORTRAN_SRC)
     211            os.chdir(_config.PATH_FORTRAN_SRC)
    212212        else: # creates the target working directory for flex_extract
    213213            c.flexpart_root_scripts = os.path.expandvars(os.path.expanduser(
    214                 c.flexpart_root_scripts))
     214                                        c.flexpart_root_scripts))
    215215            if os.path.abspath(ecd) != os.path.abspath(c.flexpart_root_scripts):
    216                 os.chdir('/')
    217                 mk_tarball(ecd, tarball_name)
    218                 make_dir(c.flexpart_root_scripts + '/' + target_dir)
    219                 os.chdir(c.flexpart_root_scripts + '/' + target_dir)
    220                 print 'Untar ...'
    221                 subprocess.check_call(['tar', '-xvf',
    222                                        ecd + '../' + tarball_name])
    223                 os.chdir(c.flexpart_root_scripts + '/' + target_dir + '/src')
     216                mk_tarball(tar_file)
     217                make_dir(os.path.join(c.flexpart_root_scripts,
     218                                      target_dirname))
     219                os.chdir(os.path.join(c.flexpart_root_scripts,
     220                                      target_dirname))
     221                un_tarball(tar_file)
     222                os.chdir(os.path.join(c.flexpart_root_scripts,
     223                                      target_dirname,
     224                                      _config.PATH_RELATIVE_FORTRAN_SRC))
    224225
    225226        # Create Fortran executable - CONVERT2
    226         print 'Install ' + target_dir + ' software on ' + \
    227               c.install_target + ' in directory ' + \
    228               os.path.abspath(os.getcwd() + '/../') + '\n'
    229 
    230         delete_convert_build('')
    231         make_convert_build('', c.makefile, fortran_executable)
    232 
    233     return
    234 
    235 def mk_tarball(ecd, tarname):
    236     '''
    237     @Description:
    238         Creates a tarball from all files which need to be sent to the
     227        print('Install ' + target_dirname + ' software at ' +
     228              c.install_target + ' in directory ' +
     229              os.path.abspath(c.flexpart_root_scripts) + '\n')
     230
     231        delete_convert_build('.')
     232        make_convert_build('.', c.makefile)
     233
     234        os.chdir(ecd)
     235        if os.path.isfile(tar_file):
     236            os.remove(tar_file)
     237
     238    return
     239
     240def mk_tarball(tarball_path):
     241    '''
     242    @Description:
     243        Creates a tarball with all necessary files which need to be sent to the
    239244        installation directory.
    240245        It does not matter if this is local or remote.
    241246        Collects all python files, the Fortran source and makefiles,
    242         the ECMWF_ENV file, the CONTROL files as well as
    243         the korn shell and template files.
    244 
    245     @Input:
    246         ecd: string
    247             The path were the file is to be stored.
    248 
    249         tarname: string
    250             The name of the file to send to the ECMWF server.
    251 
    252     @Return:
    253         <nothing>
    254     '''
    255 
    256     print 'Create tarball ...'
     247        the ECMWF_ENV file, the CONTROL files as well as the
     248        template files.
     249
     250    @Input:
     251        tarball_path: string
     252            The complete path to the tar file which will contain all
     253            relevant data for flex_extract.
     254
     255    @Return:
     256        <nothing>
     257    '''
     258    import tarfile
     259    from glob import glob
     260
     261    print('Create tarball ...')
     262
     263    # change to FLEXEXTRACT directory so that the tar can contain
     264    # relative pathes to the files and directories
     265    ecd = _config.PATH_FLEXEXTRACT_DIR + '/'
     266    os.chdir(ecd)
     267
     268    # get lists of the files to be added to the tar file
     269    ECMWF_ENV_FILE = [_config.PATH_RELATIVE_ECMWF_ENV]
     270    pyfiles = [os.path.relpath(x, ecd)
     271               for x in glob(_config.PATH_LOCAL_PYTHON +
     272                             os.path.sep + '*py')]
     273    controlfiles = [os.path.relpath(x, ecd)
     274                    for x in glob(_config.PATH_CONTROLFILES +
     275                                  os.path.sep + 'CONTROL*')]
     276    tempfiles = [os.path.relpath(x, ecd)
     277                 for x in glob(_config.PATH_TEMPLATES +
     278                               os.path.sep + '*')]
     279    ffiles = [os.path.relpath(x, ecd)
     280              for x in glob(_config.PATH_FORTRAN_SRC +
     281                            os.path.sep + '*.f*')]
     282    hfiles = [os.path.relpath(x, ecd)
     283              for x in glob(_config.PATH_FORTRAN_SRC +
     284                            os.path.sep + '*.h')]
     285    makefiles = [os.path.relpath(x, ecd)
     286                 for x in glob(_config.PATH_FORTRAN_SRC +
     287                               os.path.sep + 'Makefile*')]
     288
     289    # concatenate single lists to one for a better looping
     290    filelist = pyfiles + controlfiles + tempfiles + ffiles + hfiles + \
     291               makefiles + ECMWF_ENV_FILE
     292
     293    # create installation tar-file
    257294    try:
    258         subprocess.check_call(['tar -cvf '+
    259                                ecd + '../' + tarname + ' ' +
    260                                ecd + 'python/*py ' +
    261                                ecd + 'python/CONTROL* ' +
    262                                ecd + 'python/*ksh ' +
    263                                ecd + 'python/*temp* ' +
    264                                ecd + 'python/ECMWF_ENV ' +
    265                                ecd + '_templates ' +
    266                                ecd + 'src/*.f ' +
    267                                ecd + 'src/*.f90 ' +
    268                                ecd + 'src/*.h ' +
    269                                ecd + 'src/Makefile*'], shell=True)
     295        with tarfile.open(tarball_path, "w:gz") as tar_handle:
     296            for file in filelist:
     297                tar_handle.add(file)
     298
    270299    except subprocess.CalledProcessError as e:
    271         print 'ERROR:'
    272         print e.output
    273         sys.exit('could not make installation tar ball!')
    274 
    275     return
    276 
    277 def mk_env_vars(ecd, ecuid, ecgid, gateway, destination):
     300        print('... ERROR CODE:\n ... ' + str(e.returncode))
     301        print('... ERROR MESSAGE:\n ... ' + str(e))
     302
     303        sys.exit('... could not make installation tar ball!')
     304
     305    return
     306
     307
     308def un_tarball(tarball_path):
     309    '''
     310    @Description:
     311        Extracts the given tarball into current directory.
     312
     313    @Input:
     314        tarball_path: string
     315            The complete path to the tar file which will contain all
     316            relevant data for flex_extract.
     317
     318    @Return:
     319        <nothing>
     320    '''
     321    import tarfile
     322
     323    print('Untar ...')
     324
     325    with tarfile.open(tarball_path) as tar_handle:
     326        tar_handle.extractall()
     327
     328    return
     329
     330def mk_env_vars(ecuid, ecgid, gateway, destination):
    278331    '''
    279332    @Description:
     
    282335
    283336    @Input:
    284         ecd: string
    285             The path were the file is to be stored.
    286 
    287337        ecuid: string
    288338            The user id on ECMWF server.
     
    302352    '''
    303353
    304     with open(ecd + 'python/ECMWF_ENV', 'w') as fo:
     354    with open(_config.PATH_RELATIVE_ECMWF_ENV, 'w') as fo:
    305355        fo.write('ECUID ' + ecuid + '\n')
    306356        fo.write('ECGID ' + ecgid + '\n')
     
    310360    return
    311361
    312 def mk_compilejob(template, makefile, target, ecuid, ecgid, fp_root):
     362def mk_compilejob(makefile, target, ecuid, ecgid, fp_root):
    313363    '''
    314364    @Description:
     
    318368
    319369    @Input:
    320         template: string
    321             File which contains the original text for the job template.
    322             It must contain the complete path to the file.
    323 
    324370        makefile: string
    325371            Name of the makefile which should be used to compile FORTRAN
     
    343389    '''
    344390
     391    template = os.path.join(_config.PATH_RELATIVE_TEMPLATES,
     392                            _config.TEMPFILE_INSTALL_COMPILEJOB)
    345393    with open(template) as f:
    346394        fdata = f.read().split('\n')
    347395
    348     with open(template[:-4] + 'ksh', 'w') as fo:
     396    compilejob = os.path.join(_config.PATH_RELATIVE_JOBSCRIPTS,
     397                              _config.FILE_INSTALL_COMPILEJOB)
     398    with open(compilejob, 'w') as fo:
    349399        for data in fdata:
    350400            if 'MAKEFILE=' in data:
     
    371421    return
    372422
    373 def mk_job_template(template, ecuid, ecgid, gateway, destination, fp_root):
     423def mk_job_template(ecuid, ecgid, gateway, destination, fp_root):
    374424    '''
    375425    @Description:
    376426        Modifies the original job template file so that it is specified
    377427        for the user and the environment were it will be applied. Result
    378         is stored in a new file "job.temp" in the python directory.
    379 
    380     @Input:
    381         template: string
    382             File which contains the original text for the job template.
    383             It must contain the complete path to the file.
    384 
     428        is stored in a new file.
     429
     430    @Input:
    385431        ecuid: string
    386432            The user id on ECMWF server.
     
    403449        <nothing>
    404450    '''
    405 
     451    fp_root_path_to_python = os.path.join(fp_root, _config.FLEXEXTRACT_DIRNAME,
     452                         _config.PATH_RELATIVE_PYTHON)
     453
     454    template = os.path.join(_config.PATH_RELATIVE_TEMPLATES,
     455                            _config.TEMPFILE_INSTALL_JOB)
    406456    with open(template) as f:
    407457        fdata = f.read().split('\n')
    408458
    409     with open(template[:-2], 'w') as fo:
     459    jobfile_temp = os.path.join(_config.PATH_RELATIVE_TEMPLATES,
     460                                _config.TEMPFILE_JOB)
     461    with open(jobfile_temp, 'w') as fo:
    410462        for data in fdata:
    411463            if '--workdir' in data:
    412                 data = '#SBATCH --workdir=/scratch/ms/' + ecgid + \
    413                         '/' + ecuid
     464                data = '#SBATCH --workdir=/scratch/ms/' + ecgid + '/' + ecuid
    414465            elif '##PBS -o' in data:
    415466                data = '##PBS -o /scratch/ms/' + ecgid + '/' + \
    416467                        ecuid + 'flex_ecmwf.$Jobname.$Job_ID.out'
    417468            elif  'export PATH=${PATH}:' in data:
    418                 data += fp_root + '/flex_extract_v7.1/python'
     469                data += fp_root_path_to_python
    419470
    420471            fo.write(data + '\n')
    421472    return
    422473
    423 def delete_convert_build(ecd):
     474def delete_convert_build(src_path):
    424475    '''
    425476    @Description:
     
    428479
    429480    @Input:
    430         ecd: string
    431             The path to the Fortran program.
    432 
    433     @Return:
    434         <nothing>
    435     '''
    436 
    437     modfiles = UioFiles(ecd, '*.mod')
    438     objfiles = UioFiles(ecd, '*.o')
    439     exefile = UioFiles(ecd, 'CONVERT2')
     481        src_path: string
     482            Path to the fortran source directory.
     483
     484    @Return:
     485        <nothing>
     486    '''
     487
     488    modfiles = UioFiles(src_path, '*.mod')
     489    objfiles = UioFiles(src_path, '*.o')
     490    exefile = UioFiles(src_path, _config.FORTRAN_EXECUTABLE)
    440491
    441492    modfiles.delete_files()
     
    445496    return
    446497
    447 def make_convert_build(ecd, makefile, f_executable):
     498def make_convert_build(src_path, makefile):
    448499    '''
    449500    @Description:
     
    451502
    452503    @Input:
    453         ecd: string
    454             The path were the file is to be stored.
     504        src_path: string
     505            Path to the fortran source directory.
    455506
    456507        makefile: string
    457508            The name of the makefile which should be used.
    458509
    459         f_executable: string
    460             The name of the executable the Fortran program generates after
    461             compilation.
    462 
    463510    @Return:
    464511        <nothing>
     
    466513
    467514    try:
    468         print 'Using makefile: ' + makefile
    469         p = subprocess.Popen(['make', '-f', ecd + makefile],
     515        print('Using makefile: ' + makefile)
     516        p = subprocess.Popen(['make', '-f',
     517                              os.path.join(src_path, makefile)],
    470518                             stdin=subprocess.PIPE,
    471519                             stdout=subprocess.PIPE,
     
    473521                             bufsize=1)
    474522        pout, perr = p.communicate()
    475         print pout
     523        print(pout)
    476524        if p.returncode != 0:
    477             print perr
    478             print 'Please edit ' + makefile + \
    479                   ' or try another Makefile in the src directory.'
    480             print 'Most likely GRIB_API_INCLUDE_DIR, GRIB_API_LIB ' \
    481                   'and EMOSLIB must be adapted.'
    482             print 'Available Makefiles:'
    483             print UioFiles('.', 'Makefile*')
     525            print(perr)
     526            print('Please edit ' + makefile +
     527                  ' or try another Makefile in the src directory.')
     528            print('Most likely GRIB_API_INCLUDE_DIR, GRIB_API_LIB '
     529                  'and EMOSLIB must be adapted.')
     530            print('Available Makefiles:')
     531            print(UioFiles(src_path, 'Makefile*'))
    484532            sys.exit('Compilation failed!')
    485533    except ValueError as e:
    486         print 'ERROR: Makefile call failed:'
    487         print e
     534        print('ERROR: Makefile call failed:')
     535        print(e)
    488536    else:
    489         subprocess.check_call(['ls', '-l', ecd + f_executable])
     537        subprocess.check_call(['ls', '-l',
     538                               os.path.join(src_path,
     539                                            _config.FORTRAN_EXECUTABLE)])
    490540
    491541    return
  • python/prepare_flexpart.py

    r54a8a01 r2fb99de  
    5757import sys
    5858import socket
    59 import _config
    6059
    6160# software specific classes and modules from flex_extract
     61import _config
    6262from UioFiles import UioFiles
    6363from tools import clean_up, get_cmdline_arguments, read_ecenv
     
    7070except ImportError:
    7171    ecapi = False
    72 
    73 # add path to pythonpath so that python finds its buddies
    74 LOCAL_PYTHON_PATH = os.path.dirname(os.path.abspath(
    75     inspect.getfile(inspect.currentframe())))
    76 if LOCAL_PYTHON_PATH not in sys.path:
    77     sys.path.append(LOCAL_PYTHON_PATH)
    78 
    7972
    8073# ------------------------------------------------------------------------------
     
    10093        c = ControlFile(args.controlfile)
    10194    except IOError:
    102         try:
    103             c = ControlFile(LOCAL_PYTHON_PATH + args.controlfile)
    104         except IOError:
    105             print 'Could not read CONTROL file "' + args.controlfile + '"'
    106             print 'Either it does not exist or its syntax is wrong.'
    107             print 'Try "' + sys.argv[0].split('/')[-1] + \
    108                   ' -h" to print usage information'
    109             sys.exit(1)
     95        print('Could not read CONTROL file "' + args.controlfile + '"')
     96        print('Either it does not exist or its syntax is wrong.')
     97        print('Try "' + sys.argv[0].split('/')[-1] + \
     98              ' -h" to print usage information')
     99        sys.exit(1)
    110100
    111     env_parameter = read_ecenv(c.ecmwfdatadir + 'python/ECMWF_ENV')
     101    env_parameter = read_ecenv(_config.PATH_ECMWF_ENV)
    112102    c.assign_args_to_control(args, env_parameter)
    113103    c.assign_envs_to_control(env_parameter)
    114     c.check_conditions()
     104    c.check_conditions(args.queue)
    115105    prepare_flexpart(args.ppid, c)
    116106
     
    170160        start = start - datetime.timedelta(days=1)
    171161
    172     print 'Prepare ' + start.strftime("%Y%m%d") + \
    173            "/to/" + end.strftime("%Y%m%d")
     162    print('Prepare ' + start.strftime("%Y%m%d") +
     163           "/to/" + end.strftime("%Y%m%d"))
    174164
    175165    # create output dir if necessary
     
    182172    # deaccumulate the flux data
    183173    flexpart = EcFlexpart(c, fluxes=True)
    184     flexpart.write_namelist(c, 'fort.4')
     174    flexpart.write_namelist(c, _config.FILE_NAMELIST)
    185175    flexpart.deacc_fluxes(inputfiles, c)
    186176
     
    197187    # otherwise delete temporary files
    198188    if int(c.debug) != 0:
    199         print '\nTemporary files left intact'
     189        print('\nTemporary files left intact')
    200190    else:
    201191        clean_up(c)
  • python/profiling.py

    r54a8a01 r2fb99de  
    6666        result = fn(*args, **kwargs)
    6767        t2 = time.time()
    68         print "@timefn:" + fn.func_name + " took " + str(t2 - t1) + " seconds"
     68        print("@timefn:" + fn.func_name + " took " + str(t2 - t1) + " seconds")
    6969
    7070        return result
  • python/pythontest/TestInstall.py

    r067a0c3 r2fb99de  
    66import os
    77import inspect
    8 sys.path.append('../python')
     8sys.path.append('../')
     9import _config
    910import install
     11from tools import make_dir
    1012
    1113
     
    1719        pass
    1820
     21    #    - main
     22    #    - get_install_cmdline_arguments
     23    #    - install_via_gateway
     24    #!    - mk_tarball
     25    #!    - un_tarball
     26    #    - mk_env_vars
     27    #    - mk_compilejob
     28    #    - mk_job_template
     29    #    - delete_convert_build
     30    #    - make_convert_build
    1931
    2032    def test_mk_tarball(self):
    21         ecd = os.path.dirname(os.path.abspath(inspect.getfile(
    22             inspect.currentframe()))) + '/../'
    23         #print ecd
    24         install.mk_tarball(ecd)
     33        import tarfile
    2534
     35        ecd = _config.PATH_FLEXEXTRACT_DIR + os.path.sep
     36
     37        # list comparison files for tarball content
     38        tar_test_dir = os.path.join(_config.PATH_TEST_DIR +
     39                                    os.path.sep + 'TestInstallTar')
     40        tar_test_fedir = os.path.join(tar_test_dir, 'flex_extract_v7.1')
     41
     42        comparison_list = []
     43        for path, subdirs, files in os.walk(tar_test_fedir):
     44            for name in files:
     45                if 'tar' not in name:
     46                    comparison_list.append(os.path.relpath(os.path.join(path, name), tar_test_fedir))
     47
     48        # create test tarball and list its content files
     49        tarballname = _config.FLEXEXTRACT_DIRNAME + '_test.tar'
     50        install.mk_tarball(ecd + tarballname)
     51        with tarfile.open(ecd + tarballname, 'r') as tar_handle:
     52            tar_content_list = tar_handle.getnames()
     53
     54        # remove test tar file from flex_extract directory
     55        os.remove(ecd + tarballname)
     56
     57        # test if comparison filelist is equal to the
     58        # filelist of tarball content
     59        assert sorted(comparison_list) == sorted(tar_content_list)
     60
     61    def test_un_tarball(self):
     62        import tarfile
     63        import shutil
     64
     65        ecd = _config.PATH_FLEXEXTRACT_DIR + os.path.sep
     66
     67        # list comparison files for tarball content
     68        tar_test_dir = os.path.join(_config.PATH_TEST_DIR +
     69                                        os.path.sep + 'TestInstallTar')
     70        tar_test_fedir = os.path.join(tar_test_dir, 'flex_extract_v7.1')
     71        comparison_list = []
     72        for path, subdirs, files in os.walk(tar_test_fedir):
     73            for name in files:
     74                if 'tar' not in name:
     75                    comparison_list.append(os.path.relpath(os.path.join(path, name), tar_test_fedir))
     76
     77        # untar in test directory
     78        test_dir = os.path.join(tar_test_dir, 'test_untar')
     79        make_dir(test_dir)
     80        os.chdir(test_dir)
     81        tarballname = _config.FLEXEXTRACT_DIRNAME + '.tar'
     82        install.un_tarball(os.path.join(tar_test_dir, tarballname))
     83        tarfiles_list = []
     84        for path, subdirs, files in os.walk(test_dir):
     85            for name in files:
     86                tarfiles_list.append(os.path.relpath(os.path.join(path, name), test_dir))
     87
     88        # test for equality
     89        assert sorted(tarfiles_list) == sorted(comparison_list)
     90
     91        # clean up temp test dir
     92        shutil.rmtree(test_dir)
    2693
    2794
  • python/submit.py

    r222aa11 r2fb99de  
    1616#        - added documentation
    1717#        - minor changes in programming style (for consistence)
     18#        - changed path names to variables from config file
     19#        - added option for writing mars requests to extra file
     20#          additionally,as option without submitting the mars jobs
    1821#
    1922# @License:
     
    7376    '''
    7477
    75     called_from_dir = os.getcwd()
    76 
    7778    args = get_cmdline_arguments()
    7879
     
    8081        c = ControlFile(args.controlfile)
    8182    except IOError:
    82         try:
    83             c = ControlFile(_config.PATH_LOCAL_PYTHON + args.controlfile)
    84         except IOError:
    85             print 'Could not read CONTROL file "' + args.controlfile + '"'
    86             print 'Either it does not exist or its syntax is wrong.'
    87             print 'Try "' + sys.argv[0].split('/')[-1] + \
    88                   ' -h" to print usage information'
    89             sys.exit(1)
    90 
    91     env_parameter = read_ecenv(c.ecmwfdatadir + 'python/ECMWF_ENV')
     83        print('Could not read CONTROL file "' + args.controlfile + '"')
     84        print('Either it does not exist or its syntax is wrong.')
     85        print('Try "' + sys.argv[0].split('/')[-1] + \
     86              ' -h" to print usage information')
     87        sys.exit(1)
     88
     89    env_parameter = read_ecenv(_config.PATH_ECMWF_ENV)
    9290    c.assign_args_to_control(args)
    9391    c.assign_envs_to_control(env_parameter)
    94     c.check_conditions()
     92    c.check_conditions(args.queue)
    9593
    9694    # on local side
    97     # on ECMWF server this would be the local side
     95    # on ECMWF server this would also be the local side
     96    called_from_dir = os.getcwd()
    9897    if args.queue is None:
    9998        if c.inputdir[0] != '/':
     
    102101            c.outputdir = os.path.join(called_from_dir, c.outputdir)
    103102        get_mars_data(c)
    104         prepare_flexpart(args.ppid, c)
    105         normal_exit(c.mailfail, 'Done!')
    106     # on ECMWF server
     103        if c.request == 0 or c.request == 2:
     104            prepare_flexpart(args.ppid, c)
     105            normal_exit(c.mailfail, 'FLEX_EXTRACT IS DONE!')
     106        else:
     107            normal_exit(c.mailfail, 'PRINTING MARS_REQUESTS DONE!')
     108    # send files to ECMWF server and install there
    107109    else:
    108110        submit(args.job_template, c, args.queue)
     
    117119    @Input:
    118120        jtemplate: string
    119             Job template file for submission to ECMWF. It contains all necessary
     121            Job template file from sub-directory "_templates" for
     122            submission to ECMWF. It contains all necessary
    120123            module and variable settings for the ECMWF environment as well as
    121124            the job call and mail report instructions.
     
    143146
    144147    # read template file and get index for CONTROL input
    145     with open(jtemplate) as f:
     148    with open(os.path.join(_config.PATH_TEMPLATES, jtemplate)) as f:
    146149        lftext = f.read().split('\n')
    147150    insert_point = lftext.index('EOF')
     
    150153    # --------- create on demand job script ------------------------------------
    151154        if c.maxstep > 24:
    152             print '---- Pure forecast mode! ----'
     155            print('---- Pure forecast mode! ----')
    153156        else:
    154             print '---- On-demand mode! ----'
    155         job_file = jtemplate[:-4] + 'ksh'
     157            print('---- On-demand mode! ----')
     158        job_file = os.path.join(_config.PATH_JOBSCRIPTS,
     159                                jtemplate[:-4] + 'ksh')
    156160        clist = c.to_list()
    157161
     
    161165            f.write('\n'.join(lftextondemand))
    162166
    163         result_code = submit_job_to_ecserver(queue, job_file)
     167        submit_job_to_ecserver(queue, job_file)
    164168
    165169    else:
    166170    # --------- create operational job script ----------------------------------
    167         print '---- Operational mode! ----'
    168         job_file = jtemplate[:-5] + 'oper.ksh'
    169         #colist = []
     171        print('---- Operational mode! ----')
     172        job_file = os.path.join(_config.PATH_JOBSCRIPTS,
     173                                jtemplate[:-5] + 'oper.ksh')
    170174
    171175        if c.maxstep:
     
    187191            f.write('\n'.join(lftextoper))
    188192
    189         result_code = submit_job_to_ecserver(queue, job_file)
     193        submit_job_to_ecserver(queue, job_file)
    190194
    191195    # --------------------------------------------------------------------------
    192     print 'You should get an email with subject flex.hostname.pid'
     196    print('You should get an email with subject flex.hostname.pid')
    193197
    194198    return
  • python/tools.py

    refa05d7 r2fb99de  
    124124    parser.add_argument("--debug", dest="debug", default=None,
    125125                        help="debug mode - leave temporary files intact")
     126    parser.add_argument("--request", dest="request", default=None,
     127                        help="list all mars request in file mars_requests.dat \
     128                        and skip submission to mars")
    126129
    127130    args = parser.parse_args()
     
    137140    @Input:
    138141        filename: string
    139             Name of file where the ECMWV environment parameters are stored.
     142            Path to file where the ECMWV environment parameters are stored.
    140143
    141144    @Return:
    142145        envs: dict
     146            Contains the environment parameter ecuid, ecgid, gateway
     147            and destination for ECMWF server environments.
    143148    '''
    144149    envs= {}
    145     print filename
     150
    146151    with open(filename, 'r') as f:
    147152        for line in f:
     
    175180    '''
    176181
    177     print "clean_up"
     182    print("clean_up")
    178183
    179184    cleanlist = glob.glob(c.inputdir + "/*")
     
    184189            silent_remove(clist)
    185190
    186     print "Done"
     191    print("Done")
    187192
    188193    return
     
    208213    '''
    209214
    210     print message
     215    print(message)
    211216
    212217    # comment if user does not want email notification directly from python
     
    224229            pout = p.communicate(input=message + '\n\n' + trace)[0]
    225230        except ValueError as e:
    226             print 'ERROR: ', e
     231            print('ERROR: ', e)
    227232            sys.exit('Email could not be sent!')
    228233        else:
    229             print 'Email sent to ' + os.path.expandvars(user) + ' ' + \
    230                   pout.decode()
     234            print('Email sent to ' + os.path.expandvars(user) + ' ' +
     235                  pout.decode())
    231236
    232237    sys.exit(1)
     
    253258
    254259    '''
    255     print message
     260    print(message)
    256261
    257262    # comment if user does not want notification directly from python
     
    268273            pout = p.communicate(input=message+'\n\n')[0]
    269274        except ValueError as e:
    270             print 'ERROR: ', e
    271             print 'Email could not be sent!'
     275            print('ERROR: ', e)
     276            print('Email could not be sent!')
    272277        else:
    273             print 'Email sent to ' + os.path.expandvars(user) + ' ' + \
    274                   pout.decode()
     278            print('Email sent to ' + os.path.expandvars(user) + ' ' +
     279                  pout.decode())
    275280
    276281    return
     
    392397                break
    393398        else:
    394             print 'Warning: par ' + par + ' not found in table 128'
     399            print('Warning: par ' + par + ' not found in table 128')
    395400
    396401    return ipar
     
    438443            raise # re-raise exception if a different error occured
    439444        else:
    440             print 'WARNING: Directory {0} already exists!'.format(directory)
     445            print('WARNING: Directory {0} already exists!'.format(directory))
    441446
    442447    return
     
    482487                                         stderr=subprocess.STDOUT)
    483488    except subprocess.CalledProcessError as e:
    484         print '... ERROR CODE:\n ... ', e.returncode
    485         print '... ERROR MESSAGE:\n ... ', e
    486         print '... COMMAND MESSAGE:\n ...', e.output
    487 
    488         print '\nDo you have a valid eccert key?'
     489        print('... ERROR CODE:\n ... ' + str(e.returncode))
     490        print('... ERROR MESSAGE:\n ... ' + str(e))
     491
     492        print('\n... Do you have a valid ecaccess certification key?')
    489493        sys.exit('... ECACCESS-FILE-PUT FAILED!')
    490494
     
    520524                                         jobname])
    521525    except subprocess.CalledProcessError as e:
    522         print '... ERROR CODE: ', e.returncode
    523         print '... ERROR MESSAGE:\n ... ', e
    524         print '... COMMAND MESSAGE:\n ...', e.output
    525 
    526         print '\nDo you have a valid eccert key?'
     526        print('... ERROR CODE:\n ... ' + str(e.returncode))
     527        print('... ERROR MESSAGE:\n ... ' + str(e))
     528
     529
     530        print('\n... Do you have a valid ecaccess certification key?')
    527531        sys.exit('... ECACCESS-JOB-SUBMIT FAILED!')
    528532
Note: See TracChangeset for help on using the changeset viewer.
hosted by ZAMG