pythonでフォルダの監視をするときに使うライブラリの「watchdog」。
とても便利です。
しかし、私の環境でこの「watchdog」が期待通りの動作をしなかったので、紹介します。
また、すでに解決方法も発見したので合わせて共有します。
結論、普通のObserverクラスではなく、PollingObserverクラスを使うことで期待通りの動作をしました!!
「watchdog」に失敗した状況
「watchdog」に失敗したケースは、
対象のフォルダに複数ファイルを同時に移動させたとき、数個のファイルに対してしかイベントが発生しない。(いくつかのイベントが実行されない)
です。
私は、以下の環境でpythonのwatchdogでフォルダ監視をして失敗しました。
※私の同僚は以下の環境でもうまく動作したので、これ以外の何かが影響してそうです。。。
OS:Window10 Pro
Python:3.7
watchdog:0.8.2
サンプルソースコード
/* sample_watchdog */
from watchdog.events import PatternMatchingEventHandler from watchdog.observers import Observer import time class Handler(PatternMatchingEventHandler): def __init__(self, patterns): super(Handler, self).__init__(patterns=patterns) def on_created(self, event): print('create ' + event.src_path) if __name__ == '__main__': handler = Handler(['*.csv']) observer = Observer() observer.schedule(handler, 'input') observer.start() try: while True: time.sleep(0.1) except KeyboardInterrupt: observer.stop() observer.join()
このコードを実行し、「input」フォルダにcsvファイルを置くと、「create ファイル名.csv」というログを出力してくれます。
しかし、同時に複数のcsvファイルを「input」フォルダに置くと数回しか「create ファイル名.csv」の出力がされず、いくつかのファイル移動イベントが発生しない状況でした。
解決策 = PollingObserverを使う
先ほどのコードでは、イベントハンドラーを監視するクラスがObserverクラスでしたが、これをPollingObserverクラスに変更することで問題が解決しました。
ソースコード
/* sample_watchdog_2 */
from watchdog.events import PatternMatchingEventHandler # 変更点その① from watchdog.observers.polling import PollingObserver import time class Handler(PatternMatchingEventHandler): def __init__(self, patterns): super(Handler, self).__init__(patterns=patterns) def on_created(self, event): print('create ' + event.src_path) if __name__ == '__main__': handler = Handler(['*.csv']) # 変更点その② observer = PollingObserver() observer.schedule(handler, 'input') observer.start() try: while True: time.sleep(0.1) except KeyboardInterrupt: observer.stop() observer.join()
まとめ
以上、pythonのフォルダ監視ライブラリ「watchdog」についての紹介でした。
pythonはwindowsで動かすと色々な不具合が起こったりしますね。
仕事の都合上、windowsで使うことがデフォなので、いろいろ工夫しながら頑張っていきます。
以上!!
コメント