Merge branch 'stable' into documentation_reST_to_MyST
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents fbb8d77, c1a8939 · Browse files · 6 files·+535 added−578 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+535 added−578 removed
- other:+535 added−578 removed
Provenance
- Commit
59acbe9- Tree
0501096- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
fbb8d77- Parent 2
c1a8939
6 files changed+535 added−578 removed
added:docs/contrib.md+45 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445(contrib)=
# click-contrib
As the user number of Click grows, more and more major feature requests aremade. To users, it may seem reasonable to include those features with Click;however, many of them are experimental or aren't practical to supportgenerically. Maintainers have to choose what is reasonable to maintain in Clickcore.
The [click-contrib](https://github.com/click-contrib/) GitHub organization exists as a place to collect third-partypackages that extend Click's features. It is also meant to ease the effort ofsearching for such extensions.
Please note that the quality and stability of those packages may be differentfrom Click itself. While published under a common organization, they are stillseparate from Click and the Pallets maintainers.
## Third-party projects
Other projects that extend Click's features are available outside the[click-contrib](https://github.com/click-contrib/) organization.
Some of the most popular and actively maintained are listed below:
| Project | Description | Popularity | Activity ||---------------------------------------------------------|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------|| [Typer](https://github.com/fastapi/typer) | Use Python type hints to create CLI apps. |  |  || [rich-click](https://github.com/ewels/rich-click) | Format help output with Rich. |  |  || [click-app](https://github.com/simonw/click-app) | Cookiecutter template for creating new CLIs. |  |  || [Cloup](https://github.com/janluke/cloup) | Adds option groups, constraints, command aliases, help themes, suggestions and more. |  |  || [Click Extra](https://github.com/kdeldycke/click-extra) | Cloup + colorful `--help`, `--config`, `--show-params`, `--verbosity` options, etc. |  |  |
```{note}To make it into the list above, a project:
- must be actively maintained (at least one commit in the last year)- must have a reasonable number of stars (at least 20)
If you have a project that meets these criteria, please open a pull requestto add it to the list.
If a project is no longer maintained or does not meet the criteria above,please open a pull request to remove it from the list.```deleted:docs/contrib.rst-58 removed
1-.. _contrib:2-3-=============4-click-contrib5-=============6-7-As the number of users of Click grows, more and more major feature requests are8-made. To users it may seem reasonable to include those features with Click;9-however, many of them are experimental or aren't practical to support10-generically. Maintainers have to choose what is reasonable to maintain in Click11-core.12-13-The click-contrib_ GitHub organization exists as a place to collect third-party14-packages that extend Click's features. It is also meant to ease the effort of15-searching for such extensions.16-17-Please note that the quality and stability of those packages may be different18-than Click itself. While published under a common organization, they are still19-separate from Click and the Pallets maintainers.20-21-22-Third-party projects23---------------------24-25-Other projects that extend Click's features are available outside of the26-click-contrib_ organization.27-28-Some of the most popular and actively maintained are listed below:29-30-========================================================== =========================================================================================== ================================================================================================= ======================================================================================================31-Project Description Popularity Activity32-========================================================== =========================================================================================== ================================================================================================= ======================================================================================================33-`Typer <https://github.com/fastapi/typer>`_ Use Python type hints to create CLI apps. .. image:: https://img.shields.io/github/stars/fastapi/typer?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/fastapi/typer?label=%20&style=flat-square34- :alt: GitHub stars :alt: Last commit35-`rich-click <https://github.com/ewels/rich-click>`_ Format help outputwith Rich. .. image:: https://img.shields.io/github/stars/ewels/rich-click?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/ewels/rich-click?label=%20&style=flat-square36- :alt: GitHub stars :alt: Last commit37-`click-app <https://github.com/simonw/click-app>`_ Cookiecutter template for creating new CLIs. .. image:: https://img.shields.io/github/stars/simonw/click-app?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/simonw/click-app?label=%20&style=flat-square38- :alt: GitHub stars :alt: Last commit39-`Cloup <https://github.com/janluke/cloup>`_ Adds option groups, constraints, command aliases, help themes, suggestions and more. .. image:: https://img.shields.io/github/stars/janluke/cloup?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/janluke/cloup?label=%20&style=flat-square40- :alt: GitHub stars :alt: Last commit41-`Click Extra <https://github.com/kdeldycke/click-extra>`_ Cloup + colorful ``--help``, ``--config``, ``--show-params``, ``--verbosity`` options, etc. .. image:: https://img.shields.io/github/stars/kdeldycke/click-extra?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/kdeldycke/click-extra?label=%20&style=flat-square42- :alt: GitHub stars :alt: Last commit43-========================================================== =========================================================================================== ================================================================================================= ======================================================================================================44-45-.. note::46-47- To make it into the list above, a project:48-49- - must be actively maintained (at least one commit in the last year)50- - must have a reasonable number of stars (at least 20)51-52- If you have a project that meets these criteria, please open a pull request53- to add it to the list.54-55- If a project is no longer maintained or does not meet the criteria above,56- please open a pull request to remove it from the list.57-58-.. _click-contrib: https://github.com/click-contrib/added:docs/unicode-support.md+100 added
1+# Unicode Support2+3+```{currentmodule} click4+```5+6+Click has to take extra care to support Unicode text in different environments.7+8+- The command line in Unix is traditionally bytes, not Unicode. While there are encoding hints, there are some9+ situations where this can break. The most common one is SSH connections to machines with different locales.10+11+ Misconfigured environments can cause a wide range of Unicode problems due to the lack of support for roundtripping12+ surrogate escapes. This will not be fixed in Click itself!13+14+- Standard input and output is opened in text mode by default. Click has to reopen the stream in binary mode in certain15+ situations. Because there is no standard way to do this, it might not always work. Primarily this can become a problem16+ when testing command-line applications.17+18+ This is not supported:19+20+ ```python21+ sys.stdin = io.StringIO('Input here')22+ sys.stdout = io.StringIO()23+ ```24+25+ Instead you need to do this:26+27+ ```python28+ input = 'Input here'29+ in_stream = io.BytesIO(input.encode('utf-8'))30+ sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')31+ out_stream = io.BytesIO()32+ sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')33+ ```34+35+ Remember in that case, you need to use `out_stream.getvalue()` and not `sys.stdout.getvalue()` if you want to access36+ the buffer contents as the wrapper will not forward that method.37+38+- `sys.stdin`, `sys.stdout` and `sys.stderr` are by default text-based. When Click needs a binary stream, it attempts to39+ discover the underlying binary stream.40+41+- `sys.argv` is always text. This means that the native type for input values to the types in Click is Unicode, not42+ bytes.43+44+ This causes problems if the terminal is incorrectly set and Python does not figure out the encoding. In that case, the45+ Unicode string will contain error bytes encoded as surrogate escapes.46+47+- When dealing with files, Click will always use the Unicode file system API by using the operating system's reported or48+ guessed filesystem encoding. Surrogates are supported for filenames, so it should be possible to open files through49+ the {func}`File` type even if the environment is misconfigured.50+51+## Surrogate Handling52+53+Click does all the Unicode handling in the standard library and is subject to its behavior. Unicode requires extra care.54+The reason for this is that the encoding detection is done in the interpreter, and on Linux and certain other operating55+systems, its encoding handling is problematic.56+57+The biggest source of frustration is that Click scripts invoked by init systems, deployment tools, or cron jobs will58+refuse to work unless a Unicode locale is exported.59+60+If Click encounters such an environment it will prevent further execution to force you to set a locale. This is done61+because Click cannot know about the state of the system once it's invoked and restore the values before Python's Unicode62+handling kicked in.63+64+If you see something like this error:65+66+```console67+Traceback (most recent call last):68+ ...69+RuntimeError: Click will abort further execution because Python was70+ configured to use ASCII as encoding for the environment. Consult71+ https://click.palletsprojects.com/unicode-support/ for mitigation72+ steps.73+```74+75+You are dealing with an environment where Python thinks you are restricted to ASCII data. The solution to these problems76+is different depending on which locale your computer is running in.77+78+For instance, if you have a German Linux machine, you can fix the problem by exporting the locale to `de_DE.utf-8`:79+80+```console81+export LC_ALL=de_DE.utf-882+export LANG=de_DE.utf-883+```84+85+If you are on a US machine, `en_US.utf-8` is the encoding of choice. On some newer Linux systems, you could also try86+`C.UTF-8` as the locale:87+88+```console89+export LC_ALL=C.UTF-890+export LANG=C.UTF-891+```92+93+On some systems it was reported that `UTF-8` has to be written as `UTF8` and vice versa. To see which locales are94+supported you can invoke `locale -a`.95+96+You need to export the values before you invoke your Python script.97+98+In Python 3.7 and later you will no longer get a `RuntimeError` in many cases thanks to {pep}`538` and {pep}`540`, which99+changed the default assumption in unconfigured environments. This doesn't change the general issue that your locale may100+be misconfigured.deleted:docs/unicode-support.rst-112 removed
1-Unicode Support2-===============3-4-.. currentmodule:: click5-6-Click has to take extra care to support Unicode text in different7-environments.8-9-* The command line in Unix is traditionally bytes, not Unicode. While10- there are encoding hints, there are some situations where this can11- break. The most common one is SSH connections to machines with12- different locales.13-14- Misconfigured environments can cause a wide range of Unicode15- problems due to the lack of support for roundtripping surrogate16- escapes. This will not be fixed in Click itself!17-18-* Standard input and output is opened in text mode by default. Click19- has to reopen the stream in binary mode in certain situations.20- Because there is no standard way to do this, it might not always21- work. Primarily this can become a problem when testing command-line22- applications.23-24- This is not supported::25-26- sys.stdin = io.StringIO('Input here')27- sys.stdout = io.StringIO()28-29- Instead you need to do this::30-31- input = 'Input here'32- in_stream = io.BytesIO(input.encode('utf-8'))33- sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')34- out_stream = io.BytesIO()35- sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')36-37- Remember in that case, you need to use ``out_stream.getvalue()``38- and not ``sys.stdout.getvalue()`` if you want to access the buffer39- contents as the wrapper will not forward that method.40-41-* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default42- text-based. When Click needs a binary stream, it attempts to43- discover the underlying binary stream.44-45-* ``sys.argv`` is always text. This means that the native type for46- input values to the types in Click is Unicode, not bytes.47-48- This causes problems if the terminal is incorrectly set and Python49- does not figure out the encoding. In that case, the Unicode string50- will contain error bytes encoded as surrogate escapes.51-52-* When dealing with files, Click will always use the Unicode file53- system API by using the operating system's reported or guessed54- filesystem encoding. Surrogates are supported for filenames, so it55- should be possible to open files through the :class:`File` type even56- if the environment is misconfigured.57-58-59-Surrogate Handling60-------------------61-62-Click does all the Unicode handling in the standard library and is63-subject to its behavior. Unicode requires extra care. The reason for64-this is that the encoding detection is done in the interpreter, and on65-Linux and certain other operating systems, its encoding handling is66-problematic.67-68-The biggest source of frustration is that Click scripts invoked by init69-systems, deployment tools, or cron jobs will refuse to work unless a70-Unicode locale is exported.71-72-If Click encounters such an environment it will prevent further73-execution to force you to set a locale. This is done because Click74-cannot know about the state of the system once it's invoked and restore75-the values before Python's Unicode handling kicked in.76-77-If you see something like this error::78-79- Traceback (most recent call last):80- ...81- RuntimeError: Click will abort further execution because Python was82- configured to use ASCII as encoding for the environment. Consult83- https://click.palletsprojects.com/unicode-support/ for mitigation84- steps.85-86-You are dealing with an environment where Python thinks you are87-restricted to ASCII data. The solution to these problems is different88-depending on which locale your computer is running in.89-90-For instance, if you have a German Linux machine, you can fix the91-problem by exporting the locale to ``de_DE.utf-8``::92-93- export LC_ALL=de_DE.utf-894- export LANG=de_DE.utf-895-96-If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97-On some newer Linux systems, you could also try ``C.UTF-8`` as the98-locale::99-100- export LC_ALL=C.UTF-8101- export LANG=C.UTF-8102-103-On some systems it was reported that ``UTF-8`` has to be written as104-``UTF8`` and vice versa. To see which locales are supported you can105-invoke ``locale -a``.106-107-You need to export the values before you invoke your Python script.108-109-In Python 3.7 and later you will no longer get a ``RuntimeError`` in110-many cases thanks to :pep:`538` and :pep:`540`, which changed the111-default assumption in unconfigured environments. This doesn't change the112-general issue that your locale may be misconfigured.added:docs/utils.md+390 added
1+# Utilities2+3+```{currentmodule} click4+```5+6+Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunch7+of addon functionality that is useful for writing command line utilities.8+9+## Printing to Stdout10+11+The most obvious helper is the {func}`echo` function, which in many ways works like the Python `print` statement or12+function. The main difference is that it works the same in many different terminal environments.13+14+Example:15+16+```python17+import click18+19+click.echo('Hello World!')20+```21+22+It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by23+passing `nl=False`:24+25+```python26+click.echo(b'\xe2\x98\x83', nl=False)27+```28+29+Last but not least {func}`echo` uses click's intelligent internal output streams to stdout and stderr which support30+unicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicode31+characters (there are some limitations on the default font with regards to which characters can be displayed).32+33+```{versionadded} 6.034+```35+36+Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more37+information see {doc}`wincmd`.38+39+```{versionadded} 3.040+```41+42+You can also easily print to standard error by passing `err=True`:43+44+```python45+click.echo('Hello World!', err=True)46+```47+48+(ansi-colors)=49+50+## ANSI Colors51+52+```{versionadded} 2.053+```54+55+The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/).56+57+Primarily this means that:58+59+- Click's {func}`echo` function will automatically strip ANSI color codes if the stream is not connected to a terminal.60+- the {func}`echo` function will transparently connect to the terminal on Windows and translate ANSI codes to terminal61+ API calls. This means that colors will work on Windows the same way they do on other operating systems.62+63+On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not64+required for Click.65+66+For styling a string, the {func}`style` function can be used:67+68+```python69+import click70+71+click.echo(click.style('Hello World!', fg='green'))72+click.echo(click.style('Some more text', bg='blue', fg='white'))73+click.echo(click.style('ATTENTION', blink=True, bold=True))74+```75+76+The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:77+78+```python79+click.secho('Hello World!', fg='green')80+click.secho('Some more text', bg='blue', fg='white')81+click.secho('ATTENTION', blink=True, bold=True)82+```83+84+## Pager Support85+86+In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be87+achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always88+writes to stdout and, if possible, through a pager.89+90+Example:91+92+```python93+@click.command()94+def less():95+ click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))96+```97+98+If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,99+you can pass a generator (or generator function) instead of a string:100+101+```python102+def _generate_output():103+ for idx in range(50000):104+ yield f"Line {idx}\n"105+106+@click.command()107+def less():108+ click.echo_via_pager(_generate_output())109+```110+111+## Screen Clearing112+113+```{versionadded} 2.0114+```115+116+To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does117+what the name suggests: it clears the entire visible screen in a platform-agnostic way:118+119+```python120+import click121+click.clear()122+```123+124+## Getting Characters from Terminal125+126+```{versionadded} 2.0127+```128+129+Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and130+will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead131+read individual characters as they are being written.132+133+For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and134+returns it as a Unicode character.135+136+Note that this function will always read from the terminal, even if stdin is instead a pipe.137+138+Example:139+140+```python141+import click142+143+click.echo('Continue? [yn] ', nl=False)144+c = click.getchar()145+click.echo()146+if c == 'y':147+ click.echo('We will go on')148+elif c == 'n':149+ click.echo('Abort!')150+else:151+ click.echo('Invalid input :(')152+```153+154+Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape155+format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file156+exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that157+cannot be properly exited.158+159+## Waiting for Key Press160+161+```{versionadded} 2.0162+```163+164+Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows165+where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.166+167+In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the168+terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP169+(no operation instruction) if the script is not run interactively.170+171+Example:172+173+```python174+import click175+click.pause()176+```177+178+## Launching Editors179+180+```{versionadded} 2.0181+```182+183+Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line184+input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the185+editor without saving, the return value will be `None`, otherwise the entered text.186+187+Example usage:188+189+```python190+import click191+192+def get_commit_message():193+ MARKER = '# Everything below is ignored\n'194+ message = click.edit('\n\n' + MARKER)195+ if message is not None:196+ return message.split(MARKER, 1)[0].rstrip('\n')197+```198+199+Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the200+return value is always `None`.201+202+Example usage:203+204+```python205+import click206+click.edit(filename='/etc/passwd')207+```208+209+## Launching Applications210+211+```{versionadded} 2.0212+```213+214+Click supports launching applications through {func}`launch`. This can be used to open the default application215+associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition216+to this, it can also launch the file manager and automatically select the provided file.217+218+Example usage:219+220+```python221+click.launch("https://click.palletsprojects.com/")222+click.launch("/my/downloaded/file.txt", locate=True)223+```224+225+## Printing Filenames226+227+Because filenames might not be Unicode, formatting them can be a bit tricky.228+229+The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the230+filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode231+string.232+233+Example:234+235+```python236+click.echo(f"Path: {click.format_filename(b'foo.txt')}")237+```238+239+## Standard Streams240+241+For command line utilities, it's very important to get access to input and output streams reliably. Python generally242+provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between243+2.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.244+245+Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce246+consistent results with different Python versions and for a wide variety of terminal configurations.247+248+The end result is that these functions will always return a functional stream object (except in very odd cases; see249+{doc}`/unicode-support`).250+251+Example:252+253+```python254+import click255+256+stdin_text = click.get_text_stream('stdin')257+stdout_binary = click.get_binary_stream('stdout')258+```259+260+```{versionadded} 6.0261+```262+263+Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more264+information see {doc}`wincmd`.265+266+## Intelligent File Opening267+268+```{versionadded} 3.0269+```270+271+Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`272+function. It can intelligently open stdin/stdout as well as any other file.273+274+Example:275+276+```python277+import click278+279+stdout = click.open_file('-', 'w')280+test_file = click.open_file('test.txt', 'w')281+```282+283+If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent284+the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:285+286+```python287+with click.open_file(filename, 'w') as f:288+ f.write('Hello World!\n')289+```290+291+## Finding Application Folders292+293+```{versionadded} 2.0294+```295+296+Very often, you want to open a configuration file that belongs to your application. However, different operating systems297+store these configuration files in different locations depending on their standards. Click provides a298+{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application299+depending on the OS.300+301+Example usage:302+303+```python304+import os305+import click306+import ConfigParser307+308+APP_NAME = 'My Application'309+def read_config():310+cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')311+parser = ConfigParser.RawConfigParser()312+parser.read([cfg])313+rv = {}314+for section in parser.sections():315+ for key, value in parser.items(section):316+ rv[f"{section}.{key}"] = value317+return rv318+```319+320+## Showing Progress Bars321+322+Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some323+progress about how long that will take. Click supports simple progress bar rendering for that through the324+{func}`progressbar` function.325+326+```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).327+```328+329+The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the330+iterable it might take some time to do processing. So say you have a loop like this:331+332+```python333+for user in all_the_users_to_process:334+ modify_the_user(user)335+```336+337+To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:338+339+```python340+import click341+342+with click.progressbar(all_the_users_to_process) as bar:343+ for user in bar:344+ modify_the_user(user)345+```346+347+Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The348+calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the349+length, you can explicitly provide it:350+351+```python352+with click.progressbar(all_the_users_to_process,353+ length=number_of_users) as bar:354+ for user in bar:355+ modify_the_user(user)356+```357+358+Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render359+correctly:360+361+```python362+import time363+364+with click.progressbar([1, 2, 3]) as bar:365+ for x in bar:366+ print(f"sleep({x})...")367+ time.sleep(x)368+```369+370+Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:371+372+```python373+with click.progressbar(all_the_users_to_process,374+ label='Modifying user accounts',375+ length=number_of_users) as bar:376+ for user in bar:377+ modify_the_user(user)378+```379+380+Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you381+need to specify the length (and no iterable), and use the update method on the context return value instead of iterating382+directly over it:383+384+```python385+with click.progressbar(length=total_size,386+ label='Unzipping archive') as bar:387+ for archive in zip_file:388+ archive.extract()389+ bar.update(archive.size)390+```deleted:docs/utils.rst-408 removed
1-Utilities2-=========3-4-.. currentmodule:: click5-6-Besides the functionality that Click provides to interface with argument7-parsing and handling, it also provides a bunch of addon functionality that8-is useful for writing command line utilities.9-10-11-Printing to Stdout12-------------------13-14-The most obvious helper is the :func:`echo` function, which in many ways15-works like the Python ``print`` statement or function. The main difference is16-that it works the same in many different terminal environments.17-18-Example::19-20- import click21-22- click.echo('Hello World!')23-24-It can output both text and binary data. It will emit a trailing newline25-by default, which needs to be suppressed by passing ``nl=False``::26-27- click.echo(b'\xe2\x98\x83', nl=False)28-29-Last but not least :func:`echo` uses click's intelligent internal output30-streams to stdout and stderr which support unicode output on the Windows31-console. This means for as long as you are using `click.echo` you can32-output unicode characters (there are some limitations on the default font33-with regards to which characters can be displayed).34-35-.. versionadded:: 6.036-37-Click emulates output streams on Windows to support unicode to the38-Windows console through separate APIs. For more information see39-:doc:`wincmd`.40-41-.. versionadded:: 3.042-43-You can also easily print to standard error by passing ``err=True``::44-45- click.echo('Hello World!', err=True)46-47-48-.. _ansi-colors:49-50-ANSI Colors51------------52-53-.. versionadded:: 2.054-55-The :func:`echo` function supports ANSI colors and styles. On Windows56-this uses `colorama`_.57-58-Primarily this means that:59-60-- Click's :func:`echo` function will automatically strip ANSI color codes61- if the stream is not connected to a terminal.62-- the :func:`echo` function will transparently connect to the terminal on63- Windows and translate ANSI codes to terminal API calls. This means64- that colors will work on Windows the same way they do on other65- operating systems.66-67-On Windows, Click uses colorama without calling ``colorama.init()``. You68-can still call that in your code, but it's not required for Click.69-70-For styling a string, the :func:`style` function can be used::71-72- import click73-74- click.echo(click.style('Hello World!', fg='green'))75- click.echo(click.style('Some more text', bg='blue', fg='white'))76- click.echo(click.style('ATTENTION', blink=True, bold=True))77-78-The combination of :func:`echo` and :func:`style` is also available in79-a single function called :func:`secho`::80-81- click.secho('Hello World!', fg='green')82- click.secho('Some more text', bg='blue', fg='white')83- click.secho('ATTENTION', blink=True, bold=True)84-85-86-.. _colorama: https://pypi.org/project/colorama/87-88-Pager Support89--------------90-91-In some situations, you might want to show long texts on the terminal and92-let a user scroll through it. This can be achieved by using the93-:func:`echo_via_pager` function which works similarly to the :func:`echo`94-function, but always writes to stdout and, if possible, through a pager.95-96-Example:97-98-.. click:example::99-100- @click.command()101- def less():102- click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))103-104-If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:105-106-.. click:example::107- def _generate_output():108- for idx in range(50000):109- yield f"Line {idx}\n"110-111- @click.command()112- def less():113- click.echo_via_pager(_generate_output())114-115-116-Screen Clearing117----------------118-119-.. versionadded:: 2.0120-121-To clear the terminal screen, you can use the :func:`clear` function that122-is provided starting with Click 2.0. It does what the name suggests: it123-clears the entire visible screen in a platform-agnostic way:124-125-::126-127- import click128- click.clear()129-130-131-Getting Characters from Terminal132---------------------------------133-134-.. versionadded:: 2.0135-136-Normally, when reading input from the terminal, you would read from137-standard input. However, this is buffered input and will not show up until138-the line has been terminated. In certain circumstances, you might not want139-to do that and instead read individual characters as they are being written.140-141-For this, Click provides the :func:`getchar` function which reads a single142-character from the terminal buffer and returns it as a Unicode character.143-144-Note that this function will always read from the terminal, even if stdin145-is instead a pipe.146-147-Example::148-149- import click150-151- click.echo('Continue? [yn] ', nl=False)152- c = click.getchar()153- click.echo()154- if c == 'y':155- click.echo('We will go on')156- elif c == 'n':157- click.echo('Abort!')158- else:159- click.echo('Invalid input :(')160-161-Note that this reads raw input, which means that things like arrow keys162-will show up in the platform's native escape format. The only characters163-translated are ``^C`` and ``^D`` which are converted into keyboard164-interrupts and end of file exceptions respectively. This is done because165-otherwise, it's too easy to forget about that and to create scripts that166-cannot be properly exited.167-168-169-Waiting for Key Press170----------------------171-172-.. versionadded:: 2.0173-174-Sometimes, it's useful to pause until the user presses any key on the175-keyboard. This is especially useful on Windows where ``cmd.exe`` will176-close the window at the end of the command execution by default, instead177-of waiting.178-179-In click, this can be accomplished with the :func:`pause` function. This180-function will print a quick message to the terminal (which can be181-customized) and wait for the user to press a key. In addition to that,182-it will also become a NOP (no operation instruction) if the script is not183-run interactively.184-185-Example::186-187- import click188- click.pause()189-190-191-Launching Editors192------------------193-194-.. versionadded:: 2.0195-196-Click supports launching editors automatically through :func:`edit`. This197-is very useful for asking users for multi-line input. It will198-automatically open the user's defined editor or fall back to a sensible199-default. If the user closes the editor without saving, the return value200-will be ``None``, otherwise the entered text.201-202-Example usage::203-204- import click205-206- def get_commit_message():207- MARKER = '# Everything below is ignored\n'208- message = click.edit('\n\n' + MARKER)209- if message is not None:210- return message.split(MARKER, 1)[0].rstrip('\n')211-212-Alternatively, the function can also be used to launch editors for files by213-a specific filename. In this case, the return value is always `None`.214-215-Example usage::216-217- import click218- click.edit(filename='/etc/passwd')219-220-221-Launching Applications222-----------------------223-224-.. versionadded:: 2.0225-226-Click supports launching applications through :func:`launch`. This can be227-used to open the default application associated with a URL or filetype.228-This can be used to launch web browsers or picture viewers, for instance.229-In addition to this, it can also launch the file manager and automatically230-select the provided file.231-232-Example usage::233-234- click.launch("https://click.palletsprojects.com/")235- click.launch("/my/downloaded/file.txt", locate=True)236-237-238-Printing Filenames239-------------------240-241-Because filenames might not be Unicode, formatting them can be a bit242-tricky.243-244-The way this works with click is through the :func:`format_filename`245-function. It does a best-effort conversion of the filename to Unicode and246-will never fail. This makes it possible to use these filenames in the247-context of a full Unicode string.248-249-Example::250-251- click.echo(f"Path: {click.format_filename(b'foo.txt')}")252-253-254-Standard Streams255-----------------256-257-For command line utilities, it's very important to get access to input and258-output streams reliably. Python generally provides access to these259-streams through ``sys.stdout`` and friends, but unfortunately, there are260-API differences between 2.x and 3.x, especially with regards to how these261-streams respond to Unicode and binary data.262-263-Because of this, click provides the :func:`get_binary_stream` and264-:func:`get_text_stream` functions, which produce consistent results with265-different Python versions and for a wide variety of terminal configurations.266-267-The end result is that these functions will always return a functional268-stream object (except in very odd cases; see :doc:`/unicode-support`).269-270-Example::271-272- import click273-274- stdin_text = click.get_text_stream('stdin')275- stdout_binary = click.get_binary_stream('stdout')276-277-.. versionadded:: 6.0278-279-Click now emulates output streams on Windows to support unicode to the280-Windows console through separate APIs. For more information see281-:doc:`wincmd`.282-283-284-Intelligent File Opening285-------------------------286-287-.. versionadded:: 3.0288-289-Starting with Click 3.0 the logic for opening files from the :class:`File`290-type is exposed through the :func:`open_file` function. It can291-intelligently open stdin/stdout as well as any other file.292-293-Example::294-295- import click296-297- stdout = click.open_file('-', 'w')298- test_file = click.open_file('test.txt', 'w')299-300-If stdin or stdout are returned, the return value is wrapped in a special301-file where the context manager will prevent the closing of the file. This302-makes the handling of standard streams transparent and you can always use303-it like this::304-305- with click.open_file(filename, 'w') as f:306- f.write('Hello World!\n')307-308-309-Finding Application Folders310----------------------------311-312-.. versionadded:: 2.0313-314-Very often, you want to open a configuration file that belongs to your315-application. However, different operating systems store these configuration316-files in different locations depending on their standards. Click provides317-a :func:`get_app_dir` function which returns the most appropriate location318-for per-user config files for your application depending on the OS.319-320-Example usage::321-322- import os323- import click324- import ConfigParser325-326- APP_NAME = 'My Application'327-328- def read_config():329- cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')330- parser = ConfigParser.RawConfigParser()331- parser.read([cfg])332- rv = {}333- for section in parser.sections():334- for key, value in parser.items(section):335- rv[f"{section}.{key}"] = value336- return rv337-338-339-Showing Progress Bars340----------------------341-342-Sometimes, you have command line scripts that need to process a lot of data,343-but you want to quickly show the user some progress about how long that344-will take. Click supports simple progress bar rendering for that through345-the :func:`progressbar` function.346-347-.. note::348-349- If you find that you have requirements beyond what Click's progress350- bar supports, try using `tqdm`_.351-352- .. _tqdm: https://tqdm.github.io/353-354-The basic usage is very simple: the idea is that you have an iterable that355-you want to operate on. For each item in the iterable it might take some356-time to do processing. So say you have a loop like this::357-358- for user in all_the_users_to_process:359- modify_the_user(user)360-361-To hook this up with an automatically updating progress bar, all you need362-to do is to change the code to this::363-364- import click365-366- with click.progressbar(all_the_users_to_process) as bar:367- for user in bar:368- modify_the_user(user)369-370-Click will then automatically print a progress bar to the terminal and371-calculate the remaining time for you. The calculation of remaining time372-requires that the iterable has a length. If it does not have a length373-but you know the length, you can explicitly provide it::374-375- with click.progressbar(all_the_users_to_process,376- length=number_of_users) as bar:377- for user in bar:378- modify_the_user(user)379-380-Note that :func:`progressbar` updates the bar *after* each iteration of the381-loop. So code like this will render correctly::382-383- import time384-385- with click.progressbar([1, 2, 3]) as bar:386- for x in bar:387- print(f"sleep({x})...")388- time.sleep(x)389-390-Another useful feature is to associate a label with the progress bar which391-will be shown preceding the progress bar::392-393- with click.progressbar(all_the_users_to_process,394- label='Modifying user accounts',395- length=number_of_users) as bar:396- for user in bar:397- modify_the_user(user)398-399-Sometimes, one may need to iterate over an external iterator, and advance the400-progress bar irregularly. To do so, you need to specify the length (and no401-iterable), and use the update method on the context return value instead of402-iterating directly over it::403-404- with click.progressbar(length=total_size,405- label='Unzipping archive') as bar:406- for archive in zip_file:407- archive.extract()408- bar.update(archive.size)