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

Source Code for Module PyFoam.Execution.BasicWatcher

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