Created
March 15, 2016 23:10
-
-
Save davidbj/88e5711521a2d334a2c5 to your computer and use it in GitHub Desktop.
python tailf demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import re | |
| class Tail: | |
| def __init__(self, file=None, regex=None): | |
| self.__file = file | |
| self.__mode = 'r' | |
| self.__regex = regex | |
| def tail(self): | |
| with open(self.__file, self.__mode) as fd: | |
| fd.seek(0, 2) | |
| while True: | |
| cur = fd.tell() | |
| line = fd.readline() | |
| if line: | |
| rst = self.regex(line) | |
| if rst: | |
| yield rst | |
| def regex(self, data): | |
| print(self.__regex) | |
| r = re.compile(self.__regex) | |
| rst = re.match(r, data) | |
| if rst: | |
| return rst.group() | |
| if __name__ == "__main__": | |
| tail_obj = Tail(file='./access.log', regex='I Love Python.') | |
| for i in tail_obj.tail(): | |
| print(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment