很多时候,我们需要及时对文件系统(file sytem)的变化进行监控,以便第一时间 增量处理。Python 在这方面提供两个非常优秀的第三方开源工具:watchdog
和 pyinotify
,背后都是依赖 Linux 系统的 inotify
库。
inotify 是一个Linux系统的特性,用于监控文件系统操作,比如:读取、写入和创建,比频繁的轮询要高效很多。
当然,监控文件系统时,我们可以轮询的方式,但这样效果非常低,极不优雅。所以,强烈建议使用 watchdog
或 pyinotify
。
库 | 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]