'python watchdog on another logging file not firing events

I have a python script that logs mouse click events to mouse_log.csv file and i want to track changes in this file using watchdog,

import threading
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

from pynput.mouse import Listener


def mouse_logging():
    logging.basicConfig(filename="mouse_log.csv", level=logging.DEBUG,
                        datefmt="%y-%m-%d, %H:%M:%S", format='%(asctime)s, %(message)s')

    def on_click(x, y, button, pressed):
        if pressed:
            logging.info(' {2}'.format(x, y, button))

    with Listener(on_click=on_click) as listener:
        listener.join()


class Handler(FileSystemEventHandler):

    def on_modified(self, event):
        print(f'event type: {event.event_type}  path : {event.src_path}')
        if "mouse_log.csv" in event.src_path:
            with open(event.src_path) as file:
                data = file.readlines()[-1]
            print("Last change: {}".format(data))


if __name__ == "__main__":
    mouse_thread = threading.Thread(target=mouse_logging, daemon=True)

    mouse_thread.start()

    event_handler = Handler()
    observer = Observer()
    observer.schedule(event_handler, ".", recursive=False)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

But watchdog does not fire event for every file change e.g mouse click event. It only works for the first time or whenver i open the file. How do fix this issue?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source