`
-- coding: utf-8 --
@Time : 2024/3/1 10:02
@Author : Rohing
@File : 监控文件.py
@Software: PyCharm`
import time
import logging
import fnmatch
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
handler = logging.FileHandler('monitor.log')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
class MyHandler(FileSystemEventHandler):
def init(self, patterns):
super().init()
self.patterns = patterns
def on_modified(self, event):# 文件被修改时触发for pattern in self.patterns:if fnmatch.fnmatch(event.src_path, pattern):logger.info(f'File {event.src_path} has been modified')
if name == "main":
print("请输入监控的文本格式以逗号分隔 ")
patterns = input("例如:.txt,.html,.php,.js,*.sh:").split(",")
event_handler = MyHandler(patterns)
observer = Observer()
observer.schedule(event_handler, path='.', recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()`