我想创建一个会监视文件夹的模块。我写了一些代码:
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:新代码
答案 0 :(得分:1)
尝试以下代码。它与您的代码基本相同;我只添加了
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 delete
import 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
也不会以某种方式让你摆脱这个循环。
如果您计划使用线程,则可能需要将threading.Event
传递给start_watch
,并在while-loop
内检查其状态,以确定何时突破循环。