目录结构
安装watchdog 包
pip install watchdog
watch_fold.py
import sys
import time
from logger import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
if __name__ =="__main__":
path =sys.argv[1] if len(sys.argv) > 1 else "."
#生成事件处理对象
event_handler = LoggingEventHandler()
#生成监控对象
observer = Observer()
#注册事件处理器,配置监控目录
observer.schedule(event_handler, path, recursive=True)
#监控器启动--创建线程
observer.start()
# 以上代码是为了保持主线程运行
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
#等待其他的子线程执行结束之后,主线程在终止
observer.join()
logger.py
# -*- coding:utf-8 -*-
import os
import logging
LOG_DIR = "./log"
file_handler = logging.FileHandler(filename=os.path.join(LOG_DIR, 'watch.log'), mode="w")
stream_handler = logging.StreamHandler()
logging.basicConfig(format="%(levelname)s %(asctime)s %(message)s", handlers=[file_handler, stream_handler],
level=logging.INFO)
run.sh
python watch_fold.py /home/wws/***/
运行
bash run.sh
然后在/home/wws/***/ 文件夹下一顿增删改查操作
原来空的文件夹log 下多了一个watch.log
里面是我们在这个文件下的操作记录