utils.md
This file
Path
docs/utils.md
413 lines · 12.6 KiB · Markdown
Last changed by
Update documentation following Colorama removal (#3671)Rowlando13before adoptiona44e9f0
History of this fileTake it
Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 1–54why, one step back1# Utilities23```{currentmodule} click4```56Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunch7of addon functionality that is useful for writing command line utilities.89## Printing to Stdout1011The most obvious helper is the {func}`echo` function, which in many ways works like the Python `print` statement or12function. The main difference is that it works the same in many different terminal environments.1314Example:1516```python17import click1819click.echo('Hello World!')20```2122It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by23passing `nl=False`:2425```python26click.echo(b'\xe2\x98\x83', nl=False)27```2829Last but not least {func}`echo` uses click's intelligent internal output streams to stdout and stderr which support30unicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicode31characters (there are some limitations on the default font with regards to which characters can be displayed).3233```{versionadded} 6.034```3536Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more37information see {doc}`wincmd`.3839```{versionadded} 3.040```4142You can also easily print to standard error by passing `err=True`:4344```python45click.echo('Hello World!', err=True)46```4748(ansi-colors)=4950## ANSI Colors5152```{versionadded} 2.053```54Update documentation following Colorama removal (#3671)Rowlando13before adoptiona44e9f0
lines 55–57why, one step back55The {func}`echo` function supports ANSI colors and styles. It will56automatically strip ANSI color codes if the stream is not connected to a57terminal.Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
line 58why, one step back58remove colorama (#3505)David Lordbefore adoption6a141c3
lines 59–65why, one step back59:::{admonition} Older Windows Support60:class: note6162Recent Windows 11 supports ANSI styling by default, in both Terminal and cmd.exe.63If you need to support color output on older versions of Windows, install64[colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.65:::Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 66–92why, one step back6667For styling a string, the {func}`style` function can be used:6869```python70import click7172click.echo(click.style('Hello World!', fg='green'))73click.echo(click.style('Some more text', bg='blue', fg='white'))74click.echo(click.style('ATTENTION', blink=True, bold=True))75```7677The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:7879```python80click.secho('Hello World!', fg='green')81click.secho('Some more text', bg='blue', fg='white')82click.secho('ATTENTION', blink=True, bold=True)83```8485## Pager Support8687In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be88achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always89writes to stdout and, if possible, through a pager.9091Example:92Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 93–97why, one step back93```{eval-rst}94.. click:example::95 @click.command()96 def less():97 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 98–102why, one step back98```99100If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,101you can pass a generator (or generator function) instead of a string:102Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 103–107why, one step back103```{eval-rst}104.. click:example::105 def _generate_output():106 for idx in range(50000):107 yield f"Line {idx}\n"Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
line 108why, one step back108Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 109–111why, one step back109 @click.command()110 def less():111 click.echo_via_pager(_generate_output())Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 112–113why, one step back112```113Add file-like pager: `click.get_pager_file()` (#1572)Craig de Stigterbefore adoptionc69643b
lines 114–126why, one step back114For more complex programs, which can't easily use a simple generator, you115can get access to a writable file-like object for the pager, and write to116that instead:117118```{eval-rst}119.. click:example::120 @click.command()121 def less():122 with click.get_pager_file() as pager:123 for idx in range(50000):124 print(idx, file=pager)125```126Add `@custom_version_option`, freeze `@version_option` (#3581)Rowlando13before adoption94c191c
lines 127–133why, one step back127```{hint} Why print instead of echo?128The pager object deals with ANSI color and style codes itself: they are kept or129stripped depending on what the pager supports, exactly as {func}`echo` would do.130Any code that writes to a file, including plain {func}`print`, can therefore be131used with it.132```133Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 134–388why, one step back134## Screen Clearing135136```{versionadded} 2.0137```138139To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does140what the name suggests: it clears the entire visible screen in a platform-agnostic way:141142```python143import click144click.clear()145```146147## Getting Characters from Terminal148149```{versionadded} 2.0150```151152Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and153will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead154read individual characters as they are being written.155156For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and157returns it as a Unicode character.158159Note that this function will always read from the terminal, even if stdin is instead a pipe.160161Example:162163```python164import click165166click.echo('Continue? [yn] ', nl=False)167c = click.getchar()168click.echo()169if c == 'y':170 click.echo('We will go on')171elif c == 'n':172 click.echo('Abort!')173else:174 click.echo('Invalid input :(')175```176177Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape178format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file179exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that180cannot be properly exited.181182## Waiting for Key Press183184```{versionadded} 2.0185```186187Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows188where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.189190In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the191terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP192(no operation instruction) if the script is not run interactively.193194Example:195196```python197import click198click.pause()199```200201## Launching Editors202203```{versionadded} 2.0204```205206Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line207input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the208editor without saving, the return value will be `None`, otherwise the entered text.209210Example usage:211212```python213import click214215def get_commit_message():216 MARKER = '# Everything below is ignored\n'217 message = click.edit('\n\n' + MARKER)218 if message is not None:219 return message.split(MARKER, 1)[0].rstrip('\n')220```221222Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the223return value is always `None`.224225Example usage:226227```python228import click229click.edit(filename='/etc/passwd')230```231232## Launching Applications233234```{versionadded} 2.0235```236237Click supports launching applications through {func}`launch`. This can be used to open the default application238associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition239to this, it can also launch the file manager and automatically select the provided file.240241Example usage:242243```python244click.launch("https://click.palletsprojects.com/")245click.launch("/my/downloaded/file.txt", locate=True)246```247248## Printing Filenames249250Because filenames might not be Unicode, formatting them can be a bit tricky.251252The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the253filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode254string.255256Example:257258```python259click.echo(f"Path: {click.format_filename(b'foo.txt')}")260```261262## Standard Streams263264For command line utilities, it's very important to get access to input and output streams reliably. Python generally265provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between2662.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.267268Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce269consistent results with different Python versions and for a wide variety of terminal configurations.270271The end result is that these functions will always return a functional stream object (except in very odd cases; see272{doc}`/unicode-support`).273274Example:275276```python277import click278279stdin_text = click.get_text_stream('stdin')280stdout_binary = click.get_binary_stream('stdout')281```282283```{versionadded} 6.0284```285286Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more287information see {doc}`wincmd`.288289## Intelligent File Opening290291```{versionadded} 3.0292```293294Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`295function. It can intelligently open stdin/stdout as well as any other file.296297Example:298299```python300import click301302stdout = click.open_file('-', 'w')303test_file = click.open_file('test.txt', 'w')304```305306If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent307the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:308309```python310with click.open_file(filename, 'w') as f:311 f.write('Hello World!\n')312```313314## Finding Application Folders315316```{versionadded} 2.0317```318319Very often, you want to open a configuration file that belongs to your application. However, different operating systems320store these configuration files in different locations depending on their standards. Click provides a321{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application322depending on the OS.323324Example usage:325326```python327import os328import click329import ConfigParser330331APP_NAME = 'My Application'332def read_config():333cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')334parser = ConfigParser.RawConfigParser()335parser.read([cfg])336rv = {}337for section in parser.sections():338 for key, value in parser.items(section):339 rv[f"{section}.{key}"] = value340return rv341```342343## Showing Progress Bars344345Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some346progress about how long that will take. Click supports simple progress bar rendering for that through the347{func}`progressbar` function.348349```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).350```351352The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the353iterable it might take some time to do processing. So say you have a loop like this:354355```python356for user in all_the_users_to_process:357 modify_the_user(user)358```359360To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:361362```python363import click364365with click.progressbar(all_the_users_to_process) as bar:366 for user in bar:367 modify_the_user(user)368```369370Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The371calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the372length, you can explicitly provide it:373374```python375with 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```380381Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render382correctly:383384```python385import time386387with click.progressbar([1, 2, 3]) as bar:388 for x in bar:Add `@custom_version_option`, freeze `@version_option` (#3581)Rowlando13before adoption94c191c
line 389why, one step back389 click.echo(f"sleep({x})...")Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 390–413why, one step back390 time.sleep(x)391```392393Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:394395```python396with click.progressbar(all_the_users_to_process,397 label='Modifying user accounts',398 length=number_of_users) as bar:399 for user in bar:400 modify_the_user(user)401```402403Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you404need to specify the length (and no iterable), and use the update method on the context return value instead of iterating405directly over it:406407```python408with click.progressbar(length=total_size,409 label='Unzipping archive') as bar:410 for archive in zip_file:411 archive.extract()412 bar.update(archive.size)413```