簡體   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