Why it doesn't work?

作業のメモ、記録をブログに残しています。

Python ファイルの更新を監視する

Pythonでいろいろなツールを作っていますが、接続先のIPアドレスや認証キーなどの可変な情報は別ファイルに保存して、起動時にファイルアクセスして情報を取得しています。このやり方だと、接続先を変更したい場合、ファイルを修正して、ツールを再起動する必要があり面倒です。
いろいろ調べてみると、watchdogモジュールを使用したファイル監視が便利そうなのでやってみます。
公式ページです。
pythonhosted.org

1. インストール

インストールはいつものようにpipコマンドを実行します。

pip install watchdog

2. 前提条件

スクリプトと同ディレクトリに"ip_info.txt"というファイルがあるという前提です。そのファイルは以下のような情報を持ち、これが動的に書き換えられるとします。

IP:169.254.10.xxx

3. 実装

そんな前提を条件として以下のように実装してみました。

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

def findStringFromFile(fname, seekString) :
    foundString = None
    with open(fname, "r") as f :
        for l in f :
            if l.find(seekString) == 0 :
                foundString = l
                break
    if foundString is None :
        return None
    return foundString[len(seekString):].strip('\n')

class hookModifiedHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if os.path.basename(event.src_path) == 'ip_info.txt':
            newip = findStringFromFile('ip_info.txt', 'IP:')
            print(newip)
            return

if __name__ in '__main__':
    basepath = os.path.abspath(os.path.dirname(__file__))
    ipaddr = findStringFromFile('ip_info.txt', 'IP:')
    print(ipaddr)
    event_handler = hookModifiedHandler()
    observer = Observer()
    observer.schedule(event_handler,basepath,recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

若干長くなってしまいましたが、これを実行すると、起動時に現在の"IP:"情報を出力し、ファイルに変更を加えると変更された"IP:"情報が出力されます。
他のイベントやディレクトの変更については、公式サイトを参照してください。
とりあえず、今回はこれまで。早くWordpressの作業に戻らないと。。。