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()