| 1 |
# Utilities |
| 2 |
|
| 3 |
```{currentmodule} click |
| 4 |
``` |
| 5 |
|
| 6 |
Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunch |
| 7 |
of addon functionality that is useful for writing command line utilities. |
| 8 |
|
| 9 |
## Printing to Stdout |
| 10 |
|
| 11 |
The most obvious helper is the {func}`echo` function, which in many ways works like the Python `print` statement or |
| 12 |
function. The main difference is that it works the same in many different terminal environments. |
| 13 |
|
| 14 |
Example: |
| 15 |
|
| 16 |
```python |
| 17 |
import click |
| 18 |
|
| 19 |
click.echo('Hello World!') |
| 20 |
``` |
| 21 |
|
| 22 |
It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by |
| 23 |
passing `nl=False`: |
| 24 |
|
| 25 |
```python |
| 26 |
click.echo(b'\xe2\x98\x83', nl=False) |
| 27 |
``` |
| 28 |
|
| 29 |
Last but not least {func}`echo` uses click's intelligent internal output streams to stdout and stderr which support |
| 30 |
unicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicode |
| 31 |
characters (there are some limitations on the default font with regards to which characters can be displayed). |
| 32 |
|
| 33 |
```{versionadded} 6.0 |
| 34 |
``` |
| 35 |
|
| 36 |
Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more |
| 37 |
information see {doc}`wincmd`. |
| 38 |
|
| 39 |
```{versionadded} 3.0 |
| 40 |
``` |
| 41 |
|
| 42 |
You can also easily print to standard error by passing `err=True`: |
| 43 |
|
| 44 |
```python |
| 45 |
click.echo('Hello World!', err=True) |
| 46 |
``` |
| 47 |
|
| 48 |
(ansi-colors)= |
| 49 |
|
| 50 |
## ANSI Colors |
| 51 |
|
| 52 |
```{versionadded} 2.0 |
| 53 |
``` |
| 54 |
|
| 55 |
The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/). |
| 56 |
|
| 57 |
Primarily this means that: |
| 58 |
|
| 59 |
- 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 terminal |
| 61 |
API calls. This means that colors will work on Windows the same way they do on other operating systems. |
| 62 |
|
| 63 |
On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not |
| 64 |
required for Click. |
| 65 |
|
| 66 |
For styling a string, the {func}`style` function can be used: |
| 67 |
|
| 68 |
```python |
| 69 |
import click |
| 70 |
|
| 71 |
click.echo(click.style('Hello World!', fg='green')) |
| 72 |
click.echo(click.style('Some more text', bg='blue', fg='white')) |
| 73 |
click.echo(click.style('ATTENTION', blink=True, bold=True)) |
| 74 |
``` |
| 75 |
|
| 76 |
The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`: |
| 77 |
|
| 78 |
```python |
| 79 |
click.secho('Hello World!', fg='green') |
| 80 |
click.secho('Some more text', bg='blue', fg='white') |
| 81 |
click.secho('ATTENTION', blink=True, bold=True) |
| 82 |
``` |
| 83 |
|
| 84 |
## Pager Support |
| 85 |
|
| 86 |
In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be |
| 87 |
achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always |
| 88 |
writes to stdout and, if possible, through a pager. |
| 89 |
|
| 90 |
Example: |
| 91 |
|
| 92 |
```{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))) |
| 97 |
``` |
| 98 |
|
| 99 |
If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, |
| 100 |
you can pass a generator (or generator function) instead of a string: |
| 101 |
|
| 102 |
```{eval-rst} |
| 103 |
.. click:example:: |
| 104 |
def _generate_output(): |
| 105 |
for idx in range(50000): |
| 106 |
yield f"Line {idx}\n" |
| 107 |
|
| 108 |
@click.command() |
| 109 |
def less(): |
| 110 |
click.echo_via_pager(_generate_output()) |
| 111 |
``` |
| 112 |
|
| 113 |
## Screen Clearing |
| 114 |
|
| 115 |
```{versionadded} 2.0 |
| 116 |
``` |
| 117 |
|
| 118 |
To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does |
| 119 |
what the name suggests: it clears the entire visible screen in a platform-agnostic way: |
| 120 |
|
| 121 |
```python |
| 122 |
import click |
| 123 |
click.clear() |
| 124 |
``` |
| 125 |
|
| 126 |
## Getting Characters from Terminal |
| 127 |
|
| 128 |
```{versionadded} 2.0 |
| 129 |
``` |
| 130 |
|
| 131 |
Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and |
| 132 |
will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead |
| 133 |
read individual characters as they are being written. |
| 134 |
|
| 135 |
For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and |
| 136 |
returns it as a Unicode character. |
| 137 |
|
| 138 |
Note that this function will always read from the terminal, even if stdin is instead a pipe. |
| 139 |
|
| 140 |
Example: |
| 141 |
|
| 142 |
```python |
| 143 |
import click |
| 144 |
|
| 145 |
click.echo('Continue? [yn] ', nl=False) |
| 146 |
c = click.getchar() |
| 147 |
click.echo() |
| 148 |
if c == 'y': |
| 149 |
click.echo('We will go on') |
| 150 |
elif c == 'n': |
| 151 |
click.echo('Abort!') |
| 152 |
else: |
| 153 |
click.echo('Invalid input :(') |
| 154 |
``` |
| 155 |
|
| 156 |
Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape |
| 157 |
format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file |
| 158 |
exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that |
| 159 |
cannot be properly exited. |
| 160 |
|
| 161 |
## Waiting for Key Press |
| 162 |
|
| 163 |
```{versionadded} 2.0 |
| 164 |
``` |
| 165 |
|
| 166 |
Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows |
| 167 |
where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting. |
| 168 |
|
| 169 |
In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the |
| 170 |
terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP |
| 171 |
(no operation instruction) if the script is not run interactively. |
| 172 |
|
| 173 |
Example: |
| 174 |
|
| 175 |
```python |
| 176 |
import click |
| 177 |
click.pause() |
| 178 |
``` |
| 179 |
|
| 180 |
## Launching Editors |
| 181 |
|
| 182 |
```{versionadded} 2.0 |
| 183 |
``` |
| 184 |
|
| 185 |
Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line |
| 186 |
input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the |
| 187 |
editor without saving, the return value will be `None`, otherwise the entered text. |
| 188 |
|
| 189 |
Example usage: |
| 190 |
|
| 191 |
```python |
| 192 |
import click |
| 193 |
|
| 194 |
def get_commit_message(): |
| 195 |
MARKER = '# Everything below is ignored\n' |
| 196 |
message = click.edit('\n\n' + MARKER) |
| 197 |
if message is not None: |
| 198 |
return message.split(MARKER, 1)[0].rstrip('\n') |
| 199 |
``` |
| 200 |
|
| 201 |
Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the |
| 202 |
return value is always `None`. |
| 203 |
|
| 204 |
Example usage: |
| 205 |
|
| 206 |
```python |
| 207 |
import click |
| 208 |
click.edit(filename='/etc/passwd') |
| 209 |
``` |
| 210 |
|
| 211 |
## Launching Applications |
| 212 |
|
| 213 |
```{versionadded} 2.0 |
| 214 |
``` |
| 215 |
|
| 216 |
Click supports launching applications through {func}`launch`. This can be used to open the default application |
| 217 |
associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition |
| 218 |
to this, it can also launch the file manager and automatically select the provided file. |
| 219 |
|
| 220 |
Example usage: |
| 221 |
|
| 222 |
```python |
| 223 |
click.launch("https://click.palletsprojects.com/") |
| 224 |
click.launch("/my/downloaded/file.txt", locate=True) |
| 225 |
``` |
| 226 |
|
| 227 |
## Printing Filenames |
| 228 |
|
| 229 |
Because filenames might not be Unicode, formatting them can be a bit tricky. |
| 230 |
|
| 231 |
The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the |
| 232 |
filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode |
| 233 |
string. |
| 234 |
|
| 235 |
Example: |
| 236 |
|
| 237 |
```python |
| 238 |
click.echo(f"Path: {click.format_filename(b'foo.txt')}") |
| 239 |
``` |
| 240 |
|
| 241 |
## Standard Streams |
| 242 |
|
| 243 |
For command line utilities, it's very important to get access to input and output streams reliably. Python generally |
| 244 |
provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between |
| 245 |
2.x and 3.x, especially with regards to how these streams respond to Unicode and binary data. |
| 246 |
|
| 247 |
Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce |
| 248 |
consistent results with different Python versions and for a wide variety of terminal configurations. |
| 249 |
|
| 250 |
The end result is that these functions will always return a functional stream object (except in very odd cases; see |
| 251 |
{doc}`/unicode-support`). |
| 252 |
|
| 253 |
Example: |
| 254 |
|
| 255 |
```python |
| 256 |
import click |
| 257 |
|
| 258 |
stdin_text = click.get_text_stream('stdin') |
| 259 |
stdout_binary = click.get_binary_stream('stdout') |
| 260 |
``` |
| 261 |
|
| 262 |
```{versionadded} 6.0 |
| 263 |
``` |
| 264 |
|
| 265 |
Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more |
| 266 |
information see {doc}`wincmd`. |
| 267 |
|
| 268 |
## Intelligent File Opening |
| 269 |
|
| 270 |
```{versionadded} 3.0 |
| 271 |
``` |
| 272 |
|
| 273 |
Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file` |
| 274 |
function. It can intelligently open stdin/stdout as well as any other file. |
| 275 |
|
| 276 |
Example: |
| 277 |
|
| 278 |
```python |
| 279 |
import click |
| 280 |
|
| 281 |
stdout = click.open_file('-', 'w') |
| 282 |
test_file = click.open_file('test.txt', 'w') |
| 283 |
``` |
| 284 |
|
| 285 |
If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent |
| 286 |
the closing of the file. This makes the handling of standard streams transparent and you can always use it like this: |
| 287 |
|
| 288 |
```python |
| 289 |
with click.open_file(filename, 'w') as f: |
| 290 |
f.write('Hello World!\n') |
| 291 |
``` |
| 292 |
|
| 293 |
## Finding Application Folders |
| 294 |
|
| 295 |
```{versionadded} 2.0 |
| 296 |
``` |
| 297 |
|
| 298 |
Very often, you want to open a configuration file that belongs to your application. However, different operating systems |
| 299 |
store these configuration files in different locations depending on their standards. Click provides a |
| 300 |
{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application |
| 301 |
depending on the OS. |
| 302 |
|
| 303 |
Example usage: |
| 304 |
|
| 305 |
```python |
| 306 |
import os |
| 307 |
import click |
| 308 |
import ConfigParser |
| 309 |
|
| 310 |
APP_NAME = 'My Application' |
| 311 |
def read_config(): |
| 312 |
cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini') |
| 313 |
parser = ConfigParser.RawConfigParser() |
| 314 |
parser.read([cfg]) |
| 315 |
rv = {} |
| 316 |
for section in parser.sections(): |
| 317 |
for key, value in parser.items(section): |
| 318 |
rv[f"{section}.{key}"] = value |
| 319 |
return rv |
| 320 |
``` |
| 321 |
|
| 322 |
## Showing Progress Bars |
| 323 |
|
| 324 |
Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some |
| 325 |
progress about how long that will take. Click supports simple progress bar rendering for that through the |
| 326 |
{func}`progressbar` function. |
| 327 |
|
| 328 |
```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/). |
| 329 |
``` |
| 330 |
|
| 331 |
The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the |
| 332 |
iterable it might take some time to do processing. So say you have a loop like this: |
| 333 |
|
| 334 |
```python |
| 335 |
for user in all_the_users_to_process: |
| 336 |
modify_the_user(user) |
| 337 |
``` |
| 338 |
|
| 339 |
To hook this up with an automatically updating progress bar, all you need to do is to change the code to this: |
| 340 |
|
| 341 |
```python |
| 342 |
import click |
| 343 |
|
| 344 |
with click.progressbar(all_the_users_to_process) as bar: |
| 345 |
for user in bar: |
| 346 |
modify_the_user(user) |
| 347 |
``` |
| 348 |
|
| 349 |
Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The |
| 350 |
calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the |
| 351 |
length, you can explicitly provide it: |
| 352 |
|
| 353 |
```python |
| 354 |
with click.progressbar(all_the_users_to_process, |
| 355 |
length=number_of_users) as bar: |
| 356 |
for user in bar: |
| 357 |
modify_the_user(user) |
| 358 |
``` |
| 359 |
|
| 360 |
Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render |
| 361 |
correctly: |
| 362 |
|
| 363 |
```python |
| 364 |
import time |
| 365 |
|
| 366 |
with click.progressbar([1, 2, 3]) as bar: |
| 367 |
for x in bar: |
| 368 |
print(f"sleep({x})...") |
| 369 |
time.sleep(x) |
| 370 |
``` |
| 371 |
|
| 372 |
Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar: |
| 373 |
|
| 374 |
```python |
| 375 |
with click.progressbar(all_the_users_to_process, |
| 376 |
label='Modifying user accounts', |
| 377 |
length=number_of_users) as bar: |
| 378 |
for user in bar: |
| 379 |
modify_the_user(user) |
| 380 |
``` |
| 381 |
|
| 382 |
Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you |
| 383 |
need to specify the length (and no iterable), and use the update method on the context return value instead of iterating |
| 384 |
directly over it: |
| 385 |
|
| 386 |
```python |
| 387 |
with click.progressbar(length=total_size, |
| 388 |
label='Unzipping archive') as bar: |
| 389 |
for archive in zip_file: |
| 390 |
archive.extract() |
| 391 |
bar.update(archive.size) |
| 392 |
``` |