PythonのコマンドラインツールClintを試す

pythonコマンドラインツールclintが面白そうなので試してみます

https://github.com/kennethreitz/clint

clint自体がコマンドラインツールというわけではなく、pythonコマンドラインツールを作成するときに便利なライブラリです

インストール

pip install clint

使い方

出力に色をつける
from clint.textui import colored

print colored.red('hello!')
print colored.green('hello!')
print colored.blue('hello!')


結果

出力をインデントする
from clint.textui import indent, puts

# インデントしない
puts('not intended hello')

# 4文字分インデント
with indent(4):
    puts('indented hello')

# 4文字分インデントでquoteをつける
with indent(4, quote='>'):
    puts('quote intended hello')

# インデントのネスト
with indent(4):
    puts('indented hello')
    with indent(4):
        puts('nexted indented hello')


結果

コマンドライン引数を扱う
import clint

print('# すべての引数のリスト')
print clint.args.all

print('# フラグだけのリスト')
print clint.args.flags.all

print('# ファイル引数のリスト')
print clint.args.files

print('# ファイル引数以外のリスト')
print clint.args.not_files.all

print('# 引数をグルーピングして取得')
print dict(clint.args.grouped)


結果

$ python clint_arg.py a b c -f *.py

# すべての引数のリスト
['a', 'b', 'c', '-f', 'clint_arg.py', 'clint_color.py', 'clint_indent.py']
# フラグだけのリスト
['-f']
# ファイル引数のリスト
['clint_arg.py', 'clint_color.py', 'clint_indent.py']
# ファイル引数以外のリスト
['a', 'b', 'c', '-f']
# 引数をグルーピングして取得
{'-f': <args ['clint_arg.py', 'clint_color.py', 'clint_indent.py']>, '_': <args ['a', 'b', 'c']>}

clint.fliesがリストなのに、clint.not_filesはリストではなくclint.arguments.Argsのオブジェクト

プログレスバー

from time import sleep
from random import random
from clint.textui import progress

for i in progress.bar(range(100)):
    sleep(random() * 0.2)

これは動かすと面白い

結果

[########################      ] 78/100

パイプを扱う

piped_inでパイプで渡された文字列を取得できる

from clint import piped_in

in_data = piped_in()
    
print('Data was piped in! Here it is:')
print(in_data)


試しにdateの結果を渡してみる

$ date | python ./clint_pipe.py 
Data was piped in! Here it is:
2012年 1月13日 金曜日 22時01分05秒 JST

感想

本家のexamplesにもっと面白いサンプルがいっぱいあった!
https://github.com/kennethreitz/clint/tree/develop/examples

https://github.com/kennethreitz/clint/blob/develop/examples/colors_all.pyの実行結果


使ってみた感じ、インターフェースがシンプルでわかりやすいです。
以前試したtablibと同じように、知っておくと日々の仕事で活躍の場がありそう。

参考

Pythonで表データを扱うライブラリ「tablib」を試す
http://d.hatena.ne.jp/yuheiomori0718/20120108/1326003688