python看门狗(watchdog)、多线程、实现文件夹实时监听、日志输出、备份
代码展示
import _thread
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
import shutil
from xml.dom.minidom import parse
import datetime as dt
import os
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
log_path = os.path.dirname(os.getcwd()) + '/dycktozslogs/'
log_name = log_path + rq + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
class MyDirEventHandler(FileSystemEventHandler):
def on_moved(self, event):
print(event)
def on_created(self, event):
_thread.start_new_thread(copy_remove_file, (event,))
def on_deleted(self, event):
print(event)
def on_modified(self, event):
print("modified:", event)
def copy_remove_file(event):
time.sleep(6)
try:
year = dt.datetime.now().strftime('%G')
month = dt.datetime.now().strftime('%m')
day = dt.datetime.now().strftime('%d')
path ="D:\\Backup"
path = os.path.join(path, year)
path = os.path.join(path, month)
path = os.path.join(path, day)
if os.path.exists(path):
try:
shutil.copy(event.src_path, path)
except shutil.Error:
logger.error("备份文件出错,文件被占用:" + event.src_path)
return
else:
try:
os.makedirs(path)
except Exception:
logger.error("当文件已存在,无法创建该文件:" + path+"--报文路径:"+event.src_path)
finally:
try:
shutil.copy(event.src_path, path)
except shutil.Error:
logger.error("备份文件出错,文件被占用:" + event.src_path)
return
try:
zspath = "D:\\test2"
if os.path.exists(zspath):
shutil.move(event.src_path, zspath)
else:
try:
os.makedirs(zspath)
except Exception:
logger.error("当文件已存在,无法创建该文件:" + path+"--报文路径:"+event.src_path)
finally:
shutil.move(event.src_path, zspath)
except shutil.Error:
logger.error("移动文件出错,文件已经存在:" + event.src_path)
return
logger.info("增加文件的文件夹路径:" + event.src_path)
except Exception as err:
logger.error("程序运行报错了:" + event.src_path+",报错内容:"+err)
return
"""
使用watchdog 监控文件的变化
"""
if __name__ == '__main__':
observer = Observer()
fileHandler = MyDirEventHandler()
observer.schedule(fileHandler, "D:\\test1", True)
observer.start()
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
print("500程序错误,文移动失败。")
pass
observer.join()
效果展示