Package PyFoam :: Package Execution :: Module BasicWatcher
[hide private]
[frames] | no frames]

Source Code for Module PyFoam.Execution.BasicWatcher

  1  #  ICE Revision: $Id: /local/openfoam/Python/PyFoam/PyFoam/Execution/BasicWatcher.py 6675 2010-06-05T12:42:37.337813Z bgschaid  $  
  2  """Watches the output of Foam-run""" 
  3   
  4  from os import path 
  5  import stat 
  6  import os 
  7  import gzip 
  8  from time import sleep 
  9   
 10  from PyFoam.Basics.LineReader import LineReader 
 11   
12 -class BasicWatcher(object):
13 """Base class for watching the output of commands 14 15 Works like the UNIX-command 'tail -f <file>': the last lines of the file are output. 16 If the file grows then these lines are output as they arrive""" 17
18 - def __init__(self,filename, 19 silent=False, 20 tailLength=1000, 21 sleep=0.1, 22 follow=True):
23 """@param filename: name of the logfile to watch 24 @param silent: if True no output is sent to stdout 25 @param tailLength: number of bytes at the end of the fail that should be output. 26 @param follow: if the end of the file is reached wait for further input 27 Because data is output on a per-line-basis 28 @param sleep: interval to sleep if no line is returned""" 29 30 self.filename=filename 31 self.silent=silent 32 self.tail=tailLength 33 self.sleep=sleep 34 self.follow=follow 35 self.isTailing=False 36 37 if not path.exists(self.filename): 38 print "Error: Logfile ",self.filename,"does not exist" 39 40 self.reader=LineReader()
41
42 - def getSize(self):
43 """@return: the current size (in bytes) of the file""" 44 return os.stat(self.filename)[stat.ST_SIZE]
45
46 - def start(self):
47 """Reads the file and does the processing""" 48 49 currSize=self.getSize() 50 51 fn,ext=path.splitext(self.filename) 52 if ext=='.gz': 53 fh=gzip.open(self.filename) 54 else: 55 fh=open(self.filename) 56 57 self.startHandle() 58 59 while self.follow or currSize>self.reader.bytesRead(): 60 try: 61 status=self.reader.read(fh) 62 if status: 63 line=self.reader.line 64 if (currSize-self.reader.bytesRead())<=self.tail: 65 if not self.isTailing: 66 self.isTailing=True 67 self.timeHandle() 68 self.tailingHandle() 69 70 if not self.silent: 71 print line 72 73 self.lineHandle(line) 74 else: 75 if self.reader.userSaidStop(): 76 break 77 sleep(self.sleep) 78 except KeyboardInterrupt,e: 79 print "Watcher: Keyboard interrupt" 80 break 81 82 self.stopHandle() 83 84 fh.close()
85
86 - def startHandle(self):
87 """to be called before the program is started""" 88 pass
89
90 - def stopHandle(self):
91 """called after the program has stopped""" 92 pass
93
94 - def tailingHandle(self):
95 """called when the first line is output""" 96 pass
97
98 - def lineHandle(self,line):
99 """called every time a new line is read""" 100 pass
101