コンテンツへスキップ

typer コマンド

typer コマンドは、独自の小さなスクリプトに対して、ターミナルでの ✨ 補完 ✨ を提供します。内部で Typer を使用していなくてもです。もちろん、スクリプトで Typer を使用している方がより効果的です。

おそらく最も役立つのは、Typer を使用した小さなカスタム Python スクリプト(おそらく何らかのプロジェクトの一部として)、いくつかの小さなタスクのためにあり、それに対して完全なインストール可能な Python パッケージを作成するほど複雑/重要ではない場合(pip でインストールするもの)です。

その場合、ターミナルで typer コマンドを使用してプログラムを実行でき、スクリプトの補完機能が提供されます。

typer コマンドには、独自の Typer プログラム用の Markdown ドキュメントを生成する機能もあります 📝。

インストール

Typer を以下のようにインストールすると

pip install typer

...typer コマンドが含まれます。

typer コマンドが不要な場合は、代わりに以下をインストールできます。

pip install typer-slim

モジュールとして Typer ライブラリを呼び出すことで、引き続き使用できます。

python -m typer

補完のインストール

typer コマンドの補完は、以下でインストールできます。

$ typer --install-completion

bash completion installed in /home/user/.bashrc.
Completion will take effect once you restart the terminal.

サンプルスクリプト

my_custom_script.pyTyper を使用するスクリプトがあるとします。

from typing import Optional

import typer

app = typer.Typer()


@app.command()
def hello(name: Optional[str] = None):
    if name:
        typer.echo(f"Hello {name}")
    else:
        typer.echo("Hello World!")


@app.command()
def bye(name: Optional[str] = None):
    if name:
        typer.echo(f"Bye {name}")
    else:
        typer.echo("Goodbye!")


if __name__ == "__main__":
    app()

機能させるには、Typer もインストールする必要があります。

$ python -m pip install typer
---> 100%
Successfully installed typer

Pythonで実行

次に、通常の Python でスクリプトを実行できます。

$ python my_custom_script.py hello

Hello World!

$ python my_custom_script.py hello --name Camila

Hello Camila!

$ python my_custom_script.py bye --name Camila

Bye Camila

Python を直接使用して実行することに問題はありません。そして、実際、他のコードやプログラムがスクリプトを使用する場合、おそらくそれが最良の方法でしょう。

⛔️ ただし、ターミナルでは、hellobye--name などのサブコマンドやオプションで TAB キーを押しても補完は行われません。

typerコマンドで実行。

同じスクリプトを typer コマンドで実行することもできます。

$ typer my_custom_script.py run hello

Hello World!

$ typer my_custom_script.py run hello --name Camila

Hello Camila!

$ typer my_custom_script.py run bye --name Camila

Bye Camila
  • python を直接使用する代わりに、typer コマンドを使用します。
  • ファイル名の後に、サブコマンド run を追加します。

✔️ 上記のように typer コマンドの補完をインストールした場合、TAB キーを押すと、スクリプトのすべてのサブコマンドやオプション(hellobye--name など)を含む ✨ すべての補完機能 ✨ が利用できるようになります 🚀。

if main

typer コマンドは以下のブロックを使用しないため

if __name__ == "__main__":
    app()

...そのスクリプトを typer コマンドのみで呼び出す場合は、削除することもできます。

他のファイルの実行

typer コマンドは Typer を使用した任意のスクリプトを実行できますが、スクリプトが Typer をまったく使用する必要はありません。

typer.run() で使用できる関数を含むファイルを、スクリプトが typer.run() やその他のものを使用していなくても実行できます。

たとえば、次のようなファイル main.py は引き続き動作します。

def main(name: str = "World"):
    """
    Say hi to someone, by default to the World.
    """
    print(f"Hello {name}")

次に、以下で呼び出すことができます。

$ typer main.py run --help
Usage: typer run [OPTIONS]

  Say hi to someone, by default to the World.

Options:
  --name TEXT
  --help       Show this message and exit.

$ typer main.py run --name Camila

Hello Camila

--name CLIオプション などの補完も行われます。

パッケージまたはモジュールの実行

ファイルパスの代わりに、インポートするモジュール(おそらくパッケージ内)を渡すことができます。

$ typer my_package.main run --help
Usage: typer run [OPTIONS]

Options:
  --name TEXT
  --help       Show this message and exit.

$ typer my_package.main run --name Camila

Hello Camila

オプション

次の CLIオプション のいずれかを指定できます。

  • --app:メインアプリとして実行する Typer() オブジェクトを持つ変数の名前。
  • --functyper.run() で使用される関数の変数の名前。

デフォルト

typer コマンドでスクリプトを実行すると、次の優先順位でアプリが使用されます。

  • --app CLIオプション からのアプリオブジェクト。
  • --func CLIオプション から Typer アプリに変換する関数(typer.run() を使用する場合と同様)。
  • appcli、または main という名前の変数内の Typer アプリ。
  • ファイル内で利用可能な最初の Typer アプリ(任意の名前にできます)。
  • maincli、または app という名前の変数内の関数。
  • ファイル内の最初の関数(任意の名前にできます)。

ドキュメントの生成

typer コマンドを使用して、Typer アプリケーションの Markdown ドキュメントを生成することもできます。

ドキュメント付きサンプルスクリプト

たとえば、次のようなスクリプトを作成できます。

import typer

app = typer.Typer(help="Awesome CLI user manager.")


@app.command()
def create(username: str):
    """
    Create a new user with USERNAME.
    """
    print(f"Creating user: {username}")


@app.command()
def delete(
    username: str,
    force: bool = typer.Option(
        ...,
        prompt="Are you sure you want to delete the user?",
        help="Force deletion without confirmation.",
    ),
):
    """
    Delete a user with USERNAME.

    If --force is not used, will ask for confirmation.
    """
    if force:
        print(f"Deleting user: {username}")
    else:
        print("Operation cancelled")


@app.command()
def delete_all(
    force: bool = typer.Option(
        ...,
        prompt="Are you sure you want to delete ALL users?",
        help="Force deletion without confirmation.",
    ),
):
    """
    Delete ALL users in the database.

    If --force is not used, will ask for confirmation.
    """
    if force:
        print("Deleting all users")
    else:
        print("Operation cancelled")


@app.command()
def init():
    """
    Initialize the users database.
    """
    print("Initializing user database")


if __name__ == "__main__":
    app()

typerコマンドでのドキュメント生成

次に、typer コマンドを使用してドキュメントを生成できます。

サブコマンド utils を使用できます。

次に、サブコマンド docs を使用します。

$ typer some_script.py utils docs

ヒント

typer-slim のみをインストールしていて、typer コマンドがない場合でも、以下でドキュメントを生成できます。

$ python -m typer some_script.py utils docs

オプション:

  • --name TEXT:ドキュメントで使用するCLIプログラムの名前。
  • --output FILE:ドキュメントの書き込み先の出力ファイル(README.mdなど)。
  • --title TEXT:ドキュメントで使用するタイトル(デフォルトではコマンドの名前)。

$ typer my_package.main utils docs --name awesome-cli --output README.md

Docs saved to: README.md

ドキュメント出力例

たとえば、前のスクリプトの場合、生成されたドキュメントは次のようになります。


awesome-cli

素晴らしいCLIユーザーマネージャー。

使用法:

$ awesome-cli [OPTIONS] COMMAND [ARGS]...

オプション:

  • --install-completion:現在のシェルに補完をインストールします。
  • --show-completion:現在のシェルの補完を表示して、コピーするかインストールをカスタマイズします。
  • --help:このメッセージを表示して終了します。

コマンド:

  • create:USERNAMEで新しいユーザーを作成します。
  • delete:USERNAMEでユーザーを削除します。
  • delete-all:データベース内のすべてのユーザーを削除します。
  • init:ユーザーデータベースを初期化します。

awesome-cli create

USERNAMEで新しいユーザーを作成します。

使用法:

$ awesome-cli create [OPTIONS] USERNAME

オプション:

  • --help:このメッセージを表示して終了します。

awesome-cli delete

USERNAMEでユーザーを削除します。

--force が使用されていない場合は、確認を求めます。

使用法:

$ awesome-cli delete [OPTIONS] USERNAME

オプション:

  • --force / --no-force: 確認なしで強制的に削除します。[必須]
  • --help:このメッセージを表示して終了します。

awesome-cli delete-all

データベース内のすべてのユーザーを削除します。

--force が使用されていない場合は、確認を求めます。

使用法:

$ awesome-cli delete-all [OPTIONS]

オプション:

  • --force / --no-force: 確認なしで強制的に削除します。[必須]
  • --help:このメッセージを表示して終了します。

awesome-cli init

ユーザーデータベースを初期化します。

使用法:

$ awesome-cli init [OPTIONS]

オプション:

  • --help:このメッセージを表示して終了します。