casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
rmtables_cli.py
Go to the documentation of this file.
00001 #
00002 # This file was generated using xslt from its XML file
00003 #
00004 # Copyright 2008, Associated Universities Inc., Washington DC
00005 #
00006 import sys
00007 import os
00008 #from casac import *
00009 import casac
00010 import string
00011 import time
00012 import inspect
00013 import gc
00014 import numpy
00015 from odict import odict
00016 from taskmanager import tm
00017 from task_rmtables import rmtables
00018 class rmtables_cli_:
00019     __name__ = "rmtables"
00020     __async__ = {}
00021     rkey = None
00022     i_am_a_casapy_task = None
00023     # The existence of the i_am_a_casapy_task attribute allows help()
00024     # (and other) to treat casapy tasks as a special case.
00025 
00026     def __init__(self) :
00027        self.__bases__ = (rmtables_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'tablenames':None,  'async':None}
00031 
00032 
00033     def result(self, key=None):
00034             #### here we will scan the task-ids in __async__
00035             #### and add any that have completed...
00036             if key is not None and self.__async__.has_key(key) and self.__async__[key] is not None:
00037                ret = tm.retrieve(self.__async__[key])
00038                if ret['state'] == "done" :
00039                   self.__async__[key] = None
00040                elif ret['state'] == 'crashed' :
00041                   self.__async__[key] = None
00042                return ret
00043             return None
00044 
00045 
00046     def __call__(self, tablenames=None,  async=None):
00047 
00048         """
00049         Removes tables cleanly.
00050         Arguments may contain * or ?. Ranges [] are support but
00051         not ~ expansion.
00052  
00053         """
00054         if not hasattr(self, "__globals__") or self.__globals__ == None :
00055            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00056         #casac = self.__globals__['casac']
00057         casalog = self.__globals__['casalog']
00058         #casalog = casac.casac.logsink()
00059         self.__globals__['__last_task'] = 'rmtables'
00060         self.__globals__['taskname'] = 'rmtables'
00061         ###
00062         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00063         ###
00064         ###
00065         #Handle globals or user over-ride of arguments
00066         #
00067         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00068         useLocalDefaults = False
00069 
00070         for item in function_signature_defaults.iteritems():
00071                 key,val = item
00072                 keyVal = eval(key)
00073                 if (keyVal == None):
00074                         #user hasn't set it - use global/default
00075                         pass
00076                 else:
00077                         #user has set it - use over-ride
00078                         if (key != 'self') :
00079                            useLocalDefaults = True
00080 
00081         myparams = {}
00082         if useLocalDefaults :
00083            for item in function_signature_defaults.iteritems():
00084                key,val = item
00085                keyVal = eval(key)
00086                exec('myparams[key] = keyVal')
00087                self.parameters[key] = keyVal
00088                if (keyVal == None):
00089                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00090                    keyVal = eval(key)
00091                    if(type(keyVal) == dict) :
00092                       if len(keyVal) > 0 :
00093                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00094                       else :
00095                          exec('myparams[key] = ' + key + ' = {}')
00096 
00097         else :
00098             async = self.parameters['async']
00099             myparams['tablenames'] = tablenames = self.parameters['tablenames']
00100 
00101         if type(tablenames)==str: tablenames=[tablenames]
00102 
00103         result = None
00104 
00105 #
00106 #    The following is work around to avoid a bug with current python translation
00107 #
00108         mytmp = {}
00109 
00110         mytmp['tablenames'] = tablenames
00111         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00112         trec = casac.casac.utils().torecord(pathname+'rmtables.xml')
00113 
00114         casalog.origin('rmtables')
00115         try :
00116           #if not trec.has_key('rmtables') or not casac.casac.utils().verify(mytmp, trec['rmtables']) :
00117             #return False
00118 
00119           casac.casac.utils().verify(mytmp, trec['rmtables'], True)
00120           scriptstr=['']
00121           saveinputs = self.__globals__['saveinputs']
00122           saveinputs('rmtables', 'rmtables.last', myparams, self.__globals__,scriptstr=scriptstr)
00123           if async :
00124             count = 0
00125             keybase =  time.strftime("%y%m%d.%H%M%S")
00126             key = keybase + "_" + str(count)
00127             while self.__async__.has_key(key) :
00128                count += 1
00129                key = keybase + "_" + str(count)
00130             result = tm.execute('rmtables', tablenames)
00131             print "Use: "
00132             print "      tm.retrieve(return_value) # to retrieve the status"
00133             print 
00134             self.rkey = key
00135             self.__async__[key] = result
00136           else :
00137               tname = 'rmtables'
00138               spaces = ' '*(18-len(tname))
00139               casalog.post('\n##########################################'+
00140                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00141               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00142               result = rmtables(tablenames)
00143               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00144                            '\n##########################################')
00145 
00146         except Exception, instance:
00147           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00148              raise
00149           else :
00150              #print '**** Error **** ',instance
00151              tname = 'rmtables'
00152              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00153              pass
00154 
00155         gc.collect()
00156         return result
00157 #
00158 #
00159 #
00160     def paramgui(self, useGlobals=True, ipython_globals=None):
00161         """
00162         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00163         """
00164         import paramgui
00165         if not hasattr(self, "__globals__") or self.__globals__ == None :
00166            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00167 
00168         if useGlobals:
00169             if ipython_globals == None:
00170                 myf=self.__globals__
00171             else:
00172                 myf=ipython_globals
00173 
00174             paramgui.setGlobals(myf)
00175         else:
00176             paramgui.setGlobals({})
00177 
00178         paramgui.runTask('rmtables', myf['_ip'])
00179         paramgui.setGlobals({})
00180 
00181 #
00182 #
00183 #
00184     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00185         if not hasattr(self, "__globals__") or self.__globals__ == None :
00186            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00187         if ipython_globals == None:
00188             myf=self.__globals__
00189         else:
00190             myf=ipython_globals
00191 
00192         a = odict()
00193         a['tablenames']  = ['']
00194 
00195         a['async']=False
00196 
00197 ### This function sets the default values but also will return the list of
00198 ### parameters or the default value of a given parameter
00199         if(param == None):
00200                 myf['__set_default_parameters'](a)
00201         elif(param == 'paramkeys'):
00202                 return a.keys()
00203         else:
00204             if(paramvalue==None and subparam==None):
00205                if(a.has_key(param)):
00206                   return a[param]
00207                else:
00208                   return self.itsdefault(param)
00209             else:
00210                retval=a[param]
00211                if(type(a[param])==dict):
00212                   for k in range(len(a[param])):
00213                      valornotval='value'
00214                      if(a[param][k].has_key('notvalue')):
00215                         valornotval='notvalue'
00216                      if((a[param][k][valornotval])==paramvalue):
00217                         retval=a[param][k].copy()
00218                         retval.pop(valornotval)
00219                         if(subparam != None):
00220                            if(retval.has_key(subparam)):
00221                               retval=retval[subparam]
00222                            else:
00223                               retval=self.itsdefault(subparam)
00224                      else:
00225                         retval=self.itsdefault(subparam)
00226                return retval
00227 
00228 
00229 #
00230 #
00231     def check_params(self, param=None, value=None, ipython_globals=None):
00232       if ipython_globals == None:
00233           myf=self.__globals__
00234       else:
00235           myf=ipython_globals
00236 #      print 'param:', param, 'value:', value
00237       try :
00238          if str(type(value)) != "<type 'instance'>" :
00239             value0 = value
00240             value = myf['cu'].expandparam(param, value)
00241             matchtype = False
00242             if(type(value) == numpy.ndarray):
00243                if(type(value) == type(value0)):
00244                   myf[param] = value.tolist()
00245                else:
00246                   #print 'value:', value, 'value0:', value0
00247                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00248                   myf[param] = value0
00249                   if type(value0) != list :
00250                      matchtype = True
00251             else :
00252                myf[param] = value
00253             value = myf['cu'].verifyparam({param:value})
00254             if matchtype:
00255                value = False
00256       except Exception, instance:
00257          #ignore the exception and just return it unchecked
00258          myf[param] = value
00259       return value
00260 #
00261 #
00262     def description(self, key='rmtables', subkey=None):
00263         desc={'rmtables': '',
00264                'tablenames': 'Name of the tables',
00265 
00266                'async': 'If true the taskname must be started using rmtables(...)'
00267               }
00268 
00269         if(desc.has_key(key)) :
00270            return desc[key]
00271 
00272     def itsdefault(self, paramname) :
00273         a = {}
00274         a['tablenames']  = ['']
00275 
00276         #a = sys._getframe(len(inspect.stack())-1).f_globals
00277 
00278         if a.has_key(paramname) :
00279               return a[paramname]
00280 rmtables_cli = rmtables_cli_()