Python监控(monitor)文件系统(Linux file system)事件(变化):watchdog、pyinotify

很多时候,我们需要及时对文件系统(file sytem)的变化进行监控,以便第一时间 增量处理。Python 在这方面提供两个非常优秀的第三方开源工具:watchdogpyinotify ,背后都是依赖 Linux 系统的 inotify 库。

inotify 是一个Linux系统的特性,用于监控文件系统操作,比如:读取、写入和创建,比频繁的轮询要高效很多。

当然,监控文件系统时,我们可以轮询的方式,但这样效果非常低,极不优雅。所以,强烈建议使用 watchdogpyinotify

github star 最近更新
watchdog https://github.com/gorakhargosh/watchdog 3.9k 2020-01
pyinotify https://github.com/seb-m/pyinotify 2k 2015-06

通过对比,不难发现 watchdog 大有取代 pyinotify 之势。所以,新项目就最好直接使用 watchdog ,但旧项目就没有必要替换掉 pyinotify 了。

watchdog

通过 pip install watchdog 安装之后,我们就可以在 Python 代码中直接使用 watchdog,十分方便。可以自己实现监控的回调函数,或直接用已经提供好的函数。

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    # 配置日志模块
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    # 定义监控目录的参数
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    
    # 日志事件句柄,实现了日志记录功能,也可以自己定义Handler
    event_handler = LoggingEventHandler()
    observer = Observer()

	# 定义监控
    observer.schedule(event_handler, path, recursive=True)
    
    # 启动
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

LoggingEventHandler 的实现代码如下:

class LoggingEventHandler(FileSystemEventHandler):
    """Logs all the events captured."""

    def on_moved(self, event):
        super(LoggingEventHandler, self).on_moved(event)

        what = 'directory' if event.is_directory else 'file'
        logging.info("Moved %s: from %s to %s", what, event.src_path,
                     event.dest_path)

    def on_created(self, event):
        super(LoggingEventHandler, self).on_created(event)

        what = 'directory' if event.is_directory else 'file'
        logging.info("Created %s: %s", what, event.src_path)

    def on_deleted(self, event):
        super(LoggingEventHandler, self).on_deleted(event)

        what = 'directory' if event.is_directory else 'file'
        logging.info("Deleted %s: %s", what, event.src_path)

    def on_modified(self, event):
        super(LoggingEventHandler, self).on_modified(event)

        what = 'directory' if event.is_directory else 'file'
        logging.info("Modified %s: %s", what, event.src_path)

我们就可以照葫芦画瓢了,实现自己想要的回调函数,官方的文档 的质量不是特别高,有些内容需要我们阅读源码,还好源码不是很复杂。

pyinotify

pyinotify 已经是老牌的文件系统监控的库了,已经比较稳定了,功能方面也满足需求。

也是可以通过 pip install pyinotify 进行安装。

import pyinotify

wm = pyinotify.WatchManager()

# 定义监控事件,删除和创建
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE 

# 返回的对象,方便之后的管理,比如:删除等
wdd = wm.add_watch('/tmp', mask, rec=True)

# 定义回调函数
class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        print "Creating:", event.pathname

    def process_IN_DELETE(self, event):
        print "Removing:", event.pathname


handler = EventHandler()

# 将回调函数和监控组合
notifier = pyinotify.Notifier(wm, handler)

# 循环监控
notifier.loop()

相比 watchdog 的 API,pyinotify 的 API 稍微繁琐了一点点,整体上不分伯仲。pyinotify 的文档方面要强于 watchdog ,有大量的细节讲解。

总结

watchdog 目前还在持续更新,热度也很高,所以相比 pyinotify 已经很长时间不更新了,watchdog 的使用前景更可期待,API 的风格更符合现在的代码设计,推荐使用 watchdog

最后,安利大家一本书《深入理解NLP的中文分词:从原理到实践》,让你从零掌握中文分词技术,踏入NLP的大门。

如果因为以上内容对你有所帮助,希望你能帮个忙,点个赞、评个论、转个发,关个注。

此公众号每周分享一篇干货文章,实实在在把一个课题说明白,讲清楚,望关注!
Python监控(monitor)文件系统(Linux file system)事件(变化):watchdog、pyinotify

Python监控(monitor)文件系统(Linux file system)事件(变化):watchdog、pyinotifyPython监控(monitor)文件系统(Linux file system)事件(变化):watchdog、pyinotify 周星星0_o 发布了12 篇原创文章 · 获赞 18 · 访问量 4848 私信 关注
上一篇:linux内核bug问题排查过程详细报告


下一篇:k8s node节点网络插件工作正常、kubelet工作正常情况下,node状态为NotReady,导致pod调度失败的排查过程。