inotify 是 Linux 系统中的一个功能,用于监控文件系统事件。它在 Ubuntu 和其他基于 Linux 的发行版中可用。然而,在非 Linux 系统(如 Windows 或 macOS)上,您需要使用其他方法来监控文件系统事件。
对于跨平台的解决方案,您可以使用第三方库,例如 watchdog。watchdog 是一个 Python 库,可以在 Windows、macOS 和 Linux 上运行。它提供了一个简单的 API 来监控文件系统事件。
以下是如何在 Ubuntu 和其他平台上使用 watchdog 的示例:
- 首先,安装
watchdog:
pip install watchdog
- 创建一个名为
watcher.py的 Python 脚本,并添加以下代码:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f"文件 {event.src_path} 已修改")
def on_created(self, event):
print(f"文件 {event.src_path} 已创建")
def on_deleted(self, event):
print(f"文件 {event.src_path} 已删除")
if __name__ == "__main__":
path = "/path/to/your/directory"
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
-
将
/path/to/your/directory替换为您要监控的目录。 -
运行脚本:
python watcher.py
现在,无论您在哪个平台上,watchdog 都会监控指定目录中的文件系统事件,并在事件发生时打印相应的消息。