gorakhargosh/watchdog
GitHub: gorakhargosh/watchdog
跨平台 Python 文件系统事件监控库,提供 API 和命令行工具,支持实时检测目录中文件的创建、修改、删除和移动等变更。
Stars: 7359 | Forks: 747
# Watchdog
|PyPI Version|
|PyPI Status|
|PyPI Python Versions|
|GitHub Build Status|
|GitHub License|
.. tip::
用于监控文件系统事件的 Python API 和 shell 实用工具。
适用于 3.9+ 版本。
## API 使用示例
一个使用 watchdog 监控指定为命令行参数的目录并记录生成事件的简单程序:
.. code-block:: python
```
import time
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
class MyEventHandler(FileSystemEventHandler):
def on_any_event(self, event: FileSystemEvent) -> None:
print(event)
event_handler = MyEventHandler()
observer = Observer()
observer.schedule(event_handler, ".", recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()
```
或者,你可以将 observer 作为上下文管理器使用,以获得更简洁的代码:
.. code-block:: python
```
import time
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
class MyEventHandler(FileSystemEventHandler):
def on_any_event(self, event: FileSystemEvent) -> None:
print(event)
event_handler = MyEventHandler()
observer = Observer()
observer.schedule(event_handler, ".", recursive=True)
with observer:
while True:
time.sleep(1)
```
## Shell 实用工具
Watchdog 附带了一个名为 ``watchmedo`` 的*可选*实用脚本。
请在 shell 提示符下输入 ``watchmedo --help`` 以了解有关此工具的更多信息。
以下是如何递归记录当前目录中仅与 ``*.py`` 和 ``*.txt`` 文件相关的事件,同时忽略所有目录事件的方法:
.. code-block:: bash
```
watchmedo log \
--patterns='**/*.py;**/*.txt' \
--ignore-directories \
--recursive \
--verbose \
.
```
你可以使用 ``shell-command`` 子命令来响应事件并执行 shell 命令:
.. code-block:: bash
```
watchmedo shell-command \
--patterns='**/*.py;**/*.txt' \
--recursive \
--command='echo "${watch_src_path}"' \
.
```
请通过输入以下命令来查看这些命令的帮助信息:
.. code-block:: bash
```
watchmedo [command] --help
```
### 关于 ``watchmedo`` 技巧
``watchmedo`` 可以读取 ``tricks.yaml`` 文件,并在响应文件系统事件时执行其中的技巧。技巧实际上是继承自 ``watchdog.tricks.Trick`` 的事件处理程序,由插件作者编写。相比于常规的事件处理程序,Trick 类增加了一些额外的功能。
一个 ``tricks.yaml`` 文件示例:
.. code-block:: yaml
```
tricks:
- watchdog.tricks.LoggerTrick:
patterns: ["**/*.py", "**/*.js"]
- watchmedo_webtricks.GoogleClosureTrick:
patterns: ['**/*.js']
hash_names: true
mappings_format: json # json|yaml|python
mappings_module: app/javascript_mappings
suffix: .min.js
compilation_level: advanced # simple|advanced
source_directory: app/static/js/
destination_directory: app/public/js/
files:
index-page:
- app/static/js/vendor/jquery*.js
- app/static/js/base.js
- app/static/js/index-page.js
about-page:
- app/static/js/vendor/jquery*.js
- app/static/js/base.js
- app/static/js/about-page/**/*.js
```
包含 ``tricks.yaml`` 文件的目录将被监控。每个 Trick 类在初始化时,会使用 ``tricks.yaml`` 文件中对应的键作为参数,并且当事件到达时,这些事件会被传递给该类的实例。
## 安装
使用 ``pip`` 从 PyPI 安装:
.. code-block:: bash
```
$ python -m pip install -U watchdog
# 或安装 watchmedo 工具:
$ python -m pip install -U 'watchdog[watchmedo]'
```
从源码安装:
.. code-block:: bash
```
$ python -m pip install -e .
# 或安装 watchmedo 工具:
$ python -m pip install -e '.[watchmedo]'
```
## 文档
你可以在线浏览最新版本的 documentation_。
## 支持的平台
* Linux 2.6 (inotify)
* macOS (FSEvents, kqueue)
* FreeBSD/BSD (kqueue)
* Windows (ReadDirectoryChangesW with I/O completion ports;
ReadDirectoryChangesW worker threads)
* OS-independent (polling the disk for directory snapshots and comparing them
periodically; slow and not recommended)
请注意,当 watchdog 与 kqueue 一起使用时,你需要增加系统允许程序打开的文件描述符数量,使其多于你将要监控的文件数量。最简单的方法是编辑你的 ``~/.profile`` 文件,并添加类似于以下内容的一行代码:
```
ulimit -n 1024
```
或者:
```
ulimit -n unlimited
```
这是 kqueue 固有的问题,因为它使用文件描述符来监控文件。加上 watchdog 为了监控文件描述符而需要做的大量内部状态维护,使得这成为一种令人痛苦的监控文件和目录的方式。本质上,当监控包含大量文件的深层嵌套目录时,kqueue 并不是一种具有良好扩展性的方式。
## 自由线程支持
`watchdog` 支持在自由线程 (free-threaded) 的 CPython 下构建和运行。但是,尚未完成完整的线程安全审计,特别是这会影响 `macOS FSEvents` 接口。
## 关于与 Vim 等编辑器一起使用 watchdog
除非有明确指示,否则 Vim 不会直接修改文件。
它会创建备份文件,然后将它们交换以替换磁盘上你正在编辑的文件。这意味着如果你使用 Vim 编辑文件,watchdog 将不会触发这些文件的 on-modified 事件。
你可能需要适当配置 Vim 以禁用此功能。
## 关于与 CIFS 一起使用 watchdog
当你想要监控 CIFS 中的更改时,你需要明确告诉 watchdog 使用 ``PollingObserver``,也就是说,不要像上面的示例那样让 watchdog 自行决定合适的 observer,而是这样做:
```
from watchdog.observers.polling import PollingObserver as Observer
```
## 依赖
1. Python 3.9 或更高版本。
2. XCode_(仅在从源码安装时用于 macOS)
3. PyYAML_(仅用于 ``watchmedo``)
## 使用 Watchdog 的应用程序
* `Watchdog.app`_ — 一个用于监控所选目录中文件更改的 macOS 应用程序。它使用 OMC 引擎构建,提供了一个用于观察目录的图形界面。
经过 Apple 公证的应用可以直接使用,无需额外安装。
## 许可
Watchdog 根据 `Apache License, version 2.0`_ 的条款进行许可。
- 版权所有 2018-2025 Mickaël Schoentgen 及贡献者
- 版权所有 2014-2018 Thomas Amland 及贡献者
- 版权所有 2012-2014 Google, Inc.
- 版权所有 2011-2012 Yesudeep Mangalapilly
项目 `source code`_ 可在 Github 上获取。请在 `issue tracker`_ 中报告错误并提出功能增强请求。
## 为什么要有 Watchdog?
有太多人尝试做同样的事情,但没有一个能满足我需要 Python 做到的:
* pnotify_
* `unison fsmonitor`_
* fsmonitor_
* guard_
* pyinotify_
* `inotify-tools`_
* jnotify_
* treewatcher_
* `file.monitor`_
* pyfilesystem_
.. links:
.. _Yesudeep Mangalapilly: yesudeep@gmail.com
.. _source code: https://github.com/gorakhargosh/watchdog
.. _issue tracker: https://github.com/gorakhargosh/watchdog/issues
.. _Apache License, version 2.0: https://www.apache.org/licenses/LICENSE-2.0
.. _documentation: https://python-watchdog.readthedocs.io/
.. _stackoverflow: https://stackoverflow.com/questions/tagged/python-watchdog
.. _repository: https://github.com/gorakhargosh/watchdog
.. _issue tracker: https://github.com/gorakhargosh/watchdog/issues
.. _changelog: https://github.com/gorakhargosh/watchdog/blob/master/changelog.rst
.. _PyYAML: https://www.pyyaml.org/
.. _XCode: https://developer.apple.com/technologies/tools/xcode.html
.. _Watchdog.app: https://github.com/abra-code/WatchdogApp
.. _pnotify: http://mark.heily.com/pnotify
.. _unison fsmonitor: https://webdav.seas.upenn.edu/viewvc/unison/trunk/src/fsmonitor.py?view=markup&pathrev=471
.. _fsmonitor: https://github.com/shaurz/fsmonitor
.. _guard: https://github.com/guard/guard
.. _pyinotify: https://github.com/seb-m/pyinotify
.. _inotify-tools: https://github.com/rvoicilas/inotify-tools
.. _jnotify: http://jnotify.sourceforge.net/
.. _treewatcher: https://github.com/jbd/treewatcher
.. _file.monitor: https://github.com/pke/file.monitor
.. _pyfilesystem: https://github.com/PyFilesystem/pyfilesystem
.. |PyPI Version| image:: https://img.shields.io/pypi/v/watchdog.svg
:target: https://pypi.python.org/pypi/watchdog/
.. |PyPI Status| image:: https://img.shields.io/pypi/status/watchdog.svg
:target: https://pypi.python.org/pypi/watchdog/
.. |PyPI Python Versions| image:: https://img.shields.io/pypi/pyversions/watchdog.svg
:target: https://pypi.python.org/pypi/watchdog/
.. |Github Build Status| image:: https://github.com/gorakhargosh/watchdog/workflows/Tests/badge.svg
:target: https://github.com/gorakhargosh/watchdog/actions?query=workflow%3ATests
.. |GitHub License| image:: https://img.shields.io/github/license/gorakhargosh/watchdog.svg
:target: https://github.com/gorakhargosh/watchdog/blob/master/LICENSE
.. |Patreon| image:: https://img.shields.io/badge/Patreon-F96854?style=for-the-badge&logo=patreon&logoColor=white
:target: https://www.patreon.com/mschoentgen
标签:CLI, FSEvents, inotify, Python, ReadDirectoryChangesW, Shell工具, SOC Prime, Watchdog, WiFi技术, 事件监听, 库, 应急响应, 开发工具, 恶意代码分类, 文件变动, 文件系统事件, 文件系统监控, 无后门, 日志, 目录监控, 网络调试, 自动化, 运维工具, 逆向工具