1

python watchdog monitoring file for changes

I have referred the above link and am able to monitor the directory for changes in files. The paths are getting populated from a csv file.

Now I want to run the program, and while it is running, I want to also monitor the new paths added to csv file without interrupting or stopping the program execution

#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import logging
import csv


class TestHandler(FileSystemEventHandler):

    def on_created(self, event):
        print("created: " + event.src_path)

    def on_deleted(self, event):
        print("deleted: " + event.src_path)

    def on_modified(self, event):
        print("modified: " + event.src_path)
    def on_moved(self, event):
        print("moved/renamed: " + event.src_path)
if __name__ == "__main__":

    paths=[]
    with open('F:\August Project Dev\Log Monitor\LogPath.csv', 'rb') as f:
        reader = csv.DictReader(f)
        for row in reader:
            paths.append(row['LogPath'])

    event_handler = TestHandler()
    observer = Observer()

    observers = []

    # iterate through paths and attach observers
    for line in paths:
         # convert line into string and strip newline character
        targetPath = str(line).rstrip()

        # Schedules watching of a given path
        observer.schedule(event_handler, targetPath)
        # Add observable to list of observers
        observers.append(observer)

    # start observer
    observer.start()

    try:
        while True:
            # poll every 5 second
            print 'while loop'
            time.sleep(5)
    except KeyboardInterrupt:
        for o in observers:
            o.unschedule_all()
            # stop observer if interrupted
            o.stop()
    for o in observers:
        # Wait until the thread terminates before exit
        o.join()
SiHa
  • 7,830
  • 13
  • 34
  • 43
B Kumar
  • 11
  • 3
  • A `observer.add_handler_for_watch(event_handler, watch)`should do it. [BaseObserver.add_handler_for_watch](https://pythonhosted.org/watchdog/api.html#watchdog.observers.api.BaseObserver.add_handler_for_watch) – stovfl Aug 23 '17 at 15:08
  • Hi thanks but am not able to work it out how to use this. can you help me with how to apply it in the above code – B Kumar Aug 24 '17 at 05:47
  • [Edit] your Question and show what you trying and what you get, e.g. Traceback. – stovfl Aug 24 '17 at 06:50

0 Answers0