LoginSignup
8
7

More than 5 years have passed since last update.

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

Posted at

Python の一番スクリプト言語っぽくない部分が、外部コマンドを実行するのに import subprocess; subprocess.call("ls -l") しないといけなくて面倒な点ですね。

Paver は外部コマンド実行を楽にする sh() 関数を定義しています。これも from paver.easy import * するとインポートできます。

使い方

sh("ls -l /") のように書くと、そのコマンドがシェル経由で実行されます。

キャプチャ

デフォルトでは実行したコマンドの出力はそのまま標準出力に表示されますが、 capture=True を指定すると

pavement.py
from paver.easy import *
import os

@task
def list():
    ret = sh("ls -l /", capture=True)
    print(len(ret.splitlines()))
$ paver list
---> pavement.list
ls -l /
22

dryrun

path クラスのメソッドと同じく、 sh() 関数も paver を dryrun モードで実行した場合は、コマンドを表示するだけで実際には実行しません。

pavement.py
from paver.easy import *

@task
def barusu():
    sh("rm -rf /")
$ paver -n barusu
---> pavement.barusu
rm -rf /
8
7
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
8
7