[Python] check if multiple Output folders are new and monitor them

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I have a script1.py to process videos one by one frequently The extract is saved in a folder.

    script1.py - process videos

    Output_Videos\namevideo1_Output


    And the second script monitoring.py When running it monitors the following folders:

    monitoring.py - monitoring

    Output_Videos\namevideo1_Output\Images
    Output_Videos\namevideo1_Output\Text


    But when script1.py processing the second video automatic

    Output_Videos\namevideo1_Output - is complete
    Output_Videos\namevideo2_Output


    Script monitoring.py stops monitoring Because when it was run for the first time, "monitoring.py" it only found one folder to monitor. how to run the "monitoring.py" script once and it checks repeatedly if any new folders Output_Videos and monitoring

    example

    Output_Videos\namevideo1_Output\Images
    Output_Videos\namevideo1_Output\Text
    Output_Videos\namevideo2_Output\Images
    Output_Videos\namevideo2_Output\Text
    Output_Videos\namevideo3_Output\Images
    Output_Videos\namevideo3_Output\Text
    ...


    monitoring.py

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


    class EventHandler(FileSystemEventHandler):

    def __init__(self, text):
    self.text = text

    def on_created(self, event):
    action, path = (event.event_type, event.src_path)
    print(self.text.format(path))


    def monitor_directories(data):
    observer = Observer()
    for directory, text in data:
    event_handler = EventHandler(text)
    observer.schedule(event_handler, directory, recursive=True)
    observer.start()
    observer = PollingObserver()

    try:
    while True:
    time.sleep(1)
    except KeyboardInterrupt:
    observer.stop()
    observer.join()


    if __name__ == "__main__":
    print("Crop sub area\n")
    data = [
    # always select a dir path (if using glob, be careful, it returns list), then custom text with {} in it that will become path
    [glob("Output_Videos/*/Images")[0], " Crop images [Images] : {} Done"],
    [glob("Output_Videos/*/Text")[0], " Crop images [Text] : {} Done"]
    ]
    monitor_directories(data)

    Continue reading...

Compartilhe esta Página