LoginSignup
6
9

More than 5 years have passed since last update.

watchmedo(watchdog)を使ってエディタでファイルを保存する度にテストを実行する時の設定

Last updated at Posted at 2013-10-26

エディタでファイルを保存する度にタスクを実行したい時、RubyであればGuard、JSを書いている時であればGruntを使えば良いのだが、Pythonのコードを書いている時はその手のツールもPython製の物を使いたい。ここではwatchdogを使う。

導入は

pip install watchdog

するとコマンドラインユーティリティのwatchmedoコマンドが使えるようになる。ファイルシステムのイベントを監視して、特定のコマンドを実行したい場合はこんな感じ

watchmedo shell-command --patterns="*.py" --recursive --command='echo "${watch_src_path} is saved"' .

vimの設定

watchdogのReadmeにある通り、MacOSX + ターミナル上でvimを使っているとファイルシステムイベントを取れない。スワップファイルを作らないように、vimの次の設定を変えると良い。自分の.vimrcは次の通りにしてある。もしくは .*.swpファイルを監視対象にしてしまえば動作する。

let OSTYPE = system('uname')
if OSTYPE == "Darwin\n"
    set noswapfile
    set nowritebackup
endif

テストを実行するwatchタスクを作る

例えばMakefileにtestタスクがあり、ファイル保存時にtestタスクを実行するwatchタスクを追加したい場合

Makefile
watch:
    # appディレクトリ以下の*.pyファイルのイベントを監視してmake testを実行する
    @echo Watch file changes and run test
    watchmedo shell-command --interval=5 --patterns="*.py" -R -W -D --command='make test' app

test:
    # (例) Djangoのテストを実行する
    python app/manage.py test;

ファイルシステムイベントが複数飛んだ時に、テストが何度も実行されるのを抑止するための二重起動防止オプションが必要。

6
9
2

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
6
9