2020-02-12 文件系统监控

watchdog用来监控指定目录/文件的变化,如添加删除文件或目录、修改文件内容、重命名文件或目录等,每种变化都会产生一个事件,且有一个特定的事件类与之对应,然后通过事件处理类来处理对应的事件,怎么样处理事件完全可以自定义,只需继承事件处理类的基类并重写对应实例的方法。

from watchdog.observers import Observer
from watchdog.events import *
import time


class FileEventHandler(FileSystemEventHandler):

    def __init__(self):
        FileSystemEventHandler.__init__(self)

    def on_moved(self, event):
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if event.is_directory:
            print(f"{ now } 文件夹由 { event.src_path } 移动至 { event.dest_path }")
        else:
            print(f"{ now } 文件由 { event.src_path } 移动至 { event.dest_path }")

    def on_created(self, event):
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if event.is_directory:
            print(f"{ now } 文件夹 { event.src_path } 创建")
        else:
            print(f"{ now } 文件 { event.src_path } 创建")

    def on_deleted(self, event):
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if event.is_directory:
            print(f"{ now } 文件夹 { event.src_path } 删除")
        else:
            print(f"{ now } 文件 { event.src_path } 删除")

    def on_modified(self, event):
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if event.is_directory:
            print(f"{ now } 文件夹 { event.src_path } 修改")
        else:
            print(f"{ now } 文件 { event.src_path } 修改")


if __name__ == "__main__":
    observer = Observer()
    event_handler = FileEventHandler()
    path = r"F:\Python\test"
    observer.schedule(event_handler, path, True)
    print(f"监控目录{path}")
    observer.start()
    observer.join()

运维中以下场景十分适合使用watchdog:
(1)监控文件系统中文件或目录的增、删、改情况。
(2)当特定的文件被创建、删除、修改、移动时执行相应的任务。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  •   JavaScript 与 HTML 之间的交互是通过事件实现的。   事件,就是文档或浏览器窗口中发生的一些特...
    霜天晓阅读 3,662评论 1 11
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,690评论 0 5
  • 早习惯了 我躲在你不知道的地方 欣赏 或者憧憬 看你身边的浪 看携着你的风 看那撒欢的 如何陪着你 从春到夏从秋到...
    本无痕阅读 1,190评论 14 43
  • 千年梦幻为谁狂, 本是浮尘无根人! 心灰意冷无情否, 魂牵梦...
    千山慕箫北阅读 272评论 0 0
  • 做为一个人,既便单身,你也得有个家。你不能总去街上乱跑。既便用不着起火落灶,你也得有个安神落梦的地方。 家,其实不...
    牛犁阅读 909评论 18 21

友情链接更多精彩内容