好的,我不知道它是否会有所帮助,但在这里你可以如何做到:
假设我们有一个文件:
echo "line 1" >> testfile.txt
比写一个脚本(确保你指向这个文件):
import os, pyinotify
PATH = os.path.join(os.path.expanduser('~/'), 'testfile.txt')
class EventHandler(pyinotify.ProcessEvent):
def __init__(self, *args, **kwargs):
super(EventHandler, self).__init__(*args, **kwargs)
self.file = open(PATH)
self.position = 0
self.print_lines()
def process_IN_MODIFY(self, event):
self.print_lines()
def print_lines(self):
new_lines = self.file.read()
last_n = new_lines.rfind('\n')
if last_n >= 0:
self.position += last_n + 1
print new_lines[:last_n]
else:
print 'no line'
self.file.seek(self.position)
wm = pyinotify.WatchManager()
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)
wm.add_watch(PATH, pyinotify.IN_MODIFY, rec=True)
notifier.loop()
运行文件:
python notify.py
你会看见
line 1
比从不同终端添加另一行到文件(确保脚本仍在运行)
echo "line 2" >> testfile.txt
你会在脚本输出中看到它