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, KeyboardInterrupt) as e: 209 click.echo(file=sys.stderr) 210 raise click.Abort() from e 211 except click.ClickException as e: 212 if not standalone_mode: 213 raise 214 # Typer override 215 if rich and rich_markup_mode is not None: 216 rich_utils.rich_format_error(e) 217 else: 218 e.show() 219 # Typer override end 220 sys.exit(e.exit_code) 221 except OSError as e: 222 if e.errno == errno.EPIPE: 223 sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout)) 224 sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr)) 225 sys.exit(1) 226 else: 227 raise 228 except click.exceptions.Exit as e: 229 if standalone_mode: 230 sys.exit(e.exit_code) 231 else: 232 # in non-standalone mode, return the exit code 233 # note that this is only reached if `self.invoke` above raises 234 # an Exit explicitly -- thus bypassing the check there which 235 # would return its result 236 # the results of non-standalone execution may therefore be 237 # somewhat ambiguous: if there are codepaths which lead to 238 # `ctx.exit(1)` and to `return 1`, the caller won't be able to 239 # tell the difference between the two 240 return e.exit_code 241 except click.Abort: 242 if not standalone_mode: 243 raise 244 # Typer override 245 if rich and rich_markup_mode is not None: 246 rich_utils.rich_abort_error() 247 else: 248 click.echo(_("Aborted!"), file=sys.stderr) 249 # Typer override end 250 sys.exit(1) 251 252 253class TyperArgument(click.core.Argument): 254 def __init__( 255 self, 256 *, 257 # Parameter 258 param_decls: List[str], 259 type: Optional[Any] = None, 260 required: Optional[bool] = None, 261 default: Optional[Any] = None, 262 callback: Optional[Callable[..., Any]] = None, 263 nargs: Optional[int] = None, 264 metavar: Optional[str] = None, 265 expose_value: bool = True, 266 is_eager: bool = False, 267 envvar: Optional[Union[str, List[str]]] = None, 268 shell_complete: Optional[ 269 Callable[ 270 [click.Context, click.Parameter, str], 271 Union[List["click.shell_completion.CompletionItem"], List[str]], 272 ] 273 ] = None, 274 autocompletion: Optional[Callable[..., Any]] = None, 275 # TyperArgument 276 show_default: Union[bool, str] = True, 277 show_choices: bool = True, 278 show_envvar: bool = True, 279 help: Optional[str] = None, 280 hidden: bool = False, 281 # Rich settings 282 rich_help_panel: Union[str, None] = None, 283 ): 284 self.help = help 285 self.show_default = show_default 286 self.show_choices = show_choices 287 self.show_envvar = show_envvar 288 self.hidden = hidden 289 self.rich_help_panel = rich_help_panel 290 291 super().__init__( 292 param_decls=param_decls, 293 type=type, 294 required=required, 295 default=default, 296 callback=callback, 297 nargs=nargs, 298 metavar=metavar, 299 expose_value=expose_value, 300 is_eager=is_eager, 301 envvar=envvar, 302 shell_complete=shell_complete, 303 ) 304 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 305 306 def _get_default_string( 307 self, 308 *, 309 ctx: click.Context, 310 show_default_is_str: bool, 311 default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any], 312 ) -> str: 313 return _get_default_string( 314 self, 315 ctx=ctx, 316 show_default_is_str=show_default_is_str, 317 default_value=default_value, 318 ) 319 320 def _extract_default_help_str( 321 self, *, ctx: click.Context 322 ) -> Optional[Union[Any, Callable[[], Any]]]: 323 return _extract_default_help_str(self, ctx=ctx) 324 325 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 326 # Modified version of click.core.Option.get_help_record() 327 # to support Arguments 328 if self.hidden: 329 return None 330 name = self.make_metavar() 331 help = self.help or "" 332 extra = [] 333 if self.show_envvar: 334 envvar = self.envvar 335 # allow_from_autoenv is currently not supported in Typer for CLI Arguments 336 if envvar is not None: 337 var_str = ( 338 ", ".join(str(d) for d in envvar) 339 if isinstance(envvar, (list, tuple)) 340 else envvar 341 ) 342 extra.append(f"env var: {var_str}") 343 344 # Typer override: 345 # Extracted to _extract_default_help_str() to allow re-using it in rich_utils 346 default_value = self._extract_default_help_str(ctx=ctx) 347 # Typer override end 348 349 show_default_is_str = isinstance(self.show_default, str) 350 351 if show_default_is_str or ( 352 default_value is not None and (self.show_default or ctx.show_default) 353 ): 354 # Typer override: 355 # Extracted to _get_default_string() to allow re-using it in rich_utils 356 default_string = self._get_default_string( 357 ctx=ctx, 358 show_default_is_str=show_default_is_str, 359 default_value=default_value, 360 ) 361 # Typer override end 362 if default_string: 363 extra.append(_("default: {default}").format(default=default_string)) 364 if self.required: 365 extra.append(_("required")) 366 if extra: 367 extra_str = ";".join(extra) 368 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 369 return name, help 370 371 def make_metavar(self) -> str: 372 # Modified version of click.core.Argument.make_metavar() 373 # to include Argument name 374 if self.metavar is not None: 375 return self.metavar 376 var = (self.name or "").upper() 377 if not self.required: 378 var = f"[{var}]" 379 type_var = self.type.get_metavar(self) 380 if type_var: 381 var += f":{type_var}" 382 if self.nargs != 1: 383 var += "..." 384 return var 385 386 387class TyperOption(click.core.Option): 388 def __init__( 389 self, 390 *, 391 # Parameter 392 param_decls: List[str], 393 type: Optional[Union[click.types.ParamType, Any]] = None, 394 required: Optional[bool] = None, 395 default: Optional[Any] = None, 396 callback: Optional[Callable[..., Any]] = None, 397 nargs: Optional[int] = None, 398 metavar: Optional[str] = None, 399 expose_value: bool = True, 400 is_eager: bool = False, 401 envvar: Optional[Union[str, List[str]]] = None, 402 shell_complete: Optional[ 403 Callable[ 404 [click.Context, click.Parameter, str], 405 Union[List["click.shell_completion.CompletionItem"], List[str]], 406 ] 407 ] = None, 408 autocompletion: Optional[Callable[..., Any]] = None, 409 # Option 410 show_default: Union[bool, str] = False, 411 prompt: Union[bool, str] = False, 412 confirmation_prompt: Union[bool, str] = False, 413 prompt_required: bool = True, 414 hide_input: bool = False, 415 is_flag: Optional[bool] = None, 416 flag_value: Optional[Any] = None, 417 multiple: bool = False, 418 count: bool = False, 419 allow_from_autoenv: bool = True, 420 help: Optional[str] = None, 421 hidden: bool = False, 422 show_choices: bool = True, 423 show_envvar: bool = False, 424 # Rich settings 425 rich_help_panel: Union[str, None] = None, 426 ): 427 super().__init__( 428 param_decls=param_decls, 429 type=type, 430 required=required, 431 default=default, 432 callback=callback, 433 nargs=nargs, 434 metavar=metavar, 435 expose_value=expose_value, 436 is_eager=is_eager, 437 envvar=envvar, 438 show_default=show_default, 439 prompt=prompt, 440 confirmation_prompt=confirmation_prompt, 441 hide_input=hide_input, 442 is_flag=is_flag, 443 flag_value=flag_value, 444 multiple=multiple, 445 count=count, 446 allow_from_autoenv=allow_from_autoenv, 447 help=help, 448 hidden=hidden, 449 show_choices=show_choices, 450 show_envvar=show_envvar, 451 prompt_required=prompt_required, 452 shell_complete=shell_complete, 453 ) 454 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 455 self.rich_help_panel = rich_help_panel 456 457 def _get_default_string( 458 self, 459 *, 460 ctx: click.Context, 461 show_default_is_str: bool, 462 default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any], 463 ) -> str: 464 return _get_default_string( 465 self, 466 ctx=ctx, 467 show_default_is_str=show_default_is_str, 468 default_value=default_value, 469 ) 470 471 def _extract_default_help_str( 472 self, *, ctx: click.Context 473 ) -> Optional[Union[Any, Callable[[], Any]]]: 474 return _extract_default_help_str(self, ctx=ctx) 475 476 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 477 # Duplicate all of Click's logic only to modify a single line, to allow boolean 478 # flags with only names for False values as it's currently supported by Typer 479 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false 480 if self.hidden: 481 return None 482 483 any_prefix_is_slash = False 484 485 def _write_opts(opts: Sequence[str]) -> str: 486 nonlocal any_prefix_is_slash 487 488 rv, any_slashes = click.formatting.join_options(opts) 489 490 if any_slashes: 491 any_prefix_is_slash = True 492 493 if not self.is_flag and not self.count: 494 rv += f" {self.make_metavar()}" 495 496 return rv 497 498 rv = [_write_opts(self.opts)] 499 500 if self.secondary_opts: 501 rv.append(_write_opts(self.secondary_opts)) 502 503 help = self.help or "" 504 extra = [] 505 506 if self.show_envvar: 507 envvar = self.envvar 508 509 if envvar is None: 510 if ( 511 self.allow_from_autoenv 512 and ctx.auto_envvar_prefix is not None 513 and self.name is not None 514 ): 515 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 516 517 if envvar is not None: 518 var_str = ( 519 envvar 520 if isinstance(envvar, str) 521 else ", ".join(str(d) for d in envvar) 522 ) 523 extra.append(_("env var: {var}").format(var=var_str)) 524 525 # Typer override: 526 # Extracted to _extract_default() to allow re-using it in rich_utils 527 default_value = self._extract_default_help_str(ctx=ctx) 528 # Typer override end 529 530 show_default_is_str = isinstance(self.show_default, str) 531 532 if show_default_is_str or ( 533 default_value is not None and (self.show_default or ctx.show_default) 534 ): 535 # Typer override: 536 # Extracted to _get_default_string() to allow re-using it in rich_utils 537 default_string = self._get_default_string( 538 ctx=ctx, 539 show_default_is_str=show_default_is_str, 540 default_value=default_value, 541 ) 542 # Typer override end 543 if default_string: 544 extra.append(_("default: {default}").format(default=default_string)) 545 546 if isinstance(self.type, click.types._NumberRangeBase): 547 range_str = self.type._describe_range() 548 549 if range_str: 550 extra.append(range_str) 551 552 if self.required: 553 extra.append(_("required")) 554 555 if extra: 556 extra_str = "; ".join(extra) 557 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 558 559 return ("; " if any_prefix_is_slash else " / ").join(rv), help 560 561 562def _typer_format_options( 563 self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter 564) -> None: 565 args = [] 566 opts = [] 567 for param in self.get_params(ctx): 568 rv = param.get_help_record(ctx) 569 if rv is not None: 570 if param.param_type_name == "argument": 571 args.append(rv) 572 elif param.param_type_name == "option": 573 opts.append(rv) 574 575 if args: 576 with formatter.section(_("Arguments")): 577 formatter.write_dl(args) 578 if opts: 579 with formatter.section(_("Options")): 580 formatter.write_dl(opts) 581 582 583def _typer_main_shell_completion( 584 self: click.core.Command, 585 *, 586 ctx_args: MutableMapping[str, Any], 587 prog_name: str, 588 complete_var: Optional[str] = None, 589) -> None: 590 if complete_var is None: 591 complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper() 592 593 instruction = os.environ.get(complete_var) 594 595 if not instruction: 596 return 597 598 from .completion import shell_complete 599 600 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) 601 sys.exit(rv) 602 603 604class TyperCommand(click.core.Command): 605 def __init__( 606 self, 607 name: Optional[str], 608 *, 609 context_settings: Optional[Dict[str, Any]] = None, 610 callback: Optional[Callable[..., Any]] = None, 611 params: Optional[List[click.Parameter]] = None, 612 help: Optional[str] = None, 613 epilog: Optional[str] = None, 614 short_help: Optional[str] = None, 615 options_metavar: Optional[str] = "[OPTIONS]", 616 add_help_option: bool = True, 617 no_args_is_help: bool = False, 618 hidden: bool = False, 619 deprecated: bool = False, 620 # Rich settings 621 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 622 rich_help_panel: Union[str, None] = None, 623 ) -> None: 624 super().__init__( 625 name=name, 626 context_settings=context_settings, 627 callback=callback, 628 params=params, 629 help=help, 630 epilog=epilog, 631 short_help=short_help, 632 options_metavar=options_metavar, 633 add_help_option=add_help_option, 634 no_args_is_help=no_args_is_help, 635 hidden=hidden, 636 deprecated=deprecated, 637 ) 638 self.rich_markup_mode: MarkupMode = rich_markup_mode 639 self.rich_help_panel = rich_help_panel 640 641 def format_options( 642 self, ctx: click.Context, formatter: click.HelpFormatter 643 ) -> None: 644 _typer_format_options(self, ctx=ctx, formatter=formatter) 645 646 def _main_shell_completion( 647 self, 648 ctx_args: MutableMapping[str, Any], 649 prog_name: str, 650 complete_var: Optional[str] = None, 651 ) -> None: 652 _typer_main_shell_completion( 653 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 654 ) 655 656 def main( 657 self, 658 args: Optional[Sequence[str]] = None, 659 prog_name: Optional[str] = None, 660 complete_var: Optional[str] = None, 661 standalone_mode: bool = True, 662 windows_expand_args: bool = True, 663 **extra: Any, 664 ) -> Any: 665 return _main( 666 self, 667 args=args, 668 prog_name=prog_name, 669 complete_var=complete_var, 670 standalone_mode=standalone_mode, 671 windows_expand_args=windows_expand_args, 672 rich_markup_mode=self.rich_markup_mode, 673 **extra, 674 ) 675 676 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 677 if not rich or self.rich_markup_mode is None: 678 return super().format_help(ctx, formatter) 679 return rich_utils.rich_format_help( 680 obj=self, 681 ctx=ctx, 682 markup_mode=self.rich_markup_mode, 683 ) 684 685 686class TyperGroup(click.core.Group): 687 def __init__( 688 self, 689 *, 690 name: Optional[str] = None, 691 commands: Optional[ 692 Union[Dict[str, click.Command], Sequence[click.Command]] 693 ] = None, 694 # Rich settings 695 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 696 rich_help_panel: Union[str, None] = None, 697 **attrs: Any, 698 ) -> None: 699 super().__init__(name=name, commands=commands, **attrs) 700 self.rich_markup_mode: MarkupMode = rich_markup_mode 701 self.rich_help_panel = rich_help_panel 702 703 def format_options( 704 self, ctx: click.Context, formatter: click.HelpFormatter 705 ) -> None: 706 _typer_format_options(self, ctx=ctx, formatter=formatter) 707 self.format_commands(ctx, formatter) 708 709 def _main_shell_completion( 710 self, 711 ctx_args: MutableMapping[str, Any], 712 prog_name: str, 713 complete_var: Optional[str] = None, 714 ) -> None: 715 _typer_main_shell_completion( 716 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 717 ) 718 719 def main( 720 self, 721 args: Optional[Sequence[str]] = None, 722 prog_name: Optional[str] = None, 723 complete_var: Optional[str] = None, 724 standalone_mode: bool = True, 725 windows_expand_args: bool = True, 726 **extra: Any, 727 ) -> Any: 728 return _main( 729 self, 730 args=args, 731 prog_name=prog_name, 732 complete_var=complete_var, 733 standalone_mode=standalone_mode, 734 windows_expand_args=windows_expand_args, 735 rich_markup_mode=self.rich_markup_mode, 736 **extra, 737 ) 738 739 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 740 if not rich or self.rich_markup_mode is None: 741 return super().format_help(ctx, formatter) 742 return rich_utils.rich_format_help( 743 obj=self, 744 ctx=ctx, 745 markup_mode=self.rich_markup_mode, 746 )
254class TyperArgument(click.core.Argument): 255 def __init__( 256 self, 257 *, 258 # Parameter 259 param_decls: List[str], 260 type: Optional[Any] = None, 261 required: Optional[bool] = None, 262 default: Optional[Any] = None, 263 callback: Optional[Callable[..., Any]] = None, 264 nargs: Optional[int] = None, 265 metavar: Optional[str] = None, 266 expose_value: bool = True, 267 is_eager: bool = False, 268 envvar: Optional[Union[str, List[str]]] = None, 269 shell_complete: Optional[ 270 Callable[ 271 [click.Context, click.Parameter, str], 272 Union[List["click.shell_completion.CompletionItem"], List[str]], 273 ] 274 ] = None, 275 autocompletion: Optional[Callable[..., Any]] = None, 276 # TyperArgument 277 show_default: Union[bool, str] = True, 278 show_choices: bool = True, 279 show_envvar: bool = True, 280 help: Optional[str] = None, 281 hidden: bool = False, 282 # Rich settings 283 rich_help_panel: Union[str, None] = None, 284 ): 285 self.help = help 286 self.show_default = show_default 287 self.show_choices = show_choices 288 self.show_envvar = show_envvar 289 self.hidden = hidden 290 self.rich_help_panel = rich_help_panel 291 292 super().__init__( 293 param_decls=param_decls, 294 type=type, 295 required=required, 296 default=default, 297 callback=callback, 298 nargs=nargs, 299 metavar=metavar, 300 expose_value=expose_value, 301 is_eager=is_eager, 302 envvar=envvar, 303 shell_complete=shell_complete, 304 ) 305 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 306 307 def _get_default_string( 308 self, 309 *, 310 ctx: click.Context, 311 show_default_is_str: bool, 312 default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any], 313 ) -> str: 314 return _get_default_string( 315 self, 316 ctx=ctx, 317 show_default_is_str=show_default_is_str, 318 default_value=default_value, 319 ) 320 321 def _extract_default_help_str( 322 self, *, ctx: click.Context 323 ) -> Optional[Union[Any, Callable[[], Any]]]: 324 return _extract_default_help_str(self, ctx=ctx) 325 326 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 327 # Modified version of click.core.Option.get_help_record() 328 # to support Arguments 329 if self.hidden: 330 return None 331 name = self.make_metavar() 332 help = self.help or "" 333 extra = [] 334 if self.show_envvar: 335 envvar = self.envvar 336 # allow_from_autoenv is currently not supported in Typer for CLI Arguments 337 if envvar is not None: 338 var_str = ( 339 ", ".join(str(d) for d in envvar) 340 if isinstance(envvar, (list, tuple)) 341 else envvar 342 ) 343 extra.append(f"env var: {var_str}") 344 345 # Typer override: 346 # Extracted to _extract_default_help_str() to allow re-using it in rich_utils 347 default_value = self._extract_default_help_str(ctx=ctx) 348 # Typer override end 349 350 show_default_is_str = isinstance(self.show_default, str) 351 352 if show_default_is_str or ( 353 default_value is not None and (self.show_default or ctx.show_default) 354 ): 355 # Typer override: 356 # Extracted to _get_default_string() to allow re-using it in rich_utils 357 default_string = self._get_default_string( 358 ctx=ctx, 359 show_default_is_str=show_default_is_str, 360 default_value=default_value, 361 ) 362 # Typer override end 363 if default_string: 364 extra.append(_("default: {default}").format(default=default_string)) 365 if self.required: 366 extra.append(_("required")) 367 if extra: 368 extra_str = ";".join(extra) 369 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 370 return name, help 371 372 def make_metavar(self) -> str: 373 # Modified version of click.core.Argument.make_metavar() 374 # to include Argument name 375 if self.metavar is not None: 376 return self.metavar 377 var = (self.name or "").upper() 378 if not self.required: 379 var = f"[{var}]" 380 type_var = self.type.get_metavar(self) 381 if type_var: 382 var += f":{type_var}" 383 if self.nargs != 1: 384 var += "..." 385 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.
255 def __init__( 256 self, 257 *, 258 # Parameter 259 param_decls: List[str], 260 type: Optional[Any] = None, 261 required: Optional[bool] = None, 262 default: Optional[Any] = None, 263 callback: Optional[Callable[..., Any]] = None, 264 nargs: Optional[int] = None, 265 metavar: Optional[str] = None, 266 expose_value: bool = True, 267 is_eager: bool = False, 268 envvar: Optional[Union[str, List[str]]] = None, 269 shell_complete: Optional[ 270 Callable[ 271 [click.Context, click.Parameter, str], 272 Union[List["click.shell_completion.CompletionItem"], List[str]], 273 ] 274 ] = None, 275 autocompletion: Optional[Callable[..., Any]] = None, 276 # TyperArgument 277 show_default: Union[bool, str] = True, 278 show_choices: bool = True, 279 show_envvar: bool = True, 280 help: Optional[str] = None, 281 hidden: bool = False, 282 # Rich settings 283 rich_help_panel: Union[str, None] = None, 284 ): 285 self.help = help 286 self.show_default = show_default 287 self.show_choices = show_choices 288 self.show_envvar = show_envvar 289 self.hidden = hidden 290 self.rich_help_panel = rich_help_panel 291 292 super().__init__( 293 param_decls=param_decls, 294 type=type, 295 required=required, 296 default=default, 297 callback=callback, 298 nargs=nargs, 299 metavar=metavar, 300 expose_value=expose_value, 301 is_eager=is_eager, 302 envvar=envvar, 303 shell_complete=shell_complete, 304 ) 305 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
326 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 327 # Modified version of click.core.Option.get_help_record() 328 # to support Arguments 329 if self.hidden: 330 return None 331 name = self.make_metavar() 332 help = self.help or "" 333 extra = [] 334 if self.show_envvar: 335 envvar = self.envvar 336 # allow_from_autoenv is currently not supported in Typer for CLI Arguments 337 if envvar is not None: 338 var_str = ( 339 ", ".join(str(d) for d in envvar) 340 if isinstance(envvar, (list, tuple)) 341 else envvar 342 ) 343 extra.append(f"env var: {var_str}") 344 345 # Typer override: 346 # Extracted to _extract_default_help_str() to allow re-using it in rich_utils 347 default_value = self._extract_default_help_str(ctx=ctx) 348 # Typer override end 349 350 show_default_is_str = isinstance(self.show_default, str) 351 352 if show_default_is_str or ( 353 default_value is not None and (self.show_default or ctx.show_default) 354 ): 355 # Typer override: 356 # Extracted to _get_default_string() to allow re-using it in rich_utils 357 default_string = self._get_default_string( 358 ctx=ctx, 359 show_default_is_str=show_default_is_str, 360 default_value=default_value, 361 ) 362 # Typer override end 363 if default_string: 364 extra.append(_("default: {default}").format(default=default_string)) 365 if self.required: 366 extra.append(_("required")) 367 if extra: 368 extra_str = ";".join(extra) 369 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 370 return name, help
372 def make_metavar(self) -> str: 373 # Modified version of click.core.Argument.make_metavar() 374 # to include Argument name 375 if self.metavar is not None: 376 return self.metavar 377 var = (self.name or "").upper() 378 if not self.required: 379 var = f"[{var}]" 380 type_var = self.type.get_metavar(self) 381 if type_var: 382 var += f":{type_var}" 383 if self.nargs != 1: 384 var += "..." 385 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
388class TyperOption(click.core.Option): 389 def __init__( 390 self, 391 *, 392 # Parameter 393 param_decls: List[str], 394 type: Optional[Union[click.types.ParamType, Any]] = None, 395 required: Optional[bool] = None, 396 default: Optional[Any] = None, 397 callback: Optional[Callable[..., Any]] = None, 398 nargs: Optional[int] = None, 399 metavar: Optional[str] = None, 400 expose_value: bool = True, 401 is_eager: bool = False, 402 envvar: Optional[Union[str, List[str]]] = None, 403 shell_complete: Optional[ 404 Callable[ 405 [click.Context, click.Parameter, str], 406 Union[List["click.shell_completion.CompletionItem"], List[str]], 407 ] 408 ] = None, 409 autocompletion: Optional[Callable[..., Any]] = None, 410 # Option 411 show_default: Union[bool, str] = False, 412 prompt: Union[bool, str] = False, 413 confirmation_prompt: Union[bool, str] = False, 414 prompt_required: bool = True, 415 hide_input: bool = False, 416 is_flag: Optional[bool] = None, 417 flag_value: Optional[Any] = None, 418 multiple: bool = False, 419 count: bool = False, 420 allow_from_autoenv: bool = True, 421 help: Optional[str] = None, 422 hidden: bool = False, 423 show_choices: bool = True, 424 show_envvar: bool = False, 425 # Rich settings 426 rich_help_panel: Union[str, None] = None, 427 ): 428 super().__init__( 429 param_decls=param_decls, 430 type=type, 431 required=required, 432 default=default, 433 callback=callback, 434 nargs=nargs, 435 metavar=metavar, 436 expose_value=expose_value, 437 is_eager=is_eager, 438 envvar=envvar, 439 show_default=show_default, 440 prompt=prompt, 441 confirmation_prompt=confirmation_prompt, 442 hide_input=hide_input, 443 is_flag=is_flag, 444 flag_value=flag_value, 445 multiple=multiple, 446 count=count, 447 allow_from_autoenv=allow_from_autoenv, 448 help=help, 449 hidden=hidden, 450 show_choices=show_choices, 451 show_envvar=show_envvar, 452 prompt_required=prompt_required, 453 shell_complete=shell_complete, 454 ) 455 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 456 self.rich_help_panel = rich_help_panel 457 458 def _get_default_string( 459 self, 460 *, 461 ctx: click.Context, 462 show_default_is_str: bool, 463 default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any], 464 ) -> str: 465 return _get_default_string( 466 self, 467 ctx=ctx, 468 show_default_is_str=show_default_is_str, 469 default_value=default_value, 470 ) 471 472 def _extract_default_help_str( 473 self, *, ctx: click.Context 474 ) -> Optional[Union[Any, Callable[[], Any]]]: 475 return _extract_default_help_str(self, ctx=ctx) 476 477 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 478 # Duplicate all of Click's logic only to modify a single line, to allow boolean 479 # flags with only names for False values as it's currently supported by Typer 480 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false 481 if self.hidden: 482 return None 483 484 any_prefix_is_slash = False 485 486 def _write_opts(opts: Sequence[str]) -> str: 487 nonlocal any_prefix_is_slash 488 489 rv, any_slashes = click.formatting.join_options(opts) 490 491 if any_slashes: 492 any_prefix_is_slash = True 493 494 if not self.is_flag and not self.count: 495 rv += f" {self.make_metavar()}" 496 497 return rv 498 499 rv = [_write_opts(self.opts)] 500 501 if self.secondary_opts: 502 rv.append(_write_opts(self.secondary_opts)) 503 504 help = self.help or "" 505 extra = [] 506 507 if self.show_envvar: 508 envvar = self.envvar 509 510 if envvar is None: 511 if ( 512 self.allow_from_autoenv 513 and ctx.auto_envvar_prefix is not None 514 and self.name is not None 515 ): 516 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 517 518 if envvar is not None: 519 var_str = ( 520 envvar 521 if isinstance(envvar, str) 522 else ", ".join(str(d) for d in envvar) 523 ) 524 extra.append(_("env var: {var}").format(var=var_str)) 525 526 # Typer override: 527 # Extracted to _extract_default() to allow re-using it in rich_utils 528 default_value = self._extract_default_help_str(ctx=ctx) 529 # Typer override end 530 531 show_default_is_str = isinstance(self.show_default, str) 532 533 if show_default_is_str or ( 534 default_value is not None and (self.show_default or ctx.show_default) 535 ): 536 # Typer override: 537 # Extracted to _get_default_string() to allow re-using it in rich_utils 538 default_string = self._get_default_string( 539 ctx=ctx, 540 show_default_is_str=show_default_is_str, 541 default_value=default_value, 542 ) 543 # Typer override end 544 if default_string: 545 extra.append(_("default: {default}").format(default=default_string)) 546 547 if isinstance(self.type, click.types._NumberRangeBase): 548 range_str = self.type._describe_range() 549 550 if range_str: 551 extra.append(range_str) 552 553 if self.required: 554 extra.append(_("required")) 555 556 if extra: 557 extra_str = "; ".join(extra) 558 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 559 560 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.
389 def __init__( 390 self, 391 *, 392 # Parameter 393 param_decls: List[str], 394 type: Optional[Union[click.types.ParamType, Any]] = None, 395 required: Optional[bool] = None, 396 default: Optional[Any] = None, 397 callback: Optional[Callable[..., Any]] = None, 398 nargs: Optional[int] = None, 399 metavar: Optional[str] = None, 400 expose_value: bool = True, 401 is_eager: bool = False, 402 envvar: Optional[Union[str, List[str]]] = None, 403 shell_complete: Optional[ 404 Callable[ 405 [click.Context, click.Parameter, str], 406 Union[List["click.shell_completion.CompletionItem"], List[str]], 407 ] 408 ] = None, 409 autocompletion: Optional[Callable[..., Any]] = None, 410 # Option 411 show_default: Union[bool, str] = False, 412 prompt: Union[bool, str] = False, 413 confirmation_prompt: Union[bool, str] = False, 414 prompt_required: bool = True, 415 hide_input: bool = False, 416 is_flag: Optional[bool] = None, 417 flag_value: Optional[Any] = None, 418 multiple: bool = False, 419 count: bool = False, 420 allow_from_autoenv: bool = True, 421 help: Optional[str] = None, 422 hidden: bool = False, 423 show_choices: bool = True, 424 show_envvar: bool = False, 425 # Rich settings 426 rich_help_panel: Union[str, None] = None, 427 ): 428 super().__init__( 429 param_decls=param_decls, 430 type=type, 431 required=required, 432 default=default, 433 callback=callback, 434 nargs=nargs, 435 metavar=metavar, 436 expose_value=expose_value, 437 is_eager=is_eager, 438 envvar=envvar, 439 show_default=show_default, 440 prompt=prompt, 441 confirmation_prompt=confirmation_prompt, 442 hide_input=hide_input, 443 is_flag=is_flag, 444 flag_value=flag_value, 445 multiple=multiple, 446 count=count, 447 allow_from_autoenv=allow_from_autoenv, 448 help=help, 449 hidden=hidden, 450 show_choices=show_choices, 451 show_envvar=show_envvar, 452 prompt_required=prompt_required, 453 shell_complete=shell_complete, 454 ) 455 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 456 self.rich_help_panel = rich_help_panel
477 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: 478 # Duplicate all of Click's logic only to modify a single line, to allow boolean 479 # flags with only names for False values as it's currently supported by Typer 480 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false 481 if self.hidden: 482 return None 483 484 any_prefix_is_slash = False 485 486 def _write_opts(opts: Sequence[str]) -> str: 487 nonlocal any_prefix_is_slash 488 489 rv, any_slashes = click.formatting.join_options(opts) 490 491 if any_slashes: 492 any_prefix_is_slash = True 493 494 if not self.is_flag and not self.count: 495 rv += f" {self.make_metavar()}" 496 497 return rv 498 499 rv = [_write_opts(self.opts)] 500 501 if self.secondary_opts: 502 rv.append(_write_opts(self.secondary_opts)) 503 504 help = self.help or "" 505 extra = [] 506 507 if self.show_envvar: 508 envvar = self.envvar 509 510 if envvar is None: 511 if ( 512 self.allow_from_autoenv 513 and ctx.auto_envvar_prefix is not None 514 and self.name is not None 515 ): 516 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 517 518 if envvar is not None: 519 var_str = ( 520 envvar 521 if isinstance(envvar, str) 522 else ", ".join(str(d) for d in envvar) 523 ) 524 extra.append(_("env var: {var}").format(var=var_str)) 525 526 # Typer override: 527 # Extracted to _extract_default() to allow re-using it in rich_utils 528 default_value = self._extract_default_help_str(ctx=ctx) 529 # Typer override end 530 531 show_default_is_str = isinstance(self.show_default, str) 532 533 if show_default_is_str or ( 534 default_value is not None and (self.show_default or ctx.show_default) 535 ): 536 # Typer override: 537 # Extracted to _get_default_string() to allow re-using it in rich_utils 538 default_string = self._get_default_string( 539 ctx=ctx, 540 show_default_is_str=show_default_is_str, 541 default_value=default_value, 542 ) 543 # Typer override end 544 if default_string: 545 extra.append(_("default: {default}").format(default=default_string)) 546 547 if isinstance(self.type, click.types._NumberRangeBase): 548 range_str = self.type._describe_range() 549 550 if range_str: 551 extra.append(range_str) 552 553 if self.required: 554 extra.append(_("required")) 555 556 if extra: 557 extra_str = "; ".join(extra) 558 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 559 560 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
605class TyperCommand(click.core.Command): 606 def __init__( 607 self, 608 name: Optional[str], 609 *, 610 context_settings: Optional[Dict[str, Any]] = None, 611 callback: Optional[Callable[..., Any]] = None, 612 params: Optional[List[click.Parameter]] = None, 613 help: Optional[str] = None, 614 epilog: Optional[str] = None, 615 short_help: Optional[str] = None, 616 options_metavar: Optional[str] = "[OPTIONS]", 617 add_help_option: bool = True, 618 no_args_is_help: bool = False, 619 hidden: bool = False, 620 deprecated: bool = False, 621 # Rich settings 622 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 623 rich_help_panel: Union[str, None] = None, 624 ) -> None: 625 super().__init__( 626 name=name, 627 context_settings=context_settings, 628 callback=callback, 629 params=params, 630 help=help, 631 epilog=epilog, 632 short_help=short_help, 633 options_metavar=options_metavar, 634 add_help_option=add_help_option, 635 no_args_is_help=no_args_is_help, 636 hidden=hidden, 637 deprecated=deprecated, 638 ) 639 self.rich_markup_mode: MarkupMode = rich_markup_mode 640 self.rich_help_panel = rich_help_panel 641 642 def format_options( 643 self, ctx: click.Context, formatter: click.HelpFormatter 644 ) -> None: 645 _typer_format_options(self, ctx=ctx, formatter=formatter) 646 647 def _main_shell_completion( 648 self, 649 ctx_args: MutableMapping[str, Any], 650 prog_name: str, 651 complete_var: Optional[str] = None, 652 ) -> None: 653 _typer_main_shell_completion( 654 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 655 ) 656 657 def main( 658 self, 659 args: Optional[Sequence[str]] = None, 660 prog_name: Optional[str] = None, 661 complete_var: Optional[str] = None, 662 standalone_mode: bool = True, 663 windows_expand_args: bool = True, 664 **extra: Any, 665 ) -> Any: 666 return _main( 667 self, 668 args=args, 669 prog_name=prog_name, 670 complete_var=complete_var, 671 standalone_mode=standalone_mode, 672 windows_expand_args=windows_expand_args, 673 rich_markup_mode=self.rich_markup_mode, 674 **extra, 675 ) 676 677 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 678 if not rich or self.rich_markup_mode is None: 679 return super().format_help(ctx, formatter) 680 return rich_utils.rich_format_help( 681 obj=self, 682 ctx=ctx, 683 markup_mode=self.rich_markup_mode, 684 )
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.
606 def __init__( 607 self, 608 name: Optional[str], 609 *, 610 context_settings: Optional[Dict[str, Any]] = None, 611 callback: Optional[Callable[..., Any]] = None, 612 params: Optional[List[click.Parameter]] = None, 613 help: Optional[str] = None, 614 epilog: Optional[str] = None, 615 short_help: Optional[str] = None, 616 options_metavar: Optional[str] = "[OPTIONS]", 617 add_help_option: bool = True, 618 no_args_is_help: bool = False, 619 hidden: bool = False, 620 deprecated: bool = False, 621 # Rich settings 622 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 623 rich_help_panel: Union[str, None] = None, 624 ) -> None: 625 super().__init__( 626 name=name, 627 context_settings=context_settings, 628 callback=callback, 629 params=params, 630 help=help, 631 epilog=epilog, 632 short_help=short_help, 633 options_metavar=options_metavar, 634 add_help_option=add_help_option, 635 no_args_is_help=no_args_is_help, 636 hidden=hidden, 637 deprecated=deprecated, 638 ) 639 self.rich_markup_mode: MarkupMode = rich_markup_mode 640 self.rich_help_panel = rich_help_panel
642 def format_options( 643 self, ctx: click.Context, formatter: click.HelpFormatter 644 ) -> None: 645 _typer_format_options(self, ctx=ctx, formatter=formatter)
Writes all the options into the formatter if they exist.
657 def main( 658 self, 659 args: Optional[Sequence[str]] = None, 660 prog_name: Optional[str] = None, 661 complete_var: Optional[str] = None, 662 standalone_mode: bool = True, 663 windows_expand_args: bool = True, 664 **extra: Any, 665 ) -> Any: 666 return _main( 667 self, 668 args=args, 669 prog_name=prog_name, 670 complete_var=complete_var, 671 standalone_mode=standalone_mode, 672 windows_expand_args=windows_expand_args, 673 rich_markup_mode=self.rich_markup_mode, 674 **extra, 675 )
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.
677 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 678 if not rich or self.rich_markup_mode is None: 679 return super().format_help(ctx, formatter) 680 return rich_utils.rich_format_help( 681 obj=self, 682 ctx=ctx, 683 markup_mode=self.rich_markup_mode, 684 )
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
687class TyperGroup(click.core.Group): 688 def __init__( 689 self, 690 *, 691 name: Optional[str] = None, 692 commands: Optional[ 693 Union[Dict[str, click.Command], Sequence[click.Command]] 694 ] = None, 695 # Rich settings 696 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 697 rich_help_panel: Union[str, None] = None, 698 **attrs: Any, 699 ) -> None: 700 super().__init__(name=name, commands=commands, **attrs) 701 self.rich_markup_mode: MarkupMode = rich_markup_mode 702 self.rich_help_panel = rich_help_panel 703 704 def format_options( 705 self, ctx: click.Context, formatter: click.HelpFormatter 706 ) -> None: 707 _typer_format_options(self, ctx=ctx, formatter=formatter) 708 self.format_commands(ctx, formatter) 709 710 def _main_shell_completion( 711 self, 712 ctx_args: MutableMapping[str, Any], 713 prog_name: str, 714 complete_var: Optional[str] = None, 715 ) -> None: 716 _typer_main_shell_completion( 717 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 718 ) 719 720 def main( 721 self, 722 args: Optional[Sequence[str]] = None, 723 prog_name: Optional[str] = None, 724 complete_var: Optional[str] = None, 725 standalone_mode: bool = True, 726 windows_expand_args: bool = True, 727 **extra: Any, 728 ) -> Any: 729 return _main( 730 self, 731 args=args, 732 prog_name=prog_name, 733 complete_var=complete_var, 734 standalone_mode=standalone_mode, 735 windows_expand_args=windows_expand_args, 736 rich_markup_mode=self.rich_markup_mode, 737 **extra, 738 ) 739 740 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 741 if not rich or self.rich_markup_mode is None: 742 return super().format_help(ctx, formatter) 743 return rich_utils.rich_format_help( 744 obj=self, 745 ctx=ctx, 746 markup_mode=self.rich_markup_mode, 747 )
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.
688 def __init__( 689 self, 690 *, 691 name: Optional[str] = None, 692 commands: Optional[ 693 Union[Dict[str, click.Command], Sequence[click.Command]] 694 ] = None, 695 # Rich settings 696 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 697 rich_help_panel: Union[str, None] = None, 698 **attrs: Any, 699 ) -> None: 700 super().__init__(name=name, commands=commands, **attrs) 701 self.rich_markup_mode: MarkupMode = rich_markup_mode 702 self.rich_help_panel = rich_help_panel
704 def format_options( 705 self, ctx: click.Context, formatter: click.HelpFormatter 706 ) -> None: 707 _typer_format_options(self, ctx=ctx, formatter=formatter) 708 self.format_commands(ctx, formatter)
Writes all the options into the formatter if they exist.
720 def main( 721 self, 722 args: Optional[Sequence[str]] = None, 723 prog_name: Optional[str] = None, 724 complete_var: Optional[str] = None, 725 standalone_mode: bool = True, 726 windows_expand_args: bool = True, 727 **extra: Any, 728 ) -> Any: 729 return _main( 730 self, 731 args=args, 732 prog_name=prog_name, 733 complete_var=complete_var, 734 standalone_mode=standalone_mode, 735 windows_expand_args=windows_expand_args, 736 rich_markup_mode=self.rich_markup_mode, 737 **extra, 738 )
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.
740 def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: 741 if not rich or self.rich_markup_mode is None: 742 return super().format_help(ctx, formatter) 743 return rich_utils.rich_format_help( 744 obj=self, 745 ctx=ctx, 746 markup_mode=self.rich_markup_mode, 747 )
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.Group
- command_class
- group_class
- commands
- add_command
- command
- group
- get_command
- list_commands
- 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