casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
casapy.py
Go to the documentation of this file.
00001 import os
00002 if os.environ.has_key('LD_PRELOAD'):
00003     del os.environ['LD_PRELOAD']
00004 import sys
00005 import time
00006 import signal
00007 
00008 
00009 ##
00010 ## tweak path... where necessary...
00011 ##
00012 ## path_addition = [ ]
00013 ## for p in sys.path :
00014 ##     if p.startswith(sys.prefix):
00015 ##         # According to
00016 ##         # http://www.debian.org/doc/packaging-manuals/python-policy/ch-python.html
00017 ##         # "Python modules not handled by python-central or python-support must
00018 ##         # be installed in the system Python modules directory,
00019 ##         # /usr/lib/pythonX.Y/dist-packages for python2.6 and later, and
00020 ##         # /usr/lib/pythonX.Y/site-packages for python2.5 and earlier."
00021 ##         #
00022 ##         # I am not sure if this is general Python policy, or just Debian policy.
00023 ##         # In any case, dist-packages is a more honestly named site-packages, since
00024 ##         # nominally site stuff goes in /usr/local or /opt.
00025 ##         #
00026 ##         for wanted in ['lib-tk', 'dist-packages']:
00027 ##             newpath = p + os.sep + wanted
00028 ##             if os.path.isdir(newpath):
00029 ##                 path_addition.append(newpath)
00030 
00031 #sys.path = sys.path + path_addition
00032 
00033 # i.e. /usr/lib/pymodules/python2.6, needed for matplotlib in Debian and its derivatives.
00034 #pymodules_dir = sys.prefix + '/lib/pymodules/python' + '.'.join(map(str, sys.version_info[:2]))
00035 
00036 #if os.path.isdir(pymodules_dir) and pymodules_dir not in sys.path:
00037 #    sys.path.append(pymodules_dir)
00038 
00039 ##
00040 ## watchdog... which is *not* in the casapy process group
00041 ##
00042 if os.fork( ) == 0 :
00043     signal.signal(signal.SIGINT, signal.SIG_IGN)
00044     signal.signal(signal.SIGTERM, signal.SIG_IGN)
00045     signal.signal(signal.SIGHUP, signal.SIG_IGN)
00046     ## close standard input to avoid terminal interrupts
00047     sys.stdin.close( )
00048     sys.stdout.close( )
00049     sys.stderr.close( )
00050     os.close(0)
00051     os.close(1)
00052     os.close(2)
00053     ppid = os.getppid( )
00054     while True :
00055         try:
00056             os.kill(ppid,0)
00057         except:
00058             break
00059         time.sleep(3)
00060     os.killpg(ppid, signal.SIGTERM)
00061     time.sleep(6)
00062     os.killpg(ppid, signal.SIGKILL)
00063     sys.exit(1)
00064 
00065 ##
00066 ## ensure that we're the process group leader
00067 ## of all processes that we fork...
00068 ##
00069 try:
00070     os.setpgid(0,0)
00071 except OSError, e:
00072     print "setgpid( ) failed: " + e.strerror
00073     print "                   processes may be left dangling..."
00074 
00075 
00076 ##
00077 ## no one likes a bloated watchdog...
00078 ## ...do this after setting up the watchdog
00079 ##
00080 try:
00081     import casac 
00082 except ImportError, e:
00083     print "failed to load casa:\n", e
00084     sys.exit(1)
00085 
00086 try:
00087     import matplotlib
00088 except ImportError, e:
00089     print "failed to load matplotlib:\n", e
00090     print "sys.path =", "\n\t".join(sys.path)
00091     
00092 from asap_init import *
00093 
00094 
00095 homedir = os.getenv('HOME')
00096 if homedir == None :
00097    print "Environment variable HOME is not set, please set it"
00098    sys.exit(1)
00099 
00100 import casadef
00101 
00102 casa = { 'build': {
00103              'time': casadef.build_time,
00104              'version': casadef.casa_version,
00105              'number': casadef.subversion_revision
00106          },
00107          'source': {
00108              'url': casadef.subversion_url,
00109              'revision': casadef.subversion_revision
00110          },
00111          'helpers': {
00112              'logger': 'casalogger',
00113              'viewer': 'casaviewer',
00114              'info': None,
00115              'dbus': None,
00116              'ipcontroller': None,
00117              'ipengine': None
00118          },
00119          'dirs': {
00120              'rc': homedir + '/.casa',
00121              'data': None,
00122              'recipes': casadef.python_library_directory+'/recipes',
00123              'root': None
00124          },
00125          'flags': { },
00126          'files': { 
00127              'logfile': os.getcwd( ) + '/casapy-'+time.strftime("%Y%m%d-%H%M%S", time.gmtime())+'.log'
00128          },
00129          'state' : { 'startup': True }
00130        }
00131 
00132 
00133 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00134 ## set up casa root
00135 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00136 if os.environ.has_key('CASAPATH') :
00137     __casapath__ = os.environ['CASAPATH'].split(' ')[0]
00138     if not os.path.exists(__casapath__ + "/data") :
00139         raise RuntimeError, "Unable to find the data repository directory in your CASAPATH. Please fix."
00140     else :
00141         casa['dirs']['root'] = __casapath__
00142         casa['dirs']['data'] = __casapath__ + "/data"
00143 else :
00144     __casapath__ = casac.__file__
00145     while __casapath__ and __casapath__ != "/" :
00146         if os.path.exists( __casapath__ + "/data") :
00147             break
00148         __casapath__ = os.path.dirname(__casapath__)
00149     if not os.path.exists(__casapath__ + "/data") :
00150         raise RuntimeError, "casa path could not be determined"
00151     else :
00152         casa['dirs']['root'] = __casapath__
00153         casa['dirs']['data'] = __casapath__ + "/data"
00154 
00155 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00156 ## setup helper paths...
00157 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00158 ##
00159 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00160 ## try to set casapyinfo path...
00161 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00162 if os.path.exists( __casapath__ + "/bin/casapyinfo") :
00163     casa['helpers']['info'] = __casapath__ + "/bin/casapyinfo"
00164 
00165 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00166 ##     first try to find executables using casapyinfo...
00167 ##            (since system area versions may be incompatible)...
00168 ##     next try likely system areas...
00169 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00170 ##
00171 ##   note:  hosts which have dbus-daemon-1 but not dbus-daemon seem to have a broken dbus-daemon-1...
00172 ##
00173 for info in [ (['dbus-daemon'],'dbus'),
00174               (['ipcontroller','ipcontroller-2.6'], 'ipcontroller'),
00175               (['ipengine','ipengine-2.6'], 'ipengine') ]:
00176     exelist = info[0]
00177     entry = info[1]
00178     for exe in exelist:
00179         if casa['helpers']['info']:
00180             casa['helpers'][entry] = (lambda fd: fd.readline().strip('\n'))(os.popen(casa['helpers']['info'] + " --exec 'which " + exe + "'"))
00181         if casa['helpers'][entry] and os.path.exists(casa['helpers'][entry]):
00182             break
00183         else:
00184             casa['helpers'][entry] = None
00185 
00186         for dir in ['/bin', '/usr/bin', '/opt/local/bin', '/usr/lib/qt-4.3.4/dbus/bin', '/usr/lib64/qt-4.3.4/dbus/bin'] :
00187             dd = dir + os.sep + exe
00188             if os.path.exists(dd) and os.access(dd,os.X_OK) :
00189                 casa['helpers'][entry] = dd
00190                 break
00191         if casa['helpers'][entry] is not None:
00192             break
00193 
00194     ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00195     ##     next search through $PATH for executables
00196     ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00197     if casa['helpers'][entry] is None:
00198         for exe in exelist:
00199             for dir in os.getenv('PATH').split(':') :
00200                 dd = dir + os.sep + exe
00201                 if os.path.exists(dd) and os.access(dd,os.X_OK) :
00202                     casa['helpers'][entry] = dd
00203                     break
00204             if casa['helpers'][entry] is not None:
00205                 break
00206 
00207 print "CASA Version " + casa['build']['version'] + " (r" + casa['source']['revision'] + ")\n  Compiled on: " + casa['build']['time']
00208 
00209 a = [] + sys.argv             ## get a copy from goofy python
00210 a.reverse( )
00211 __ipython_colors = 'LightBG'
00212 while len(a) > 0:
00213     c = a.pop()
00214     if c == '--colors':
00215         ##
00216         ## strip out 2 element ipython flags (which we recognize) here...
00217         ##
00218         if len(a) == 0 :
00219             print "A option must be specified with " + c + "..."
00220             sys.exit(1)
00221         else:
00222             c = a.pop( )
00223             if c != 'NoColor' and c != 'Linux' and c != 'LightBG':
00224                 print "unrecognized option for '--color': " + c
00225                 sys.exit(1)
00226             else:
00227                 __ipython_colors = c
00228 
00229     elif c.startswith('--colors='):
00230         ##
00231         ## strip out single element ipython flags (which we recognize) here...
00232         ##
00233         c = c.split('=')[1]
00234         if c != 'NoColor' and c != 'Linux' and c != 'LightBG':
00235             print "unrecognized option for '--color': " + c
00236             sys.exit(1)
00237         else:
00238             __ipython_colors = c
00239         
00240     elif c == '--logfile' or c == '-c' or c == '--rcdir':
00241         ##
00242         ## we join multi-arg parameters here
00243         ##
00244         if len(a) == 0 :
00245             print "A file must be specified with " + c + "..."
00246             sys.exit(1)
00247         else :
00248             casa['flags'][c] = a.pop( )
00249             if c == '--rcdir':
00250                 casa['dirs']['rc'] = casa['flags'][c]
00251 
00252     elif c.find('=') > 0 :
00253         casa['flags'][c[0:c.find('=')]] = c[c.find('=')+1:]
00254 
00255     else :
00256         casa['flags'][c] = ''
00257 
00258 if casa['flags'].has_key('--logfile') :
00259     casa['files']['logfile'] = casa['flags']['--logfile']       ## user specifies a log file
00260 if casa['flags'].has_key('--nologfile') :
00261     casa['files'].pop('logfile')                                ## user indicates no log file
00262 
00263 if casa['flags'].has_key('--help') :
00264         print "Options are: "
00265         print "   --rcdir directory"
00266         print "   --logfile logfilename"
00267         print "   --maclogger"
00268         print "   --log2term"
00269         print "   --nologger"
00270         print "   --nologfile"
00271         print "   --nogui"
00272         print "   --colors=[NoColor|Linux|LightBG]"
00273         print "   --noipython"
00274         print "   -c filename-or-expression"
00275         print "   --help, print this text and exit"
00276         print
00277         sys.exit(0) 
00278 
00279 if os.uname()[0]=='Darwin' :
00280     casa_path = os.environ['CASAPATH'].split()
00281 
00282     casa['helpers']['viewer'] = casa_path[0]+'/'+casa_path[1]+'/apps/casaviewer.app/Contents/MacOS/casaviewer'
00283     # In the distro of the app then the apps dir is not there and you find things in MacOS
00284     if not os.path.exists(casa['helpers']['viewer']) :
00285         casa['helpers']['viewer'] = casa_path[0]+'/MacOS/casaviewer'
00286 
00287     if casa['flags'].has_key('--maclogger') :
00288         casa['helpers']['logger'] = 'console'
00289     else:
00290         casa['helpers']['logger'] = casa_path[0]+'/'+casa_path[1]+'/apps/casalogger.app/Contents/MacOS/casalogger'
00291 
00292         # In the distro of the app then the apps dir is not there and you find things in MacOS
00293         if not os.path.exists(casa['helpers']['logger']) :
00294             casa['helpers']['logger'] = casa_path[0]+'/Resources/Logger.app/Contents/MacOS/casalogger'
00295 
00296 
00297 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00298 ## ensure default initialization occurs before this point...
00299 ##
00300 ##      prelude.py  =>  setup/modification of casa settings
00301 ##      init.py     =>  user setup (with task access)
00302 ##
00303 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00304 if os.path.exists( casa['dirs']['rc'] + '/prelude.py' ) :
00305     try:
00306         execfile ( casa['dirs']['rc'] + '/prelude.py' )
00307     except:
00308         print str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1])
00309         print 'Could not execute initialization file: ' + casa['dirs']['rc'] + '/prelude.py'
00310         sys.exit(1)
00311 
00312 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00313 ## on linux set up a dbus-daemon for casa because each
00314 ## x-server (e.g. Xvfb) gets its own dbus session...
00315 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
00316 if os.uname()[0] == 'Linux' :
00317     if casa['helpers']['dbus'] is not None :
00318 
00319         argv_0_path = os.path.dirname(os.path.abspath(sys.argv[0]))
00320         dbus_path = os.path.dirname(os.path.abspath(casa['helpers']['dbus']))
00321         dbus_conf = None
00322 
00323         if argv_0_path == dbus_path :
00324             dbus_conf = dbus_path
00325             while dbus_conf != '/' and not os.path.basename(dbus_conf).startswith("lib") :
00326                 dbus_conf = os.path.dirname(dbus_conf)
00327             if os.path.basename(dbus_conf).startswith("lib"):
00328                 dbus_conf = os.path.dirname(dbus_conf) + "/etc/dbus/session.conf"
00329             else:
00330                 dbus_conf = None
00331 
00332         (r,w) = os.pipe( )
00333 
00334         if os.fork( ) == 0 :
00335             os.close(r)
00336             signal.signal(signal.SIGINT, signal.SIG_IGN)
00337             signal.signal(signal.SIGHUP, signal.SIG_IGN)
00338             ## close standard input to avoid terminal interrupts
00339             sys.stdin.close( )
00340             os.close(0)
00341             args = [ 'casa-dbus-daemon' ]
00342             args = args + ['--print-address', str(w)]
00343             if dbus_conf is not None and os.path.exists(dbus_conf) :
00344                 args = args + ['--config-file',dbus_conf]
00345             else:
00346                 args = args + ['--session']
00347             os.execvp(casa['helpers']['dbus'],args)
00348             sys.exit
00349         
00350         os.close(w)
00351         dbus_address = os.read(r,200)
00352         dbus_address = dbus_address.strip( )
00353         os.close(r)
00354         if len(dbus_address) > 0 :
00355             os.putenv('DBUS_SESSION_BUS_ADDRESS',dbus_address)
00356             os.environ['DBUS_SESSION_BUS_ADDRESS'] = dbus_address
00357 
00358 
00359 ipythonenv  = casa['dirs']['rc'] + '/ipython'
00360 ipythonpath = casa['dirs']['rc'] + '/ipython'
00361 try :
00362    os.makedirs(ipythonpath, 0755)
00363 except :
00364    pass
00365 ###check IPYTHONDIR is defined by user and make it if not there
00366 if(not os.environ.has_key('IPYTHONDIR')):
00367     os.environ['IPYTHONDIR']=ipythonpath
00368 if(not os.path.exists(os.environ['IPYTHONDIR'])):
00369     os.makedirs(os.environ['IPYTHONDIR'], 0755)
00370 
00371 os.environ['__CASARCDIR__']=casa['dirs']['rc']
00372 
00373 #import string
00374 
00375 #
00376 # Special case if the backend is set to MacOSX reset it to TkAgg as our TablePlot
00377 # stuff is specific for TkAgg
00378 #
00379 if matplotlib.get_backend() == "MacOSX" :
00380    matplotlib.use('TkAgg')
00381 
00382 #
00383 # Check if the display environment is set if not
00384 # switch the backend to Agg only if it's TkAgg
00385 #
00386 if not os.environ.has_key('DISPLAY') and matplotlib.get_backend() == "TkAgg" :
00387    matplotlib.use('Agg')
00388 
00389 #
00390 # We put in all the task declarations here...
00391 #
00392 from taskinit import *
00393 
00394 logpid=[]
00395 
00396 def casalogger(logfile=''):
00397     """
00398     Spawn a new casalogger using logfile as the filename.
00399     You should only call this if the casalogger dies or you close it
00400     and restart it again.
00401 
00402     Note: if you changed the name of the log file using casalog.setlogfile
00403     you will need to respawn casalogger with the new log filename. Eventually,
00404     we will figure out how to signal the casalogger with the new name but not
00405     for a while.
00406     """
00407 
00408     if logfile == '':
00409         if casa.has_key('files') and casa['files'].has_key('logfile') :
00410             logfile = casa['files']['logfile']
00411         else:
00412             casa['files']['logfile'] = os.getcwd( ) + '/casapy.log'
00413             logfile = 'casapy.log'
00414 
00415     pid=9999
00416     if (os.uname()[0]=='Darwin'):
00417         if casa['helpers']['logger'] == 'console':
00418            os.system("open -a console " + logfile)
00419         else:
00420            pid=os.spawnvp(os.P_NOWAIT,casa['helpers']['logger'],[casa['helpers']['logger'], logfile])
00421 
00422     elif (os.uname()[0]=='Linux'):
00423         pid=os.spawnlp(os.P_NOWAIT,casa['helpers']['logger'],casa['helpers']['logger'],logfile)
00424     else:
00425         print 'Unrecognized OS: No logger available'
00426 
00427     if (pid!=9999): logpid.append(pid)
00428 
00429 
00430 
00431 showconsole = False
00432 
00433 thelogfile = ''
00434 
00435 showconsole = casa['flags'].has_key('--log2term')
00436 if casa['files'].has_key('logfile') :
00437     thelogfile = casa['files']['logfile']
00438 if casa['flags'].has_key('--nologfile') :
00439     thelogfile = 'null'
00440 
00441 deploylogger = True
00442 if casa['flags'].has_key('--nolog') :
00443     print "--nolog is deprecated, please use --nologger"
00444     deploylogger = False
00445 
00446 if not os.access('.', os.W_OK) :
00447     print 
00448     print "********************************************************************************"
00449     print "Warning: no write permission in current directory, no log files will be written."
00450     print "********************************************************************************"
00451     deploylogger = False
00452     thelogfile = 'null'
00453     
00454 if casa['flags'].has_key('--nologger') :
00455     deploylogger = False
00456 
00457 if casa['flags'].has_key('--nogui') :
00458     deploylogger = False
00459 
00460 #print 'thelogfile:', thelogfile
00461 if thelogfile == 'null':
00462     pass
00463 else:
00464     if thelogfile.strip() != '' :
00465         if deploylogger:
00466             casalogger(thelogfile)
00467     else:
00468         thelogfile = 'casapy-'+time.strftime("%Y%m%d-%H%M%S", time.gmtime())+'.log'
00469         try:
00470             open(thelogfile, 'a').close()
00471         except:
00472             pass
00473         if deploylogger:
00474             casalogger(thelogfile)
00475 
00476 
00477 ###################
00478 #setup file catalog
00479 ###################
00480 
00481 vwrpid=9999
00482 ####################
00483 # Task Interface
00484 
00485 
00486 from parameter_check import *
00487 ####################
00488 def go(taskname=None):
00489     """ Execute taskname: """
00490     myf = sys._getframe(len(inspect.stack())-1).f_globals
00491     if taskname==None: taskname=myf['taskname']
00492     oldtaskname=taskname
00493     if(myf.has_key('taskname')):
00494         oldtaskname=myf['taskname']
00495     #myf['taskname']=taskname
00496     if type(taskname)!=str:
00497         taskname=taskname.__name__
00498         myf['taskname']=taskname
00499     try:
00500         parameter_checktype(['taskname'],[taskname],str)
00501     except TypeError, e:
00502         print "go -- TypeError: ",e
00503         return
00504     fulltaskname=taskname+'()'
00505     print 'Executing: ',fulltaskname
00506     exec(fulltaskname)
00507     myf['taskname']=oldtaskname
00508 
00509 def selectfield(vis,minstring):
00510     """Derive the fieldid from  minimum matched string(s): """
00511 
00512     tb.open(vis+'/FIELD')
00513     fields=list(tb.getcol('NAME'))#get fieldname list
00514     tb.close()          #close table
00515     indexlist=list()    #initialize list
00516     stringlist=list()
00517 
00518     fldlist=minstring.split()#split string into elements
00519     print 'fldlist is ',fldlist
00520     for fld in fldlist:     #loop over fields
00521         _iter=fields.__iter__() #create iterator for fieldnames
00522         while 1:
00523             try:
00524                 x=_iter.next() # has first value of field name
00525             except StopIteration:
00526                 break
00527             #
00528             if (x.find(fld)!=-1): 
00529                 indexlist.append(fields.index(x))
00530                 stringlist.append(x)
00531 
00532     print 'Selected fields are: ',stringlist
00533     return indexlist
00534 
00535 def selectantenna(vis,minstring):
00536     """Derive the antennaid from matched string(s): """
00537 
00538     tb.open(vis+'/ANTENNA')
00539     ants=list(tb.getcol('NAME'))#get fieldname list
00540     tb.close()          #close table
00541     indexlist=list()    #initialize list
00542     stringlist=list()
00543 
00544     antlist=minstring.split()#split string into elements
00545     for ant in antlist:     #loop over fields
00546         try:
00547             ind=ants.index(ant)
00548             indexlist.append(ind)
00549             stringlist.append(ant)
00550         except ValueError:
00551             pass
00552 
00553     print 'Selected reference antenna: ',stringlist
00554     print 'indexlist: ',indexlist
00555     return indexlist[0]
00556 
00557 def readboxfile(boxfile):
00558     """ Read a file containing clean boxes (compliant with AIPS BOXFILE)
00559 
00560     Format is:
00561     #FIELDID BLC-X BLC-Y TRC-X TRC-Y
00562     0       110   110   150   150 
00563     or
00564     0       hh:mm:ss.s dd.mm.ss.s hh:mm:ss.s dd.mm.ss.s
00565 
00566     Note all lines beginning with '#' are ignored.
00567 
00568     """
00569     union=[]
00570     f=open(boxfile)
00571     while 1:
00572         try: 
00573             line=f.readline()
00574             if (line.find('#')!=0): 
00575                 splitline=line.split('\n')
00576                 splitline2=splitline[0].split()
00577                 if (len(splitline2[1])<6): 
00578                     boxlist=[int(splitline2[1]),int(splitline2[2]),
00579                     int(splitline2[3]),int(splitline2[4])]
00580                 else:
00581                     boxlist=[splitline2[1],splitline2[2],splitline2[3],
00582                     splitline2[4]]
00583     
00584                 union.append(boxlist)
00585     
00586         except:
00587             break
00588 
00589     f.close()
00590     print 'union is: ',union
00591     return union
00592 
00593 def inp(taskname=None):
00594     try:
00595         myf=sys._getframe(len(inspect.stack())-1).f_globals
00596         if((taskname==None) and (not myf.has_key('taskname'))):
00597             print 'No task name defined for inputs display'
00598             return
00599         if taskname==None: taskname=myf['taskname']
00600         myf['taskname']=taskname
00601         if type(taskname)!=str:
00602             taskname=taskname.__name__
00603             myf['taskname']=taskname
00604 
00605         try:
00606             parameter_checktype(['taskname'],taskname,str)
00607         except TypeError, e:
00608             print "inp -- TypeError: ", e
00609             return
00610         except ValueError, e:
00611             print "inp -- OptionError: ", e
00612             return
00613 
00614         ###Check if task exists by checking if task_defaults is defined
00615         if ( not myf.has_key(taskname) and
00616              str(type(myf[taskname])) != "<type 'instance'>" and
00617              not hasattr(myf[taskname],"defaults") ):
00618             raise TypeError, "task %s is not defined " %taskname
00619         if(myf.has_key('__last_taskname')):
00620             myf['__last_taskname']=taskname
00621         else:
00622             myf.update({'__last_taskname':taskname})
00623 
00624         print '# ',myf['taskname']+' :: '+(eval(myf['taskname']+'.description()'))
00625         update_params(myf['taskname'], myf)
00626     except TypeError, e:
00627         print "inp --error: ", e
00628     except Exception, e:
00629         print "---",e
00630 
00631 def update_params(func, printtext=True, ipython_globals=None):
00632     from odict import odict
00633 
00634     if ipython_globals == None:
00635         myf=sys._getframe(len(inspect.stack())-1).f_globals
00636     else:
00637         myf=ipython_globals
00638 
00639     ### set task to the one being called
00640     myf['taskname']=func
00641     obj=myf[func]
00642 
00643     if ( str(type(obj)) == "<type 'instance'>" and
00644          hasattr(obj,"check_params") ):
00645         hascheck = True
00646     else:
00647         hascheck = False
00648 
00649     noerror=True
00650     ###check if task has defined a task_check_params function
00651 
00652     if (hascheck):
00653         has_othertasks = myf.has_key('task_location')
00654         if(has_othertasks) :
00655            has_task = myf['task_location'].has_key(myf['taskname'])
00656            if (has_task) :
00657                 pathname=myf['task_location'][myf['taskname']]
00658            else :
00659                 pathname = os.environ.get('CASAPATH').split()[0]+'/share/xml'
00660                 if not os.path.exists(pathname) :
00661                    pathname = os.environ.get('CASAPATH').split()[0]+'/Resources/xml'
00662                 
00663         else :
00664            pathname = os.environ.get('CASAPATH').split()[0]+'/share/xml'
00665            if not os.path.exists(pathname) :
00666               pathname = os.environ.get('CASAPATH').split()[0]+'/Resources/xml'
00667         xmlfile=pathname+'/'+myf['taskname']+'.xml'
00668         if(os.path.exists(xmlfile)) :
00669             cu.setconstraints('file://'+xmlfile);
00670 
00671     a=myf[myf['taskname']].defaults("paramkeys",myf)
00672     itsdef=myf[myf['taskname']].defaults
00673     itsparams=myf[myf['taskname']].parameters
00674     params=a
00675     #print 'itsparams:', itsparams
00676     for k in range(len(params)):
00677         paramval = obj.defaults(params[k], myf)
00678 
00679         notdict=True
00680         ###if a dictionary with key 0, 1 etc then need to peel-open
00681         ###parameters
00682         if(type(paramval)==dict):
00683             if(paramval.has_key(0)):
00684                 notdict=False
00685         if(myf.has_key(params[k])):
00686             itsparams.update({params[k]:myf[params[k]]})
00687         else:
00688             itsparams.update({params[k]:obj.itsdefault(params[k])})
00689         if (notdict ):
00690             if(not myf.has_key(params[k])):
00691                 myf.update({params[k]:paramval})
00692                 itsparams.update({params[k]:paramval})
00693             if(printtext):
00694                 #print 'params:', params[k], '; myf[params]:', myf[params[k]]
00695                 if(hascheck):
00696                     noerror = obj.check_params(params[k],myf[params[k]],myf)
00697                 # RI this doesn't work with numpy arrays anymore.  Noone seems
00698                 # interested, so I'll be the red hen and try to fix it.
00699                 
00700                 #print 'params:', params[k], '; noerror:', noerror, '; myf[params]:', myf[params[k]]
00701                 myfparamsk=myf[params[k]]
00702                 if(type(myf[params[k]])==pl.ndarray):
00703                     myfparamsk=myfparamsk.tolist()
00704                 #if(myf[params[k]]==paramval):
00705                 if(myfparamsk==paramval):
00706                     print_params_col(params[k],myf[params[k]],obj.description(params[k]), 'ndpdef', 'black',noerror)
00707                 else:
00708                     print_params_col(params[k],myf[params[k]],obj.description(params[k]), 'ndpnondef', 'black', noerror)
00709                 itsparams[params[k]] = myf[params[k]]
00710         else:
00711             subdict=odict(paramval)
00712             ##printtext is False....called most probably to set
00713             ##undefined params..no harm in doing it anyways
00714             if(not printtext):
00715                 ##locate which dictionary is user selected
00716                 userdict={}
00717                 subkeyupdated={}
00718                 for somekey in paramval:
00719                     somedict=dict(paramval[somekey])
00720                     subkeyupdated.update(dict.fromkeys(somedict, False))
00721                     if(somedict.has_key('value') and myf.has_key(params[k])):
00722                         if(somedict['value']==myf[params[k]]):
00723                             userdict=somedict
00724                     elif(somedict.has_key('notvalue') and myf.has_key(params[k])):
00725                         if(somedict['notvalue']!=myf[params[k]]):
00726                             userdict=somedict
00727                 ###The behaviour is to use the task.defaults
00728                 ### for all non set parameters and parameters that
00729                 ### have no meaning for this selection
00730                 for j in range(len(subdict)):
00731                     subkey=subdict[j].keys()
00732                    
00733                     for kk in range(len(subkey)):
00734                         
00735                         if( (subkey[kk] != 'value') & (subkey[kk] != 'notvalue') ):
00736                             #if user selecteddict
00737                             #does not have the key
00738                             ##put default
00739                             if(userdict.has_key(subkey[kk])):
00740                                 if(myf.has_key(subkey[kk])):
00741                                     itsparams.update({subkey[kk]:myf[subkey[kk]]})
00742                                 else:
00743                                     itsparams.update({subkey[kk]:userdict[subkey[kk]]})
00744                                 subkeyupdated[subkey[kk]]=True
00745                             elif((not subkeyupdated[subkey[kk]])):
00746                                 itsparams.update({subkey[kk]:itsdef(params[k], None, itsparams[params[k]], subkey[kk])})
00747                                 subkeyupdated[subkey[kk]]=True
00748             ### need to do default when user has not set val
00749             if(not myf.has_key(params[k])):
00750                 if(paramval[0].has_key('notvalue')):
00751                     itsparams.update({params[k]:paramval[0]['notvalue']})
00752                     myf.update({params[k]:paramval[0]['notvalue']})
00753                 else:
00754                     itsparams.update({params[k]:paramval[0]['value']})
00755                     myf.update({params[k]:paramval[0]['value']})
00756             userval=myf[params[k]]
00757             choice=0
00758             notchoice=-1
00759             valuekey='value'
00760             for j in range(len(subdict)):
00761                 if(subdict[j].has_key('notvalue')):
00762                     valuekey='notvalue'
00763                     if(subdict[j]['notvalue'] != userval):
00764                         notchoice=j;
00765                         break
00766                 else:
00767                     if(subdict[j]['value']==userval):
00768                         choice=j
00769                         notchoice=j
00770                         break
00771             subkey=subdict[choice].keys()
00772             if(hascheck):
00773                 noerror=obj.check_params(params[k],userval,myf)
00774             if(printtext):
00775                 if(myf[params[k]]==paramval[0][valuekey]):
00776                     print_params_col(params[k],myf[params[k]],obj.description(params[k]),'dpdef','black', noerror)
00777                 else:
00778                     print_params_col(params[k],myf[params[k]],obj.description(params[k]),'dpnondef','black', noerror)
00779                 itsparams[params[k]] = myf[params[k]]
00780             for j in range(len(subkey)):
00781                 if((subkey[j] != valuekey) & (notchoice > -1)):
00782                     ###put default if not there
00783                     if(not myf.has_key(subkey[j])):
00784                         myf.update({subkey[j]:subdict[choice][subkey[j]]})
00785                     paramval=subdict[choice][subkey[j]]
00786                     if (j==(len(subkey)-1)):
00787                         # last subparameter - need to add an extra line to allow cut/pasting
00788                         comment='last'
00789                     else:
00790                         comment='blue'
00791                     if(hascheck):
00792                         noerror = obj.check_params(subkey[j],myf[subkey[j]],myf)
00793                     if(printtext):
00794                         if(myf[subkey[j]]==paramval):
00795                             print_params_col(subkey[j],myf[subkey[j]],obj.description(subkey[j],userval),'spdef',comment, noerror)
00796                         else:
00797                             print_params_col(subkey[j],myf[subkey[j]],obj.description(subkey[j],userval),'spnondef',comment, noerror)
00798                         itsparams[params[k]] = myf[params[k]]                    
00799     #
00800     # Verify the complete record, with errors being reported to the user
00801     #
00802     #cu.verify(itsparams, cu.torecord('file://'+xmlfile)[myf['taskname']]);
00803 
00804 ####function to print inputs with coloring
00805 ####colorparam 'blue'=> non-default, colorcomment 'green'=> can have sub params
00806 #### 'blue' => is a sub-parameter 
00807 # blue = \x1B[94m
00808 # bold = \x1B[1m
00809 # red  = \x1B[91m
00810 # cyan = \x1B[96m
00811 # green= \x1B[92m
00812 # normal   = \x1B[0m
00813 # underline= \x1B[04m
00814 # reverse = \x1B[7m
00815 # highlight with black = \x1B[40s
00816 
00817 def print_params_col(param=None, value=None, comment='', colorparam=None,
00818                      colorcomment=None, noerrorval=True):
00819     try:
00820         from TerminalController import TerminalController
00821         term = TerminalController()
00822         cols = term.COLS
00823         del term
00824     except:
00825         cols = 80
00826     #
00827     #print 'colorparam is: ', colorparam
00828     #
00829     if type(value) == str:
00830         printval = "'" + value + "'"
00831     else:
00832         printval = value
00833 
00834     if colorparam == 'ndpnondef':
00835         firstcol = '\x1B[0m'
00836         valcol   = '\x1B[94m'
00837     elif colorparam == 'dpdef':
00838         firstcol = '\x1B[1m' + '\x1B[47m'
00839         valcol   = '\x1B[1m' + '\x1B[0m'
00840     elif colorparam == 'dpnondef':
00841         firstcol = '\x1B[1m' + '\x1B[47m'
00842         valcol   = '\x1B[1m' + '\x1B[94m'
00843     elif colorparam == 'spdef':
00844         firstcol = '\x1B[32m'
00845         valcol   = '\x1B[0m'
00846     elif colorparam == 'spnondef':
00847         firstcol = '\x1B[32m'
00848         valcol   = '\x1B[94m'
00849     else:
00850         firstcol = '\x1B[0m'
00851         valcol   = '\x1B[0m'
00852 
00853     if not noerrorval:
00854         valcol = '\x1B[1m' + '\x1B[91m'
00855 
00856     if colorcomment == 'green':
00857         secondcol = '\x1B[102m'
00858     elif colorcomment == 'blue':
00859         #secondcol='\x1B[104m'
00860         secondcol = '\x1B[0m'
00861     else:
00862         secondcol = '\x1B[0m'
00863 
00864     # RR: I think colorcomment should really be called submenu.
00865     #     Since these are left justified, I've absorbed the right space into
00866     #     the %s's, in order to handle as long a parameter name as possible.
00867     #     (The uvfilterb* params were busting out of %-10s.)
00868     if colorcomment in ('last', 'blue'):
00869         parampart = firstcol + '     %-14s ='
00870     else:
00871         parampart = firstcol + '%-19s ='
00872     parampart %= param
00873 
00874     valpart = valcol + ' %10s \x1B[0m' % printval + secondcol
00875     # Well behaved (short) parameters and values tally up to 33 characters
00876     # so far.  Pad them up to 40, assuming the param is short enough.
00877     pad = 7
00878     paramlen = len(str(param))
00879     if colorcomment in ('last', 'blue') and paramlen > 14:
00880         pad -= paramlen - 14
00881     elif paramlen > 19:
00882         pad -= paramlen - 19
00883     valuelen = len(str(printval))
00884     if valuelen > 10:
00885         pad -= valuelen - 10
00886     if pad > 0:
00887         valpart += ' ' * pad
00888 
00889     try:
00890         from textwrap import fill
00891         if pad < 0:
00892             firstskip = 40 - pad
00893             firstfiller = ' ' * firstskip + '#  '
00894             afterfiller = ' ' * 40 + '#   '
00895         else:
00896             firstskip = 40
00897             firstfiller = ' ' * 40 + '#  '
00898             afterfiller = firstfiller + ' '
00899         commentpart = fill(comment, cols, initial_indent=firstfiller,
00900                            subsequent_indent=afterfiller)[firstskip:]
00901     except:
00902         if comment:
00903             commentpart = '#  ' + comment
00904         else:
00905             commentpart = ''
00906     commentpart += '\x1B[0m'          # RR: I think this might be redundant.
00907     if colorcomment == 'last':        #     (Is colorcomment ever green?)
00908         commentpart += "\n"
00909 
00910     print parampart + valpart + commentpart
00911 
00912 def __set_default_parameters(b):
00913     myf=sys._getframe(len(inspect.stack())-1).f_globals
00914     a=b
00915     elkey=a.keys()
00916     for k in range(len(a)):
00917         if (type(a[elkey[k]]) != dict):
00918             myf[elkey[k]]=a[elkey[k]]
00919         elif (type(a[elkey[k]]) == dict and len(a[elkey[k]])==0):
00920             myf[elkey[k]]=a[elkey[k]]
00921         else:
00922             subdict=a[elkey[k]]
00923             ##clear out variables of other options if they exist
00924             for j in range(1,len(subdict)):
00925                 subkey=subdict[j].keys()
00926                 for kk in range(len(subkey)):
00927                     if((subkey[kk] != 'value') & (subkey[kk] != 'notvalue') ):
00928                         if(myf.has_key(subkey[kk])):
00929                             del myf[subkey[kk]]
00930             ###
00931             if(subdict[0].has_key('notvalue')):
00932                 myf[elkey[k]]=subdict[0]['notvalue']
00933             else:
00934                 myf[elkey[k]]=subdict[0]['value']
00935             subkey=subdict[0].keys()
00936             for j in range(0, len(subkey)):
00937                 if((subkey[j] != 'value') & (subkey[j] != 'notvalue')):
00938                     myf[subkey[j]]=subdict[0][subkey[j]]
00939 
00940 def tput(taskname=None, outfile=''):
00941         myf = sys._getframe(len(inspect.stack())-1).f_globals
00942         if taskname == None: taskname = myf['taskname']
00943         if type(taskname) != str:
00944                 taskname=taskname.__name__
00945         myf['taskname'] = taskname
00946         outfile = myf['taskname']+'.last'
00947         saveinputs(taskname, outfile)
00948 
00949 def saveinputs(taskname=None, outfile='', myparams=None, ipython_globals=None, scriptstr=['']):
00950     #parameter_printvalues(arg_names,arg_values,arg_types)
00951     """ Save current input values to file on disk for a specified task:
00952 
00953     taskname -- Name of task
00954         default: <unset>; example: taskname='bandpass'
00955         <Options: type tasklist() for the complete list>
00956     outfile -- Output file for the task inputs
00957         default: taskname.saved; example: outfile=taskname.orion
00958 
00959     """
00960 
00961     try:
00962         if ipython_globals == None:
00963             myf = sys._getframe(len(inspect.stack())-1).f_globals
00964         else:
00965             myf=ipython_globals
00966 
00967         if taskname==None: taskname=myf['taskname']
00968         myf['taskname']=taskname
00969         if type(taskname)!=str:
00970             taskname=taskname.__name__
00971             myf['taskname']=taskname
00972 
00973         parameter_checktype(['taskname','outfile'],[taskname,outfile],[str,str])
00974 
00975         ###Check if task exists by checking if task_defaults is defined
00976         obj = False
00977         if ( not myf.has_key(taskname) and
00978              str(type(myf[taskname])) != "<type 'instance'>" and
00979              not hasattr(myf[taskname],"defaults") ):
00980             raise TypeError, "task %s is not defined " %taskname
00981         else:
00982             obj = myf[taskname]
00983 
00984         if taskname==None: taskname=myf['taskname']
00985         myf['taskname']=taskname
00986         if outfile=='': outfile=taskname+'.saved'
00987         ##make sure unfolded parameters get their default values
00988         myf['update_params'](func=myf['taskname'], printtext=False, ipython_globals=myf)
00989         ###
00990         taskparameterfile=open(outfile,'w')
00991         print >>taskparameterfile, '%-15s    = "%s"'%('taskname', taskname)
00992         f=zip(myf[taskname].__call__.func_code.co_varnames,myf[taskname].__call__.func_defaults)
00993         scriptstring='#'+str(taskname)+'('
00994         if myparams == None :
00995                 myparams = {}
00996         l=0
00997         for j in range(len(f)):
00998             k=f[j][0]
00999             if not myparams.has_key(k) and k != 'self' :
01000                     myparams[k] = myf[taskname].parameters[k]
01001             if(k != 'self' and type(myparams[k])==str):
01002                 if ( myparams[k].count( '"' ) < 1 ):
01003                     # if the string doesn't contain double quotes then
01004                     # use double quotes around it in the parameter file.
01005                     print >>taskparameterfile, '%-15s    =  "%s"'%(k, myparams[k])
01006                     scriptstring=scriptstring+k+'="'+myparams[k]+'",'
01007                 else:
01008                     # use single quotes.
01009                     print >>taskparameterfile, "%-15s    =  '%s'"%(k, myparams[k])
01010                     scriptstring=scriptstring+k+"='"+myparams[k]+"',"
01011             else :
01012                 if ( j != 0 or k != "self" or
01013                      str(type(myf[taskname])) != "<type 'instance'>" ) :
01014                     print >>taskparameterfile, '%-15s    =  %s'%(k, myparams[k])
01015                     scriptstring=scriptstring+k+'='+str(myparams[k])+','
01016 
01017             ###Now delete varianle from global user space because
01018             ###the following applies: "It would be nice if one
01019             ### could tell the system to NOT recall
01020             ### previous non-default settings sometimes."
01021             if(not myf['casaglobals'] and myf.has_key(k)):
01022                 del myf[k]
01023             l=l+1
01024             if l%5==0:
01025                 scriptstring=scriptstring+'\n        '
01026         scriptstring=scriptstring.rstrip()
01027         scriptstring=scriptstring.rstrip('\n')
01028         scriptstring=scriptstring.rstrip(',')
01029         scriptstring=scriptstring+')'        
01030         scriptstr.append(scriptstring)
01031         scriptstring=scriptstring.replace('        ', '')
01032         scriptstring=scriptstring.replace('\n', '')
01033         print >>taskparameterfile,scriptstring
01034         taskparameterfile.close()
01035     except TypeError, e:
01036         print "saveinputs --error: ", e
01037 
01038 def default(taskname=None):
01039     """ reset given task to its default values :
01040 
01041     taskname -- Name of task
01042 
01043 
01044     """
01045 
01046     try:
01047         myf = sys._getframe(len(inspect.stack())-1).f_globals
01048         if taskname==None: taskname=myf['taskname']
01049         myf['taskname']=taskname
01050         if type(taskname)!=str:
01051             taskname=taskname.__name__
01052             myf['taskname']=taskname
01053 
01054         ###Check if task exists by checking if task_defaults is defined
01055         if ( not myf.has_key(taskname) and
01056              str(type(myf[taskname])) != "<type 'instance'>" and
01057              not hasattr(myf[taskname],"defaults") ):
01058             raise TypeError, "task %s is not defined " %taskname
01059         eval(myf['taskname']+'.defaults()')
01060 
01061         casalog.origin('default')
01062         taskstring=str(taskname).split()[0]
01063         casalog.post(' #######  Setting values to default for task: '+taskstring+'  #######')
01064 
01065 
01066     except TypeError, e:
01067         print "default --error: ", e
01068 
01069 def taskparamgui(useGlobals=True):
01070     """
01071         Show a parameter-setting GUI for all available tasks.
01072     """
01073     import paramgui
01074 
01075     if useGlobals:
01076         paramgui.setGlobals(sys._getframe(len(inspect.stack())-1).f_globals)
01077     else:
01078         paramgui.setGlobals({})
01079 
01080     paramgui.runAll(_ip)
01081     paramgui.setGlobals({})
01082 
01083 ####################
01084 
01085 def exit():
01086     __IPYTHON__.exit_now=True
01087     #print 'Use CNTRL-D to exit'
01088     #return
01089 
01090 import pylab as pl
01091 
01092 #
01093 # 
01094 import platform
01095 ##
01096 ## CAS-951: matplotlib unresponsive on some 64bit systems
01097 ##
01098 
01099 if (platform.architecture()[0]=='64bit'):
01100     if os.environ.has_key('DISPLAY') and os.environ['DISPLAY']!="" and not casa['flags'].has_key('--nogui'):
01101         pl.ioff( )
01102         pl.clf( )
01103         pl.ion( )
01104 ##
01105 ##
01106 
01107 # Provide flexibility for boolean representation in the CASA shell
01108 true  = True
01109 T     = True
01110 false = False
01111 F     = False
01112 
01113 # Case where casapy is run non-interactively
01114 ipython = not casa['flags'].has_key('--noipython')
01115 try:
01116    import IPython
01117 except ImportError, e:
01118    print 'Failed to load IPython: ', e
01119    exit(1)
01120 
01121 
01122 # setup available tasks
01123 #
01124 from math import *
01125 from tasks import *
01126 from parameter_dictionary import *
01127 from task_help import *
01128 
01129 #
01130 # import testing environment
01131 #
01132 import publish_summary
01133 import runUnitTest
01134 #
01135 home=os.environ['HOME']
01136 
01137 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
01138 ##
01139 ##      prelude.py  =>  setup/modification of casa settings (above)
01140 ##      init.py     =>  user setup (with task access)
01141 ##
01142 ## ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
01143 if os.path.exists( casa['dirs']['rc'] + '/init.py' ) :
01144     try:
01145         execfile ( casa['dirs']['rc'] + '/init.py' )
01146     except:
01147         print str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1])
01148         print 'Could not execute initialization file: ' + casa['dirs']['rc'] + '/init.py'
01149         sys.exit(1)
01150 
01151 if ipython:
01152     startup()
01153 
01154 # assignment protection
01155 #
01156 #pathname=os.environ.get('CASAPATH').split()[0]
01157 #uname=os.uname()
01158 #unameminusa=str.lower(uname[0])
01159 fullpath = casadef.python_library_directory + 'assignmentFilter.py'
01160 casalog.origin('casa')
01161 
01162 #
01163 # Use something else than python's builtin help() for
01164 # documenting casapy tasks
01165 #
01166 import pydoc
01167 
01168 class casaDocHelper(pydoc.Helper):
01169     def help(self, request):
01170         if hasattr(request, 'i_am_a_casapy_task'):
01171             pydoc.pager('Help on ' + pydoc.text.bold(request.__name__) + ' task:\n\n' + request.__doc__)
01172         else:
01173             return pydoc.Helper.help(self, request)
01174 
01175 pydoc.help = casaDocHelper(sys.stdin, sys.stdout)
01176 
01177 fullpath=casadef.python_library_directory + '/assignmentFilter.py'
01178 
01179 if os.environ.has_key('__CASAPY_PYTHONDIR'):
01180     fullpath=os.environ['__CASAPY_PYTHONDIR'] + '/assignmentFilter.py'
01181 
01182 if ipython:
01183     ipythonlog = 'ipython-'+time.strftime("%Y%m%d-%H%M%S", time.gmtime())+'.log'
01184     #if os.path.exists('ipython.log') and not os.access('ipython.log', os.W_OK):
01185     #    print
01186     #    print
01187     #    print
01188     #    print "**********************************************************"
01189     #    print "Error: ipython.log is not writable, unable to start casapy"
01190     #    print "**********************************************************"
01191     #    sys.exit(1) 
01192 
01193    
01194     if casa['flags'].has_key('-c') :
01195         print 'will execute script',casa['flags']['-c']
01196         if os.path.exists( casa['dirs']['rc']+'/ipython/ipy_user_conf.py' ) :
01197             if os.path.exists( casa['flags']['-c'] ) :
01198                 ###
01199                 ###  assume casa['flags']['-c'] is a file to execute...
01200                 ###
01201                 try:
01202                     ipshell = IPython.Shell.IPShell( argv=['-prompt_in1','CASA <\#>: ','-autocall','2','-colors',__ipython_colors, '-nomessages', '-nobanner','-logfile',ipythonlog,'-ipythondir',casa['dirs']['rc']+'/ipython','-c','execfile("'+casa['flags']['-c']+'")'], user_ns=globals() )
01203                 except:
01204                     print "ERROR: falied to create an instance of IPython.Shell.IPShell"
01205             else:
01206                 ###
01207                 ###  assume casa['flags']['-c'] is a python command...
01208                 ###
01209                 try:
01210                     ipshell = IPython.Shell.IPShell( argv=['-prompt_in1','CASA <\#>: ','-autocall','2','-colors',__ipython_colors, '-nomessages', '-nobanner','-logfile',ipythonlog,'-ipythondir',casa['dirs']['rc']+'/ipython','-c',casa['flags']['-c']], user_ns=globals() )
01211                 except: 
01212                     print "ERROR: falied to create an instance of IPython.Shell.IPShell"
01213         else:
01214             if os.path.exists( casa['flags']['-c'] ) :
01215                 ###
01216                 ###  assume casa['flags']['-c'] is a file to execute...
01217                 ###
01218                 try:
01219                     ipshell = IPython.Shell.IPShell( argv=['-prompt_in1','CASA <\#>: ','-autocall','2','-colors',__ipython_colors, '-nomessages', '-nobanner','-logfile',ipythonlog,'-upgrade','-ipythondir',casa['dirs']['rc']+'/ipython','-c','execfile("'+casa['flags']['-c']+'")'], user_ns=globals() )
01220                 except: 
01221                     print "ERROR: falied to create an instance of IPython.Shell.IPShell"
01222             else:
01223                 ###
01224                 ###  assume casa['flags']['-c'] is a python command...
01225                 ###
01226                 try:
01227                     ipshell = IPython.Shell.IPShell( argv=['-prompt_in1','CASA <\#>: ','-autocall','2','-colors',__ipython_colors, '-nomessages', '-nobanner','-logfile',ipythonlog,'-upgrade','-ipythondir',casa['dirs']['rc']+'/ipython','-c',casa['flags']['-c']], user_ns=globals() )
01228                 except: 
01229                     print "ERROR: falied to create an instance of IPython.Shell.IPShell"
01230     else:
01231         if os.path.exists( casa['dirs']['rc']+'/ipython/ipy_user_conf.py' ) :
01232             if(thelogfile != 'null') :
01233                 try:
01234                     ipshell = IPython.Shell.IPShell( argv=['-prompt_in1','CASA <\#>: ','-autocall','2','-colors',__ipython_colors, '-nomessages', '-nobanner','-logfile',ipythonlog,'-ipythondir',casa['dirs']['rc']+'/ipython'], user_ns=globals() )
01235                 except: 
01236                     print "ERROR: falied to create an instance of IPython.Shell.IPShell"
01237             else :
01238                 try:
01239                     ipshell = IPython.Shell.IPShell( argv=['-prompt_in1','CASA <\#>: ','-autocall','2','-colors',__ipython_colors, '-nomessages', '-nobanner','-ipythondir',casa['dirs']['rc']+'/ipython'], user_ns=globals() )
01240                 except: 
01241                     print "ERROR: falied to create an instance of IPython.Shell.IPShell"
01242         else:
01243             if(thelogfile != 'null') :
01244                 try:
01245                     ipshell = IPython.Shell.IPShell( argv=['-prompt_in1','CASA <\#>: ','-autocall','2','-colors',__ipython_colors, '-nomessages', '-nobanner','-logfile',ipythonlog,'-upgrade','-ipythondir',casa['dirs']['rc']+'/ipython'], user_ns=globals() )
01246                 except: 
01247                     print "ERROR: falied to create an instance of IPython.Shell.IPShell"
01248             else :
01249                 try:
01250                     ipshell = IPython.Shell.IPShell( argv=['-prompt_in1','CASA <\#>: ','-autocall','2','-colors',__ipython_colors, '-nomessages', '-nobanner','-upgrade','-ipythondir',casa['dirs']['rc']+'/ipython'], user_ns=globals() )
01251                 except: 
01252                     print "ERROR: falied to create an instance of IPython.Shell.IPShell"
01253         ipshell.IP.runlines('execfile("'+fullpath+'")')
01254 
01255 #ipshell = IPython.Shell.IPShell( argv=['-prompt_in1','CASA <\#>: ','-autocall','2','-colors',__ipython_colors,'-logfile',ipythonlog,'-ipythondir',casa['dirs']['rc']+'/ipython'], user_ns=globals() )
01256 
01257 casalog.setlogfile(thelogfile)
01258 
01259 try:
01260     casalog.post('---')
01261 except:
01262     print "Error: the logfile is not writable"
01263     sys.exit(1)
01264 
01265 
01266 casalog.showconsole(showconsole)
01267 casalog.version()
01268 
01269 ### Try loading ASAP
01270 try:
01271     asap_init()
01272 except ImportError, e:
01273     casalog.post("%s\nCould not load ASAP. sd* tasks will not be available." % e,'WARN')
01274 except Exception, instance:
01275     casalog.post("Could not load ASAP. sd* tasks will not be available.",'WARN')
01276     casalog.post(str(instance),'WARN',origin="asap_init")
01277 ##
01278 ## warn when available memory is < 512M (clean throws and exception)
01279 if cu.hostinfo( )['memory']['available'] < 524288:
01280     casalog.post( 'available memory less than 512MB (with casarc settings)\n...some things will not run correctly', 'SEVERE' )
01281 
01282 casa['state']['startup'] = False
01283 
01284 #print '----thelogfile:', thelogfile
01285 #print 'casapy.log exists:', os.path.exists('casapy.log')
01286 
01287 if (thelogfile == 'null' or thelogfile != 'casapy.log') and os.path.exists('casapy.log'):
01288     os.remove('casapy.log')
01289 
01290 import shutil
01291 if ipython:
01292     ipshell.mainloop( )
01293     if(os.uname()[0] == 'Darwin') and type(casa) == "<type 'dict'>" and casa['flags'].has_key('--maclogger') :
01294            os.system("osascript -e 'tell application \"Console\" to quit'")
01295     for pid in logpid: 
01296         #print 'pid: ',pid
01297         os.kill(pid,9)
01298 
01299     for x in os.listdir('.'):
01300        if x.lower().startswith('casapy.scratch-'):
01301           if os.path.isdir(x):
01302              #shutil.rmtree(x, ignore_errors=True)
01303              os.system("rm -rf %s" % x)
01304              #print "Removed: ", x, "\n"
01305 
01306     ## leave killing off children to the watchdog...
01307     ## so everyone has a chance to die naturally...
01308     print "leaving casapy..."