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