• watchdog应用实例


    watchdog应用实例

    By 鬼猫猫 20130504 http://www.cnblogs.com/muyr/

    实例:监测某文件夹,一旦文件夹里有文件,就把它剪切到其他服务器

    import sys
    import os, shutil
    import time
    import logging
    from watchdog.observers import Observer
    from watchdog.events import (LoggingEventHandler, FileSystemEventHandler)
    
    
    backupDir = 'D:/Work/backup'
    baseDir = 'S:/Test/Upload'
    
    def copyFile(fromFile, toDir):
        if os.path.isdir(fromFile):
            clearDir = fromFile[len(baseDir):]
            try:
                os.makedirs(toDir + clearDir)
                print 'NewFolder: ', fromFile.encode('utf-8'), ' ===> ', (toDir + fromFile[len(baseDir):]).encode('utf-8')
            except:
                print 'NewFolder-PASS:', fromFile.encode('utf-8')
                return
        else:
            clearDir = os.path.dirname(fromFile)[len(baseDir):]
            if not os.path.isdir(toDir + clearDir):
                os.makedirs(toDir + clearDir)
            try:
                time.sleep(0.2)
                shutil.move(fromFile, toDir + fromFile[len(baseDir):])
                print 'MoveFile: ', fromFile.encode('utf-8'), ' ===> ', (toDir + fromFile[len(baseDir):]).encode('utf-8')
            except:
                print 'MoveFile-PASS:', fromFile.encode('utf-8')
                return
    
        return
    
    
    class TestEventHandler(FileSystemEventHandler):
        def on_any_event(self, event):
            # print("event noticed: " + event.event_type + 
            #              " on file " + event.src_path.encode('utf-8') + " at " + time.asctime())
            pass
    
        def __init__(self, pattern='*'):
            self.pattern = pattern
    
        def on_moved(self, event):
            print ("moved src path:"+ event.src_path.encode('utf-8'))
            print ("moved dest path:"+ event.dest_path)
            copyFile(event.dest_path, backupDir)
    
        def on_created(self, event):
            print ("created path:"+ event.src_path.encode('utf-8'))
            copyFile(event.src_path, backupDir)
    
        def on_deleted(self, event):
            print ("deleted path:"+ event.src_path.encode('utf-8'))
    
        def should_reload(self, event):
            if isinstance(event, FileSystemMovedEvent):
                return True
            return False
    
        def on_modified(self, event):
            print ("modified path:"+ event.src_path.encode('utf-8'))
            copyFile(event.src_path, backupDir)
    
    
    if __name__ == "__main__":
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s - %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S')
        # path = sys.argv[1] if len(sys.argv) > 1 else '.'
    
        # event_handler = LoggingEventHandler()
        event_handler = TestEventHandler()
        observer = Observer()
        observer.schedule(event_handler, baseDir, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()
    

    补充一点:程序最终的效果,监测文件夹一旦有文件,就立马剪切到备份路径下,但是检测位置里的文件夹将不会被删除

    Powered by Sublog

  • 相关阅读:
    TP5常用函数总结1
    swiper 自定义的一些需求
    jQuery 点击元素以外任意地方隐藏该元素
    fastadmin中编辑时的fieldlist选项类型,如何跟数据库里的保持一致,并且显示匹配的样式
    leetcode——63. 不同路径 II
    leetcode——62.不同路径
    数组标签结束,下一个标签,动态规划
    leetcode——48. 旋转图像
    leetcode——45. 跳跃游戏 II
    leetcode——41. 缺失的第一个正数
  • 原文地址:https://www.cnblogs.com/muyr/p/3723507.html
Copyright © 2020-2023  润新知