python watchdog 文件监控
python watchdog 文件监控
安装
pip install watchdog
demo
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
#重写on_created 函数
class Handler(LoggingEventHandler):
def on_created(self, event):
super(LoggingEventHandler, self).on_created(event)
print("Watchdog received created event - % s." % event.src_path)
# Event is created, you can process it now
def on_modified(self, event):
super(LoggingEventHandler, self).on_created(event)
print("Watchdog received modified event - % s." % event.src_path)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = Handler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
https://www.geeksforgeeks.org/create-a-watchdog-in-python-to-look-for-filesystem-changes/