Skip to main content

Typer - python package

Python 預設的 typing 用作 CLI 的 arg parser https://typer.tiangolo.com/

import typer


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


if __name__ == "__main__":
typer.run(main)
$ python main.py Camila

Hello Camila
  • names: list = typer.Option([])
    • --names Alice --names Bob
  • debug: bool = False
    • --debug
  • save: bool = typer.Option(False, "--save", help="Save output to file")

Dynamic Defaults for Options

Use dynamic default values for options, which can be particularly useful for settings that might change based on external factors (like environment variables or config files).

import typer
import os

def get_default_username():
return os.getenv("USER", "admin")

@app.command()
def login(username: str = typer.Option(default=get_default_username)):
typer.echo(f"Logging in as {username}")

if __name__ == "__main__":
app()