utils.md
This file
Path
docs/utils.md
389 lines · 11.7 KiB · Markdown
Last changed by
Stable (#3851)Rowlando13before adoption6aabf09
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 back58Pre-8.5.0 release changelog and doc fixes (#3697)Rowlando13before adoption00e592c
line 59why, one step back59```{admonition} Older Windows Supportremove colorama (#3505)David Lordbefore adoption6a141c3
lines 60–61why, one step back60:class: note61Pre-8.5.0 release changelog and doc fixes (#3697)Rowlando13before adoption00e592c
lines 62–64why, one step back62Recent versions of Windows 11 support ANSI styling by default, in both63Windows Terminal and cmd.exe. If you need to support color output on older64versions of Windows, installremove colorama (#3505)David Lordbefore adoption6a141c3
line 65why, one step back65[colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.Pre-8.5.0 release changelog and doc fixes (#3697)Rowlando13before adoption00e592c
line 66why, one step back66```Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 67–93why, one step back6768For styling a string, the {func}`style` function can be used:6970```python71import click7273click.echo(click.style('Hello World!', fg='green'))74click.echo(click.style('Some more text', bg='blue', fg='white'))75click.echo(click.style('ATTENTION', blink=True, bold=True))76```7778The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:7980```python81click.secho('Hello World!', fg='green')82click.secho('Some more text', bg='blue', fg='white')83click.secho('ATTENTION', blink=True, bold=True)84```8586## Pager Support8788In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be89achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always90writes to stdout and, if possible, through a pager.9192Example:93Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 94–98why, one step back94```{eval-rst}95.. click:example::96 @click.command()97 def less():98 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 99–103why, one step back99```100101If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,102you can pass a generator (or generator function) instead of a string:103Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 104–108why, one step back104```{eval-rst}105.. click:example::106 def _generate_output():107 for idx in range(50000):108 yield f"Line {idx}\n"Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
line 109why, one step back109Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 110–112why, one step back110 @click.command()111 def less():112 click.echo_via_pager(_generate_output())Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 113–114why, one step back113```114Add file-like pager: `click.get_pager_file()` (#1572)Craig de Stigterbefore adoptionc69643b
lines 115–127why, one step back115For more complex programs, which can't easily use a simple generator, you116can get access to a writable file-like object for the pager, and write to117that instead:118119```{eval-rst}120.. click:example::121 @click.command()122 def less():123 with click.get_pager_file() as pager:124 for idx in range(50000):125 print(idx, file=pager)126```127Pre-8.5.0 release changelog and doc fixes (#3697)Rowlando13before adoption00e592c
lines 128–130why, one step back128```{admonition} Why print() instead of echo()?129:class: hint130Add `@custom_version_option`, freeze `@version_option` (#3581)Rowlando13before adoption94c191c
lines 131–136why, one step back131The pager object deals with ANSI color and style codes itself: they are kept or132stripped depending on what the pager supports, exactly as {func}`echo` would do.133Any code that writes to a file, including plain {func}`print`, can therefore be134used with it.135```136Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 137–180why, one step back137## Screen Clearing138139```{versionadded} 2.0140```141142To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does143what the name suggests: it clears the entire visible screen in a platform-agnostic way:144145```python146import click147click.clear()148```149150## Getting Characters from Terminal151152```{versionadded} 2.0153```154155Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and156will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead157read individual characters as they are being written.158159For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and160returns it as a Unicode character.161162Note that this function will always read from the terminal, even if stdin is instead a pipe.163164Example:165166```python167import click168169click.echo('Continue? [yn] ', nl=False)170c = click.getchar()171click.echo()172if c == 'y':173 click.echo('We will go on')174elif c == 'n':175 click.echo('Abort!')176else:177 click.echo('Invalid input :(')178```179180Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escapeStable (#3851)Rowlando13before adoption6aabf09
lines 181–183why, one step back181format. The only characters translated are the ones produced by {kbd}`Ctrl+C` and {kbd}`Ctrl+D`, or {kbd}`Ctrl+Z` on182Windows, which are converted into keyboard interrupts and end of file exceptions respectively. This is done because183otherwise, it's too easy to forget about that and to create scripts that cannot be properly exited.Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 184–364why, one step back184185## Waiting for Key Press186187```{versionadded} 2.0188```189190Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows191where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.192193In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the194terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP195(no operation instruction) if the script is not run interactively.196197Example:198199```python200import click201click.pause()202```203204## Launching Editors205206```{versionadded} 2.0207```208209Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line210input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the211editor without saving, the return value will be `None`, otherwise the entered text.212213Example usage:214215```python216import click217218def get_commit_message():219 MARKER = '# Everything below is ignored\n'220 message = click.edit('\n\n' + MARKER)221 if message is not None:222 return message.split(MARKER, 1)[0].rstrip('\n')223```224225Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the226return value is always `None`.227228Example usage:229230```python231import click232click.edit(filename='/etc/passwd')233```234235## Launching Applications236237```{versionadded} 2.0238```239240Click supports launching applications through {func}`launch`. This can be used to open the default application241associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition242to this, it can also launch the file manager and automatically select the provided file.243244Example usage:245246```python247click.launch("https://click.palletsprojects.com/")248click.launch("/my/downloaded/file.txt", locate=True)249```250251## Printing Filenames252253Because filenames might not be Unicode, formatting them can be a bit tricky.254255The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the256filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode257string.258259Example:260261```python262click.echo(f"Path: {click.format_filename(b'foo.txt')}")263```264265## Intelligent File Opening266267```{versionadded} 3.0268```269270Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`271function. It can intelligently open stdin/stdout as well as any other file.272273Example:274275```python276import click277278stdout = click.open_file('-', 'w')279test_file = click.open_file('test.txt', 'w')280```281282If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent283the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:284285```python286with click.open_file(filename, 'w') as f:287 f.write('Hello World!\n')288```289290## Finding Application Folders291292```{versionadded} 2.0293```294295Very often, you want to open a configuration file that belongs to your application. However, different operating systems296store these configuration files in different locations depending on their standards. Click provides a297{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application298depending on the OS.299300Example usage:301302```python303import os304import click305import ConfigParser306307APP_NAME = 'My Application'308def read_config():309cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')310parser = ConfigParser.RawConfigParser()311parser.read([cfg])312rv = {}313for section in parser.sections():314 for key, value in parser.items(section):315 rv[f"{section}.{key}"] = value316return rv317```318319## Showing Progress Bars320321Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some322progress about how long that will take. Click supports simple progress bar rendering for that through the323{func}`progressbar` function.324325```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).326```327328The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the329iterable it might take some time to do processing. So say you have a loop like this:330331```python332for user in all_the_users_to_process:333 modify_the_user(user)334```335336To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:337338```python339import click340341with click.progressbar(all_the_users_to_process) as bar:342 for user in bar:343 modify_the_user(user)344```345346Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The347calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the348length, you can explicitly provide it:349350```python351with click.progressbar(all_the_users_to_process,352 length=number_of_users) as bar:353 for user in bar:354 modify_the_user(user)355```356357Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render358correctly:359360```python361import time362363with click.progressbar([1, 2, 3]) as bar:364 for x in bar:Add `@custom_version_option`, freeze `@version_option` (#3581)Rowlando13before adoption94c191c
line 365why, one step back365 click.echo(f"sleep({x})...")Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 366–389why, one step back366 time.sleep(x)367```368369Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:370371```python372with click.progressbar(all_the_users_to_process,373 label='Modifying user accounts',374 length=number_of_users) as bar:375 for user in bar:376 modify_the_user(user)377```378379Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you380need to specify the length (and no iterable), and use the update method on the context return value instead of iterating381directly over it:382383```python384with click.progressbar(length=total_size,385 label='Unzipping archive') as bar:386 for archive in zip_file:387 archive.extract()388 bar.update(archive.size)389```