【发布时间】:2009-04-26 14:07:21
【问题描述】:
每次在某个目录中创建新文件时,我都想解析一个文件。为此,我尝试使用pyinotify 设置一个目录来监视IN_CREATE 内核事件,并触发parse() 方法。
这是模块:
from pyinotify import WatchManager,
ThreadedNotifier, ProcessEvent, IN_CREATE
class Watcher(ProcessEvent):
watchdir = '/tmp/watch'
def __init__(self):
ProcessEvent.__init__(self)
wm = WatchManager()
self.notifier = ThreadedNotifier(wm, self)
wdd = wm.add_watch(self.watchdir, IN_CREATE)
self.notifier.start()
def process_IN_CREATE(self, event):
pfile = self._parse(event.pathname)
print(pfile)
def _parse(self, filename):
f = open(filename)
file = [line.strip() for line in f.readlines()]
f.close()
return file
if __name__ == '__main__':
Watcher()
问题是_parse返回的列表在被新的文件创建事件触发时是empty,像这样(文件是在另一个窗口中创建的,而watcher.py正在运行): p>
$ python watcher.py
[]
...但奇怪的是,当直接调用时,它在解释器会话中工作。
>>> import watcher
>>> w = watcher.Watcher()
>>> w._parse('/tmp/watch/sample')
['This is a sample file', 'Another line', 'And another...']
为什么会这样?我调试这个东西的最远距离是知道某些东西使 pyinotify 无法正确读取文件。但是……为什么?
【问题讨论】:
-
除了
IN_CREATE,你还应该挂上IN_MODIFY。即pyinotify.IN_CREATE| pyinotify.IN_MODIFY