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

Source Code for Module PyFoam.Execution.BasicWatcher

 1  #  ICE Revision: $Id: BasicWatcher.py 10428 2009-05-07 14:22:40Z 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,silent=False,tailLength=1000,sleep=0.1):
19 """@param filename: name of the logfile to watch 20 @param silent: if True no output is sent to stdout 21 @param tailLength: number of bytes at the end of the fail that should be output. 22 Because data is output on a per-line-basis 23 @param sleep: interval to sleep if no line is returned""" 24 25 self.filename=filename 26 self.silent=silent 27 self.tail=tailLength 28 self.sleep=sleep 29 self.isTailing=False 30 31 if not path.exists(self.filename): 32 print "Error: Logfile ",self.filename,"does not exist" 33 34 self.reader=LineReader()
35
36 - def getSize(self):
37 """@return: the current size (in bytes) of the file""" 38 return os.stat(self.filename)[stat.ST_SIZE]
39
40 - def start(self):
41 """Reads the file and does the processing""" 42 43 currSize=self.getSize() 44 45 fn,ext=path.splitext(self.filename) 46 if ext=='.gz': 47 fh=gzip.open(self.filename) 48 else: 49 fh=open(self.filename) 50 51 self.startHandle() 52 53 while 1: 54 try: 55 status=self.reader.read(fh) 56 if status: 57 line=self.reader.line 58 if (currSize-self.reader.bytesRead())<=self.tail: 59 if not self.isTailing: 60 self.isTailing=True 61 self.timeHandle() 62 self.tailingHandle() 63 64 if not self.silent: 65 print line 66 67 self.lineHandle(line) 68 else: 69 if self.reader.userSaidStop(): 70 break 71 sleep(self.sleep) 72 except KeyboardInterrupt,e: 73 print "Watcher: Keyboard interrupt" 74 break 75 76 self.stopHandle() 77 78 fh.close()
79
80 - def startHandle(self):
81 """to be called before the program is started""" 82 pass
83
84 - def stopHandle(self):
85 """called after the program has stopped""" 86 pass
87
88 - def tailingHandle(self):
89 """called when the first line is output""" 90 pass
91
92 - def lineHandle(self,line):
93 """called every time a new line is read""" 94 pass
95