監控文件系統事件的Python庫和shell工具:watchdog

jopen 10年前發布 | 24K 次閱讀 watchdog Python開發

watchdog提供了Python API和shell工具集來監控文件系統的事件。它包含跨平臺的API,一個shell工具可以讓你運行命令來監控目錄的變化。

以下是一個使用watchdog來監控目錄變化的的簡單程序,當事件發生的時候記錄日志:

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

watchdog包含一個實用的腳本,名為watch demo。使用watchdog —helpming’l命令可以查看更多關于這個腳本的信息。

以下是一個監控*.py和*.txt文件的變化,記錄到日志而忽略其他目錄中文件變化的腳本:

watchmedo log \
    --patterns="*.py;*.txt" \
    --ignore-directories \
    --recursive \
    .

可以使用shell-command子命令來執行shell命令:

watchmedo shell-command \
    --patterns="*.py;*.txt" \
    --recursive \
    --command='echo "${watch_src_path}"' \
    .

項目主頁:http://www.baiduhome.net/lib/view/home/1404378150249

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!