pyinotify asyncio监控文件和文件夹变化

你可能会问,为什么不用python的watchdog?因为watchdog用户可重写的实例方法就那么几个:

self.on_any_event(event)
# 任何事件发生都会首先执行该方法,该方法默认为空,dispatch()方法会先执行该方法,然后再把 event 分派给其他方法处理
self.on_moved(event)
# 处理 DirMovedEvent 和 FileMovedEvent 事件,默认为空
self.on_created(event)
# 处理 DirCreatedEvent 和 FileCreatedEvent 事件,默认为空
self.on_deleted(event)
# 处理 DirDeletedEvent 和 FileDeletedEvent 事件,默认为空
self.on_modified(event)
# 处理 DirModifiedEvent 和 FileModifiedEvent 事件,默认为空

它无法判断文件操作是否完成,你需要自己写其他逻辑来判断。关于watchdog在CSDN有篇很详尽的博文–WatchDog 使用经验总结,以上事件也转自那篇博文。

下面我们来说说pyinotify,Pyinotify依赖于Linux内核的功能—inotify(内核2.6.13合并),它支持的事件如下:

@cvar IN_ACCESS: File was accessed.
@type IN_ACCESS: int
@cvar IN_MODIFY: File was modified.
@type IN_MODIFY: int
@cvar IN_ATTRIB: Metadata changed.
@type IN_ATTRIB: int
@cvar IN_CLOSE_WRITE: Writtable file was closed.
@type IN_CLOSE_WRITE: int
@cvar IN_CLOSE_NOWRITE: Unwrittable file closed.
@type IN_CLOSE_NOWRITE: int
@cvar IN_OPEN: File was opened.
@type IN_OPEN: int
@cvar IN_MOVED_FROM: File was moved from X.
@type IN_MOVED_FROM: int
@cvar IN_MOVED_TO: File was moved to Y.
@type IN_MOVED_TO: int
@cvar IN_CREATE: Subfile was created.
@type IN_CREATE: int
@cvar IN_DELETE: Subfile was deleted.
@type IN_DELETE: int
@cvar IN_DELETE_SELF: Self (watched item itself) was deleted.
@type IN_DELETE_SELF: int
@cvar IN_MOVE_SELF: Self (watched item itself) was moved.
@type IN_MOVE_SELF: int
@cvar IN_UNMOUNT: Backing fs was unmounted.
@type IN_UNMOUNT: int
@cvar IN_Q_OVERFLOW: Event queued overflowed.
@type IN_Q_OVERFLOW: int
@cvar IN_IGNORED: File was ignored.
@type IN_IGNORED: int
@cvar IN_ONLYDIR: only watch the path if it is a directory (new
                  in kernel 2.6.15).
@type IN_ONLYDIR: int
@cvar IN_DONT_FOLLOW: don't follow a symlink (new in kernel 2.6.15).
                      IN_ONLYDIR we can make sure that we don't watch
                      the target of symlinks.
@type IN_DONT_FOLLOW: int
@cvar IN_EXCL_UNLINK: Events are not generated for children after they
                      have been unlinked from the watched directory.
                      (new in kernel 2.6.36).
@type IN_EXCL_UNLINK: int
@cvar IN_MASK_ADD: add to the mask of an already existing watch (new
                   in kernel 2.6.14).
@type IN_MASK_ADD: int
@cvar IN_ISDIR: Event occurred against dir.
@type IN_ISDIR: int
@cvar IN_ONESHOT: Only send event once.
@type IN_ONESHOT: int
@cvar ALL_EVENTS: Alias for considering all of the events.
@type ALL_EVENTS: int

如果你需要监控一个文件夹,它定期有文件上传,上传完成后需要对最新的文件进行操作,那么使用pyinotifyIN_CLOSE_WRITE事件就非常合适。
使用pyinotify的方法有如下几种:

  1. Using the Notifier class without timeout
    The corresponding tutorial file can be found here: tutorial_notifier.py
  2. Using the Notifier class with a timeout
  3. Using the ThreadedNotifier Class
    The corresponding tutorial file can be found here: tutorial_threadednotifier.py.
  4. Using the AsyncNotifier Class
    The corresponding tutorial file can be found here: tutorial_asyncnotifier.py.
  5. 由于python3.6之后,asyncore已经被asyncio 取代,所以有了这个诡异的官方例程:pyinotify/asyncio_notifier.py。里面完全没写各种事件怎么处理,文档也没有。

后来一番搜索,终于找到了这个Using pyinotify with python 3 asyncio,代码如下:

import pyinotify
import asyncio


class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        if not event.dir:
            print("Got new file: ", event.pathname)
            print("Something changed in path: ", event.path)
            print("The file changed: ", event.name)

wm = pyinotify.WatchManager()  # Watch Manager
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE  # watched events

loop = asyncio.get_event_loop()

notifier = pyinotify.AsyncioNotifier(wm, loop, default_proc_fun=EventHandler())
wdd = wm.add_watch('.', mask, rec=True, auto_add=True)

try:
    loop.run_forever()
except:
    print('\nshutting down...')

loop.stop()
notifier.stop()

参考文献:

  1. python文件夹,文件监听工具(pyinotify,watchdog)
  2. pyinotify
  3. Tutorial · seb-m/pyinotify Wiki
  4. Using pyinotify with python 3 asyncio
  5. WatchDog 使用经验总结
<think>好的,我现在需要解决用户的问题,关于使用Python实时监控文件夹变化的解决方案。首先,用户提到了几个引用,我需要先理解这些引用的内容,看看是否有相关的库或方法已经被提到。 引用[1]提到了PyInotify,这个库用于监听文件系统的变化,并且可以集成到Django或Flask等框架中。引用[2]讨论了在Windows下监控新增文件夹的需求,可能使用了不同的库,比如watchdog。引用[3][4]也提到了实时监控文件夹中的文件变化,特别是处理日志文件的情况,可能涉及到持续读取新文件的需求。 接下来,我需要确定Python中常用的库有哪些。常见的库包括watchdogpyinotify。watchdog是一个跨平台的库,支持Linux、macOSWindows,而pyinotify主要针对Linux系统,因为inotify是Linux内核的特性。用户的问题没有指定操作系统,但引用[2][4]提到了Windows,所以需要确保推荐的库在Windows下可用。 watchdog库应该是首选,因为它跨平台,且API友好。而pyinotify可能在Windows上不可用,因此需要指出这一点。另外,用户可能还需要知道如何处理事件,比如创建、修改、删除等,以及如何编写事件处理程序。 另外,用户的问题还提到了生成相关问题,需要根据回答内容提出相关问题,比如如何过滤特定事件、处理性能问题、与其他框架集成等。 现在需要整理步骤,先介绍推荐的库,再给出代码示例,说明不同库的适用场景,最后生成相关问题。同时,要确保使用正确的LaTeX格式,行内公式用$...$,独立公式用$$...$$,但在这个问题中可能用不上太多数学公式,不过如果有性能分析可能需要用到。但根据用户的问题,可能不需要数学公式,所以重点放在代码库的介绍上。 需要检查是否有遗漏的库,比如os模块的轮询方式,虽然效率低,但简单。不过用户需要的是实时监控,所以可能更推荐watchdog或pyinotify。此外,引用[3]中提到的代码可能需要用到tail -f的功能,可以结合文件读取来实时监控日志文件变化。 最后,确保回答结构清晰,分点说明,代码示例正确,引用正确标注。同时,生成的相关问题要围绕监控文件夹变化的应用场景、优化方法、不同库比较等。</think>### Python实时监控文件夹变化的解决方案 在Python中,实时监控文件夹变化的常用工具库包括 **Watchdog** **PyInotify**。两者的核心原理均基于操作系统提供的文件系统事件通知机制,但适用场景平台支持有所不同。 --- #### 1. Watchdog(跨平台推荐) **Watchdog** 是一个跨平台库,支持 Windows、Linux macOS。它通过抽象不同操作系统的底层API(如Windows的 `ReadDirectoryChangesW` Linux的 `inotify`)实现统一的事件监听接口[^4]。 **安装方法**: ```bash pip install watchdog ``` **示例代码**(监控文件夹创建/修改/删除事件): ```python from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class MyHandler(FileSystemEventHandler): def on_modified(self, event): if not event.is_directory: 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 = "监控文件夹路径" observer = Observer() observer.schedule(MyHandler(), path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() ``` **特点**: - 支持递归监控子目录(`recursive=True`) - 可区分文件类型(通过 `event.is_directory`) - 跨平台兼容性强[^2][^4] --- #### 2. PyInotify(仅限Linux) **PyInotify** 基于Linux内核的 `inotify` 机制,性能高效但仅适用于Linux系统[^1]。 **安装方法**: ```bash pip install pyinotify ``` **示例代码**: ```python import pyinotify class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): print(f"新增文件: {event.pathname}") def process_IN_MODIFY(self, event): print(f"文件被修改: {event.pathname}") wm = pyinotify.WatchManager() handler = EventHandler() notifier = pyinotify.Notifier(wm, handler) wdd = wm.add_watch("监控文件夹路径", pyinotify.IN_CREATE | pyinotify.IN_MODIFY) notifier.loop() ``` **特点**: - 低延迟,适合高频率事件场景 - 支持细粒度事件(如权限变更、移动操作) --- #### 3. 其他方法:轮询检测(不推荐) 通过 `os.listdir()` 定期检查文件夹内容,适用于简单场景但效率较低: ```python import os import time def monitor_folder(path): previous = set(os.listdir(path)) while True: current = set(os.listdir(path)) added = current - previous removed = previous - current if added: print(f"新增文件: {added}") if removed: print(f"删除文件: {removed}") previous = current time.sleep(5) ``` --- ### 选择建议 - **跨平台需求** → 使用 **Watchdog** - **Linux高性能场景** → 使用 **PyInotify** - **与其他框架集成**(如Django/Flask) → Watchdog更易扩展[^1] --- 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值