python中文件变化监控watchdog的示例


本文摘自php中文网,作者黄舟,侵删。

这篇文章主要介绍了python中文件变化监控示例(watchdog),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

在python中文件监控主要有两个库,一个是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),一个是watchdog(http://pythonhosted.org/watchdog/)。pyinotify依赖于Linux平台的inotify,后者则对不同平台的的事件都进行了封装。因为我主要用于Windows平台,所以下面着重介绍watchdog(推荐大家阅读一下watchdog实现源码,有利于深刻的理解其中的原理)。

watchdog在不同的平台使用不同的方法进行文件检测。在init.py中发现了如下注释:


1

2

3

4

5

|Inotify| Linux 2.6.13+ ``inotify(7)`` based observer

|FSEvents| Mac OS X FSEvents based observer

|Kqueue| Mac OS X and BSD with kqueue(2) ``kqueue(2)`` based observer

|WinApi|(ReadDirectoryChangesW) MS Windows Windows API-based observer

|Polling| Any fallback implementation

给出示例代码如下:


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

from watchdog.observers import Observer

from watchdog.events import *

import time

 

class FileEventHandler(FileSystemEventHandler):

def __init__(self):

FileSystemEventHandler.__init__(self)

 

def on_moved(self, event):

if event.is_directory:

print("directory moved from {0} to {1}".format(event.src_path,event.dest_path))

else:

print("file moved from {0} to {1}".format(event.src_path,event.dest_path))

 

def on_created(self, event):

if event.is_directory:

print("directory created:{0}".format(event.src_path))

else:

print("file created:{0}".format(event.src_path))

 

def on_deleted(self, event):

if event.is_directory:

print("directory deleted:{0}".format(event.src_path))

else:

print("file deleted:{0}".format(event.src_path))

 

def on_modified(self, event):

if event.is_directory:

print("directory modified:{0}".format(event.src_path))

else:

print("file modified:{0}".format(event.src_path))

 

if __name__ == "__main__":

observer = Observer()

event_handler = FileEventHandler()

observer.schedule(event_handler,"d:/dcm",True)

observer.start()

try:

while True:

time.sleep(1)

except KeyboardInterrupt:

observer.stop()

observer.join()

watchdog主要采用观察者模型(废话,从变量命名就可以看出来)。主要有三个角色:observer,event_handler,被监控的文件夹。三者原本是独立的,主要通过observer.schedule函数将三者串起来,意思为observer不断检测调用平台依赖代码对监控文件夹进行变动检测,当发现改变时,通知event_handler处理。最后特别推荐读者有时间可以阅读一下watchdog的源码,写的易懂而且架构很好。

以上就是python中文件变化监控watchdog的示例的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python去掉空白行的多种实现代码

Python具体做些什么

使用Python操作excel文件

详谈Python在windows中的文件路径问题

Python中字符串如何比较大小

编写一个简单的 django 应用

Python flask 多对多表查询的实例详解

Python怎么念

Python model怎么用

Python如何保留一位小数

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...