from typing import List, Optional
import typer
def main(device: Optional[List[str]] = typer.Option(None)):
if not device:
print("No provided devices")
raise typer.Abort()
for d in device:
print(f"Processing device: {d}")
if __name__ == "__main__":
typer.run(main)
And then it can be used like in:
$ ./my_cli --device 1 --device 2
Take a look at the documentation.
If the only input for the CLI is a list of devices, you can simplify it to using arguments instead. Then it could be used like:
$ ./my_cli 1 2
Answer from ericbn on Stack OverflowTyper
typer.tiangolo.com › tutorial › multiple-values › arguments-with-multiple-values
CLI Arguments with Multiple Values - Typer
You can define the type of a CLI argument using list. Python 3.10+ from pathlib import Path import typer app = typer.Typer() @app.command() 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__ ...
Stack Overflow
stackoverflow.com › questions › 77486338 › how-to-pass-a-list-as-an-argument-to-typer
python - How to pass a list as an argument to typer - Stack Overflow
main.py import typer from typing import List def typer_main( channels: List[int] = typer.Argument([1, 2, 3], help='List of channels'), ): for channel in channels: print(channel) Run
Typer
typer.tiangolo.com › tutorial › multiple-values › multiple-options
Multiple CLI Options - Typer
For this, use the standard Python list to declare it as a list of str: Python 3.10+ from typing import Annotated import typer app = typer.Typer() @app.command() def main(user: Annotated[list[str] | None, typer.Option()] = None): if not user: print(f"No provided users (raw input = {user})") raise typer.Abort() for u in user: print(f"Processing user: {u}") if __name__ == "__main__": app() 🤓 Other versions and variants ·
GitHub
github.com › fastapi › typer › issues › 110
[FEATURE] Handling Mutliple Variable Length Arguments · Issue #110 · fastapi/typer
May 26, 2020 - from typing import Optional, List import typer app = typer.Typer() @app.command() def main(first_list: List[str], option: bool = False, second_list: List[str] = ()): print(first_list, second_list) Where the expected behavior is: $ python main.py a b c --option d e f ('a', 'b', 'c') ('d', 'e', 'f') $ python main.py a b c d e f --option ('a', 'b', 'c', 'd', 'e', 'f') () $ python main.py a b c d e f ('a', 'b', 'c', 'd', 'e', 'f') () However the actual behavior in this case does not adhere to the above: $ python main.py a b c --option d e f ('a', 'b', 'c', 'd', 'e', 'f') True () This can presently
Author: fastapi
Typer
typer.tiangolo.com › tutorial › multiple-values › options-with-multiple-values
CLI Options with Multiple Values - Typer
from typing import Annotated import typer app = typer.Typer() @app.command() def main(user: Annotated[tuple[str, int, bool], typer.Option()] = (None, None, None)): username, coins, is_wizard = user if not username: print("No user provided") raise typer.Abort() print(f"The username {username} has {coins} coins") if is_wizard: print("And this user is a wizard!") if __name__ == "__main__": app()
Typer
typer.tiangolo.com › tutorial › arguments › optional
Optional CLI Arguments - Typer
As we no longer have the Python function default value (or its absence) to tell if something is required or not and what is the default value, typer.Argument() receives a first parameter default that serves the same purpose of defining that default value, or making it required.
Top answer 1 of 2
1
from typing import List, Optional
import typer
def main(device: Optional[List[str]] = typer.Option(None)):
if not device:
print("No provided devices")
raise typer.Abort()
for d in device:
print(f"Processing device: {d}")
if __name__ == "__main__":
typer.run(main)
And then it can be used like in:
$ ./my_cli --device 1 --device 2
Take a look at the documentation.
If the only input for the CLI is a list of devices, you can simplify it to using arguments instead. Then it could be used like:
$ ./my_cli 1 2
2 of 2
-2
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)
Typer
typer.tiangolo.com › tutorial › parameter-types
CLI Parameter Types - Typer
You can use several data types for the CLI options and CLI arguments, and you can add data validation requirements too. When you declare a CLI parameter with some type Typer will convert the data received in the command line to that data type.
Typer
typer.tiangolo.com › tutorial › arguments › help
CLI Arguments with Help - Typer
But you can customize it with the metavar parameter for typer.Argument().
Calmcode
calmcode.io › course › typer › options
Calmcode - typer: Options
import typer from typing import List from pathlib import Path app = typer.Typer(name="demo", add_completion=False, help="This is a demo app.") @app.command() def talk(text: str = typer.Argument(..., help="The text to type."), repeat: int = typer.Option(1, help="Number of times to repeat."), loud: bool = typer.Option(False, is_flag=True)): """Talks some text below""" if loud: text = text.upper() for _ in range(repeat): print(text) if __name__ == "__main__": app() The talk command can be run in multiple ways now. python cli.py talk "hello there" python cli.py talk "hello there" --repeat 2 python cli.py talk "hello there" --loud python cli.py talk "hello there" --loud --repeat 3
Typer
typer.tiangolo.com › reference › parameters
Parameters - Typer - Tiangolo.com
**Example** ```python from pathlib import Path @app.command() def main(config: Annotated[Path, typer.Argument(exists=True, file_okay=False)]): print(f"Directory listing: {[x.name for x in config.iterdir()]}") ``` """ ), ] = True, dir_okay: Annotated[ bool, Doc( """ Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/) is allowed to refer to a directory.
Typer
typer.tiangolo.com › tutorial › commands › arguments
Command CLI Arguments - Typer
The same way as with a CLI application with a single command, subcommands (or just "commands") can also have their own CLI arguments: ... import typer app = typer.Typer() @app.command() def create(username: str): print(f"Creating user: {username}") @app.command() def delete(username: str): print(f"Deleting user: {username}") if __name__ == "__main__": app() // Check the help for create $ uv run python main.py create --help Usage: main.py create [OPTIONS] {username} Arguments: username [required] Options: --help Show this message and exit.
Typer
typer.tiangolo.com › tutorial › arguments › default
CLI Arguments with Default - Typer
We can also use the same typer.Argument() to set a default value.
Calmcode
calmcode.io › course › typer › arguments
Calmcode - typer: Arguments
This is why typer allows you to attach details to your arguments. The command line app below is the app we end with in the video. import typer from typing import List from pathlib import Path app = typer.Typer(name="demo", add_completion=False, help="This is a demo app.") @app.command() def hello_world(name): """Say hello""" print(f"hello {name}!") @app.command() def goodbye_world(name): """Say goodbye""" print(f"goodbye {name}!") @app.command() def add(n1: int = typer.Argument(..., help="An integer"), n2: int = typer.Argument(1, help="An integer")): """Add two numbers""" print(n1 + n2) if __name__ == "__main__": app()
GitHub
github.com › fastapi › typer › issues › 387
Does Typer support Tuples as Multiple Multi Value Options - List[Tuple[str, str]] - like Click does? · Issue #387 · fastapi/typer
April 20, 2022 - import typer from typing import List, Tuple app = typer.Typer() @app.command() def test(opts: List[Tuple[str, str]]): ... I'm converting a small Click app to Typer and hit the following issue; I can't seem to get Tuples as Multiple Multi Value Options working. I would like to achieve the following: python main.py test --opt "--some-arg" "value" --opt "--another-arg" "value" This is achieved in Click with the following option: @click.option( "--opt", "opts", multiple=True, type=(str, str), required=False, default=(), help=( "Append to current config string.
Author: fastapi
GitHub
github.com › fastapi › typer › issues › 108
[BUG] Cannot create optional multi-valued positional argument · Issue #108 · fastapi/typer
May 26, 2020 - import typer import typing app = typer.Typer() @app.command() def test( patterns: typing.List[str] = typer.Argument([]), untracked: bool = typer.Option(False, "-u", "--untracked"), ): typer.echo(locals()) if __name__ == "__main__": app() Running this with python test.py gives me the following stack trace: % python test.py Traceback (most recent call last): File "test.py", line 14, in <module> app() File "/home/rui/miniconda3/envs/test/lib/python3.8/site-packages/typer/main.py", line 213, in __call__ return get_command(self)() File "/home/rui/miniconda3/envs/test/lib/python3.8/site-packages/typ
Author: fastapi
Typer
typer.tiangolo.com › tutorial › parameter-types › enum
Enum - Choices - Typer
// Notice the upper case CONV $ uv run python main.py --network CONV Training neural network of type: conv // A mix also works $ uv run python main.py --network LsTm Training neural network of type: lstm · A CLI parameter can also take a list of Enum values: ... from enum import Enum from typing import Annotated import typer class Food(str, Enum): food_1 = "Eggs" food_2 = "Bacon" food_3 = "Cheese" app = typer.Typer() @app.command() def main(groceries: Annotated[list[Food], typer.Option()] = [Food.food_1, Food.food_3]): print(f"Buying groceries: {', '.join([f.value for f in groceries])}") if __name__ == "__main__": app()
Typer
typer.tiangolo.com › tutorial › parameter-types › custom-types
Custom Types - Typer
typer.Argument and typer.Option can create custom parameter types with a parser callable. Python 3.10+ from typing import Annotated import typer class CustomClass: def __init__(self, value: str): self.value = value def __str__(self): return f"<CustomClass: value={self.value}>" def parse_custom_class(value: str): return CustomClass(value * 2) app = typer.Typer() @app.command() def main( custom_arg: Annotated[CustomClass, typer.Argument(parser=parse_custom_class)], custom_opt: Annotated[CustomClass, typer.Option(parser=parse_custom_class)] = "Foo", ): print(f"custom_arg is {custom_arg}") print(f"--custom-opt is {custom_opt}") if __name__ == "__main__": app() 🤓 Other versions and variants ·