utils.md
This file
Path
docs/utils.md
410 lines · 12.6 KiB · Markdown
Last changed by
remove colorama (#3505)David Lordbefore adoption6a141c3
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```54remove colorama (#3505)David Lordbefore adoption6a141c3
line 55why, one step back55The {func}`echo` function supports ANSI colors and styles.Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 56–62why, one step back5657Primarily 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.62remove colorama (#3505)David Lordbefore adoption6a141c3
lines 63–69why, one step back63:::{admonition} Older Windows Support64:class: note6566Recent Windows 11 supports ANSI styling by default, in both Terminal and cmd.exe.67If you need to support color output on older versions of Windows, install68[colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.69:::Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 70–96why, one step back7071For styling a string, the {func}`style` function can be used:7273```python74import click7576click.echo(click.style('Hello World!', fg='green'))77click.echo(click.style('Some more text', bg='blue', fg='white'))78click.echo(click.style('ATTENTION', blink=True, bold=True))79```8081The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:8283```python84click.secho('Hello World!', fg='green')85click.secho('Some more text', bg='blue', fg='white')86click.secho('ATTENTION', blink=True, bold=True)87```8889## Pager Support9091In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be92achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always93writes to stdout and, if possible, through a pager.9495Example:96Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 97–101why, one step back97```{eval-rst}98.. click:example::99 @click.command()100 def less():101 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 102–106why, one step back102```103104If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,105you can pass a generator (or generator function) instead of a string:106Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 107–111why, one step back107```{eval-rst}108.. click:example::109 def _generate_output():110 for idx in range(50000):111 yield f"Line {idx}\n"Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
line 112why, one step back112Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 113–115why, one step back113 @click.command()114 def less():115 click.echo_via_pager(_generate_output())Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 116–117why, one step back116```117Add file-like pager: `click.get_pager_file()` (#1572)Craig de Stigterbefore adoptionc69643b
lines 118–130why, one step back118For more complex programs, which can't easily use a simple generator, you119can get access to a writable file-like object for the pager, and write to120that instead:121122```{eval-rst}123.. click:example::124 @click.command()125 def less():126 with click.get_pager_file() as pager:127 for idx in range(50000):128 print(idx, file=pager)129```130Move Utils and Unicode-support docs from reST to MyST (#2960)Rowlando13before adoption86d6b6b
lines 131–410why, one step back131## Screen Clearing132133```{versionadded} 2.0134```135136To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does137what the name suggests: it clears the entire visible screen in a platform-agnostic way:138139```python140import click141click.clear()142```143144## Getting Characters from Terminal145146```{versionadded} 2.0147```148149Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and150will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead151read individual characters as they are being written.152153For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and154returns it as a Unicode character.155156Note that this function will always read from the terminal, even if stdin is instead a pipe.157158Example:159160```python161import click162163click.echo('Continue? [yn] ', nl=False)164c = click.getchar()165click.echo()166if c == 'y':167 click.echo('We will go on')168elif c == 'n':169 click.echo('Abort!')170else:171 click.echo('Invalid input :(')172```173174Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape175format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file176exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that177cannot be properly exited.178179## Waiting for Key Press180181```{versionadded} 2.0182```183184Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows185where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.186187In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the188terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP189(no operation instruction) if the script is not run interactively.190191Example:192193```python194import click195click.pause()196```197198## Launching Editors199200```{versionadded} 2.0201```202203Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line204input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the205editor without saving, the return value will be `None`, otherwise the entered text.206207Example usage:208209```python210import click211212def get_commit_message():213 MARKER = '# Everything below is ignored\n'214 message = click.edit('\n\n' + MARKER)215 if message is not None:216 return message.split(MARKER, 1)[0].rstrip('\n')217```218219Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the220return value is always `None`.221222Example usage:223224```python225import click226click.edit(filename='/etc/passwd')227```228229## Launching Applications230231```{versionadded} 2.0232```233234Click supports launching applications through {func}`launch`. This can be used to open the default application235associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition236to this, it can also launch the file manager and automatically select the provided file.237238Example usage:239240```python241click.launch("https://click.palletsprojects.com/")242click.launch("/my/downloaded/file.txt", locate=True)243```244245## Printing Filenames246247Because filenames might not be Unicode, formatting them can be a bit tricky.248249The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the250filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode251string.252253Example:254255```python256click.echo(f"Path: {click.format_filename(b'foo.txt')}")257```258259## Standard Streams260261For command line utilities, it's very important to get access to input and output streams reliably. Python generally262provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between2632.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.264265Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce266consistent results with different Python versions and for a wide variety of terminal configurations.267268The end result is that these functions will always return a functional stream object (except in very odd cases; see269{doc}`/unicode-support`).270271Example:272273```python274import click275276stdin_text = click.get_text_stream('stdin')277stdout_binary = click.get_binary_stream('stdout')278```279280```{versionadded} 6.0281```282283Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more284information see {doc}`wincmd`.285286## Intelligent File Opening287288```{versionadded} 3.0289```290291Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`292function. It can intelligently open stdin/stdout as well as any other file.293294Example:295296```python297import click298299stdout = click.open_file('-', 'w')300test_file = click.open_file('test.txt', 'w')301```302303If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent304the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:305306```python307with click.open_file(filename, 'w') as f:308 f.write('Hello World!\n')309```310311## Finding Application Folders312313```{versionadded} 2.0314```315316Very often, you want to open a configuration file that belongs to your application. However, different operating systems317store these configuration files in different locations depending on their standards. Click provides a318{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application319depending on the OS.320321Example usage:322323```python324import os325import click326import ConfigParser327328APP_NAME = 'My Application'329def read_config():330cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')331parser = ConfigParser.RawConfigParser()332parser.read([cfg])333rv = {}334for section in parser.sections():335 for key, value in parser.items(section):336 rv[f"{section}.{key}"] = value337return rv338```339340## Showing Progress Bars341342Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some343progress about how long that will take. Click supports simple progress bar rendering for that through the344{func}`progressbar` function.345346```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).347```348349The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the350iterable it might take some time to do processing. So say you have a loop like this:351352```python353for user in all_the_users_to_process:354 modify_the_user(user)355```356357To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:358359```python360import click361362with click.progressbar(all_the_users_to_process) as bar:363 for user in bar:364 modify_the_user(user)365```366367Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The368calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the369length, you can explicitly provide it:370371```python372with click.progressbar(all_the_users_to_process,373 length=number_of_users) as bar:374 for user in bar:375 modify_the_user(user)376```377378Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render379correctly:380381```python382import time383384with click.progressbar([1, 2, 3]) as bar:385 for x in bar:386 print(f"sleep({x})...")387 time.sleep(x)388```389390Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:391392```python393with 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```399400Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you401need to specify the length (and no iterable), and use the update method on the context return value instead of iterating402directly over it:403404```python405with click.progressbar(length=total_size,406 label='Unzipping archive') as bar:407 for archive in zip_file:408 archive.extract()409 bar.update(archive.size)410```