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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390# Utilities
```{currentmodule} click```
Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunchof addon functionality that is useful for writing command line utilities.
## Printing to Stdout
The most obvious helper is the {func}`echo` function, which in many ways works like the Python `print` statement orfunction. The main difference is that it works the same in many different terminal environments.
Example:
```pythonimport click
click.echo('Hello World!')```
It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed bypassing `nl=False`:
```pythonclick.echo(b'\xe2\x98\x83', nl=False)```
Last but not least {func}`echo` uses click's intelligent internal output streams to stdout and stderr which supportunicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicodecharacters (there are some limitations on the default font with regards to which characters can be displayed).
```{versionadded} 6.0```
Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For moreinformation see {doc}`wincmd`.
```{versionadded} 3.0```
You can also easily print to standard error by passing `err=True`:
```pythonclick.echo('Hello World!', err=True)```
(ansi-colors)=
## ANSI Colors
```{versionadded} 2.0```
The {func}`echo` function supports ANSI colors and styles. It willautomatically strip ANSI color codes if the stream is not connected to aterminal.
```{admonition} Older Windows Support:class: note
Recent versions of Windows 11 support ANSI styling by default, in bothWindows Terminal and cmd.exe. If you need to support color output on olderversions of Windows, install[colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.```
For styling a string, the {func}`style` function can be used:
```pythonimport click
click.echo(click.style('Hello World!', fg='green'))click.echo(click.style('Some more text', bg='blue', fg='white'))click.echo(click.style('ATTENTION', blink=True, bold=True))```
The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:
```pythonclick.secho('Hello World!', fg='green')click.secho('Some more text', bg='blue', fg='white')click.secho('ATTENTION', blink=True, bold=True)```
## Pager Support
In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can beachieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but alwayswrites to stdout and, if possible, through a pager.
Example:
```{eval-rst}.. click:example:: @click.command() def less(): click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))```
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:
```{eval-rst}.. click:example:: def _generate_output(): for idx in range(50000): yield f"Line {idx}\n"
@click.command() def less(): click.echo_via_pager(_generate_output())```
For more complex programs, which can't easily use a simple generator, youcan get access to a writable file-like object for the pager, and write tothat instead:
```{eval-rst}.. click:example:: @click.command() def less(): with click.get_pager_file() as pager: for idx in range(50000): print(idx, file=pager)```
```{admonition} Why print() instead of echo()?:class: hint
The pager object deals with ANSI color and style codes itself: they are kept orstripped depending on what the pager supports, exactly as {func}`echo` would do.Any code that writes to a file, including plain {func}`print`, can therefore beused with it.```
## Screen Clearing
```{versionadded} 2.0```
To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It doeswhat the name suggests: it clears the entire visible screen in a platform-agnostic way:
```pythonimport clickclick.clear()```
## Getting Characters from Terminal
```{versionadded} 2.0```
Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input andwill not show up until the line has been terminated. In certain circumstances, you might not want to do that and insteadread individual characters as they are being written.
For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer andreturns it as a Unicode character.
Note that this function will always read from the terminal, even if stdin is instead a pipe.
Example:
```pythonimport click
click.echo('Continue? [yn] ', nl=False)c = click.getchar()click.echo()if c == 'y': click.echo('We will go on')elif c == 'n': click.echo('Abort!')else: click.echo('Invalid input :(')```
Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escapeformat. The only characters translated are the ones produced by {kbd}`Ctrl+C` and {kbd}`Ctrl+D`, or {kbd}`Ctrl+Z` onWindows, which are converted into keyboard interrupts and end of file exceptions respectively. This is done becauseotherwise, it's too easy to forget about that and to create scripts that cannot be properly exited.
## Waiting for Key Press
```{versionadded} 2.0```
Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windowswhere `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.
In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to theterminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP(no operation instruction) if the script is not run interactively.
Example:
```pythonimport clickclick.pause()```
## Launching Editors
```{versionadded} 2.0```
Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-lineinput. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes theeditor without saving, the return value will be `None`, otherwise the entered text.
Example usage:
```pythonimport click
def get_commit_message(): MARKER = '# Everything below is ignored\n' message = click.edit('\n\n' + MARKER) if message is not None: return message.split(MARKER, 1)[0].rstrip('\n')```
Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, thereturn value is always `None`.
Example usage:
```pythonimport clickclick.edit(filename='/etc/passwd')```
## Launching Applications
```{versionadded} 2.0```
Click supports launching applications through {func}`launch`. This can be used to open the default applicationassociated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In additionto this, it can also launch the file manager and automatically select the provided file.
Example usage:
```pythonclick.launch("https://click.palletsprojects.com/")click.launch("/my/downloaded/file.txt", locate=True)```
## Printing Filenames
Because filenames might not be Unicode, formatting them can be a bit tricky.
The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of thefilename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicodestring.
Example:
```pythonclick.echo(f"Path: {click.format_filename(b'foo.txt')}")```
## Intelligent File Opening
```{versionadded} 3.0```
Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`function. It can intelligently open stdin/stdout as well as any other file.
Example:
```pythonimport click
stdout = click.open_file('-', 'w')test_file = click.open_file('test.txt', 'w')```
If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will preventthe closing of the file. This makes the handling of standard streams transparent and you can always use it like this:
```pythonwith click.open_file(filename, 'w') as f: f.write('Hello World!\n')```
## Finding Application Folders
```{versionadded} 2.0```
Very often, you want to open a configuration file that belongs to your application. However, different operating systemsstore these configuration files in different locations depending on their standards. Click provides a{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your applicationdepending on the OS.
Example usage:
```pythonimport osimport clickimport ConfigParser
APP_NAME = 'My Application'def read_config():cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')parser = ConfigParser.RawConfigParser()parser.read([cfg])rv = {}for section in parser.sections(): for key, value in parser.items(section): rv[f"{section}.{key}"] = valuereturn rv```
## Showing Progress Bars
Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user someprogress about how long that will take. Click supports simple progress bar rendering for that through the{func}`progressbar` function.
```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).```
The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in theiterable it might take some time to do processing. So say you have a loop like this:
```pythonfor user in all_the_users_to_process: modify_the_user(user)```
To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:
```pythonimport click
with click.progressbar(all_the_users_to_process) as bar: for user in bar: modify_the_user(user)```
Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. Thecalculation of remaining time requires that the iterable has a length. If it does not have a length but you know thelength, you can explicitly provide it:
```pythonwith click.progressbar(all_the_users_to_process, length=number_of_users) as bar: for user in bar: modify_the_user(user)```
Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will rendercorrectly:
```pythonimport time
with click.progressbar([1, 2, 3]) as bar: for x in bar: click.echo(f"sleep({x})...") time.sleep(x)```
Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:
```pythonwith click.progressbar(all_the_users_to_process, label='Modifying user accounts', length=number_of_users) as bar: for user in bar: modify_the_user(user)```
Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, youneed to specify the length (and no iterable), and use the update method on the context return value instead of iteratingdirectly over it:
```pythonwith click.progressbar(length=total_size, label='Unzipping archive') as bar: for archive in zip_file: archive.extract() bar.update(archive.size)```