Python有没有办法监测txt被更改的内容,并记录内容和时间?
补充一下:
我现在有一个软件会生成一个txt的log,但是每一个条目添加只是单纯的换行,我现在想知道每一条被添加的时间。
给你说下思路吧。
用python定时去读这个文件检查里面内容,例如每隔1min,10min?具体情况视你的需求来定;
如果内容不太长的话可以直接比较前后的字符串,如果内容比较大可以尝试比较前后两个文件的md5值;
检查到变动之后将变动以及变动的时间保存下来,可以以文本文件的形式保存;
你的软件添加log的时候,把时间添加上去就是了
用 pyinotify 或者 watchdog 都可以,但是对于你的需求来说都比较浪费代码。其实你只需要调用 tail -f 命令,然后一行一行地读它的输出就可以了。
记得好像有个叫watchdog的模块可以实现监控文件变动.
另外如果要记录修改的内容的话,那就只限于文本了..这个只要能diff出来,就能记录了。自己实现也可以。
可以使用python的ifnotify模块来做,具体代码如下:
#coding = utf-8 import os import pyinotify class OnWriteHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): print "create file: %s " % os.path.join(event.path,event.name) def process_IN_MODIFY(self, event): print "modify file: %s " % os.path.join(event.path,event.name) def auto_compile(path='/home/dyp/test'): wm = pyinotify.WatchManager() mask = pyinotify.IN_CREATE | pyinotify.IN_MODIFY # 还有删除等,可以查看下官网资料 notifier = pyinotify.Notifier(wm, OnWriteHandler()) wm.add_watch(path, mask, rec=True, auto_add=True) print '==start to watch path: %s' % path while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break if __name__ == "__main__": auto_compile() #启动之后,可以到指定的目录下面创建或者修改文件,然后看shell输出信息
watchdog
安装:
pip install watchdog
python3
import os, sys
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class FileEventHandler(FileSystemEventHandler):
def __init__(self):
FileSystemEventHandler.__init__(self)
def on_modified(self, event):
if not event.is_directory:
path = os.path.realpath(event.src_path)
print("被修改的文件> {0}".format(path))
ext = os.path.splitext(path)[1]
if ext == '.txt':
txt = open(path).read()
print("文件内容>")
print(txt)
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = FileEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
print('正在监视文件夹:%s' % os.path.realpath(path))
print('Ctrl-C 退出程序!')
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()