typer.core
1import errno 2import inspect 3import os 4import sys 5from enum import Enum 6from gettext import gettext as _ 7from typing import ( 8 Any, 9 Callable, 10 Dict, 11 List, 12 MutableMapping, 13 Optional, 14 Sequence, 15 TextIO, 16 Tuple, 17 Union, 18 cast, 19) 20 21import click 22import click.core 23import click.formatting 24import click.parser 25import click.shell_completion 26import click.types 27import click.utils 28 29if sys.version_info >= (3, 8): 30 from typing import Literal 31else: 32 from typing_extensions import Literal 33 34MarkupMode = Literal["markdown", "rich", None] 35 36try: 37 import rich 38 39 from . import rich_utils 40 41 DEFAULT_MARKUP_MODE: MarkupMode = "rich" 42 43except ImportError: # pragma: no cover 44 rich = None # type: ignore 45 DEFAULT_MARKUP_MODE = None 46 47 48# Copy from click.parser._split_opt 49def _split_opt(opt: str) -> Tuple[str, str]: 50 first = opt[:1] 51 if first.isalnum(): 52 return "", opt 53 if opt[1:2] == first: 54 return opt[:2], opt[2:] 55 return first, opt[1:] 56 57 58def _typer_param_setup_autocompletion_compat( 59 self: click.Parameter, 60 *, 61 autocompletion: Optional[ 62 Callable[[click.Context, List[str], str], List[Union[Tuple[str, str], str]]] 63 ] = None, 64) -> None: 65 if autocompletion is not None and self._custom_shell_complete is None: 66 import warnings 67 68 warnings.warn( 69 "'autocompletion' is renamed to 'shell_complete'. The old name is" 70 " deprecated and will be removed in Click 8.1. See the docs about" 71 " 'Parameter' for information about new behavior.", 72 DeprecationWarning, 73 stacklevel=2, 74 ) 75 76 def compat_autocompletion( 77 ctx: click.Context, param: click.core.Parameter, incomplete: str 78 ) -> List["click.shell_completion.CompletionItem"]: 79 from click.shell_completion import CompletionItem 80 81 out = [] 82 83 for c in autocompletion(ctx, [], incomplete): 84 if isinstance(c, tuple): 85 use_completion = CompletionItem(c[0], help=c[1]) 86 else: 87 assert isinstance(c, str) 88 use_completion = CompletionItem(c) 89 90 if use_completion.value.startswith(incomplete): 91 out.append(use_completion) 92 93 return out 94 95 self._custom_shell_complete = compat_autocompletion 96 97 98def _get_default_string( 99 obj: Union["TyperArgument", "TyperOption"], 100 *, 101 ctx: click.Context, 102 show_default_is_str: bool, 103 default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any], 104) -> str: 105 # Extracted from click.core.Option.get_help_record() to be reused by 106 # rich_utils avoiding RegEx hacks 107 if show_default_is_str: 108 default_string = f"({obj.show_default})" 109 elif isinstance(default_value, (list, tuple)): 110 default_string = ", ".join( 111 _get_default_string( 112 obj, ctx=ctx, show_default_is_str=show_default_is_str, default_value=d 113 ) 114 for d in default_value 115 ) 116 elif isinstance(default_value, Enum): 117 default_string = str(default_value.value) 118 elif inspect.isfunction(default_value): 119 default_string = _("(dynamic)") 120 elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts: 121 # For boolean flags that have distinct True/False opts, 122 # use the opt without prefix instead of the value. 123 # Typer override, original commented 124 # default_string = click.parser.split_opt( 125 # (self.opts if self.default else self.secondary_opts)[0] 126 # )[1] 127 if obj.default: 128 if obj.opts: 129 default_string = _split_opt(obj.opts[0])[1] 130 else: 131 default_string = str(default_value) 132 else: 133 default_string = _split_opt(obj.secondary_opts[0])[1] 134 # Typer override end 135 elif ( 136 isinstance(obj, TyperOption) 137 and obj.is_bool_flag 138 and not obj.secondary_opts 139 and not default_value 140 ): 141 default_string = "" 142 else: 143 default_string = str(default_value) 144 return default_string 145 146 147def _extract_default_help_str( 148 obj: Union["TyperArgument", "TyperOption"], *, ctx: click.Context 149) -> Optional[Union[Any, Callable[[], Any]]]: 150 # Extracted from click.core.Option.get_help_record() to be reused by 151 # rich_utils avoiding RegEx hacks 152 # Temporarily enable resilient parsing to avoid type casting 153 # failing for the default. Might be possible to extend this to 154 # help formatting in general. 155 resilient = ctx.resilient_parsing 156 ctx.resilient_parsing = True 157 158 try: 159 default_value = obj.get_default(ctx, call=False) 160 finally: 161 ctx.resilient_parsing = resilient 162 return default_value 163 164 165def _main( 166 self: click.Command, 167 *, 168 args: Optional[Sequence[str]] = None, 169 prog_name: Optional[str] = None, 170 complete_var: Optional[str] = None, 171 standalone_mode: bool = True, 172 windows_expand_args: bool = True, 173 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 174 **extra: Any, 175) -> Any: 176 # Typer override, duplicated from click.main() to handle custom rich exceptions 177 # Verify that the environment is configured correctly, or reject 178 # further execution to avoid a broken script. 179 if args is None: 180 args = sys.argv[1:] 181 182 # Covered in Click tests 183 if os.name == "nt" and windows_expand_args: # pragma: no cover 184 args = click.utils._expand_args(args) 185 else: 186 args = list(args) 187 188 if prog_name is None: 189 prog_name = click.utils._detect_program_name() 190 191 # Process shell completion requests and exit early. 192 self._main_shell_completion(extra, prog_name, complete_var) 193 194 try: 195 try: 196 with self.make_context(prog_name, args, **extra) as ctx: 197 rv = self.invoke(ctx) 198 if not standalone_mode: 199 return rv 200 # it's not safe to `ctx.exit(rv)` here! 201 # note that `rv` may actually contain data like "1" which 202 # has obvious effects 203 # more subtle case: `rv=[None, None]` can come out of 204 # chained commands which all returned `None` -- so it's not 205 # even always obvious that `rv` indicates success/failure 206 # by its truthiness/falsiness 207 ctx.exit() 208 except EOFError as e: 209 click.echo(file=sys.stderr) 210 raise click.Abort() from e 211 except KeyboardInterrupt as e: 212 raise click.exceptions.Exit(130) from e 213 except click.ClickException as e: 214 if not standalone_mode: 215 raise 216 # Typer override 217 if rich and rich_markup_mode is not None: 218 rich_utils.rich_format_error(e) 219 else: 220 e.show() 221 # Typer override end 222 sys.exit(e.exit_code) 223 except OSError as e: 224 if e.errno == errno.EPIPE: 225 sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout)) 226 sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr)) 227 sys.exit(1) 228 else: 229 raise 230 except click.exceptions.Exit as e: 231 if standalone_mode: 232 sys.exit(e.exit_code) 233 else: 234 # in non-standalone mode, return the exit code 235 # note that this is only reached if `self.invoke` above raises 236 # an Exit explicitly -- thus bypassing the check there which 237 # would return its result 238 # the results of non-standalone execution may therefore be 239 # somewhat ambiguous: if there are codepaths which lead to 240 # `ctx.exit(1)` and to `return 1`, the caller won't be able to 241 # tell the difference between the two 242 return e.exit_code 243 except click.Abort: 244 if not standalone_mode: 245 raise 246 # Typer override 247 if rich and rich_markup_mode is not None: 248 rich_utils.rich_abort_error() 249 else: 250 click.echo(_("Aborted!"), file=sys.stderr) 251 # Typer override end 252 sys.exit(1) 253 254 255class TyperArgument(click.core.Argument): 256 def __init__( 257 self, 258 *, 259 # Parameter 260 param_decls: List[str], 261 type: Optional[Any] = None, 262 required: Optional[bool] = None, 263 default: Optional[Any] = None, 264 callback: Optional[Callable[..., Any]] = None, 265 nargs: Optional[int] = None, 266 metavar: Optional[str] = None, 267 expose_value: bool = True, 268 is_eager: bool = False, 269 envvar: Optional[Union[str, List[str]]] = None, 270 shell_complete: Optional[ 271 Callable[ 272 [click.Context, click.Parameter, str], 273 Union[List["click.shell_completion.CompletionItem"], List[str]], 274 ] 275 ] = None, 276 autocompletion: Optional[Callable[..., Any]] = None, 277 # TyperArgument 278 show_default: Union[bool, str] = True, 279 show_choices: bool = True, 280 show_envvar: bool = True, 281 help: Optional[str] = None, 282 hidden: bool = False, 283 # Rich settings 284 rich_help_panel: Union[str, None] = None, 285 ): 286 self.help = help 287 self.show_default = show_default 288 self.show_choices = show_choices 289 self.show_envvar = show_envvar 290 self.hidden = hidden 291 self.rich_help_panel = rich_help_panel 292 293 super().__init__( 294 param_decls=param_decls, 295 type=type, 296 required=required, 297 default=default, 298 callback=callback, 299 nargs=nargs, 300 metavar=metavar, 301 expose_value=expose_value, 302 is_eager=is_eager, 303 envvar=envvar, 304 shell_complete=shell_complete, 305 ) 306 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 307 308 def _get_default_string( 309 self, 310 *, 311 ctx: click.Context, 312 show_default_is_str: bool, 313 default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any], 314 ) -> str: 315 return _get_default_string( 316 self, 317 ctx=ctx, 318 show_default_is_str=show_default_is_str, 319 default_value=default_value, 320 ) 321 322 def _extract_default_help_str( 323 self, *, ctx: click.Context 324 ) -> Optional[Union[Any, Callable[[], Any]]]: 325 return _extract_default_help_str(self, ctx=ctx) 326 327 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 328 # Modified version of click.core.Option.get_help_record() 329 # to support Arguments 330 if self.hidden: 331 return None 332 name = self.make_metavar() 333 help = self.help or "" 334 extra = [] 335 if self.show_envvar: 336 envvar = self.envvar 337 # allow_from_autoenv is currently not supported in Typer for CLI Arguments 338 if envvar is not None: 339 var_str = ( 340 ", ".join(str(d) for d in envvar) 341 if isinstance(envvar, (list, tuple)) 342 else envvar 343 ) 344 extra.append(f"env var: {var_str}") 345 346 # Typer override: 347 # Extracted to _extract_default_help_str() to allow re-using it in rich_utils 348 default_value = self._extract_default_help_str(ctx=ctx) 349 # Typer override end 350 351 show_default_is_str = isinstance(self.show_default, str) 352 353 if show_default_is_str or ( 354 default_value is not None and (self.show_default or ctx.show_default) 355 ): 356 # Typer override: 357 # Extracted to _get_default_string() to allow re-using it in rich_utils 358 default_string = self._get_default_string( 359 ctx=ctx, 360 show_default_is_str=show_default_is_str, 361 default_value=default_value, 362 ) 363 # Typer override end 364 if default_string: 365 extra.append(_("default: {default}").format(default=default_string)) 366 if self.required: 367 extra.append(_("required")) 368 if extra: 369 extra_str = "; ".join(extra) 370 extra_str = f"[{extra_str}]" 371 if rich is not None: 372 # This is needed for when we want to export to HTML 373 extra_str = rich.markup.escape(extra_str).strip() 374 375 help = f"{help} {extra_str}" if help else f"{extra_str}" 376 return name, help 377 378 def make_metavar(self) -> str: 379 # Modified version of click.core.Argument.make_metavar() 380 # to include Argument name 381 if self.metavar is not None: 382 return self.metavar 383 var = (self.name or "").upper() 384 if not self.required: 385 var = f"[{var}]" 386 type_var = self.type.get_metavar(self) 387 if type_var: 388 var += f":{type_var}" 389 if self.nargs != 1: 390 var += "..." 391 return var 392 393 394class TyperOption(click.core.Option): 395 def __init__( 396 self, 397 *, 398 # Parameter 399 param_decls: List[str], 400 type: Optional[Union[click.types.ParamType, Any]] = None, 401 required: Optional[bool] = None, 402 default: Optional[Any] = None, 403 callback: Optional[Callable[..., Any]] = None, 404 nargs: Optional[int] = None, 405 metavar: Optional[str] = None, 406 expose_value: bool = True, 407 is_eager: bool = False, 408 envvar: Optional[Union[str, List[str]]] = None, 409 shell_complete: Optional[ 410 Callable[ 411 [click.Context, click.Parameter, str], 412 Union[List["click.shell_completion.CompletionItem"], List[str]], 413 ] 414 ] = None, 415 autocompletion: Optional[Callable[..., Any]] = None, 416 # Option 417 show_default: Union[bool, str] = False, 418 prompt: Union[bool, str] = False, 419 confirmation_prompt: Union[bool, str] = False, 420 prompt_required: bool = True, 421 hide_input: bool = False, 422 is_flag: Optional[bool] = None, 423 multiple: bool = False, 424 count: bool = False, 425 allow_from_autoenv: bool = True, 426 help: Optional[str] = None, 427 hidden: bool = False, 428 show_choices: bool = True, 429 show_envvar: bool = False, 430 # Rich settings 431 rich_help_panel: Union[str, None] = None, 432 ): 433 super().__init__( 434 param_decls=param_decls, 435 type=type, 436 required=required, 437 default=default, 438 callback=callback, 439 nargs=nargs, 440 metavar=metavar, 441 expose_value=expose_value, 442 is_eager=is_eager, 443 envvar=envvar, 444 show_default=show_default, 445 prompt=prompt, 446 confirmation_prompt=confirmation_prompt, 447 hide_input=hide_input, 448 is_flag=is_flag, 449 multiple=multiple, 450 count=count, 451 allow_from_autoenv=allow_from_autoenv, 452 help=help, 453 hidden=hidden, 454 show_choices=show_choices, 455 show_envvar=show_envvar, 456 prompt_required=prompt_required, 457 shell_complete=shell_complete, 458 ) 459 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 460 self.rich_help_panel = rich_help_panel 461 462 def _get_default_string( 463 self, 464 *, 465 ctx: click.Context, 466 show_default_is_str: bool, 467 default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any], 468 ) -> str: 469 return _get_default_string( 470 self, 471 ctx=ctx, 472 show_default_is_str=show_default_is_str, 473 default_value=default_value, 474 ) 475 476 def _extract_default_help_str( 477 self, *, ctx: click.Context 478 ) -> Optional[Union[Any, Callable[[], Any]]]: 479 return _extract_default_help_str(self, ctx=ctx) 480 481 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 482 # Duplicate all of Click's logic only to modify a single line, to allow boolean 483 # flags with only names for False values as it's currently supported by Typer 484 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false 485 if self.hidden: 486 return None 487 488 any_prefix_is_slash = False 489 490 def _write_opts(opts: Sequence[str]) -> str: 491 nonlocal any_prefix_is_slash 492 493 rv, any_slashes = click.formatting.join_options(opts) 494 495 if any_slashes: 496 any_prefix_is_slash = True 497 498 if not self.is_flag and not self.count: 499 rv += f" {self.make_metavar()}" 500 501 return rv 502 503 rv = [_write_opts(self.opts)] 504 505 if self.secondary_opts: 506 rv.append(_write_opts(self.secondary_opts)) 507 508 help = self.help or "" 509 extra = [] 510 511 if self.show_envvar: 512 envvar = self.envvar 513 514 if envvar is None: 515 if ( 516 self.allow_from_autoenv 517 and ctx.auto_envvar_prefix is not None 518 and self.name is not None 519 ): 520 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 521 522 if envvar is not None: 523 var_str = ( 524 envvar 525 if isinstance(envvar, str) 526 else ", ".join(str(d) for d in envvar) 527 ) 528 extra.append(_("env var: {var}").format(var=var_str)) 529 530 # Typer override: 531 # Extracted to _extract_default() to allow re-using it in rich_utils 532 default_value = self._extract_default_help_str(ctx=ctx) 533 # Typer override end 534 535 show_default_is_str = isinstance(self.show_default, str) 536 537 if show_default_is_str or ( 538 default_value is not None and (self.show_default or ctx.show_default) 539 ): 540 # Typer override: 541 # Extracted to _get_default_string() to allow re-using it in rich_utils 542 default_string = self._get_default_string( 543 ctx=ctx, 544 show_default_is_str=show_default_is_str, 545 default_value=default_value, 546 ) 547 # Typer override end 548 if default_string: 549 extra.append(_("default: {default}").format(default=default_string)) 550 551 if isinstance(self.type, click.types._NumberRangeBase): 552 range_str = self.type._describe_range() 553 554 if range_str: 555 extra.append(range_str) 556 557 if self.required: 558 extra.append(_("required")) 559 560 if extra: 561 extra_str = "; ".join(extra) 562 extra_str = f"[{extra_str}]" 563 if rich is not None: 564 # This is needed for when we want to export to HTML 565 extra_str = rich.markup.escape(extra_str).strip() 566 567 help = f"{help} {extra_str}" if help else f"{extra_str}" 568 569 return ("; " if any_prefix_is_slash else " / ").join(rv), help 570 571 572def _typer_format_options( 573 self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter 574) -> None: 575 args = [] 576 opts = [] 577 for param in self.get_params(ctx): 578 rv = param.get_help_record(ctx) 579 if rv is not None: 580 if param.param_type_name == "argument": 581 args.append(rv) 582 elif param.param_type_name == "option": 583 opts.append(rv) 584 585 if args: 586 with formatter.section(_("Arguments")): 587 formatter.write_dl(args) 588 if opts: 589 with formatter.section(_("Options")): 590 formatter.write_dl(opts) 591 592 593def _typer_main_shell_completion( 594 self: click.core.Command, 595 *, 596 ctx_args: MutableMapping[str, Any], 597 prog_name: str, 598 complete_var: Optional[str] = None, 599) -> None: 600 if complete_var is None: 601 complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper() 602 603 instruction = os.environ.get(complete_var) 604 605 if not instruction: 606 return 607 608 from .completion import shell_complete 609 610 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) 611 sys.exit(rv) 612 613 614class TyperCommand(click.core.Command): 615 def __init__( 616 self, 617 name: Optional[str], 618 *, 619 context_settings: Optional[Dict[str, Any]] = None, 620 callback: Optional[Callable[..., Any]] = None, 621 params: Optional[List[click.Parameter]] = None, 622 help: Optional[str] = None, 623 epilog: Optional[str] = None, 624 short_help: Optional[str] = None, 625 options_metavar: Optional[str] = "[OPTIONS]", 626 add_help_option: bool = True, 627 no_args_is_help: bool = False, 628 hidden: bool = False, 629 deprecated: bool = False, 630 # Rich settings 631 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 632 rich_help_panel: Union[str, None] = None, 633 ) -> None: 634 super().__init__( 635 name=name, 636 context_settings=context_settings, 637 callback=callback, 638 params=params, 639 help=help, 640 epilog=epilog, 641 short_help=short_help, 642 options_metavar=options_metavar, 643 add_help_option=add_help_option, 644 no_args_is_help=no_args_is_help, 645 hidden=hidden, 646 deprecated=deprecated, 647 ) 648 self.rich_markup_mode: MarkupMode = rich_markup_mode 649 self.rich_help_panel = rich_help_panel 650 651 def format_options( 652 self, ctx: click.Context, formatter: click.HelpFormatter 653 ) -> None: 654 _typer_format_options(self, ctx=ctx, formatter=formatter) 655 656 def _main_shell_completion( 657 self, 658 ctx_args: MutableMapping[str, Any], 659 prog_name: str, 660 complete_var: Optional[str] = None, 661 ) -> None: 662 _typer_main_shell_completion( 663 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 664 ) 665 666 def main( 667 self, 668 args: Optional[Sequence[str]] = None, 669 prog_name: Optional[str] = None, 670 complete_var: Optional[str] = None, 671 standalone_mode: bool = True, 672 windows_expand_args: bool = True, 673 **extra: Any, 674 ) -> Any: 675 return _main( 676 self, 677 args=args, 678 prog_name=prog_name, 679 complete_var=complete_var, 680 standalone_mode=standalone_mode, 681 windows_expand_args=windows_expand_args, 682 rich_markup_mode=self.rich_markup_mode, 683 **extra, 684 ) 685 686 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 687 if not rich or self.rich_markup_mode is None: 688 return super().format_help(ctx, formatter) 689 return rich_utils.rich_format_help( 690 obj=self, 691 ctx=ctx, 692 markup_mode=self.rich_markup_mode, 693 ) 694 695 696class TyperGroup(click.core.Group): 697 def __init__( 698 self, 699 *, 700 name: Optional[str] = None, 701 commands: Optional[ 702 Union[Dict[str, click.Command], Sequence[click.Command]] 703 ] = None, 704 # Rich settings 705 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 706 rich_help_panel: Union[str, None] = None, 707 **attrs: Any, 708 ) -> None: 709 super().__init__(name=name, commands=commands, **attrs) 710 self.rich_markup_mode: MarkupMode = rich_markup_mode 711 self.rich_help_panel = rich_help_panel 712 713 def format_options( 714 self, ctx: click.Context, formatter: click.HelpFormatter 715 ) -> None: 716 _typer_format_options(self, ctx=ctx, formatter=formatter) 717 self.format_commands(ctx, formatter) 718 719 def _main_shell_completion( 720 self, 721 ctx_args: MutableMapping[str, Any], 722 prog_name: str, 723 complete_var: Optional[str] = None, 724 ) -> None: 725 _typer_main_shell_completion( 726 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 727 ) 728 729 def main( 730 self, 731 args: Optional[Sequence[str]] = None, 732 prog_name: Optional[str] = None, 733 complete_var: Optional[str] = None, 734 standalone_mode: bool = True, 735 windows_expand_args: bool = True, 736 **extra: Any, 737 ) -> Any: 738 return _main( 739 self, 740 args=args, 741 prog_name=prog_name, 742 complete_var=complete_var, 743 standalone_mode=standalone_mode, 744 windows_expand_args=windows_expand_args, 745 rich_markup_mode=self.rich_markup_mode, 746 **extra, 747 ) 748 749 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 750 if not rich or self.rich_markup_mode is None: 751 return super().format_help(ctx, formatter) 752 return rich_utils.rich_format_help( 753 obj=self, 754 ctx=ctx, 755 markup_mode=self.rich_markup_mode, 756 ) 757 758 def list_commands(self, ctx: click.Context) -> List[str]: 759 """Returns a list of subcommand names. 760 Note that in Click's Group class, these are sorted. 761 In Typer, we wish to maintain the original order of creation (cf Issue #933)""" 762 return [n for n, c in self.commands.items()]
256class TyperArgument(click.core.Argument): 257 def __init__( 258 self, 259 *, 260 # Parameter 261 param_decls: List[str], 262 type: Optional[Any] = None, 263 required: Optional[bool] = None, 264 default: Optional[Any] = None, 265 callback: Optional[Callable[..., Any]] = None, 266 nargs: Optional[int] = None, 267 metavar: Optional[str] = None, 268 expose_value: bool = True, 269 is_eager: bool = False, 270 envvar: Optional[Union[str, List[str]]] = None, 271 shell_complete: Optional[ 272 Callable[ 273 [click.Context, click.Parameter, str], 274 Union[List["click.shell_completion.CompletionItem"], List[str]], 275 ] 276 ] = None, 277 autocompletion: Optional[Callable[..., Any]] = None, 278 # TyperArgument 279 show_default: Union[bool, str] = True, 280 show_choices: bool = True, 281 show_envvar: bool = True, 282 help: Optional[str] = None, 283 hidden: bool = False, 284 # Rich settings 285 rich_help_panel: Union[str, None] = None, 286 ): 287 self.help = help 288 self.show_default = show_default 289 self.show_choices = show_choices 290 self.show_envvar = show_envvar 291 self.hidden = hidden 292 self.rich_help_panel = rich_help_panel 293 294 super().__init__( 295 param_decls=param_decls, 296 type=type, 297 required=required, 298 default=default, 299 callback=callback, 300 nargs=nargs, 301 metavar=metavar, 302 expose_value=expose_value, 303 is_eager=is_eager, 304 envvar=envvar, 305 shell_complete=shell_complete, 306 ) 307 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 308 309 def _get_default_string( 310 self, 311 *, 312 ctx: click.Context, 313 show_default_is_str: bool, 314 default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any], 315 ) -> str: 316 return _get_default_string( 317 self, 318 ctx=ctx, 319 show_default_is_str=show_default_is_str, 320 default_value=default_value, 321 ) 322 323 def _extract_default_help_str( 324 self, *, ctx: click.Context 325 ) -> Optional[Union[Any, Callable[[], Any]]]: 326 return _extract_default_help_str(self, ctx=ctx) 327 328 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 329 # Modified version of click.core.Option.get_help_record() 330 # to support Arguments 331 if self.hidden: 332 return None 333 name = self.make_metavar() 334 help = self.help or "" 335 extra = [] 336 if self.show_envvar: 337 envvar = self.envvar 338 # allow_from_autoenv is currently not supported in Typer for CLI Arguments 339 if envvar is not None: 340 var_str = ( 341 ", ".join(str(d) for d in envvar) 342 if isinstance(envvar, (list, tuple)) 343 else envvar 344 ) 345 extra.append(f"env var: {var_str}") 346 347 # Typer override: 348 # Extracted to _extract_default_help_str() to allow re-using it in rich_utils 349 default_value = self._extract_default_help_str(ctx=ctx) 350 # Typer override end 351 352 show_default_is_str = isinstance(self.show_default, str) 353 354 if show_default_is_str or ( 355 default_value is not None and (self.show_default or ctx.show_default) 356 ): 357 # Typer override: 358 # Extracted to _get_default_string() to allow re-using it in rich_utils 359 default_string = self._get_default_string( 360 ctx=ctx, 361 show_default_is_str=show_default_is_str, 362 default_value=default_value, 363 ) 364 # Typer override end 365 if default_string: 366 extra.append(_("default: {default}").format(default=default_string)) 367 if self.required: 368 extra.append(_("required")) 369 if extra: 370 extra_str = "; ".join(extra) 371 extra_str = f"[{extra_str}]" 372 if rich is not None: 373 # This is needed for when we want to export to HTML 374 extra_str = rich.markup.escape(extra_str).strip() 375 376 help = f"{help} {extra_str}" if help else f"{extra_str}" 377 return name, help 378 379 def make_metavar(self) -> str: 380 # Modified version of click.core.Argument.make_metavar() 381 # to include Argument name 382 if self.metavar is not None: 383 return self.metavar 384 var = (self.name or "").upper() 385 if not self.required: 386 var = f"[{var}]" 387 type_var = self.type.get_metavar(self) 388 if type_var: 389 var += f":{type_var}" 390 if self.nargs != 1: 391 var += "..." 392 return var
Arguments are positional parameters to a command. They generally
provide fewer features than options but can have infinite nargs
and are required by default.
All parameters are passed onwards to the constructor of Parameter.
257 def __init__( 258 self, 259 *, 260 # Parameter 261 param_decls: List[str], 262 type: Optional[Any] = None, 263 required: Optional[bool] = None, 264 default: Optional[Any] = None, 265 callback: Optional[Callable[..., Any]] = None, 266 nargs: Optional[int] = None, 267 metavar: Optional[str] = None, 268 expose_value: bool = True, 269 is_eager: bool = False, 270 envvar: Optional[Union[str, List[str]]] = None, 271 shell_complete: Optional[ 272 Callable[ 273 [click.Context, click.Parameter, str], 274 Union[List["click.shell_completion.CompletionItem"], List[str]], 275 ] 276 ] = None, 277 autocompletion: Optional[Callable[..., Any]] = None, 278 # TyperArgument 279 show_default: Union[bool, str] = True, 280 show_choices: bool = True, 281 show_envvar: bool = True, 282 help: Optional[str] = None, 283 hidden: bool = False, 284 # Rich settings 285 rich_help_panel: Union[str, None] = None, 286 ): 287 self.help = help 288 self.show_default = show_default 289 self.show_choices = show_choices 290 self.show_envvar = show_envvar 291 self.hidden = hidden 292 self.rich_help_panel = rich_help_panel 293 294 super().__init__( 295 param_decls=param_decls, 296 type=type, 297 required=required, 298 default=default, 299 callback=callback, 300 nargs=nargs, 301 metavar=metavar, 302 expose_value=expose_value, 303 is_eager=is_eager, 304 envvar=envvar, 305 shell_complete=shell_complete, 306 ) 307 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
328 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 329 # Modified version of click.core.Option.get_help_record() 330 # to support Arguments 331 if self.hidden: 332 return None 333 name = self.make_metavar() 334 help = self.help or "" 335 extra = [] 336 if self.show_envvar: 337 envvar = self.envvar 338 # allow_from_autoenv is currently not supported in Typer for CLI Arguments 339 if envvar is not None: 340 var_str = ( 341 ", ".join(str(d) for d in envvar) 342 if isinstance(envvar, (list, tuple)) 343 else envvar 344 ) 345 extra.append(f"env var: {var_str}") 346 347 # Typer override: 348 # Extracted to _extract_default_help_str() to allow re-using it in rich_utils 349 default_value = self._extract_default_help_str(ctx=ctx) 350 # Typer override end 351 352 show_default_is_str = isinstance(self.show_default, str) 353 354 if show_default_is_str or ( 355 default_value is not None and (self.show_default or ctx.show_default) 356 ): 357 # Typer override: 358 # Extracted to _get_default_string() to allow re-using it in rich_utils 359 default_string = self._get_default_string( 360 ctx=ctx, 361 show_default_is_str=show_default_is_str, 362 default_value=default_value, 363 ) 364 # Typer override end 365 if default_string: 366 extra.append(_("default: {default}").format(default=default_string)) 367 if self.required: 368 extra.append(_("required")) 369 if extra: 370 extra_str = "; ".join(extra) 371 extra_str = f"[{extra_str}]" 372 if rich is not None: 373 # This is needed for when we want to export to HTML 374 extra_str = rich.markup.escape(extra_str).strip() 375 376 help = f"{help} {extra_str}" if help else f"{extra_str}" 377 return name, help
379 def make_metavar(self) -> str: 380 # Modified version of click.core.Argument.make_metavar() 381 # to include Argument name 382 if self.metavar is not None: 383 return self.metavar 384 var = (self.name or "").upper() 385 if not self.required: 386 var = f"[{var}]" 387 type_var = self.type.get_metavar(self) 388 if type_var: 389 var += f":{type_var}" 390 if self.nargs != 1: 391 var += "..." 392 return var
Inherited Members
- click.core.Argument
- param_type_name
- human_readable_name
- get_usage_pieces
- get_error_hint
- add_to_parser
- click.core.Parameter
- name
- opts
- secondary_opts
- type
- required
- callback
- nargs
- multiple
- expose_value
- default
- is_eager
- metavar
- envvar
- to_info_dict
- get_default
- consume_value
- type_cast_value
- value_is_missing
- process_value
- resolve_envvar_value
- value_from_envvar
- handle_parse_result
- shell_complete
395class TyperOption(click.core.Option): 396 def __init__( 397 self, 398 *, 399 # Parameter 400 param_decls: List[str], 401 type: Optional[Union[click.types.ParamType, Any]] = None, 402 required: Optional[bool] = None, 403 default: Optional[Any] = None, 404 callback: Optional[Callable[..., Any]] = None, 405 nargs: Optional[int] = None, 406 metavar: Optional[str] = None, 407 expose_value: bool = True, 408 is_eager: bool = False, 409 envvar: Optional[Union[str, List[str]]] = None, 410 shell_complete: Optional[ 411 Callable[ 412 [click.Context, click.Parameter, str], 413 Union[List["click.shell_completion.CompletionItem"], List[str]], 414 ] 415 ] = None, 416 autocompletion: Optional[Callable[..., Any]] = None, 417 # Option 418 show_default: Union[bool, str] = False, 419 prompt: Union[bool, str] = False, 420 confirmation_prompt: Union[bool, str] = False, 421 prompt_required: bool = True, 422 hide_input: bool = False, 423 is_flag: Optional[bool] = None, 424 multiple: bool = False, 425 count: bool = False, 426 allow_from_autoenv: bool = True, 427 help: Optional[str] = None, 428 hidden: bool = False, 429 show_choices: bool = True, 430 show_envvar: bool = False, 431 # Rich settings 432 rich_help_panel: Union[str, None] = None, 433 ): 434 super().__init__( 435 param_decls=param_decls, 436 type=type, 437 required=required, 438 default=default, 439 callback=callback, 440 nargs=nargs, 441 metavar=metavar, 442 expose_value=expose_value, 443 is_eager=is_eager, 444 envvar=envvar, 445 show_default=show_default, 446 prompt=prompt, 447 confirmation_prompt=confirmation_prompt, 448 hide_input=hide_input, 449 is_flag=is_flag, 450 multiple=multiple, 451 count=count, 452 allow_from_autoenv=allow_from_autoenv, 453 help=help, 454 hidden=hidden, 455 show_choices=show_choices, 456 show_envvar=show_envvar, 457 prompt_required=prompt_required, 458 shell_complete=shell_complete, 459 ) 460 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 461 self.rich_help_panel = rich_help_panel 462 463 def _get_default_string( 464 self, 465 *, 466 ctx: click.Context, 467 show_default_is_str: bool, 468 default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any], 469 ) -> str: 470 return _get_default_string( 471 self, 472 ctx=ctx, 473 show_default_is_str=show_default_is_str, 474 default_value=default_value, 475 ) 476 477 def _extract_default_help_str( 478 self, *, ctx: click.Context 479 ) -> Optional[Union[Any, Callable[[], Any]]]: 480 return _extract_default_help_str(self, ctx=ctx) 481 482 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 483 # Duplicate all of Click's logic only to modify a single line, to allow boolean 484 # flags with only names for False values as it's currently supported by Typer 485 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false 486 if self.hidden: 487 return None 488 489 any_prefix_is_slash = False 490 491 def _write_opts(opts: Sequence[str]) -> str: 492 nonlocal any_prefix_is_slash 493 494 rv, any_slashes = click.formatting.join_options(opts) 495 496 if any_slashes: 497 any_prefix_is_slash = True 498 499 if not self.is_flag and not self.count: 500 rv += f" {self.make_metavar()}" 501 502 return rv 503 504 rv = [_write_opts(self.opts)] 505 506 if self.secondary_opts: 507 rv.append(_write_opts(self.secondary_opts)) 508 509 help = self.help or "" 510 extra = [] 511 512 if self.show_envvar: 513 envvar = self.envvar 514 515 if envvar is None: 516 if ( 517 self.allow_from_autoenv 518 and ctx.auto_envvar_prefix is not None 519 and self.name is not None 520 ): 521 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 522 523 if envvar is not None: 524 var_str = ( 525 envvar 526 if isinstance(envvar, str) 527 else ", ".join(str(d) for d in envvar) 528 ) 529 extra.append(_("env var: {var}").format(var=var_str)) 530 531 # Typer override: 532 # Extracted to _extract_default() to allow re-using it in rich_utils 533 default_value = self._extract_default_help_str(ctx=ctx) 534 # Typer override end 535 536 show_default_is_str = isinstance(self.show_default, str) 537 538 if show_default_is_str or ( 539 default_value is not None and (self.show_default or ctx.show_default) 540 ): 541 # Typer override: 542 # Extracted to _get_default_string() to allow re-using it in rich_utils 543 default_string = self._get_default_string( 544 ctx=ctx, 545 show_default_is_str=show_default_is_str, 546 default_value=default_value, 547 ) 548 # Typer override end 549 if default_string: 550 extra.append(_("default: {default}").format(default=default_string)) 551 552 if isinstance(self.type, click.types._NumberRangeBase): 553 range_str = self.type._describe_range() 554 555 if range_str: 556 extra.append(range_str) 557 558 if self.required: 559 extra.append(_("required")) 560 561 if extra: 562 extra_str = "; ".join(extra) 563 extra_str = f"[{extra_str}]" 564 if rich is not None: 565 # This is needed for when we want to export to HTML 566 extra_str = rich.markup.escape(extra_str).strip() 567 568 help = f"{help} {extra_str}" if help else f"{extra_str}" 569 570 return ("; " if any_prefix_is_slash else " / ").join(rv), help
Options are usually optional values on the command line and have some extra features that arguments don't have.
All other parameters are passed onwards to the parameter constructor.
Parameters
- show_default: Show the default value for this option in its
help text. Values are not shown by default, unless
Context.show_defaultisTrue. If this value is a string, it shows that string in parentheses instead of the actual value. This is particularly useful for dynamic options. For single option boolean flags, the default remains hidden if its value isFalse. - show_envvar: Controls if an environment variable should be shown on the help page. Normally, environment variables are not shown.
- prompt: If set to
Trueor a non empty string then the user will be prompted for input. If set toTruethe prompt will be the option name capitalized. - confirmation_prompt: Prompt a second time to confirm the
value if it was prompted for. Can be set to a string instead of
Trueto customize the message. - prompt_required: If set to
False, the user will be prompted for input only when the option was specified as a flag without a value. - hide_input: If this is
Truethen the input on the prompt will be hidden from the user. This is useful for password input. - is_flag: forces this option to act as a flag. The default is auto detection.
- flag_value: which value should be used for this flag if it's enabled. This is set to a boolean automatically if the option string contains a slash to mark two options.
- multiple: if this is set to
Truethen the argument is accepted multiple times and recorded. This is similar tonargsin how it works but supports arbitrary number of arguments. - count: this flag makes an option increment an integer.
- allow_from_autoenv: if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context.
- help: the help string.
- hidden: hide this option from help outputs.
- attrs: Other command arguments described in
Parameter.
Changed in version 8.1.0:
Help text indentation is cleaned here instead of only in the
@option decorator.
Changed in version 8.1.0:
The show_default parameter overrides
Context.show_default.
Changed in version 8.1.0:
The default of a single option boolean flag is not shown if the
default value is False.
Changed in version 8.0.1:
type is detected from flag_value if given.
396 def __init__( 397 self, 398 *, 399 # Parameter 400 param_decls: List[str], 401 type: Optional[Union[click.types.ParamType, Any]] = None, 402 required: Optional[bool] = None, 403 default: Optional[Any] = None, 404 callback: Optional[Callable[..., Any]] = None, 405 nargs: Optional[int] = None, 406 metavar: Optional[str] = None, 407 expose_value: bool = True, 408 is_eager: bool = False, 409 envvar: Optional[Union[str, List[str]]] = None, 410 shell_complete: Optional[ 411 Callable[ 412 [click.Context, click.Parameter, str], 413 Union[List["click.shell_completion.CompletionItem"], List[str]], 414 ] 415 ] = None, 416 autocompletion: Optional[Callable[..., Any]] = None, 417 # Option 418 show_default: Union[bool, str] = False, 419 prompt: Union[bool, str] = False, 420 confirmation_prompt: Union[bool, str] = False, 421 prompt_required: bool = True, 422 hide_input: bool = False, 423 is_flag: Optional[bool] = None, 424 multiple: bool = False, 425 count: bool = False, 426 allow_from_autoenv: bool = True, 427 help: Optional[str] = None, 428 hidden: bool = False, 429 show_choices: bool = True, 430 show_envvar: bool = False, 431 # Rich settings 432 rich_help_panel: Union[str, None] = None, 433 ): 434 super().__init__( 435 param_decls=param_decls, 436 type=type, 437 required=required, 438 default=default, 439 callback=callback, 440 nargs=nargs, 441 metavar=metavar, 442 expose_value=expose_value, 443 is_eager=is_eager, 444 envvar=envvar, 445 show_default=show_default, 446 prompt=prompt, 447 confirmation_prompt=confirmation_prompt, 448 hide_input=hide_input, 449 is_flag=is_flag, 450 multiple=multiple, 451 count=count, 452 allow_from_autoenv=allow_from_autoenv, 453 help=help, 454 hidden=hidden, 455 show_choices=show_choices, 456 show_envvar=show_envvar, 457 prompt_required=prompt_required, 458 shell_complete=shell_complete, 459 ) 460 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 461 self.rich_help_panel = rich_help_panel
482 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 483 # Duplicate all of Click's logic only to modify a single line, to allow boolean 484 # flags with only names for False values as it's currently supported by Typer 485 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false 486 if self.hidden: 487 return None 488 489 any_prefix_is_slash = False 490 491 def _write_opts(opts: Sequence[str]) -> str: 492 nonlocal any_prefix_is_slash 493 494 rv, any_slashes = click.formatting.join_options(opts) 495 496 if any_slashes: 497 any_prefix_is_slash = True 498 499 if not self.is_flag and not self.count: 500 rv += f" {self.make_metavar()}" 501 502 return rv 503 504 rv = [_write_opts(self.opts)] 505 506 if self.secondary_opts: 507 rv.append(_write_opts(self.secondary_opts)) 508 509 help = self.help or "" 510 extra = [] 511 512 if self.show_envvar: 513 envvar = self.envvar 514 515 if envvar is None: 516 if ( 517 self.allow_from_autoenv 518 and ctx.auto_envvar_prefix is not None 519 and self.name is not None 520 ): 521 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 522 523 if envvar is not None: 524 var_str = ( 525 envvar 526 if isinstance(envvar, str) 527 else ", ".join(str(d) for d in envvar) 528 ) 529 extra.append(_("env var: {var}").format(var=var_str)) 530 531 # Typer override: 532 # Extracted to _extract_default() to allow re-using it in rich_utils 533 default_value = self._extract_default_help_str(ctx=ctx) 534 # Typer override end 535 536 show_default_is_str = isinstance(self.show_default, str) 537 538 if show_default_is_str or ( 539 default_value is not None and (self.show_default or ctx.show_default) 540 ): 541 # Typer override: 542 # Extracted to _get_default_string() to allow re-using it in rich_utils 543 default_string = self._get_default_string( 544 ctx=ctx, 545 show_default_is_str=show_default_is_str, 546 default_value=default_value, 547 ) 548 # Typer override end 549 if default_string: 550 extra.append(_("default: {default}").format(default=default_string)) 551 552 if isinstance(self.type, click.types._NumberRangeBase): 553 range_str = self.type._describe_range() 554 555 if range_str: 556 extra.append(range_str) 557 558 if self.required: 559 extra.append(_("required")) 560 561 if extra: 562 extra_str = "; ".join(extra) 563 extra_str = f"[{extra_str}]" 564 if rich is not None: 565 # This is needed for when we want to export to HTML 566 extra_str = rich.markup.escape(extra_str).strip() 567 568 help = f"{help} {extra_str}" if help else f"{extra_str}" 569 570 return ("; " if any_prefix_is_slash else " / ").join(rv), help
Inherited Members
- click.core.Option
- param_type_name
- prompt
- confirmation_prompt
- prompt_required
- hide_input
- default
- type
- is_flag
- is_bool_flag
- flag_value
- count
- allow_from_autoenv
- help
- show_default
- show_choices
- show_envvar
- to_info_dict
- add_to_parser
- get_default
- prompt_for_value
- resolve_envvar_value
- value_from_envvar
- consume_value
- click.core.Parameter
- name
- opts
- secondary_opts
- required
- callback
- nargs
- multiple
- expose_value
- is_eager
- metavar
- envvar
- human_readable_name
- make_metavar
- type_cast_value
- value_is_missing
- process_value
- handle_parse_result
- get_usage_pieces
- get_error_hint
- shell_complete
615class TyperCommand(click.core.Command): 616 def __init__( 617 self, 618 name: Optional[str], 619 *, 620 context_settings: Optional[Dict[str, Any]] = None, 621 callback: Optional[Callable[..., Any]] = None, 622 params: Optional[List[click.Parameter]] = None, 623 help: Optional[str] = None, 624 epilog: Optional[str] = None, 625 short_help: Optional[str] = None, 626 options_metavar: Optional[str] = "[OPTIONS]", 627 add_help_option: bool = True, 628 no_args_is_help: bool = False, 629 hidden: bool = False, 630 deprecated: bool = False, 631 # Rich settings 632 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 633 rich_help_panel: Union[str, None] = None, 634 ) -> None: 635 super().__init__( 636 name=name, 637 context_settings=context_settings, 638 callback=callback, 639 params=params, 640 help=help, 641 epilog=epilog, 642 short_help=short_help, 643 options_metavar=options_metavar, 644 add_help_option=add_help_option, 645 no_args_is_help=no_args_is_help, 646 hidden=hidden, 647 deprecated=deprecated, 648 ) 649 self.rich_markup_mode: MarkupMode = rich_markup_mode 650 self.rich_help_panel = rich_help_panel 651 652 def format_options( 653 self, ctx: click.Context, formatter: click.HelpFormatter 654 ) -> None: 655 _typer_format_options(self, ctx=ctx, formatter=formatter) 656 657 def _main_shell_completion( 658 self, 659 ctx_args: MutableMapping[str, Any], 660 prog_name: str, 661 complete_var: Optional[str] = None, 662 ) -> None: 663 _typer_main_shell_completion( 664 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 665 ) 666 667 def main( 668 self, 669 args: Optional[Sequence[str]] = None, 670 prog_name: Optional[str] = None, 671 complete_var: Optional[str] = None, 672 standalone_mode: bool = True, 673 windows_expand_args: bool = True, 674 **extra: Any, 675 ) -> Any: 676 return _main( 677 self, 678 args=args, 679 prog_name=prog_name, 680 complete_var=complete_var, 681 standalone_mode=standalone_mode, 682 windows_expand_args=windows_expand_args, 683 rich_markup_mode=self.rich_markup_mode, 684 **extra, 685 ) 686 687 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 688 if not rich or self.rich_markup_mode is None: 689 return super().format_help(ctx, formatter) 690 return rich_utils.rich_format_help( 691 obj=self, 692 ctx=ctx, 693 markup_mode=self.rich_markup_mode, 694 )
Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it.
Parameters
- name: the name of the command to use unless a group overrides it.
- context_settings: an optional dictionary with defaults that are passed to the context object.
- callback: the callback to invoke. This is optional.
- params: the parameters to register with this command. This can
be either
OptionorArgumentobjects. - help: the help string to use for this command.
- epilog: like the help string but it's printed at the end of the help page after everything else.
- short_help: the short help to use for this command. This is shown on the command listing of the parent command.
- add_help_option: by default each command registers a
--helpoption. This can be disabled by this parameter. - no_args_is_help: this controls what happens if no arguments are
provided. This option is disabled by default.
If enabled this will add
--helpas argument if no arguments are passed hidden: hide this command from help outputs.
deprecated: issues a message indicating that the command is deprecated.
Changed in version 8.1:
help, epilog, and short_help are stored unprocessed,
all formatting is done when outputting help text, not at init,
and is done even if not using the @command decorator.
Changed in version 8.0:
Added a repr showing the command name.
Changed in version 7.1:
Added the no_args_is_help parameter.
Changed in version 2.0:
Added the context_settings parameter.
616 def __init__( 617 self, 618 name: Optional[str], 619 *, 620 context_settings: Optional[Dict[str, Any]] = None, 621 callback: Optional[Callable[..., Any]] = None, 622 params: Optional[List[click.Parameter]] = None, 623 help: Optional[str] = None, 624 epilog: Optional[str] = None, 625 short_help: Optional[str] = None, 626 options_metavar: Optional[str] = "[OPTIONS]", 627 add_help_option: bool = True, 628 no_args_is_help: bool = False, 629 hidden: bool = False, 630 deprecated: bool = False, 631 # Rich settings 632 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 633 rich_help_panel: Union[str, None] = None, 634 ) -> None: 635 super().__init__( 636 name=name, 637 context_settings=context_settings, 638 callback=callback, 639 params=params, 640 help=help, 641 epilog=epilog, 642 short_help=short_help, 643 options_metavar=options_metavar, 644 add_help_option=add_help_option, 645 no_args_is_help=no_args_is_help, 646 hidden=hidden, 647 deprecated=deprecated, 648 ) 649 self.rich_markup_mode: MarkupMode = rich_markup_mode 650 self.rich_help_panel = rich_help_panel
652 def format_options( 653 self, ctx: click.Context, formatter: click.HelpFormatter 654 ) -> None: 655 _typer_format_options(self, ctx=ctx, formatter=formatter)
Writes all the options into the formatter if they exist.
667 def main( 668 self, 669 args: Optional[Sequence[str]] = None, 670 prog_name: Optional[str] = None, 671 complete_var: Optional[str] = None, 672 standalone_mode: bool = True, 673 windows_expand_args: bool = True, 674 **extra: Any, 675 ) -> Any: 676 return _main( 677 self, 678 args=args, 679 prog_name=prog_name, 680 complete_var=complete_var, 681 standalone_mode=standalone_mode, 682 windows_expand_args=windows_expand_args, 683 rich_markup_mode=self.rich_markup_mode, 684 **extra, 685 )
This is the way to invoke a script with all the bells and
whistles as a command line application. This will always terminate
the application after a call. If this is not wanted, SystemExit
needs to be caught.
This method is also available by directly calling the instance of
a Command.
Parameters
- args: the arguments that should be used for parsing. If not
provided,
sys.argv[1:]is used. - prog_name: the program name that should be used. By default
the program name is constructed by taking the file
name from
sys.argv[0]. - complete_var: the environment variable that controls the
bash completion support. The default is
"_<prog_name>_COMPLETE"with prog_name in uppercase. - standalone_mode: the default behavior is to invoke the script
in standalone mode. Click will then
handle exceptions and convert them into
error messages and the function will never
return but shut down the interpreter. If
this is set to
Falsethey will be propagated to the caller and the return value of this function is the return value ofinvoke(). - windows_expand_args: Expand glob patterns, user dir, and env vars in command line args on Windows.
- extra: extra keyword arguments are forwarded to the context
constructor. See
Contextfor more information.
Changed in version 8.0.1:
Added the windows_expand_args parameter to allow
disabling command line arg expansion on Windows.
Changed in version 8.0:
When taking arguments from sys.argv on Windows, glob
patterns, user dir, and env vars are expanded.
Changed in version 3.0:
Added the standalone_mode parameter.
687 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 688 if not rich or self.rich_markup_mode is None: 689 return super().format_help(ctx, formatter) 690 return rich_utils.rich_format_help( 691 obj=self, 692 ctx=ctx, 693 markup_mode=self.rich_markup_mode, 694 )
Writes the help into the formatter if it exists.
This is a low-level method called by get_help().
This calls the following methods:
Inherited Members
- click.core.Command
- callback
- params
- help
- epilog
- options_metavar
- short_help
- add_help_option
- no_args_is_help
- deprecated
- to_info_dict
- get_usage
- get_params
- format_usage
- collect_usage_pieces
- get_help_option_names
- get_help_option
- make_parser
- get_help
- get_short_help_str
- format_help_text
- format_epilog
- parse_args
- invoke
- shell_complete
- click.core.BaseCommand
- context_class
- allow_extra_args
- allow_interspersed_args
- ignore_unknown_options
- name
- context_settings
- make_context
697class TyperGroup(click.core.Group): 698 def __init__( 699 self, 700 *, 701 name: Optional[str] = None, 702 commands: Optional[ 703 Union[Dict[str, click.Command], Sequence[click.Command]] 704 ] = None, 705 # Rich settings 706 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 707 rich_help_panel: Union[str, None] = None, 708 **attrs: Any, 709 ) -> None: 710 super().__init__(name=name, commands=commands, **attrs) 711 self.rich_markup_mode: MarkupMode = rich_markup_mode 712 self.rich_help_panel = rich_help_panel 713 714 def format_options( 715 self, ctx: click.Context, formatter: click.HelpFormatter 716 ) -> None: 717 _typer_format_options(self, ctx=ctx, formatter=formatter) 718 self.format_commands(ctx, formatter) 719 720 def _main_shell_completion( 721 self, 722 ctx_args: MutableMapping[str, Any], 723 prog_name: str, 724 complete_var: Optional[str] = None, 725 ) -> None: 726 _typer_main_shell_completion( 727 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 728 ) 729 730 def main( 731 self, 732 args: Optional[Sequence[str]] = None, 733 prog_name: Optional[str] = None, 734 complete_var: Optional[str] = None, 735 standalone_mode: bool = True, 736 windows_expand_args: bool = True, 737 **extra: Any, 738 ) -> Any: 739 return _main( 740 self, 741 args=args, 742 prog_name=prog_name, 743 complete_var=complete_var, 744 standalone_mode=standalone_mode, 745 windows_expand_args=windows_expand_args, 746 rich_markup_mode=self.rich_markup_mode, 747 **extra, 748 ) 749 750 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 751 if not rich or self.rich_markup_mode is None: 752 return super().format_help(ctx, formatter) 753 return rich_utils.rich_format_help( 754 obj=self, 755 ctx=ctx, 756 markup_mode=self.rich_markup_mode, 757 ) 758 759 def list_commands(self, ctx: click.Context) -> List[str]: 760 """Returns a list of subcommand names. 761 Note that in Click's Group class, these are sorted. 762 In Typer, we wish to maintain the original order of creation (cf Issue #933)""" 763 return [n for n, c in self.commands.items()]
A group allows a command to have subcommands attached. This is the most common way to implement nesting in Click.
Parameters
- name: The name of the group command.
- commands: A dict mapping names to
Commandobjects. Can also be a list ofCommand, which will useCommand.nameto create the dict. - attrs: Other command arguments described in
MultiCommand,Command, andBaseCommand.
Changed in version 8.0:
The commands argument can be a list of command objects.
698 def __init__( 699 self, 700 *, 701 name: Optional[str] = None, 702 commands: Optional[ 703 Union[Dict[str, click.Command], Sequence[click.Command]] 704 ] = None, 705 # Rich settings 706 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 707 rich_help_panel: Union[str, None] = None, 708 **attrs: Any, 709 ) -> None: 710 super().__init__(name=name, commands=commands, **attrs) 711 self.rich_markup_mode: MarkupMode = rich_markup_mode 712 self.rich_help_panel = rich_help_panel
714 def format_options( 715 self, ctx: click.Context, formatter: click.HelpFormatter 716 ) -> None: 717 _typer_format_options(self, ctx=ctx, formatter=formatter) 718 self.format_commands(ctx, formatter)
Writes all the options into the formatter if they exist.
730 def main( 731 self, 732 args: Optional[Sequence[str]] = None, 733 prog_name: Optional[str] = None, 734 complete_var: Optional[str] = None, 735 standalone_mode: bool = True, 736 windows_expand_args: bool = True, 737 **extra: Any, 738 ) -> Any: 739 return _main( 740 self, 741 args=args, 742 prog_name=prog_name, 743 complete_var=complete_var, 744 standalone_mode=standalone_mode, 745 windows_expand_args=windows_expand_args, 746 rich_markup_mode=self.rich_markup_mode, 747 **extra, 748 )
This is the way to invoke a script with all the bells and
whistles as a command line application. This will always terminate
the application after a call. If this is not wanted, SystemExit
needs to be caught.
This method is also available by directly calling the instance of
a Command.
Parameters
- args: the arguments that should be used for parsing. If not
provided,
sys.argv[1:]is used. - prog_name: the program name that should be used. By default
the program name is constructed by taking the file
name from
sys.argv[0]. - complete_var: the environment variable that controls the
bash completion support. The default is
"_<prog_name>_COMPLETE"with prog_name in uppercase. - standalone_mode: the default behavior is to invoke the script
in standalone mode. Click will then
handle exceptions and convert them into
error messages and the function will never
return but shut down the interpreter. If
this is set to
Falsethey will be propagated to the caller and the return value of this function is the return value ofinvoke(). - windows_expand_args: Expand glob patterns, user dir, and env vars in command line args on Windows.
- extra: extra keyword arguments are forwarded to the context
constructor. See
Contextfor more information.
Changed in version 8.0.1:
Added the windows_expand_args parameter to allow
disabling command line arg expansion on Windows.
Changed in version 8.0:
When taking arguments from sys.argv on Windows, glob
patterns, user dir, and env vars are expanded.
Changed in version 3.0:
Added the standalone_mode parameter.
750 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 751 if not rich or self.rich_markup_mode is None: 752 return super().format_help(ctx, formatter) 753 return rich_utils.rich_format_help( 754 obj=self, 755 ctx=ctx, 756 markup_mode=self.rich_markup_mode, 757 )
Writes the help into the formatter if it exists.
This is a low-level method called by get_help().
This calls the following methods:
759 def list_commands(self, ctx: click.Context) -> List[str]: 760 """Returns a list of subcommand names. 761 Note that in Click's Group class, these are sorted. 762 In Typer, we wish to maintain the original order of creation (cf Issue #933)""" 763 return [n for n, c in self.commands.items()]
Returns a list of subcommand names. Note that in Click's Group class, these are sorted. In Typer, we wish to maintain the original order of creation (cf Issue #933)
Inherited Members
- click.core.Group
- command_class
- group_class
- commands
- add_command
- command
- group
- get_command
- click.core.MultiCommand
- allow_extra_args
- allow_interspersed_args
- no_args_is_help
- invoke_without_command
- subcommand_metavar
- chain
- to_info_dict
- collect_usage_pieces
- result_callback
- format_commands
- parse_args
- invoke
- resolve_command
- shell_complete
- click.core.Command
- callback
- params
- help
- epilog
- options_metavar
- short_help
- add_help_option
- deprecated
- get_usage
- get_params
- format_usage
- get_help_option_names
- get_help_option
- make_parser
- get_help
- get_short_help_str
- format_help_text
- format_epilog
- click.core.BaseCommand
- context_class
- ignore_unknown_options
- name
- context_settings
- make_context