0

I want to use watchdog for monitoring specific filename in directory for run specific python script.

for example:

First, I want to use watchdog for monitor all of .avi file.

If name of .avi file in path (C:/User/AAxxx/video/) is : ABxxx_11.avi, I want to run ABxxx_11.py

If name of .avi file in path (C:/User/BBxxx/video/) is : CDxxx_22.avi, I want to run CDxxx_22.py

If name of .avi file in path (C:/User/CCxxx/video/) is : EFxxx_33.avi, I want to run EFxxx_33.py

And I want to pass sub-folder directory of AAxxx, BBxxx amd CCxxx folder. I want to focus only .avi file.

Now I have only watchdog for monitor .avi file and run python only one script. please see as below.

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from watchdog.events import PatternMatchingEventHandler
                    
class Watcher:
    def __init__(self, path, filename):
        self.observer = Observer()
        self.path = path
        self.filename = filename

    def run(self):
        event_handler = Handler(self.filename)
        self.observer.schedule(event_handler, self.path, recursive=True)
        self.observer.start()
        try:
            while True:
                time.sleep(1)
        except:
            self.observer.stop()
            print("Error")

        self.observer.join()


class Handler(PatternMatchingEventHandler):
    def __init__(self, filename):
        super(Handler, self).__init__(
            patterns=[filename],
            ignore_patterns=["*.tmp"],
            ignore_directories=True,
            case_sensitive=False,
        )

    def on_any_event(self, event):
        print(
            "[{}] noticed: [{}] on: [{}] ".format(
                time.asctime(), event.event_type, event.src_path
            )
        )
        #process1 = subprocess.Popen(["python", "ABxxx_11.py"])


if __name__ == "__main__":
    path = "C:/Users/xxx/AAxxx/video/"
    filename = "*.avi"

    w = Watcher(path, filename)
    w.run()
3
  • You've some context written above, but may I know what's your question? Commented Nov 21, 2022 at 6:07
  • @Han Thank you for your response. I want to know. How to adjust my code to use watchdog for monitoring specific filename in directory for run specific python script. Commented Nov 21, 2022 at 6:13
  • refer to my answer below Commented Nov 21, 2022 at 6:44

1 Answer 1

1

I can't get your code to run, so I hardcoded the values. Just check for the modified and created files, get the file name and execute the python script accordingly.

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


class Watcher:
    DIRECTORY_TO_WATCH = "C:/Users/test/AAxxx/video"

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
        self.observer.start()
        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print "Error"

        self.observer.join()


class Handler(FileSystemEventHandler):

    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # Take any action here when a file is first created.
            print "Received created event - %s." % event.src_path
            if ".avi" in event.src_path:
                print "run this file ->" + str(event.src_path.rsplit('\\')[1].split('.')[0]) + ".py"

        elif event.event_type == 'modified':
            # Taken any action here when a file is modified.
            print "Received modified event - %s." % event.src_path
            if ".avi" in event.src_path:
                print "run this file ->" + str(event.src_path.rsplit('\\')[1].split('.')[0]) + ".py"


if __name__ == '__main__':
    w = Watcher()
    w.run()

when I create a new .avi file in the path, the following is the output: enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your support. It' work when I use full of avi filename but If I want to use filename in your code like a glob path (Ext.: if "AB*_11.avi " in event.src_path:) How I can change this code support whatever name in (*) symbol.
There's a easy way. If you are sure that's the pattern, just use -> if "AB" in event.src_path and "_11.avi" in event.src_path: A more elegant way is to use regular expressions to check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.