# encoding=UTF-8
# !/usr/bin/python
# encoding: utf-8
# filename: watchdog-file-data.py
# author: gaohaixiang
# writetime:202209291116
import time
import subprocess
import threading
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
"""
1、监测文件创建和新增文件内容(追加)
2、当新监测到一个文件发生改变时,新增加的文件内容会丢失,后续追加的文件内容才会打印
3、当 监测文件时长 即 timeOuts 超过定义的时长时,将不会再监测该文件,除非该文件再次被修改
"""
def GetNumber():
# commands = "ps -ef |grep 'watchdog-test'|grep -v grep |wc -l"
getoutput = subprocess.getoutput(commands)
return getoutput
class OnMyWatch():
# Set the directory on watch
# watchDirectory = "/data/pycharmdata/"
def __init__(self,):
self.watchDirectory = watchDirectorys
self.observer = Observer()
def run(self):
event_handler = Handler()
self.observer.schedule(event_handler, self.watchDirectory, recursive=True)
self.observer.start()
try:
while True:
time.sleep(0.1)
except:
self.observer.stop()
print("Observer Stopped")
self.observer.join()
class Handler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
if event.is_directory:
return None
# 创建文件
elif event.event_type == 'created':
time.sleep(0.1)
if not event.src_path in filePathList:
# 将监测文件放入列表中
filePathList.append(event.src_path)
# 多线程监测文件
t = threading.Thread(target=fileSeek, args=(event.src_path,))
t.start()
# 修改文件
elif event.event_type == 'modified':
time.sleep(0.1)
# print("Watchdog received modified event - % s." % event.src_path)
# print(filePathList)
if not event.src_path in filePathList:
# 将监测文件放入列表中
filePathList.append(event.src_path)
# 多线程监测文件
t = threading.Thread(target=fileSeek, args=(event.src_path,))
t.start()
def fileSeek(filename):
thefile = open(filename, "r",encoding="UTF8")
thefile.seek(0, 2)
# 监测文件时长 计时
times = 0
while True:
line = thefile.readline()
if not line:
times += 1
# print(times)
time.sleep(0.1)
# 若是长时间无数据,则跳出无限循环
if times > timeOuts:
# 从列表中移除该监测文件
filePathList.remove(filename)
break
continue
times = 0
print(line)
# yield line
if __name__ == '__main__':
# 存放监测的文件路径
filePathList = []
# 监测文件的时长,秒 * 10,50为5秒
timeOuts = 50
# 监测目录路径
watchDirectorys = "/data/pycharmdata/"
# 进程是否存在判断及进程重启
commands = "ps -ef |grep 'watchdog-file-data'|grep -v grep |wc -l"
resultNub = GetNumber()
if int(resultNub) < 2 :
print("进程运行数量错误")
watch = OnMyWatch()
watch.run()
else:
pass
目录及文件内容监测
最新推荐文章于 2024-06-13 17:21:00 发布