1
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
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
43 """@return: the current size (in bytes) of the file"""
44 return os.stat(self.filename)[stat.ST_SIZE]
45
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
87 """to be called before the program is started"""
88 pass
89
91 """called after the program has stopped"""
92 pass
93
95 """called when the first line is output"""
96 pass
97
99 """called every time a new line is read"""
100 pass
101