カスタムコマンド名
デフォルトでは、コマンド名は関数名から生成されます。
したがって、関数が次のようなものの場合
def create(username: str):
...
コマンド名は作成
になります。
ただし、コードのどこかにすでにcreate()
という関数が存在する場合、CLI関数の名前を別のものに付ける必要があります。
コマンド名を作成
のままにするにはどうすればよいでしょうか。
これには、@app.command()
デコレータの最初の引数にコマンドの名前を設定できます
import typer
app = typer.Typer()
@app.command("create")
def cli_create_user(username: str):
print(f"Creating user: {username}")
@app.command("delete")
def cli_delete_user(username: str):
print(f"Deleting user: {username}")
if __name__ == "__main__":
app()
これで、機能名がcli_create_user()
とcli_delete_user()
であっても、コマンドはcreate
とdelete
のままになります。
$ python main.py --help
Usage: main.py [OPTIONS] COMMAND [ARGS]...
Options:
--install-completion Install completion for the current shell.
--show-completion Show completion for the current shell, to copy it or customize the installation.
--help Show this message and exit.
Commands:
create
delete
// Test it
$ python main.py create Camila
Creating user: Camila
関数名内の下線はすべてダッシュに置き換えられます。
したがって、関数が次のようなものの場合
def create_user(username: str):
...
create-user
になります。