使用python watchdog检查特定文件是否已被修改

时间:2015-08-31 14:46:02

标签: python file watchdog

我想知道如何检查文件夹下特定文件的更改。我发现看门狗模块可以检查文件夹中文件的更改,但我只需要1个文件(带有固定名称)。

请在此帮助,谢谢。

class MyHandler(FileModifiedEvent):
    def on_modified(self, event):

if __name__ == "__main__":
        integrity_file_path = DATASTORE_DIRECTORY_PATH + '/schedule.xml'
        event_handler = MyHandler()
        observer = Observer()
        observer.schedule(MyHandler(), path=integrity_file_path,recursive=True)
        observer.start()

        try:
            while True:
                time.sleep(5)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()

2 个答案:

答案 0 :(得分:4)

您可以继承watchdog.events.PatternMatchingEventHandler事件处理程序并将其修改为在事件的情况下执行任何操作。 您可以将模式设置为要监视的文件名。

然而,这个有点棘手。在封面下,它使用pathtools.patterns进行模式匹配。 它还将目录附加到匹配的模式。这意味着您需要将文件的完整路径作为文件名“pattern”参数传递到事件处理程序中。 如果不这样做,模式匹配将失败,您将不会收到任何事件通知。

以下是一个例子:

import sys, os.path, time, logging
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler


class MyEventHandler(PatternMatchingEventHandler):
    def on_moved(self, event):
        super(MyEventHandler, self).on_moved(event)
        logging.info("File %s was just moved" % event.src_path)

    def on_created(self, event):
        super(MyEventHandler, self).on_created(event)
        logging.info("File %s was just created" % event.src_path)

    def on_deleted(self, event):
        super(MyEventHandler, self).on_deleted(event)
        logging.info("File %s was just deleted" % event.src_path)

    def on_modified(self, event):
        super(MyEventHandler, self).on_modified(event)
        logging.info("File %s was just modified" % event.src_path)

def main(file_path=None):
    logging.basicConfig(level=logging.INFO,
        format='%(asctime)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')
    watched_dir = os.path.split(file_path)[0]
    print 'watched_dir = {watched_dir}'.format(watched_dir=watched_dir)
    patterns = [file_path]
    print 'patterns = {patterns}'.format(patterns=', '.join(patterns))
    event_handler = MyEventHandler(patterns=patterns)
    observer = Observer()
    observer.schedule(event_handler, watched_dir, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()



if __name__ == "__main__":
    if len(sys.argv) > 1:
        path = sys.argv[1]
        main(file_path=path.strip())
    else:
        sys.exit(1)

执行watchdog python脚本(在修改文件之前):

(stackoverflow)[root@joeyoung.io stackoverflow]# python watchschedule.py /usr/local/src/stackoverflow/watchdog/schedule.xml
watched_dir = /usr/local/src/stackoverflow/watchdog
patterns = /usr/local/src/stackoverflow/watchdog/schedule.xml

在单独的控制台中修改schedule.xml文件:

[root@joeyoung.io watchdog]# echo "I just modified this file" >> schedule.xml

修改schedule.xml后的结果:

(stackoverflow)[root@joeyoung.io stackoverflow]# python watchschedule.py /usr/local/src/stackoverflow/watchdog/schedule.xml
watched_dir = /usr/local/src/stackoverflow/watchdog
patterns = /usr/local/src/stackoverflow/watchdog/schedule.xml
2015-08-31 19:30:31 - File /usr/local/src/stackoverflow/watchdog/schedule.xml was just modified

答案 1 :(得分:0)

我想说你可以根据

检查文件的修改时间

How to get file creation & modification date/times in Python?

定义阈值并将当前时间与修改时间进行比较,您可能知道文件是否已更新。如果文件没有经常超级修改,这将有效。

但无论如何,如果有人打开文件,键入一些垃圾然后删除并保存,那将是误报。