Contents

Click library internals

0

This page is all about the click python library, the contents below is auto-generated by inspecting a python package’s code base.

This page is experimental: if you are seeking help with the `click` python package it's usually best to reference the libraries offical documentation page.

Package Files

  • click/__init__.py
  • click/_compat.py
  • click/_termui_impl.py
  • click/_textwrap.py
  • click/_unicodefun.py
  • click/_winconsole.py
  • click/core.py
  • click/decorators.py
  • click/exceptions.py
  • click/formatting.py
  • click/globals.py
  • click/parser.py
  • click/py.typed
  • click/shell_completion.py
  • click/termui.py
  • click/testing.py
  • click/types.py
  • click/utils.py

Package Classes

  • <class ‘click.exceptions.Abort’>
  • <class ‘click.core.Argument’>
  • <class ‘click.exceptions.BadArgumentUsage’>
  • <class ‘click.exceptions.BadOptionUsage’>
  • <class ‘click.exceptions.BadParameter’>
  • <class ‘click.core.BaseCommand’>
  • <class ‘click.types.Choice’>
  • <class ‘click.exceptions.ClickException’>
  • <class ‘click.core.Command’>
  • <class ‘click.core.CommandCollection’>
  • <class ‘click.core.Context’>
  • <class ‘click.types.DateTime’>
  • <class ‘click.types.File’>
  • <class ‘click.exceptions.FileError’>
  • <class ‘click.types.FloatRange’>
  • <class ‘click.core.Group’>
  • <class ‘click.formatting.HelpFormatter’>
  • <class ‘click.types.IntRange’>
  • <class ‘click.exceptions.MissingParameter’>
  • <class ‘click.core.MultiCommand’>
  • <class ‘click.exceptions.NoSuchOption’>
  • <class ‘click.core.Option’>
  • <class ‘click.parser.OptionParser’>
  • <class ‘click.types.ParamType’>
  • <class ‘click.core.Parameter’>
  • <class ‘click.types.Path’>
  • <class ‘click.types.Tuple’>
  • <class ‘click.exceptions.UsageError’>

Package Methods

click.argument()

passed as parameter declarations to :class:Argument; all keyword arguments are forwarded unchanged (except cls). This is equivalent to creating an :class:Argument instance manually and attaching it to the :attr:Command.params list.

click.argument(*param_decls: str, **attrs: Any) -> Callable[[~FC], ~FC]

click.argument(
  param_decls,
  attrs,
)

click.clear()

the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal.

.. versionadded:: 2.0

click.clear() -> None

click.clear(
)

click.command()

callback. This will also automatically attach all decorated

click.command(name: Optional[str] = None, cls: Optional[Type[click.core.Command]] = None, **attrs: Any) -> Callable[[~F], click.core.Command]

click.command(
  name,
  cls,
  attrs,
)

click.confirm()

If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:Abort exception.

click.confirm(text: str, default: Optional[bool] = False, abort: bool = False, prompt_suffix: str = ': ', show_default: bool = True, err: bool = False) -> bool

click.confirm(
  text,
  default,
  abort,
  prompt_suffix,
  show_default,
  err,
)

click.confirmation_option()

not passed. If the prompt is declined, the program will exit.

click.confirmation_option(*param_decls: str, **kwargs: Any) -> Callable[[~FC], ~FC]

click.confirmation_option(
  param_decls,
  kwargs,
)

click.echo()

used instead of :func:print because it provides better support for different data, files, and environments.

Compared to :func:print, this does the following:

  • Ensures that the output encoding is not misconfigured on Linux.
  • Supports Unicode in the Windows console.
  • Supports writing to binary outputs, and supports writing bytes to text outputs.
  • Supports colors and styles on Windows.
  • Removes ANSI color and style codes if the output does not look like an interactive terminal.
  • Always flushes the output.
click.echo(message: Optional[Any] = None, file: Optional[IO] = None, nl: bool = True, err: bool = False, color: Optional[bool] = None) -> None

click.echo(
  message,
  file,
  nl,
  err,
  color,
)

click.echo_via_pager()

pager on stdout.

.. versionchanged:: 3.0 Added the color flag.

click.echo_via_pager(text_or_generator: Union[Iterable[str], Callable[[], Iterable[str]], str], color: Optional[bool] = None) -> None

click.echo_via_pager(
  text_or_generator,
  color,
)

click.edit()

(should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, None is returned. In case a file is edited directly the return value is always None and require_save and extension are ignored.

If the editor cannot be opened a :exc:UsageError is raised.

Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have \n as newline markers.

click.edit(text: Optional[~AnyStr] = None, editor: Optional[str] = None, env: Optional[Mapping[str, str]] = None, require_save: bool = True, extension: str = '.txt', filename: Optional[str] = None) -> Optional[~AnyStr]

click.edit(
  text,
  editor,
  env,
  require_save,
  extension,
  filename,
)

click.format_filename()

function is to ensure that the filename can be displayed at all. This will decode the filename to unicode if necessary in a way that it will not fail. Optionally, it can shorten the filename to not include the full path to the filename.

click.format_filename(filename: Union[str, bytes, os.PathLike], shorten: bool = False) -> str

click.format_filename(
  filename,
  shorten,
)

click.get_app_dir()

is to return whatever is most appropriate for the operating system.

To give you an idea, for an app called "Foo Bar", something like the following folders could be returned:

Mac OS X: ~/Library/Application Support/Foo Bar Mac OS X (POSIX): ~/.foo-bar Unix: ~/.config/foo-bar Unix (POSIX): ~/.foo-bar Windows (roaming): C:\Users\\<user\>\AppData\Roaming\Foo Bar Windows (not roaming): C:\Users\\<user\>\AppData\Local\Foo Bar

.. versionadded:: 2.0

click.get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str

click.get_app_dir(
  app_name,
  roaming,
  force_posix,
)

click.get_binary_stream()

click.get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> <class 'BinaryIO'>

click.get_binary_stream(
  name,
)

click.get_current_context()

access the current context object from anywhere. This is a more implicit alternative to the :func:pass_context decorator. This function is primarily useful for helpers such as :func:echo which might be interested in changing its behavior based on the current context.

To push the current context, :meth:Context.scope can be used.

.. versionadded:: 5.0

click.get_current_context(silent: bool = False) -> Optional[ForwardRef('Context')]

click.get_current_context(
  silent,
)

click.get_os_args()

value which is the name of the script.

click.get_os_args() -> Sequence[str]

click.get_os_args(
)

click.get_terminal_size()

(width, height) in columns and rows.

click.get_terminal_size() -> os.terminal_size

click.get_terminal_size(
)

click.get_text_stream()

a wrapped stream around a binary stream returned from

click.get_text_stream(name: "te.Literal['stdin', 'stdout', 'stderr']", encoding: Optional[str] = None, errors: Optional[str] = 'strict') -> <class 'TextIO'>

click.get_text_stream(
  name,
  encoding,
  errors,
)

click.getchar()

will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal.

Note that this will always read from the terminal, even if something is piped into the standard input.

Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers.

.. versionadded:: 2.0

click.getchar(echo: bool = False) -> str

click.getchar(
  echo,
)

click.group()

works otherwise the same as :func:command just that the cls parameter is set to :class:Group.

click.group(name: Optional[str] = None, **attrs: Any) -> Callable[[~F], click.core.Group]

click.group(
  name,
  attrs,
)

click.help_option()

and exits the program.

This is usually unnecessary, as the --help option is added to each command automatically unless add_help_option=False is passed.

click.help_option(*param_decls: str, **kwargs: Any) -> Callable[[~FC], ~FC]

click.help_option(
  param_decls,
  kwargs,
)

click.launch()

viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, 0 indicates success.

Examples::

click.launch('https://click.palletsprojects.com/')
click.launch('/my/downloaded/file', locate=True)

.. versionadded:: 2.0

click.launch(url: str, wait: bool = False, locate: bool = False) -> int

click.launch(
  url,
  wait,
  locate,
)

click.make_pass_decorator()

similar to :func:pass_obj but instead of passing the object of the current context, it will find the innermost context of type

click.make_pass_decorator(object_type: Type, ensure: bool = False) -> 't.Callable[[F], F]'

click.make_pass_decorator(
  object_type,
  ensure,
)

click.open_file()

usage. Files are opened non lazy by default. This can open regular files as well as stdin/stdout if '-' is passed.

If stdin/stdout is returned the stream is wrapped so that the context manager will not close the stream accidentally. This makes it possible to always use the function like this without having to worry to accidentally close a standard stream::

with open_file(filename) as f:
    ...

.. versionadded:: 3.0

click.open_file(filename: str, mode: str = 'r', encoding: Optional[str] = None, errors: Optional[str] = 'strict', lazy: bool = False, atomic: bool = False) -> <class 'IO'>

click.open_file(
  filename,
  mode,
  encoding,
  errors,
  lazy,
  atomic,
)

click.option()

passed as parameter declarations to :class:Option; all keyword arguments are forwarded unchanged (except cls). This is equivalent to creating an :class:Option instance manually and attaching it to the :attr:Command.params list.

click.option(*param_decls: str, **attrs: Any) -> Callable[[~FC], ~FC]

click.option(
  param_decls,
  attrs,
)

click.pass_context()

object as first argument.

click.pass_context(f: ~F) -> ~F

click.pass_context(
  f,
)

click.pass_obj()

context onwards (:attr:Context.obj). This is useful if that object represents the state of a nested system.

click.pass_obj(f: ~F) -> ~F

click.pass_obj(
  f,
)

click.password_option()

input and asking to enter the value again for confirmation.

click.password_option(*param_decls: str, **kwargs: Any) -> Callable[[~FC], ~FC]

click.password_option(
  param_decls,
  kwargs,
)

click.pause()

key to continue. This is similar to the Windows batch “pause” command. If the program is not run through a terminal, this command will instead do nothing.

.. versionadded:: 2.0

.. versionadded:: 4.0 Added the err parameter.

click.pause(info: Optional[str] = None, err: bool = False) -> None

click.pause(
  info,
  err,
)

click.progressbar()

to iterate over something while showing a progress bar. It will either iterate over the iterable or length items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given file (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal.

The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen.

Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won’t display progress that is considered too fast, and progress where the time between steps is less than a second.

No printing must happen or the progress bar will be unintentionally destroyed.

Example usage::

with progressbar(items) as bar:
    for item in bar:
        do_something_with(item)

Alternatively, if no iterable is specified, one can manually update the progress bar through the update() method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with::

with progressbar(length=chunks.total_bytes) as bar:
    for chunk in chunks:
        process_chunk(chunk)
        bar.update(chunks.bytes)

The update() method also takes an optional value specifying the current_item at the new position. This is useful when used together with item_show_func to customize the output for each manual step::

with click.progressbar(
    length=total_size,
    label='Unzipping archive',
    item_show_func=lambda a: a.filename
) as bar:
    for archive in zip_file:
        archive.extract()
        bar.update(archive.size, archive)
click.progressbar(iterable: Optional[Iterable[~V]] = None, length: Optional[int] = None, label: Optional[str] = None, show_eta: bool = True, show_percent: Optional[bool] = None, show_pos: bool = False, item_show_func: Optional[Callable[[Optional[~V]], Optional[str]]] = None, fill_char: str = '#', empty_char: str = '-', bar_template: str = '%(label)s  [%(bar)s]  %(info)s', info_sep: str = '  ', width: int = 36, file: Optional[TextIO] = None, color: Optional[bool] = None, update_min_steps: int = 1) -> 'ProgressBar[V]'

click.progressbar(
  iterable,
  length,
  label,
  show_eta,
  show_percent,
  show_pos,
  item_show_func,
  fill_char,
  empty_char,
  bar_template,
  info_sep,
  width,
  file,
  color,
  update_min_steps,
)

click.prompt()

be used to prompt a user for input later.

If the user aborts the input by sending a interrupt signal, this function will catch it and raise a :exc:Abort exception.

click.prompt(text: str, default: Optional[Any] = None, hide_input: bool = False, confirmation_prompt: Union[bool, str] = False, type: Union[click.types.ParamType, Any, NoneType] = None, value_proc: Optional[Callable[[str], Any]] = None, prompt_suffix: str = ': ', show_default: bool = True, err: bool = False, show_choices: bool = True) -> Any

click.prompt(
  text,
  default,
  hide_input,
  confirmation_prompt,
  type,
  value_proc,
  prompt_suffix,
  show_default,
  err,
  show_choices,
)

click.secho()

call. As such the following two calls are the same::

click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))

All keyword arguments are forwarded to the underlying functions depending on which one they go with.

Non-string types will be converted to :class:str. However,

click.secho(message: Optional[Any] = None, file: Optional[IO] = None, nl: bool = True, err: bool = False, color: Optional[bool] = None, **styles: Any) -> None

click.secho(
  message,
  file,
  nl,
  err,
  color,
  styles,
)

click.style()

default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing reset=False.

Examples::

click.echo(click.style('Hello World!', fg='green'))
click.echo(click.style('ATTENTION!', blink=True))
click.echo(click.style('Some things', reverse=True, fg='cyan'))
click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))

Supported color names:

  • black (might be a gray)
  • red
  • green
  • yellow (might be an orange)
  • blue
  • magenta
  • cyan
  • white (might be light gray)
  • bright_black
  • bright_red
  • bright_green
  • bright_yellow
  • bright_blue
  • bright_magenta
  • bright_cyan
  • bright_white
  • reset (reset the color code only)

If the terminal supports it, color may also be specified as:

  • An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode.
  • An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode.

See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information.

click.style(text: Any, fg: Union[int, Tuple[int, int, int], str, NoneType] = None, bg: Union[int, Tuple[int, int, int], str, NoneType] = None, bold: Optional[bool] = None, dim: Optional[bool] = None, underline: Optional[bool] = None, overline: Optional[bool] = None, italic: Optional[bool] = None, blink: Optional[bool] = None, reverse: Optional[bool] = None, strikethrough: Optional[bool] = None, reset: bool = True) -> str

click.style(
  text,
  fg,
  bg,
  bold,
  dim,
  underline,
  overline,
  italic,
  blink,
  reverse,
  strikethrough,
  reset,
)

click.unstyle()

necessary to use this function as Click’s echo function will automatically remove styling if necessary.

.. versionadded:: 2.0

click.unstyle(text: str) -> str

click.unstyle(
  text,
)

click.version_option()

number and exits the program.

If version is not provided, Click will try to detect it using

click.version_option(version: Optional[str] = None, *param_decls: str, package_name: Optional[str] = None, prog_name: Optional[str] = None, message: Optional[str] = None, **kwargs: Any) -> Callable[[~FC], ~FC]

click.version_option(
  version,
  param_decls,
  package_name,
  prog_name,
  message,
  kwargs,
)

click.wrap_text()

assumes that it operates on a single paragraph of text but if the preserve_paragraphs parameter is provided it will intelligently handle paragraphs (defined by two empty lines).

If paragraphs are handled, a paragraph can be prefixed with an empty line containing the \b character (\x08) to indicate that no rewrapping should happen in that block.

click.wrap_text(text: str, width: int = 78, initial_indent: str = '', subsequent_indent: str = '', preserve_paragraphs: bool = False) -> str

click.wrap_text(
  text,
  width,
  initial_indent,
  subsequent_indent,
  preserve_paragraphs,
)