简体   繁体   中英

How to check specific file and run another python script

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

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: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM