最近在做一个项目,要监视一个目录下文件的变化,不多说,先看代码:

第一种方式:

#!/usr/bin/env python
#coding=utf-8
 
import os
import gtk
import gobject
from  pyinotify import  WatchManager, Notifier, ProcessEvent, ThreadedNotifier, IN_DELETE, IN_CREATE,IN_MOVED_TO,IN_MOVED_FROM
 
class hechao(ProcessEvent):
    def process_IN_CREATE(self, event):
        print   "创建文件: %s "  %   os.path.join(event.path, event.name)
 
    def process_IN_DELETE(self, event):
        print   "删除文件: %s "  %   os.path.join(event.path, event.name)
 
    def process_IN_MOVED_TO(self, event):
        print   "移来文件: %s "  %   os.path.join(event.path, event.name)
 
    def process_IN_MOVED_FROM(self, event):
        print   "移走文件: %s "  %   os.path.join(event.path, event.name)
 
path = "/home/hechao/.gnomenu/favorites"
gobject.threads_init()
wm = WatchManager() 
mask = IN_DELETE|IN_CREATE|IN_MOVED_TO|IN_MOVED_FROM
notifier = ThreadedNotifier(wm, hechao())
wm.add_watch(path, mask,rec=True)
notifier.start()
 
def __quit(widget):
notifier.stop()
gtk.main_quit()
 
if __name__ == "__main__":
    win = gtk.Window()
    win.connect("destroy",__quit)
    win.show()
    gtk.main()

第二种方式:

import gio
def directory_changed(monitor, file1, file2, evt_type):
    print evt_type
    if evt_type == gio.FILE_MONITOR_EVENT_CREATED or evt_type == gio.FILE_MONITOR_EVENT_DELETED:
    print "测试成功!"
    print "变化:",evt_type
print type(evt_type)
 
 
gfile = gio.File(".")
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
monitor.connect("changed", directory_changed) 
 
import glib
ml = glib.MainLoop()
ml.run()

再加一个定时器就OK了。

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐