我想要创建一个模块来监视文件夹。我编写了一些代码:
import os, pyinotify
class FileWatcher:
def start_watch(self, dir):
wm = pyinotify.WatchManager()
self.notifier = pyinotify.Notifier(wm, EventProcessor())
mask = pyinotify.IN_CREATE | pyinotify.IN_MODIFY | pyinotify.IN_DELETE | pyinotify.IN_DELETE_SELF | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO
wdd = wm.add_watch(dir, mask, rec=True)
while True:
self.notifier.process_events()
if self.notifier.check_events():
self.notifier.read_events()
def stop_watch(self):
self.notifier.stop()
print ('\nWatcher stopped')
class EventProcessor(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
print('in CREATE')
def process_IN_MODIFY(self, event):
print('in MODIFY')
def process_IN_DELETE(self, event):
print('in delete')
def process_IN_DELETE_SELF(self, event):
print('in delete self')
def process_IN_MOVED_FROM(self, event):
print('in MOVED_FROM')
def process_IN_MOVED_TO(self, event):
print('in IN_MOVED_TO')
if __name__ == "__main__":
watcher = FileWatcher()
try:
folder = "/home/user/Desktop/PythonFS"
watcher.start_watch(folder)
except KeyboardInterrupt:
watcher.stop_watch() 当我修改一个文件然后删除它时,process_IN_MODIFY和process_IN_DELETE方法从未被调用过。我是怎么解决的?
但是,当我创建一个文件时,调用了process_IN_CREATE()方法。
操作系统是Linux 13。
UPD:新代码
发布于 2013-03-26 17:29:47
试试下面的代码。它基本上与您的代码相同,我只添加了
f = FileWatcher()
f.start_watch('/tmp/test', None)在结束时启动FileWatcher。确保目录/tmp/test存在,否则将该行更改为指向存在的目录。
如果foo文件存在于/tmp/test中,如果我修改该文件,则上面的程序将打印
in create # after modification
in modify # after saving
in modify
in delete现在,如果我删除该文件,程序将打印:
in deleteimport os
import pyinotify
class FileWatcher:
notifier = None
def start_watch(self, dir, callback):
wm = pyinotify.WatchManager()
self.notifier = pyinotify.Notifier(wm, EventProcessor(callback))
mask = (pyinotify.IN_CREATE | pyinotify.IN_MODIFY | pyinotify.IN_DELETE
| pyinotify.IN_DELETE_SELF | pyinotify.IN_MOVED_FROM
| pyinotify.IN_MOVED_TO)
wdd = wm.add_watch(dir, mask, rec=True)
while True:
self.notifier.process_events()
if self.notifier.check_events():
self.notifier.read_events()
class EventProcessor(pyinotify.ProcessEvent):
def __init__(self, callback):
self.event_callback = callback
def process_IN_CREATE(self, event):
# if self.event_callback is not None:
# self.event_callback.on_file_created(os.path.join(event.path,
# event.name))
print('in create')
def process_IN_MODIFY(self, event):
# if self.event_callback is not None:
# self.event_callback.on_file_modifed(os.path.join(event.path,
# event.name))
print('in modify')
def process_IN_DELETE(self, event):
print('in delete')
def process_IN_DELETE_SELF(self, event):
print('in delete self')
def process_IN_MOVED_FROM(self, event):
print('in moved_from')
def process_IN_MOVED_TO(self, event):
print('in moved to')
f = FileWatcher()
f.start_watch('/tmp/test', None)顺便说一句,一旦调用了f.start_watch,进程就会落入一个while True循环中,无法逃避。即使是从另一个线程调用f.stop_watch,也不会以某种方式使您脱离will循环。
如果计划使用线程,则可能需要将threading.Event传递给start_watch,并检查其在while-loop中的状态,以确定何时退出循环。
https://stackoverflow.com/questions/15642578
复制相似问题