Skip to content
Myr

utils.rst

This file

Path

docs/utils.rst

409 lines · 12.6 KiB

Last changed by

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

History of this file

Take it

The walk stopped after 200 commits: lines older than 03e0133 point at it.

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 1–15why, one step back
1Utilities
2=========34.. currentmodule:: click56Besides the functionality that Click provides to interface with argument7parsing and handling, it also provides a bunch of addon functionality that8is useful for writing command line utilities.91011Printing to Stdout12------------------1314The most obvious helper is the :func:`echo` function, which in many ways15works like the Python ``print`` statement or function. The main difference is

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 16why, one step back
16that it works the same in many different terminal environments.

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 17–23why, one step back
17
18Example::1920 import click2122 click.echo('Hello World!')23

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

lines 24–25why, one step back
24It can output both text and binary data. It will emit a trailing newline
25by default, which needs to be suppressed by passing ``nl=False``::

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 26–31why, one step back
26
27 click.echo(b'\xe2\x98\x83', nl=False)2829Last but not least :func:`echo` uses click's intelligent internal output30streams to stdout and stderr which support unicode output on the Windows31console. This means for as long as you are using `click.echo` you can

Merge branch '7.x'David Lordbefore adoptionc6ef735

line 32why, one step back
32output unicode characters (there are some limitations on the default font

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 33why, one step back
33with regards to which characters can be displayed).

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 34–36why, one step back
34
35.. versionadded:: 6.036

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 37why, one step back
37Click emulates output streams on Windows to support unicode to the

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 38–42why, one step back
38Windows console through separate APIs. For more information see
39:doc:`wincmd`.4041.. versionadded:: 3.042

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 43why, one step back
43You can also easily print to standard error by passing ``err=True``::

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 44–54why, one step back
44
45 click.echo('Hello World!', err=True)464748.. _ansi-colors:4950ANSI Colors51-----------5253.. versionadded:: 2.054

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

lines 55–58why, one step back
55The :func:`echo` function gained extra functionality to deal with ANSI
56colors and styles. Note that on Windows, this functionality is only57available if `colorama`_ is installed. If it is installed, then ANSI58codes are intelligently handled.

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 59–107why, one step back
59
60Primarily this means that:6162- Click's :func:`echo` function will automatically strip ANSI color codes63 if the stream is not connected to a terminal.64- the :func:`echo` function will transparently connect to the terminal on65 Windows and translate ANSI codes to terminal API calls. This means66 that colors will work on Windows the same way they do on other67 operating systems.6869Note for `colorama` support: Click will automatically detect when `colorama`70is available and use it. Do *not* call ``colorama.init()``!7172To install `colorama`, run this command::7374 $ pip install colorama7576For styling a string, the :func:`style` function can be used::7778 import click7980 click.echo(click.style('Hello World!', fg='green'))81 click.echo(click.style('Some more text', bg='blue', fg='white'))82 click.echo(click.style('ATTENTION', blink=True, bold=True))8384The combination of :func:`echo` and :func:`style` is also available in85a single function called :func:`secho`::8687 click.secho('Hello World!', fg='green')88 click.secho('Some more text', bg='blue', fg='white')89 click.secho('ATTENTION', blink=True, bold=True)909192.. _colorama: https://pypi.org/project/colorama/9394Pager Support95-------------9697In some situations, you might want to show long texts on the terminal and98let a user scroll through it. This can be achieved by using the99:func:`echo_via_pager` function which works similarly to the :func:`echo`100function, but always writes to stdout and, if possible, through a pager.101102Example:103104.. click:example::105106 @click.command()107 def less():

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 108why, one step back
108 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 109–114why, one step back
109
110If 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:111112.. click:example::113 def _generate_output():114 for idx in range(50000):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 115why, one step back
115 yield f"Line {idx}\n"

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 116–205why, one step back
116
117 @click.command()118 def less():119 click.echo_via_pager(_generate_output())120121122Screen Clearing123---------------124125.. versionadded:: 2.0126127To clear the terminal screen, you can use the :func:`clear` function that128is provided starting with Click 2.0. It does what the name suggests: it129clears the entire visible screen in a platform-agnostic way:130131::132133 import click134 click.clear()135136137Getting Characters from Terminal138--------------------------------139140.. versionadded:: 2.0141142Normally, when reading input from the terminal, you would read from143standard input. However, this is buffered input and will not show up until144the line has been terminated. In certain circumstances, you might not want145to do that and instead read individual characters as they are being written.146147For this, Click provides the :func:`getchar` function which reads a single148character from the terminal buffer and returns it as a Unicode character.149150Note that this function will always read from the terminal, even if stdin151is instead a pipe.152153Example::154155 import click156157 click.echo('Continue? [yn] ', nl=False)158 c = click.getchar()159 click.echo()160 if c == 'y':161 click.echo('We will go on')162 elif c == 'n':163 click.echo('Abort!')164 else:165 click.echo('Invalid input :(')166167Note that this reads raw input, which means that things like arrow keys168will show up in the platform's native escape format. The only characters169translated are ``^C`` and ``^D`` which are converted into keyboard170interrupts and end of file exceptions respectively. This is done because171otherwise, it's too easy to forget about that and to create scripts that172cannot be properly exited.173174175Waiting for Key Press176---------------------177178.. versionadded:: 2.0179180Sometimes, it's useful to pause until the user presses any key on the181keyboard. This is especially useful on Windows where ``cmd.exe`` will182close the window at the end of the command execution by default, instead183of waiting.184185In click, this can be accomplished with the :func:`pause` function. This186function will print a quick message to the terminal (which can be187customized) and wait for the user to press a key. In addition to that,188it will also become a NOP (no operation instruction) if the script is not189run interactively.190191Example::192193 import click194 click.pause()195196197Launching Editors198-----------------199200.. versionadded:: 2.0201202Click supports launching editors automatically through :func:`edit`. This203is very useful for asking users for multi-line input. It will204automatically open the user's defined editor or fall back to a sensible205default. If the user closes the editor without saving, the return value

Merge branch '7.x'David Lordbefore adoptionc6ef735

line 206why, one step back
206will be ``None``, otherwise the entered text.

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 207–239why, one step back
207
208Example usage::209210 import click211212 def 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')217218Alternatively, the function can also be used to launch editors for files by219a specific filename. In this case, the return value is always `None`.220221Example usage::222223 import click224 click.edit(filename='/etc/passwd')225226227Launching Applications228----------------------229230.. versionadded:: 2.0231232Click supports launching applications through :func:`launch`. This can be233used to open the default application associated with a URL or filetype.234This can be used to launch web browsers or picture viewers, for instance.235In addition to this, it can also launch the file manager and automatically236select the provided file.237238Example usage::239

new docs linksDavid Lordbefore adoption7818f30

lines 240–241why, one step back
240 click.launch("https://click.palletsprojects.com/")
241 click.launch("/my/downloaded/file.txt", locate=True)

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 242–247why, one step back
242
243244Printing Filenames245------------------246247Because filenames might not be Unicode, formatting them can be a bit

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 248why, one step back
248tricky.

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 249–256why, one step back
249
250The way this works with click is through the :func:`format_filename`251function. It does a best-effort conversion of the filename to Unicode and252will never fail. This makes it possible to use these filenames in the253context of a full Unicode string.254255Example::256

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 257why, one step back
257 click.echo(f"Path: {click.format_filename(b'foo.txt')}")

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 258–273why, one step back
258
259260Standard Streams261----------------262263For command line utilities, it's very important to get access to input and264output streams reliably. Python generally provides access to these265streams through ``sys.stdout`` and friends, but unfortunately, there are266API differences between 2.x and 3.x, especially with regards to how these267streams respond to Unicode and binary data.268269Because of this, click provides the :func:`get_binary_stream` and270:func:`get_text_stream` functions, which produce consistent results with271different Python versions and for a wide variety of terminal configurations.272273The end result is that these functions will always return a functional

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 274why, one step back
274stream object (except in very odd cases; see :doc:`/unicode-support`).

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 275–340why, one step back
275
276Example::277278 import click279280 stdin_text = click.get_text_stream('stdin')281 stdout_binary = click.get_binary_stream('stdout')282283.. versionadded:: 6.0284285Click now emulates output streams on Windows to support unicode to the286Windows console through separate APIs. For more information see287:doc:`wincmd`.288289290Intelligent File Opening291------------------------292293.. versionadded:: 3.0294295Starting with Click 3.0 the logic for opening files from the :class:`File`296type is exposed through the :func:`open_file` function. It can297intelligently open stdin/stdout as well as any other file.298299Example::300301 import click302303 stdout = click.open_file('-', 'w')304 test_file = click.open_file('test.txt', 'w')305306If stdin or stdout are returned, the return value is wrapped in a special307file where the context manager will prevent the closing of the file. This308makes the handling of standard streams transparent and you can always use309it like this::310311 with click.open_file(filename, 'w') as f:312 f.write('Hello World!\n')313314315Finding Application Folders316---------------------------317318.. versionadded:: 2.0319320Very often, you want to open a configuration file that belongs to your321application. However, different operating systems store these configuration322files in different locations depending on their standards. Click provides323a :func:`get_app_dir` function which returns the most appropriate location324for per-user config files for your application depending on the OS.325326Example usage::327328 import os329 import click330 import ConfigParser331332 APP_NAME = 'My Application'333334 def read_config():335 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')336 parser = ConfigParser.RawConfigParser()337 parser.read([cfg])338 rv = {}339 for section in parser.sections():340 for key, value in parser.items(section):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 341why, one step back
341 rv[f"{section}.{key}"] = value

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 342–380why, one step back
342 return rv
343344345Showing Progress Bars346---------------------347348.. versionadded:: 2.0349350Sometimes, you have command line scripts that need to process a lot of data,351but you want to quickly show the user some progress about how long that352will take. Click supports simple progress bar rendering for that through353the :func:`progressbar` function.354355The basic usage is very simple: the idea is that you have an iterable that356you want to operate on. For each item in the iterable it might take some357time to do processing. So say you have a loop like this::358359 for user in all_the_users_to_process:360 modify_the_user(user)361362To hook this up with an automatically updating progress bar, all you need363to do is to change the code to this::364365 import click366367 with click.progressbar(all_the_users_to_process) as bar:368 for user in bar:369 modify_the_user(user)370371Click will then automatically print a progress bar to the terminal and372calculate the remaining time for you. The calculation of remaining time373requires that the iterable has a length. If it does not have a length374but you know the length, you can explicitly provide it::375376 with click.progressbar(all_the_users_to_process,377 length=number_of_users) as bar:378 for user in bar:379 modify_the_user(user)380

Merge branch '7.x'David Lordbefore adoption2269786

lines 381–387why, one step back
381Note that :func:`progressbar` updates the bar *after* each iteration of the
382loop. So code like this will render correctly::383384 import time385386 with click.progressbar([1, 2, 3]) as bar:387 for x in bar:

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 388why, one step back
388 print(f"sleep({x})...")

Merge branch '7.x'David Lordbefore adoption2269786

lines 389–390why, one step back
389 time.sleep(x)
390

Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133

lines 391–409why, one step back
391Another useful feature is to associate a label with the progress bar which
392will be shown preceding the progress bar::393394 with click.progressbar(all_the_users_to_process,395 label='Modifying user accounts',396 length=number_of_users) as bar:397 for user in bar:398 modify_the_user(user)399400Sometimes, one may need to iterate over an external iterator, and advance the401progress bar irregularly. To do so, you need to specify the length (and no402iterable), and use the update method on the context return value instead of403iterating directly over it::404405 with 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)