もた日記

くだらないことを真面目にやる

Pythonメモ : bulletでインタラクティブなコマンドラインツールを簡単に作成

bullet

github.com

bulletを使うとPythonでコマンドラインツールを開発するときに図のようなインタラクティブプロンプトを簡単に作成できる。

f:id:wonder-wall:20190318210934g:plain

インストール

pipコマンドでインストールできる。

$ pip install bullet

使い方

基本的な使い方は以下のとおり(このページにサンプルプログラムがある)。
Bulletオブジェクトを使うと単一選択のプロンプトを作成できる。

from bullet import Bullet

cli = Bullet(
        prompt = "Please choose a fruit: ",
        choices = ["apple", "banana", "orange", "watermelon", "strawberry"]
    )

result = cli.launch()
print("You chose:", result)

f:id:wonder-wall:20190318210555p:plain

レイアウトについてはこのページを参照。
indentなどを追加した場合は以下のようになる。

from bullet import Bullet

cli = Bullet(
        prompt = "Please choose a fruit: ",
        choices = ["apple", "banana", "orange", "watermelon", "strawberry"],
        indent = 0,
        align = 5,
        margin = 2,
        shift = 0,
        bullet = "",
        pad_right = 5
    )

result = cli.launch()
print("You chose:", result)

f:id:wonder-wall:20190318210803p:plain

f:id:wonder-wall:20190318210819p:plain

オブジェクト

その他のオブジェクトとしてCheck, Input, YesNo, Password, Numbersなどがある。
また、VerticalPromptを使うと図のように縦に連続して表示されていく(冒頭のアニメーションのようにするにはSlidePromptを使う)。

from bullet import Bullet, Check, YesNo, Input, Password, Numbers, VerticalPrompt

cli = VerticalPrompt(
    [
        YesNo("Are you a student? "),
        Input("Who are you? "),
        Numbers("How old are you? "),
        Password("Password? "),
        Check("What is your favorite fruits",
              choices = ["apple", "banana", "orange", "watermelon", "strawberry"]),
        Bullet("What is your favorite programming language? ",
              choices = ["C++", "Python", "Javascript", "Not here!"]),
    ],
    spacing = 1
)

result = cli.launch()
print("You chose:", result)

f:id:wonder-wall:20190318212959p:plain

色変更

色変更についてはこのページを参照。
background_colorなどで色を指定できる。

from bullet import Bullet
from bullet import colors

cli = Bullet(
        prompt = "\nPlease choose a fruit: ",
        choices = ["apple", "banana", "orange", "watermelon", "strawberry"],
        indent = 0,
        align = 5,
        margin = 2,
        shift = 0,
        bullet = "★",
        bullet_color=colors.foreground["magenta"],
        word_color=colors.foreground["red"],
        word_on_switch=colors.foreground["green"],
        background_color=colors.background["cyan"],
        background_on_switch=colors.background["yellow"],
        pad_right = 5
    )

result = cli.launch()
print("You chose:", result)

f:id:wonder-wall:20190318214015p:plain