Linux 目录变化监听 - python代码实现

在python中 文件监控主要有两个库,

一个是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),pyinotify依赖于Linux平台的inotify。

一个是watchdog(http://pythonhosted.org/watchdog/)。对不同平台的的事件都进行了封装。

 

1、watchdog实现

  

复制代码
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()
复制代码

 

 

2、pyinotify  

  http://outofmemory.cn/code-snippet/84447/Linux-environment-jiankong-directory-variety-Python-code-segment

http://www.cppcns.com/jiaoben/python/125108.html

posted @   戒骄戒躁-沉淀积蓄  阅读(700)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示