edo1z blog

プログラミングなどに関するブログです

Python3 - Clint (コマンドライン入出力を色々できるモジュール)

面白そうだからやってみる。 参考:https://github.com/kennethreitz/clint/tree/master/examples 参考:PythonのコマンドラインツールClintを試す

インストール

$ pip install clint

文字に色つける

print(colored.blue('hoge'))

コードサンプル

from clint.textui import colored

for color in colored.COLORS:
    print(getattr(colored, color)('hoge'))

プログレスバー

コードサンプル

import os
import requests
from clint.textui import progress

dirpath = './hoge'
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'
filename = url.split('/')[-1]
filepath = os.path.join(dirpath, filename)

r = requests.get(url, stream=True)
total = int(r.headers.get('content-length'))
with open(filepath, 'wb') as f:
    for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=total/1024+1):
        if chunk:
            f.write(chunk)
            f.flush()