utils.md
This file
Path
docs/utils.md
405 lines · 12.5 KiB · Markdown
Last changed by
Add file-like pager: `click.get_pager_file()` (#1572)Craig de Stigterbefore adoptionc69643b
History of this fileTake it
Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 1–91why, 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```5455The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/).5657Primarily this means that:5859- 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.6263On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not64required for Click.6566For styling a string, the {func}`style` function can be used:6768```python69import click7071click.echo(click.style('Hello World!', fg='green'))72click.echo(click.style('Some more text', bg='blue', fg='white'))73click.echo(click.style('ATTENTION', blink=True, bold=True))74```7576The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:7778```python79click.secho('Hello World!', fg='green')80click.secho('Some more text', bg='blue', fg='white')81click.secho('ATTENTION', blink=True, bold=True)82```8384## Pager Support8586In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be87achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always88writes to stdout and, if possible, through a pager.8990Example:91Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 92–96why, one step back92```{eval-rst}93.. click:example::94 @click.command()95 def less():96 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 97–101why, one step back97```9899If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,100you can pass a generator (or generator function) instead of a string:101Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 102–106why, one step back102```{eval-rst}103.. click:example::104 def _generate_output():105 for idx in range(50000):106 yield f"Line {idx}\n"Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
line 107why, one step back107Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 108–110why, one step back108 @click.command()109 def less():110 click.echo_via_pager(_generate_output())Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 111–112why, one step back111```112Add file-like pager: `click.get_pager_file()` (#1572)Craig de Stigterbefore adoptionc69643b
lines 113–125why, one step back113For more complex programs, which can't easily use a simple generator, you114can get access to a writable file-like object for the pager, and write to115that instead:116117```{eval-rst}118.. click:example::119 @click.command()120 def less():121 with click.get_pager_file() as pager:122 for idx in range(50000):123 print(idx, file=pager)124```125Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 126–405why, one step back126## Screen Clearing127128```{versionadded} 2.0129```130131To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does132what the name suggests: it clears the entire visible screen in a platform-agnostic way:133134```python135import click136click.clear()137```138139## Getting Characters from Terminal140141```{versionadded} 2.0142```143144Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and145will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead146read individual characters as they are being written.147148For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and149returns it as a Unicode character.150151Note that this function will always read from the terminal, even if stdin is instead a pipe.152153Example:154155```python156import click157158click.echo('Continue? [yn] ', nl=False)159c = click.getchar()160click.echo()161if c == 'y':162 click.echo('We will go on')163elif c == 'n':164 click.echo('Abort!')165else:166 click.echo('Invalid input :(')167```168169Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape170format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file171exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that172cannot be properly exited.173174## Waiting for Key Press175176```{versionadded} 2.0177```178179Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows180where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.181182In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the183terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP184(no operation instruction) if the script is not run interactively.185186Example:187188```python189import click190click.pause()191```192193## Launching Editors194195```{versionadded} 2.0196```197198Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line199input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the200editor without saving, the return value will be `None`, otherwise the entered text.201202Example usage:203204```python205import click206207def get_commit_message():208 MARKER = '# Everything below is ignored\n'209 message = click.edit('\n\n' + MARKER)210 if message is not None:211 return message.split(MARKER, 1)[0].rstrip('\n')212```213214Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the215return value is always `None`.216217Example usage:218219```python220import click221click.edit(filename='/etc/passwd')222```223224## Launching Applications225226```{versionadded} 2.0227```228229Click supports launching applications through {func}`launch`. This can be used to open the default application230associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition231to this, it can also launch the file manager and automatically select the provided file.232233Example usage:234235```python236click.launch("https://click.palletsprojects.com/")237click.launch("/my/downloaded/file.txt", locate=True)238```239240## Printing Filenames241242Because filenames might not be Unicode, formatting them can be a bit tricky.243244The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the245filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode246string.247248Example:249250```python251click.echo(f"Path: {click.format_filename(b'foo.txt')}")252```253254## Standard Streams255256For command line utilities, it's very important to get access to input and output streams reliably. Python generally257provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between2582.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.259260Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce261consistent results with different Python versions and for a wide variety of terminal configurations.262263The end result is that these functions will always return a functional stream object (except in very odd cases; see264{doc}`/unicode-support`).265266Example:267268```python269import click270271stdin_text = click.get_text_stream('stdin')272stdout_binary = click.get_binary_stream('stdout')273```274275```{versionadded} 6.0276```277278Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more279information see {doc}`wincmd`.280281## Intelligent File Opening282283```{versionadded} 3.0284```285286Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`287function. It can intelligently open stdin/stdout as well as any other file.288289Example:290291```python292import click293294stdout = click.open_file('-', 'w')295test_file = click.open_file('test.txt', 'w')296```297298If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent299the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:300301```python302with click.open_file(filename, 'w') as f:303 f.write('Hello World!\n')304```305306## Finding Application Folders307308```{versionadded} 2.0309```310311Very often, you want to open a configuration file that belongs to your application. However, different operating systems312store these configuration files in different locations depending on their standards. Click provides a313{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application314depending on the OS.315316Example usage:317318```python319import os320import click321import ConfigParser322323APP_NAME = 'My Application'324def read_config():325cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')326parser = ConfigParser.RawConfigParser()327parser.read([cfg])328rv = {}329for section in parser.sections():330 for key, value in parser.items(section):331 rv[f"{section}.{key}"] = value332return rv333```334335## Showing Progress Bars336337Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some338progress about how long that will take. Click supports simple progress bar rendering for that through the339{func}`progressbar` function.340341```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).342```343344The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the345iterable it might take some time to do processing. So say you have a loop like this:346347```python348for user in all_the_users_to_process:349 modify_the_user(user)350```351352To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:353354```python355import click356357with click.progressbar(all_the_users_to_process) as bar:358 for user in bar:359 modify_the_user(user)360```361362Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The363calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the364length, you can explicitly provide it:365366```python367with click.progressbar(all_the_users_to_process,368 length=number_of_users) as bar:369 for user in bar:370 modify_the_user(user)371```372373Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render374correctly:375376```python377import time378379with click.progressbar([1, 2, 3]) as bar:380 for x in bar:381 print(f"sleep({x})...")382 time.sleep(x)383```384385Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:386387```python388with click.progressbar(all_the_users_to_process,389 label='Modifying user accounts',390 length=number_of_users) as bar:391 for user in bar:392 modify_the_user(user)393```394395Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you396need to specify the length (and no iterable), and use the update method on the context return value instead of iterating397directly over it:398399```python400with click.progressbar(length=total_size,401 label='Unzipping archive') as bar:402 for archive in zip_file:403 archive.extract()404 bar.update(archive.size)405```