0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

typerでCLI引数を取れるようにする

Last updated at Posted at 2025-10-23

https://typer.tiangolo.com/#use-typer-in-your-code
https://typer.tiangolo.com/tutorial/parameter-types/path/

デコレータを使った記述方法

from pathlib import Path
from typing import Annotated
import typer
app = typer.Typer()

@app.command()
def function_sample(
    file_path: Annotated[
        Path, typer.Option(..., exists=True, file_okay=True, help="データのパス")
    ],
) -> None:
...
if __name__ == "__main__":
    app()

実行時

python main.py \
--file-path file/to/path
  • オプション引数はアンダースコア_がハイフン-になっているので注意
  • 引数がパスの場合はPathlibで受け取ると親フォルダ作成やパス連結など取り回しがしやすい
  • typingのAnnotatedで型安全を保証
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?