以下の内容はhttps://shuzo-kino.hateblo.jp/entry/2018/01/13/231948より取得しました。


ClickをつかってPython製CLIツールをスマートにする その3:yes/no

shuzo-kino.hateblo.jp
シリーズの3回目。
今回はCLIツールではよく見かけるyes/noの選択肢を表示するオプションのはなし。

実際のところ

何か文字列を表示し、yes/noを選択させるアプリを考えてみます。

import click

def abort_if_false(ctx, param, value):
    if not value:
        ctx.abort()

@click.command()
@click.option('--yes', is_flag=True, callback=abort_if_false,
              expose_value=False,
              prompt='Are you sure you want to drop the db?')
def dropdb():
    click.echo('Dropped all tables!')

def filelist():
    click.echo("some function")

if __name__ == '__main__':
   filelist()
   dropdb()

動かすとこんな感じ。
noを選択した場合でも"ctx.abort()" で中止してくれます。便利ですねぇ

$ python sample_click_yes.py
some function
Are you sure you want to drop the db? [y/N]: n
Aborted!

$ python sample_click_yes.py
some function
Are you sure you want to drop the db? [y/N]: y
Dropped all tables!

"--yes"オプションで全部yesになります。
yesコマンド使わないでよいって事かもしれませんが、まぁあんまりオススメしたくないですねコレ。

$ python sample_click_yes.py --yes
some function
Dropped all tables!



以上の内容はhttps://shuzo-kino.hateblo.jp/entry/2018/01/13/231948より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14