Python watchdog runs more than once

I am trying to learn python-watchdog, but I am a little confused why the work that I configured runs several times. So here is my setup:

#handler.py
import os
from watchdog.events import FileSystemEventHandler
from actions import run_something

def getext(filename):
    return os.path.splitext(filename)[-1].lower()

class ChangeHandler(FileSystemEventHandler):

    def on_any_event(self, event):

        if event.is_directory:
            return
        if getext(event.src_path) == '.done':
            run_something()
        else: 
            print "event not directory.. exiting..."
            pass

The observer is configured as follows:

#observer.py
import os
import time
from watchdog.observers import Observer
from handler import ChangeHandler

BASEDIR = "/path/to/some/directory/bin"

def main():

    while 1:

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

 if __name__ == '__main__':
    main()

and finally actions like this:

#actions.py
import os
import subprocess

def run_something():
    output = subprocess.check_output(['./run.sh'])
    print output
    return None

.. where ./run.shis just a shell script I would like to run when the file with the extension .doneis on/path/to/some/directory/bin

#run.sh
#!/bin/bash
echo "Job Start: $(date)"
rm -rf /path/to/some/directory/bin/job.done # remove the .done file
echo "Job Done: $(date)"

However, when I issue python observer.pyand then do touch job.doneon /path/to/some/directory/bin, I see that my shell script ./run.shis executed three times, not one.

I am confused why this is done three times and not just once (I delete the file job.donein my bash script)

+3
source share
1 answer

, , . CLI, touch, . , :

class ChangeHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        print(event)

,

% touch job.done

2014-12-24 13:11:02 - <FileCreatedEvent: src_path='/home/unutbu/tmp/job.done'>
2014-12-24 13:11:02 - <DirModifiedEvent: src_path='/home/unutbu/tmp'>
2014-12-24 13:11:02 - <FileModifiedEvent: src_path='/home/unutbu/tmp/job.done'>

src_path, job.done. ,

    if getext(event.src_path) == '.done':
        run_something()

, FileCreatedEvent a FileModifiedEvent. , FileModifiedEvent s.

+3

Source: https://habr.com/ru/post/1609588/


All Articles