繁体   English   中英

Python看门狗子进程队列

[英]Python Watchdog Subprocess Queue

我已经从以下网站复制了Python看门狗脚本: https : //www.michaelcho.me/article/using-pythons-watchdog-to-monitor-changes-to-a-directory

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


class Watcher:
    DIRECTORY_TO_WATCH = "/path/to/my/directory"

    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
            # Build up queue of subtasks here and let another thread/process 
            # take care of it so that main process can continue.

        elif event.event_type == 'modified':
            # Taken any action here when a file is modified.
            print "Received modified event - %s." % event.src_path


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

该脚本对我来说很棒,但是我还有一些其他要求。

  1. 除了打印文本,我还想开始一个可能需要几分钟的额外过程(Python脚本)。 主脚本不应等待此过程完成,而应继续检查是否有新文件或更改过的文件。

  2. 开始的辅助进程不允许彼此超越,因此必须放置在需要串行处理的某种队列中。

哪种方法/包装是解决这些要求的好方法? 我简要介绍了多处理和异步,但是不确定正确的实现。

我的一般想法是,应根据事件类型启动一个单独的进程/线程,该事件/线程检查队列并一个接一个地进行。 理想情况下,当主进程关闭时,该辅助线程/进程将完成剩余的队列。

我将此模板用于看门狗。 就我而言, on_any_event有点敏感。

回答1:您可以将任何内容代替print 函数,方法,循环等。事件发生时, Watcher将继续运行并调用Handler()

认为您需要详细说明调用on_any_event之后要on_any_event操作。

class Handler(FileSystemEventHandler):

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

    elif event.event_type == 'created':
        return run_function()

    elif event.event_type == 'modified':
        return run_other_function()

def run_function():
    W = '36 Chambers\n'
    with open('Wu-Tang.txt', '') as wu:
        wu.write(W) 
        wu.close()

def run_other_function():
    _W = 'The RZA the GZA.\n'
    with open('Wu-Tang.txt', 'a') as _wu:
        _wu.write(_W) 
        _wu.close()



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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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