プログラムの終了
コマンドを途中で終了し、後続の実行をすべて停止したい場合があります。
コードがプログラムの正常終了を判断した場合、または操作が中止された場合が考えられます。
CLIプログラムの終了
¶
通常はCLIプログラムのコードを実行完了させることができますが、場合によっては、途中で終了したい場合があります。そして、後続のコードが実行されないようにします。
これはエラーが発生したことを意味する必要はなく、他に実行する必要がないことを意味します。
その場合は、typer.Exit()
例外を発生させることができます。
import typer
existing_usernames = ["rick", "morty"]
def maybe_create_user(username: str):
if username in existing_usernames:
print("The user already exists")
raise typer.Exit()
else:
print(f"User created: {username}")
def send_new_user_notification(username: str):
# Somehow send a notification here for the new user, maybe an email
print(f"Notification sent for new user: {username}")
def main(username: str):
maybe_create_user(username=username)
send_new_user_notification(username=username)
if __name__ == "__main__":
typer.run(main)
この例では、いくつかの点を確認する必要があります。
- CLIプログラムは、他の関数ではなく、関数
main()
です。これは_CLI引数_を受け取る関数です。 - 関数
maybe_create_user()
は、typer.Exit()
を発生させることでプログラムを終了できます。 - プログラムが
maybe_create_user()
によって終了された場合、send_new_user_notification()
はmain()
内で実行されません。
確認してください
$ python main.py Camila
User created: Camila
Notification sent for new user: Camila
// Try with an existing user
$ python main.py rick
The user already exists
// Notice that the notification code was never run, the second message is not printed
ヒント
例外を発生させていても、必ずしもエラーが発生しているとは限りません。
これは、「エラー」として機能し、すべての実行を停止するため、例外によって行われます。
しかし、その後、**Typer**(実際にはClick)がそれをキャッチし、プログラムを正常に終了させます。
エラーで終了¶
typer.Exit()
はオプションのcode
パラメータを取ります。デフォルトでは、code
は0
で、エラーがないことを意味します。
0
以外の数値をcode
に渡して、プログラムの実行中にエラーが発生したことをターミナルに伝えることができます。
import typer
def main(username: str):
if username == "root":
print("The root user is reserved")
raise typer.Exit(code=1)
print(f"New user created: {username}")
if __name__ == "__main__":
typer.run(main)
確認してください
$ python main.py Camila
New user created: Camila
// Print the result code of the last program executed
$ echo $?
0
// Now make it exit with an error
$ python main.py root
The root user is reserved
// Print the result code of the last program executed
$ echo $?
1
// 1 means there was an error, 0 means no errors.
ヒント
エラーコードは、CLIプログラムを実行する他のプログラム(たとえば、Bashスクリプト)で使用される場合があります。
中止¶
プログラムを「中止」するために使用できる特別な例外があります。
これは、typer.Exit()
とほぼ同じように機能しますが、画面に「中止されました!」
と出力し、特定のケースで実行が中止されたことを明示的にするために役立ちます。
import typer
def main(username: str):
if username == "root":
print("The root user is reserved")
raise typer.Abort()
print(f"New user created: {username}")
if __name__ == "__main__":
typer.run(main)
確認してください
$ python main.py Camila
New user created: Camila
// Now make it exit with an error
$ python main.py root
The root user is reserved
Aborted!