7
6

More than 5 years have passed since last update.

python watchdog動作について

Posted at

概要

pythonでファイル変更などの監視用途としてマルチプラットフォームで動作するという watchdog モジュールを利用しようと考え、動作確認を行った際のメモです。

結論

結論ですが、ファイル作成の挙動がmacとそれ以外で異なったというだけの報告となります。

確認内容

とりあえず準備

$ pip install watchdog

簡単ですね、これでwatchdogを入れるだけです。

確認したコード

単に所定のディレクトリにあるテキストを監視するというモノです。

#!/usr/bin/env python                                                                                                 
# coding=utf8                                                                                                         

from watchdog.observers import Observer                                                                               
from watchdog.events import PatternMatchingEventHandler                                                               
import sys                                                                                                            
import os                                                                                                             
import time                                                                                                           

class TextFileEventHandler(PatternMatchingEventHandler):
        def __init__(self, patterns=['*.txt', '*.text', '*.doc', '*.md'], ignore_patterns=None,
                                 ignore_directories=True, case_sensitive=False):
                super().__init__(patterns, ignore_patterns, ignore_directories, case_sensitive)

        def on_any_event(self, event):
                print(event)
                print(event.event_type)

if __name__ == "__main__":
        wdir = os.path.abspath(sys.argv[1])
        print("watch dir: ", wdir)
        evh = TextFileEventHandler()
        obs = Observer()
        obs.schedule(evh, wdir, recursive=True)
        print("watching..")
        obs.start()

        try:
                while True:
                        time.sleep(1)
        except KeyboardInterrupt:
                obs.unschedule_all()
                print("finishing..")           
                obs.stop() 
        obs.join() 

        print("end watch.")

macでの動作確認

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.13.6
BuildVersion:   17G7024

watcher.gif

とりあえず、動作結果は上記の通りですが、結論に書いた部分として、ファイル作成時にmacではどうなったかについて記載します。

touch document/aa.txt
とすると、
createdイベントだけ生成されています。

debianでの動作確認

debianというかdockerのpythonイメージ公式を利用しました。手順としては以下のような感じなので、サクッと確認できると思います。

$ cd test
$ ls 
watch.py
$ md document
$ docker run -it -v `pwd`:/opt /bin/bash
# pip install watchgog
# cd /opt
# python watch.py document

こちらも動作イメージをぺたり
watcher_debian.gif

windows10でも確認しましたが、動きとしてはdebianと同じでした。

touch document/aa.txt
とした際に、
created
modified
となる

あとがき

内容的に何というほどのこともありませんが、macの動きの方が好きですw
とはいえ、マルチプラットフォームで動作させようとした場合には、同じ動作になっていた方が好ましいので、微妙な結果ですね。
まぁ、バックエンドで動いているものに依存するのでしょう。

現状5種類あるようですが、今回の環境では、mac:FSEventsObserver、debian:InotifyObserver、windows:WindowsApiObserver という感じです。obsを生成して、print(obs)を見るとわかります。
動作を変えたいのであれば、このObserverを自前で実装すれば良いとのこと。

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6