複数値を使用した CLI 引数
CLI 引数は複数値を受け取ることができます。
typing.List
を使用してCLI 引数のタイプを定義できます。
from pathlib import Path
from typing import List
import typer
def main(files: List[Path], celebration: str):
for path in files:
if path.is_file():
print(f"This file exists: {path.name}")
print(celebration)
if __name__ == "__main__":
typer.run(main)
その後、必要な数のCLI 引数をその型として渡すことができます。
$ python main.py ./index.md ./first-steps.md woohoo!
This file exists: index.md
woohoo!
This file exists: first-steps.md
woohoo!
ヒント
最後のCLI 引数に celebration
を宣言しましたが、最初に任意の数の files
を渡した場合でも、正しく使用されています。
情報
List
は最後のコマンドでのみ使用できます(サブコマンドがある場合)。これは右側のすべてを受け取り、それらが予測されたCLI 引数の一部であると想定するためです。
タプルを使用するCLI 引数¶
特定の数とタイプの値が必要な場合は、タプルを使用できます。このタプルはデフォルト値を持つことさえできます。
from typing import Tuple
import typer
from typing_extensions import Annotated
def main(
names: Annotated[
Tuple[str, str, str], typer.Argument(help="Select 3 characters to play with")
] = ("Harry", "Hermione", "Ron"),
):
for name in names:
print(f"Hello {name}")
if __name__ == "__main__":
typer.run(main)
ヒント
可能な限りAnnotated
バージョンを使用することを推奨します。
from typing import Tuple
import typer
def main(
names: Tuple[str, str, str] = typer.Argument(
("Harry", "Hermione", "Ron"), help="Select 3 characters to play with"
),
):
for name in names:
print(f"Hello {name}")
if __name__ == "__main__":
typer.run(main)
確認する
// Check the help
$ python main.py --help
Usage: main.py [OPTIONS] [NAMES]...
Arguments:
[NAMES]... Select 3 characters to play with [default: Harry, Hermione, Ron]
Options:
--help Show this message and exit.
// Use it with its defaults
$ python main.py
Hello Harry
Hello Hermione
Hello Ron
// If you pass an invalid number of arguments you will get an error
$ python main.py Draco Hagrid
Error: Argument 'names' takes 3 values
// And if you pass the exact number of values it will work correctly
$ python main.py Draco Hagrid Dobby
Hello Draco
Hello Hagrid
Hello Dobby