Python中使用Inotify监控文件实例

yipeiwu_com5年前Python基础

Inotify地址:访问

# -*- coding:utf-8 -*-

import os
import pyinotify
from functions import *

WATCH_PATH = '' #监控目录

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)

相关文章

一些Python中的二维数组的操作方法

需要在程序中使用二维数组,网上找到一种这样的用法:   #创建一个宽度为3,高度为4的数组 #[[0,0,0], # [0,0,0], # [0,0,0], # [0,...

socket + select 完成伪并发操作的实例

实例如下: #!/usr/bin/env python # -*- coding: utf-8 -*- import socket #创建一个socket对象 sk1 = sock...

Python中文件操作简明介绍

打开文件 open函数返回一个文件对象,基本语法: ●file_object = open(file_name, access_mode='r'[,buffering=-1]) file...

python颜色随机生成器的实例代码

1. 代码: def random_color(number=number): color = [] intnum = [str(x) for x in np.arange(...

Python探索之静态方法和类方法的区别详解

面相对象程序设计中,类方法和静态方法是经常用到的两个术语。 逻辑上讲:类方法是只能由类名调用;静态方法可以由类名或对象名进行调用。 python staticmethod and cla...