16
15

More than 5 years have passed since last update.

Paver を使ったスクリプティング - コマンド定義編

Last updated at Posted at 2012-08-27

Paver は Python でコマンドラインツールを手軽に作るためのライブラリです。

Python の標準ライブラリの argparse などを使ってもある程度コマンドラインツールを簡単に作ることができますが、 Paver を使うと特にサブコマンドを持ったスクリプトを作るのが圧倒的に楽になります。

Paver 本家のドキュメントでは Python のパッケージングを自動化することに主眼をおいて解説されているので、タスク定義&実行ツールとして解説してみたいと思います。

セットアップ

$ easy_install paver

タスクを作る

pavement.py というファイルを作成し、そこで @task というデコレータをつけた関数を作ると、それがタスクとなります。

pavement.py
from paver.easy import *

@task
def hello():
    """My first task."""
    print 'hello'

タスクを実行するには、 paver タスク名 を実行します。

$ paver hello
---> pavement.hello
hello

paver -h にも、定義したタスクが表示されます。 docstrin がそのコマンドの説明になります。

$ paver -h
---> paver.tasks.help
Usage: paver [global options] taskname [task options] [taskname [taskoptions]]

Options:
  --version             show program's version number and exit
  -n, --dry-run         don't actually do anything
…
Tasks from pavement:
  hello          - My first task.

引数を取る

引数を取るには、タスクを定義している関数に @consume_args というデコレータをつけて args という引数を書きます。

pavement.py
from paver.easy import *

@task
@consume_args
def hello(args):
    """My first task."""
    print 'hello', args
$ paver hello foo bar
---> pavement.hello
hello ['foo', 'bar']

オプションを定義する

オプションを定義するには @cmdopts デコレータを利用し、それを受け取るには options という引数を利用します。 @cmdopts デコレータには、オプションを (長い名前, 一文字, ヘルプ) の形のタプルで定義したリストを引数として渡します。長い名前の最後に = をつけると引数を取るオプションになります。

pavement.py
from paver.easy import *

@task
@cmdopts([
    ('foo', 'f', "The foo"), # -f あるいは --foo
    ('bar=', 'b', "Bar bar bar"), # -b xxxあるいは --bar=xxx
    ])
def hello(options):
    """My first task."""
    print 'hello', options.foo, options.bar
$ paver hello --foo -b 3
---> pavement.hello
hello True 3

実は、 options は引数に取らなくても paver.easy のグローバル変数として定義してあるので、 from paver.easy import * してあれば引数を取らなくても利用することができます。

pavement.py
from paver.easy import *

@task
@cmdopts([
    ('foo', 'f', "The foo"),
    ('bar=', 'b', "Bar bar bar"),
    ])
def hello():
    """My first task."""
    print 'hello', options.foo, options.bar
16
15
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
16
15