tail -f with adaptable filter
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

tail.py 2.5KB

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