|
@@ -0,0 +1,78 @@
|
|
1
|
+#!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+'''
|
|
4
|
+Python-Tail - Unix tail follow implementation in Python.
|
|
5
|
+
|
|
6
|
+python-tail can be used to monitor changes to a file.
|
|
7
|
+
|
|
8
|
+Example:
|
|
9
|
+ import tail
|
|
10
|
+
|
|
11
|
+ # Create a tail instance
|
|
12
|
+ t = tail.Tail('file-to-be-followed')
|
|
13
|
+
|
|
14
|
+ # Register a callback function to be called when a new line is found in the followed file.
|
|
15
|
+ # If no callback function is registered, new lines would be printed to standard out.
|
|
16
|
+ t.register_callback(callback_function)
|
|
17
|
+
|
|
18
|
+ # Follow the file with 5 seconds as sleep time between iterations.
|
|
19
|
+ # If sleep time is not provided 1 second is used as the default time.
|
|
20
|
+ t.follow(s=5) '''
|
|
21
|
+
|
|
22
|
+# Author - Kasun Herath <kasunh01 at gmail.com>
|
|
23
|
+# Source - https://github.com/kasun/python-tail
|
|
24
|
+
|
|
25
|
+import os
|
|
26
|
+import sys
|
|
27
|
+import time
|
|
28
|
+
|
|
29
|
+class Tail(object):
|
|
30
|
+ ''' Represents a tail command. '''
|
|
31
|
+ def __init__(self, tailed_file):
|
|
32
|
+ ''' Initiate a Tail instance.
|
|
33
|
+ Check for file validity, assigns callback function to standard out.
|
|
34
|
+
|
|
35
|
+ Arguments:
|
|
36
|
+ tailed_file - File to be followed. '''
|
|
37
|
+
|
|
38
|
+ self.check_file_validity(tailed_file)
|
|
39
|
+ self.tailed_file = tailed_file
|
|
40
|
+ self.callback = sys.stdout.write
|
|
41
|
+
|
|
42
|
+ def follow(self, s=1):
|
|
43
|
+ ''' Do a tail follow. If a callback function is registered it is called with every new line.
|
|
44
|
+ Else printed to standard out.
|
|
45
|
+
|
|
46
|
+ Arguments:
|
|
47
|
+ s - Number of seconds to wait between each iteration; Defaults to 1. '''
|
|
48
|
+
|
|
49
|
+ with open(self.tailed_file) as file_:
|
|
50
|
+ # Go to the end of file
|
|
51
|
+ file_.seek(0,2)
|
|
52
|
+ while True:
|
|
53
|
+ curr_position = file_.tell()
|
|
54
|
+ line = file_.readline()
|
|
55
|
+ if not line:
|
|
56
|
+ file_.seek(curr_position)
|
|
57
|
+ time.sleep(s)
|
|
58
|
+ else:
|
|
59
|
+ self.callback(line)
|
|
60
|
+
|
|
61
|
+ def register_callback(self, func):
|
|
62
|
+ ''' Overrides default callback function to provided function. '''
|
|
63
|
+ self.callback = func
|
|
64
|
+
|
|
65
|
+ def check_file_validity(self, file_):
|
|
66
|
+ ''' Check whether the a given file exists, readable and is a file '''
|
|
67
|
+ if not os.access(file_, os.F_OK):
|
|
68
|
+ raise TailError("File '%s' does not exist" % (file_))
|
|
69
|
+ if not os.access(file_, os.R_OK):
|
|
70
|
+ raise TailError("File '%s' not readable" % (file_))
|
|
71
|
+ if os.path.isdir(file_):
|
|
72
|
+ raise TailError("File '%s' is a directory" % (file_))
|
|
73
|
+
|
|
74
|
+class TailError(Exception):
|
|
75
|
+ def __init__(self, msg):
|
|
76
|
+ self.message = msg
|
|
77
|
+ def __str__(self):
|
|
78
|
+ return self.message
|