跳到內容

撰寫程式

Typer

Typer,建立超棒的 CLI。易於撰寫程式碼。根據 Python 型別提示建立而來。

Test Publish Coverage Package version


文件: https://typer.dev.org.tw

原始碼: https://github.com/tiangolo/typer


Typer 是個建立 CLI 應用程式的函式庫,使用者將會樂於使用,開發人員則會樂於創作。根據 Python 型別提示建立而來。

它也是個命令列工具,用於執行指令,自動將其轉換成 CLI 應用程式。

其主要特色為

  • 直覺式書寫: 優異的編輯器支援。無所不在的自動完成。縮短除錯時間。設計為易於使用和學習。縮短閱讀文件時間。
  • 易於使用: 最終使用者很容易使用。自動說明,以及對所有 shell 的自動完成。
  • 簡短: 盡量減少程式碼重複。從每個參數宣告中獲取多項特色。減少錯誤。
  • 從簡開始: 最簡單的範例只需要在應用程式中新增兩行程式碼:1 個匯入,1 個函式呼叫
  • 逐漸擴充: 以您想要的複雜度逐步擴充,建立任意的複雜指令樹和子指令群組,附帶選項和參數。
  • 執行指令: Typer 包括一個 typer 指令/程式,您可以用它來執行指令,自動將其轉換成 CLI,即使它們並未內部使用 Typer。

CLI 的 FastAPI

TyperFastAPI 的小表弟,它是 CLI 的 FastAPI。

安裝

$ pip install typer
---> 100%
Successfully installed typer rich shellingham

範例

絕對的最低限度

  • 使用下列內容建立檔案 main.py
def main(name: str):
    print(f"Hello {name}")

此指令甚至未在內部使用 Typer。但您可以使用 typer 指令將它作為 CLI 應用程式執行。

執行它

使用 typer 指令執行您的應用程式

// Run your application
$ typer main.py run

// You get a nice error, you are missing NAME
Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME
Try 'typer [PATH_OR_MODULE] run --help' for help.
╭─ Error ───────────────────────────────────────────╮
│ Missing argument 'NAME'.                          │
╰───────────────────────────────────────────────────╯


// You get a --help for free
$ typer main.py run --help

Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME

Run the provided Typer app.

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   |
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --help          Show this message and exit.       │
╰───────────────────────────────────────────────────╯

// Now pass the NAME argument
$ typer main.py run Camila

Hello Camila

// It works! 🎉

這是最簡單的使用案例,甚至未在內部使用 Typer,但對於簡單的指令來說,它已經相當實用了。

注意:當您建立 Python 套件並使用 --install-completion 執行它,或是使用 typer 指令時,自動完成才會運作。

在您的程式碼中使用 Typer

現在開始在您的程式碼中使用 Typer,更新 main.py

import typer


def main(name: str):
    print(f"Hello {name}")


if __name__ == "__main__":
    typer.run(main)

現在您可以直接使用 Python 執行它

// Run your application
$ python main.py

// You get a nice error, you are missing NAME
Usage: main.py [OPTIONS] NAME
Try 'main.py --help' for help.
╭─ Error ───────────────────────────────────────────╮
│ Missing argument 'NAME'.                          │
╰───────────────────────────────────────────────────╯


// You get a --help for free
$ python main.py --help

Usage: main.py [OPTIONS] NAME

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   |
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --help          Show this message and exit.       │
╰───────────────────────────────────────────────────╯

// Now pass the NAME argument
$ python main.py Camila

Hello Camila

// It works! 🎉

注意:您也可以使用 typer 指令呼叫此指令,但您不需要這麼做。

範例升級

這是最簡單的範例。

現在我們來看看更複雜一點的。

包含兩個子指令的範例

修改檔案 main.py

建立一個 typer.Typer() 應用程式,並建立兩個子指令與其參數。

import typer

app = typer.Typer()


@app.command()
def hello(name: str):
    print(f"Hello {name}")


@app.command()
def goodbye(name: str, formal: bool = False):
    if formal:
        print(f"Goodbye Ms. {name}. Have a good day.")
    else:
        print(f"Bye {name}!")


if __name__ == "__main__":
    app()

然後就會

  • 明確建立一個 typer.Typer 應用程式。
    • 先前 typer.run 實際上為您隱含建立一個。
  • 使用 @app.command() 新增兩個子指令。
  • 執行 app() 本身,如同它是函式(取代 typer.run)。

執行升級的範例

檢查新的說明

$ 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 ────────────────────────────────────────╮
│ goodbye                                           │
│ hello                                             │
╰───────────────────────────────────────────────────╯

// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion

// You have 2 subcommands (the 2 functions): goodbye and hello

現在查看 hello 指令的說明

$ python main.py hello --help

 Usage: main.py hello [OPTIONS] NAME

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   │
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --help          Show this message and exit.       │
╰───────────────────────────────────────────────────╯

現在查看 goodbye 指令的說明

$ python main.py goodbye --help

 Usage: main.py goodbye [OPTIONS] NAME

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   │
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --formal    --no-formal      [default: no-formal] │
│ --help                       Show this message    │
│                              and exit.            │
╰───────────────────────────────────────────────────╯

// Automatic --formal and --no-formal for the bool option 🎉

現在您可以嘗試新的命令列應用程式

// Use it with the hello command

$ python main.py hello Camila

Hello Camila

// And with the goodbye command

$ python main.py goodbye Camila

Bye Camila!

// And with --formal

$ python main.py goodbye --formal Camila

Goodbye Ms. Camila. Have a good day.

摘要

總之,您宣告參數類型(命令列引數命令列選項)作為函式參數一次

您使用標準的現代 Python 類型來完成此動作。

您無需學習新的語法、特定函式庫的方法或類別等。

只需要標準 Python

例如,對於 int

total: int

或對於 bool 旗標

force: bool

對於 **檔案**、**路徑**、**枚舉**(選擇)等也同樣如此。而且有工具可以建立 **子指令群組**、新增元資料、額外 **驗證** 等。

您會獲得:絕佳的編輯器支援,在所有地方包含 **自動完成** 和 **類型檢查**。

您的使用者會獲得:裝設您的套件或使用 typer 指令時,在他們的終端機(Bash、Zsh、Fish、PowerShell)中自動生成的 --help自動完成

如需包含更多功能的更完整範例,請參閱 教學課程 - 使用者指南

依存關係

Typer 建立在巨人的肩膀上。其唯一的內部必要依存關係是 Click

預設情況下也附帶有額外的標準依存關係

  • rich:自動顯示格式良好的錯誤訊息
  • shellingham:在安裝自動完成時自動偵測目前的 shell。
    • 使用 shellingham 您只需使用 --install-completion
    • 不使用 shellingham 時,您必須傳遞要安裝自動完成的 shell 名稱,例如 --install-completion bash.

typer-slim

如果您不需要額外的標準選擇性依賴項,請改安裝 typer-slim

當您使用以下安裝

pip install typer

...它包含的程式碼和依賴項與以下相同

pip install "typer-slim[standard]"

standard 額外的依賴項為 richshellingham

注意typer 命令僅包含在 typer 套件中。

授權條款

本專案在 MIT 授權條款下授權。