Python pyinotify用于查看文件夹中的新文件创建

Python pyinotify用于查看文件夹中的新文件创建,python,watch,pyinotify,Python,Watch,Pyinotify,我正在用python中的pyinotify模块监视一个文件夹。但是创建文件的速度比pyinotify的事件处理程序处理文件的速度要快。有没有办法解决这个问题,事件处理程序可以将创建的所有新文件排成一行或稍后处理 代码段: class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): print "Creating:", event.pathname #star

我正在用python中的pyinotify模块监视一个文件夹。但是创建文件的速度比pyinotify的事件处理程序处理文件的速度要快。有没有办法解决这个问题,事件处理程序可以将创建的所有新文件排成一行或稍后处理

代码段:

class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        print "Creating:", event.pathname
        #start_time=time.time()
        #reading the data 
        with open(str(event.pathname)) as ofile:
            d = json.loads(ofile.read())
            for _id in d:
                if d[_id]["_comment"]>0:
                    inputdata.update({_id:{"la":d[message_id]["la"],"lo":d[_id]["lo"]}})


        try:
            getcdata(inputdata,outfile)
        except RuntimeError as e:
            logger.error('Caught a Rutime exception in the getcdatadriver . '+str(e.value))

def main():
    logger = logging.getLogger('mainloop')
    logger.setLevel(logging.DEBUG)
    fh = logging.FileHandler('getcdatadriver.log')
    logger.addHandler(fh)

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    sys.excepthook=Notify(logger,"Exception caught getcdatadriver mainloop").my_excepthook
    try:
        while True:
                watch_dir="./output_watchdir"
                wm = pyinotify.WatchManager()  # Watch Manager
                mask = pyinotify.IN_CREATE  # watched events
                handler = EventHandler()
                notifier = pyinotify.Notifier(wm, handler)
                wdd = wm.add_watch(watch_dir, mask, rec=True)
                notifier.loop()
    except (KeyboardInterrupt, SystemExit):
        print '\n! Received keyboard interrupt, quitting.\n'
        Notify(logger,"getcdatadriver stopped").send_exception_email('Received keyboard interrupt, quitting.')
    except RuntimeError as e:
        print 'Caught a Rutime exception in the getcdatadriver mainloop. '+str(e.value)
        Notify(logger,"Runtime Exception getcdatadriver mainloop").send_exception_email(str(e.value))

阿肯沙,请澄清你的问题。说得更清楚些。通常,它有助于添加代码片段和您收到的任何错误。是的,inotify可能会丢失数据,它自己的文档建议您尝试清理不一致之处。我想你的手表是越窄越好。将事件处理保持在最低限度。。。。可能将它排队到另一个线程进行任何实际工作。没有收到任何错误。但是,以下func仅在监视目录中创建的少数文件上调用:几年前我使用
pyinotify
时,它非常有用
pyinotify
的性能非常差,我最终修改了自己的版本。我不知道今天是否仍然如此。你不应该在事件处理程序中做那种级别的工作。将此代码作为单独的线程和工作线程队列运行。此外,您还可能面临文件未在创建中的
过程中完全写入和关闭的风险。您还需要抓取结束事件,并在它们完成后进行工作。此外,我不确定如果您的事件引发异常会发生什么(比如文件尚未写入,因此json失败)。添加一个异常处理程序,看看它是否捕获了某些内容。