方法1(pyinotify模块):
#!/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()
方法2(pyinotify模块):
#!/usr/bin/env python
#
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()