前言:
用 python 实时实现监控一个文件夹功能,将监控到的 Excel(笔者目前用于解析excel文件)解析写到 mysql 中,起功能和 sparkStreaming 中的 textFileStream 功能,个人感觉 python 代码更好看。毕竟 java 代码看起来比较繁琐,scala 代码简洁,可是它也是借鉴 python 发展而来啊。
python 实现看门狗功能代码:
#!/usr/bin/python
#-*- coding:UTF-8 -*-
import time
from watchdog.events import *
from watchdog.observers import Observer
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, "E:/Jerry", True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
这里是一个简化版的监控文件夹代码,一般会改动 on_modified 方法里的代码(根据需求来改动)。