inotify包装器为指定的文件系统事件提供带超时的轮询
pollinotif的Python项目详细描述
1摘要
pollinotify是一个简单的扩展模块,它封装了linuxinotify服务,提供了一种监视的方法 发生在指定文件或指定目录中的特定类型的文件事件。它的主要卖点是 那:
1 It is polled, so instead of having to set up a background thread, or attach a separate event-watching package, the programmer calls it with an optional timeout, so it reports event that have already occurred, or waits for at most the specified time, or until an event occurs;
2 The polling can wait for specific kinds of event.
由于模块依赖于inotify服务,it仅在Linux上可用。
2模块结构
2.1常数
一些常量表示常见的Linux文件系统事件代码,具有友好的名称:
Constant Name | Linux Name | Interpretation |
---|---|---|
Access | IN_ACCESS | Object accessed |
Modify | IN_MODIFY | Object modified |
Attributes | IN_ATTRIB | Object attributes modified |
Open | IN_OPEN | File opened |
CloseWrite | IN_CLOSE_WRITE | File closed after contents changed |
CloseOther | IN_CLOSE_NOWRITE | File closed without contents changed |
Close | IN_CLOSE | File closed |
MoveFrom | IN_MOVED_FROM | Object moved from location |
MoveTo | IN_MOVED_TO | Object moved to location |
Move | IN_MOVE | Object moved |
MoveSelf | IN_MOVE_SELF | Object being monitored is deleted |
Create | IN_CREATE | Object created |
Delete | IN_DELETE | Object deleted |
DeleteSelf | IN_DELETE_SELF | Object being monitored is deleted |
Ignored | IN_IGNORED | Ignored |
DirEvent | IN_ISDIR | The monitored object to which the event occurred is a directory |
AllEvents | IN_ALL_EVENTS | Any event |
2.2实用功能
- maskasstring(掩码)
- 接受一个等于一个或多个事件常量{em1}$或-ed的值 并返回一个可读的字符串表示形式,由一个分隔的空格组成 匹配事件的名称列表
2.3fileevent类
fileevent表示inotify服务检测到的事件。事件信息已保存 在属性中:
- self.path
- 发生事件的文件或目录的路径
- self.mask
- 表示所遭受事件的值,表示为事件代码的或-ed集合,一个用于 检测到的每种事件
- self.decode()
- 返回事件对应的事件类型的名称列表
- self.matches(掩码)
- 返回true如果参数是对象所表示的事件类型之一的代码,false 否则
此外,如果e是fileevent对象,则
str(e) = maskAsString(e.mask) len(e) = len(e.decode()) x in e = e.matches(x)
2.4watcher类
模块的基本类。它连接到系统inotify服务并使用它 轮询一个或多个指定文件系统路径中的事件。轮询基于超时, 也可以是非阻塞的。
它有以下方法:
- \u初始化
- 无参数构造函数
- addpath(path,mode=allevents)
- 将path添加到要轮询事件的目录列表中;轮询 只收集与或-ed事件代码掩码匹配的事件 在可选参数mode中指定(默认为所有事件)
- poll(超时=0)
- 轮询指定路径上发生的事件,返回 true如果有,则false否则;超时 在timeout毫秒之后,在这种情况下返回false
- 事件(匹配=所有事件)
- 返回fileevent对象的列表,一个用于 上次轮询会话期间检测到的每个事件 与指定的可选或-ed事件代码掩码匹配的
- npaths()
- 返回当前在监视程序中注册的路径数
- nevents()
- 返回上次轮询会话中检测到的事件数
如果w是watcher实例,则
len(w) = w.nEvents() iter(w) = iter(w.events())
3示例
一个简单的例子,它以1秒的超时轮询并列出这些事件 与中的文件创建或修改(包括touch)相对应 用户的主目录。
import pollinotify n=pollinotify.Watcher() n.addPath('~') while True: got=n.poll(timeout=1000) if got: events=n.events(match=notify.CloseWrite) print('Got{} events'.format(len(events)) for event in events: print('{} : {} : {}'.format(event.path,event.mask,str(event)))