姬長信(Redy)

python – 在创建时读取文件的pyinotify错误?


我想在每次在某个目录中创建新文件时解析文件.为此,我尝试使用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返回的列表在被新文件创建事件触发时是空的,就像这样(当watcher.py运行时,文件在另一个窗口中创建):

$python watcher.py
[]

…但奇怪的是,它直接调用时从解释器会话开始工作.

>>> import watcher
>>> w = watcher.Watcher()
>>> w._parse('/tmp/watch/sample')
['This is a sample file', 'Another line', 'And another...']

为什么会这样?我调试这个东西的最远的地方就是要知道有些东西正在使pyinotify无法正确读取文件.但为什么?