Inotify 可以监视的LINUX文件系统事件包括:

  • –IN_ACCESS,文件被访问
  • –IN_MODIFY,文件被write
  • –IN_ATTRIB,文件属性被修改,如chmod、chown、touch等
  • –IN_CLOSE_WRITE,可写文件被close
  • –IN_CLOSE_NOWRITE,不可写文件被close
  • –IN_OPEN,文件被open
  • –IN_MOVED_FROM,文件被移走,如mv
  • –IN_MOVED_TO,文件被移来,如mv、cp
  • –IN_CREATE,创建新文件
  • –IN_DELETE,文件被删除,如rm
  • –IN_DELETE_SELF,自删除,即一个可执行文件在执行时删除自己
  • –IN_MOVE_SELF,自移动,即一个可执行文件在执行时移动自己
  • –IN_UNMOUNT,宿主文件系统被umount
  • –IN_CLOSE,文件被关闭,等同于(IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)
  • –IN_MOVE,文件被移动,等同于(IN_MOVED_FROM | IN_MOVED_TO)
1
pip install pyinotify
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# -*- coding:utf-8 -*-

import os
import pyinotify
from functions import *

WATCH_PATH = '/home/pi/app/inotifywait' #监控目录

if not WATCH_PATH:
wlog('Error',"The WATCH_PATH setting MUST be set.")
sys.exit()
else:
if os.path.exists(WATCH_PATH):
wlog('Watch status','Found watch path: path=%s.' % (WATCH_PATH))
else:
wlog('Error','The watch path NOT exists, watching stop now: path=%s.' % (WATCH_PATH))
sys.exit()

class OnIOHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
wlog('Action',"create file: %s " % os.path.join(event.path,event.name))

def process_IN_DELETE(self, event):
wlog('Action',"delete file: %s " % os.path.join(event.path,event.name))

def process_IN_MODIFY(self, event):
wlog('Action',"modify file: %s " % os.path.join(event.path,event.name))

def auto_compile(path = '.'):
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY
notifier = pyinotify.ThreadedNotifier(wm, OnIOHandler())
notifier.start()
wm.add_watch(path, mask,rec = True,auto_add = True)
wlog('Start Watch','Start monitoring %s' % path)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break

if __name__ == "__main__":
auto_compile(WATCH_PATH)

pyinotify使用过程中有各种各样的问题,如果要文件监控,建议使用watchdog。