LoginSignup
49
51

More than 5 years have passed since last update.

Clickで手軽にPythonのコンソールアプリケーションを作る

Posted at

コマンドラインから実行できるPythonプログラムを作成したい場合、コマンドライン引数の処理にargparseoptparseを使って引数をparseするのが一般的かと思います。

Clickライブラリを用いると、任意の関数をデコレータでwrapするだけで、手軽にコンソールアプリケーションを作成することが出来て、便利です。

試しにURLをGETする簡単な実装をしてみます。

http_fetcher.py
import click
import requests

@click.command()
@click.argument('url')
def fetch(url):
    click.echo(requests.get(url).text.encode('utf-8'))

if __name__ == '__main__':
    fetch()
% python http_fetcher.py http://www.qiita.com/
<!DOCTYPE html>...

-oで引数を指定すると、ファイルに書いてくれるようにしてみます。

http_fetcher2.py
import click
import requests
import sys

@click.command()
@click.argument('url')
@click.option('-o', '--out-file', type=click.File('w'))
def fetch(url, out_file):
    if not out_file:
        out_file = sys.stdout
    click.echo(requests.get(url).text.encode('utf-8'), file=out_file)

if __name__ == '__main__':
    fetch()
% python http_fetcher2.py -o index.html http://qiita.com
% cat index.html
<!DOCTYPE html>...

ファイルもClickが自動的に開いてくれて、File Objectとして返してくれるので便利です。

その他、コマンドのグループ化、プログレスバーの表示など、気の利いた機能がいろいろついています。ドキュメントはこちら

49
51
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
49
51