Watchdog
是python 下的文件监控器,其实在任何语言中都有对文件夹进行监控的api,Watchdog
在python中用得是最大的一个。
在默写情况下,我们需要监控一个文件夹是否发生了变化,有没有新的文件写入,旧的文件有没有被修改,这些信息我们都非常的关心。
我们需要编写代码来监控这样的一个问题。而在一些语言中,监控 起来又非常的麻烦,这里的Watchdog
简单好用。
使用pip
来安装,简单方便。
$ python -m pip install -U watchdog
# or to install the watchmedo utility:
$ python -m pip install -U "watchdog[watchmedo]"
从源来安装:
$ python -m pip install -e .
# or to install the watchmedo utility:
$ python -m pip install -e ".[watchmedo]"
Watchdog
主要兼容的版本在3.6+
,2.7的如果需要使用,可以把版本降低到1.0.0.
一下。
一个简单的程序,使用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 '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()
如果出现以下的错误:
Traceback (most recent call last):
File "wd.py", line 15, in <module>
observer.start()
File "/usr/local/lib/python3.8/dist-packages/watchdog/observers/api.py", line 262, in start
emitter.start()
File "/usr/local/lib/python3.8/dist-packages/watchdog/utils/__init__.py", line 93, in start
self.on_thread_start()
File "/usr/local/lib/python3.8/dist-packages/watchdog/observers/inotify.py", line 118, in on_thread_start
self._inotify = InotifyBuffer(path, self.watch.is_recursive)
File "/usr/local/lib/python3.8/dist-packages/watchdog/observers/inotify_buffer.py", line 35, in __init__
self._inotify = Inotify(path, recursive)
File "/usr/local/lib/python3.8/dist-packages/watchdog/observers/inotify_c.py", line 167, in __init__
self._add_dir_watch(path, recursive, event_mask)
File "/usr/local/lib/python3.8/dist-packages/watchdog/observers/inotify_c.py", line 372, in _add_dir_watch
self._add_watch(full_path, mask)
File "/usr/local/lib/python3.8/dist-packages/watchdog/observers/inotify_c.py", line 386, in _add_watch
Inotify._raise_error()
File "/usr/local/lib/python3.8/dist-packages/watchdog/observers/inotify_c.py", line 398, in _raise_error
raise OSError(errno.ENOSPC, "inotify watch limit reached")
OSError: [Errno 28] inotify watch limit reached
把代码如下的代码添加到/etc/sysctl.conf
文件中
fs.inotify.max_user_watches=524288
并执行如下的命令:
sysctl -p
当我们改变文件夹的时候,会出现如下的提示:
2022-10-12 09:23:16 - Created file: ./error.log
2022-10-12 09:23:16 - Modified directory: .
2022-10-12 09:23:16 - Modified file: ./error.log
2022-10-12 09:23:16 - Modified directory: .