Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (16.4k points)

I have a need to watch a log document for changes. In the wake of glancing through intellipaat questions, I see individuals suggesting watchog. So I'm attempting to test, and I don't know where to add the code for when files change: 

import time

from watchdog.observers import Observer

from watchdog.events import LoggingEventHandler

if __name__ == "__main__":

    event_handler = LoggingEventHandler()

    observer = Observer()

    observer.schedule(event_handler, path='.', recursive=False)

    observer.start()

    try:

        while True:

            time.sleep(1)

        else:

            print "got it"

    except KeyboardInterrupt:

        observer.stop()

    observer.join()

Where do I actually add the "got it" — in the while loop if the records have been added/changed?

1 Answer

0 votes
by (26.4k points)

You can also define your handler, Instead of LoggingEventHandler

#!/usr/bin/python

import time

from watchdog.observers import Observer

from watchdog.events import FileSystemEventHandler

class MyHandler(FileSystemEventHandler):

    def on_modified(self, event):

        print(f'event type: {event.event_type}  path : {event.src_path}')

if __name__ == "__main__":

    event_handler = MyHandler()

    observer = Observer()

    observer.schedule(event_handler, path='/data/', recursive=False)

    observer.start()

    try:

        while True:

            time.sleep(1)

    except KeyboardInterrupt:

        observer.stop()

    observer.join()

Here, on_modified will be called whenever a file or directory is modified.

Wanna become a Python expert? Come and join the python certification course and get certified.

Related questions

0 votes
1 answer
asked Jun 26, 2019 in Python by Aarav (11.4k points)
0 votes
1 answer

Browse Categories

...