Skip to content
Myr

utils.rst

This file

Path

docs/utils.rst

408 lines · 12.5 KiB

Last changed by

Merge remote-tracking branch 'origin/8.0.x'David Lordbefore adoptionce152bd

History of this file

Take it

The walk stopped after 200 commits: lines older than 1cd7593 point at it.

Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593

lines 1–345why, 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 is16that it works the same in many different terminal environments.1718Example::1920 import click2122 click.echo('Hello World!')2324It can output both text and binary data. It will emit a trailing newline25by default, which needs to be suppressed by passing ``nl=False``::2627 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 can32output unicode characters (there are some limitations on the default font33with regards to which characters can be displayed).3435.. versionadded:: 6.03637Click emulates output streams on Windows to support unicode to the38Windows console through separate APIs. For more information see39:doc:`wincmd`.4041.. versionadded:: 3.04243You can also easily print to standard error by passing ``err=True``::4445 click.echo('Hello World!', err=True)464748.. _ansi-colors:4950ANSI Colors51-----------5253.. versionadded:: 2.05455The :func:`echo` function supports ANSI colors and styles. On Windows56this uses `colorama`_.5758Primarily this means that:5960- Click's :func:`echo` function will automatically strip ANSI color codes61 if the stream is not connected to a terminal.62- the :func:`echo` function will transparently connect to the terminal on63 Windows and translate ANSI codes to terminal API calls. This means64 that colors will work on Windows the same way they do on other65 operating systems.6667On Windows, Click uses colorama without calling ``colorama.init()``. You68can still call that in your code, but it's not required for Click.6970For styling a string, the :func:`style` function can be used::7172 import click7374 click.echo(click.style('Hello World!', fg='green'))75 click.echo(click.style('Some more text', bg='blue', fg='white'))76 click.echo(click.style('ATTENTION', blink=True, bold=True))7778The combination of :func:`echo` and :func:`style` is also available in79a single function called :func:`secho`::8081 click.secho('Hello World!', fg='green')82 click.secho('Some more text', bg='blue', fg='white')83 click.secho('ATTENTION', blink=True, bold=True)848586.. _colorama: https://pypi.org/project/colorama/8788Pager Support89-------------9091In some situations, you might want to show long texts on the terminal and92let a user scroll through it. This can be achieved by using the93:func:`echo_via_pager` function which works similarly to the :func:`echo`94function, but always writes to stdout and, if possible, through a pager.9596Example:9798.. click:example::99100 @click.command()101 def less():102 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))103104If 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:105106.. click:example::107 def _generate_output():108 for idx in range(50000):109 yield f"Line {idx}\n"110111 @click.command()112 def less():113 click.echo_via_pager(_generate_output())114115116Screen Clearing117---------------118119.. versionadded:: 2.0120121To clear the terminal screen, you can use the :func:`clear` function that122is provided starting with Click 2.0. It does what the name suggests: it123clears the entire visible screen in a platform-agnostic way:124125::126127 import click128 click.clear()129130131Getting Characters from Terminal132--------------------------------133134.. versionadded:: 2.0135136Normally, when reading input from the terminal, you would read from137standard input. However, this is buffered input and will not show up until138the line has been terminated. In certain circumstances, you might not want139to do that and instead read individual characters as they are being written.140141For this, Click provides the :func:`getchar` function which reads a single142character from the terminal buffer and returns it as a Unicode character.143144Note that this function will always read from the terminal, even if stdin145is instead a pipe.146147Example::148149 import click150151 click.echo('Continue? [yn] ', nl=False)152 c = click.getchar()153 click.echo()154 if c == 'y':155 click.echo('We will go on')156 elif c == 'n':157 click.echo('Abort!')158 else:159 click.echo('Invalid input :(')160161Note that this reads raw input, which means that things like arrow keys162will show up in the platform's native escape format. The only characters163translated are ``^C`` and ``^D`` which are converted into keyboard164interrupts and end of file exceptions respectively. This is done because165otherwise, it's too easy to forget about that and to create scripts that166cannot be properly exited.167168169Waiting for Key Press170---------------------171172.. versionadded:: 2.0173174Sometimes, it's useful to pause until the user presses any key on the175keyboard. This is especially useful on Windows where ``cmd.exe`` will176close the window at the end of the command execution by default, instead177of waiting.178179In click, this can be accomplished with the :func:`pause` function. This180function will print a quick message to the terminal (which can be181customized) and wait for the user to press a key. In addition to that,182it will also become a NOP (no operation instruction) if the script is not183run interactively.184185Example::186187 import click188 click.pause()189190191Launching Editors192-----------------193194.. versionadded:: 2.0195196Click supports launching editors automatically through :func:`edit`. This197is very useful for asking users for multi-line input. It will198automatically open the user's defined editor or fall back to a sensible199default. If the user closes the editor without saving, the return value200will be ``None``, otherwise the entered text.201202Example usage::203204 import click205206 def get_commit_message():207 MARKER = '# Everything below is ignored\n'208 message = click.edit('\n\n' + MARKER)209 if message is not None:210 return message.split(MARKER, 1)[0].rstrip('\n')211212Alternatively, the function can also be used to launch editors for files by213a specific filename. In this case, the return value is always `None`.214215Example usage::216217 import click218 click.edit(filename='/etc/passwd')219220221Launching Applications222----------------------223224.. versionadded:: 2.0225226Click supports launching applications through :func:`launch`. This can be227used to open the default application associated with a URL or filetype.228This can be used to launch web browsers or picture viewers, for instance.229In addition to this, it can also launch the file manager and automatically230select the provided file.231232Example usage::233234 click.launch("https://click.palletsprojects.com/")235 click.launch("/my/downloaded/file.txt", locate=True)236237238Printing Filenames239------------------240241Because filenames might not be Unicode, formatting them can be a bit242tricky.243244The way this works with click is through the :func:`format_filename`245function. It does a best-effort conversion of the filename to Unicode and246will never fail. This makes it possible to use these filenames in the247context of a full Unicode string.248249Example::250251 click.echo(f"Path: {click.format_filename(b'foo.txt')}")252253254Standard Streams255----------------256257For command line utilities, it's very important to get access to input and258output streams reliably. Python generally provides access to these259streams through ``sys.stdout`` and friends, but unfortunately, there are260API differences between 2.x and 3.x, especially with regards to how these261streams respond to Unicode and binary data.262263Because of this, click provides the :func:`get_binary_stream` and264:func:`get_text_stream` functions, which produce consistent results with265different Python versions and for a wide variety of terminal configurations.266267The end result is that these functions will always return a functional268stream object (except in very odd cases; see :doc:`/unicode-support`).269270Example::271272 import click273274 stdin_text = click.get_text_stream('stdin')275 stdout_binary = click.get_binary_stream('stdout')276277.. versionadded:: 6.0278279Click now emulates output streams on Windows to support unicode to the280Windows console through separate APIs. For more information see281:doc:`wincmd`.282283284Intelligent File Opening285------------------------286287.. versionadded:: 3.0288289Starting with Click 3.0 the logic for opening files from the :class:`File`290type is exposed through the :func:`open_file` function. It can291intelligently open stdin/stdout as well as any other file.292293Example::294295 import click296297 stdout = click.open_file('-', 'w')298 test_file = click.open_file('test.txt', 'w')299300If stdin or stdout are returned, the return value is wrapped in a special301file where the context manager will prevent the closing of the file. This302makes the handling of standard streams transparent and you can always use303it like this::304305 with click.open_file(filename, 'w') as f:306 f.write('Hello World!\n')307308309Finding Application Folders310---------------------------311312.. versionadded:: 2.0313314Very often, you want to open a configuration file that belongs to your315application. However, different operating systems store these configuration316files in different locations depending on their standards. Click provides317a :func:`get_app_dir` function which returns the most appropriate location318for per-user config files for your application depending on the OS.319320Example usage::321322 import os323 import click324 import ConfigParser325326 APP_NAME = 'My Application'327328 def read_config():329 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')330 parser = ConfigParser.RawConfigParser()331 parser.read([cfg])332 rv = {}333 for section in parser.sections():334 for key, value in parser.items(section):335 rv[f"{section}.{key}"] = value336 return rv337338339Showing Progress Bars340---------------------341342Sometimes, you have command line scripts that need to process a lot of data,343but you want to quickly show the user some progress about how long that344will take. Click supports simple progress bar rendering for that through345the :func:`progressbar` function.

Merge remote-tracking branch 'origin/8.0.x'David Lordbefore adoptionce152bd

lines 346–352why, one step back
346
347.. note::348349 If you find that you have requirements beyond what Click's progress350 bar supports, try using `tqdm`_.351352 .. _tqdm: https://tqdm.github.io/

Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593

lines 353–408why, one step back
353
354The basic usage is very simple: the idea is that you have an iterable that355you want to operate on. For each item in the iterable it might take some356time to do processing. So say you have a loop like this::357358 for user in all_the_users_to_process:359 modify_the_user(user)360361To hook this up with an automatically updating progress bar, all you need362to do is to change the code to this::363364 import click365366 with click.progressbar(all_the_users_to_process) as bar:367 for user in bar:368 modify_the_user(user)369370Click will then automatically print a progress bar to the terminal and371calculate the remaining time for you. The calculation of remaining time372requires that the iterable has a length. If it does not have a length373but you know the length, you can explicitly provide it::374375 with click.progressbar(all_the_users_to_process,376 length=number_of_users) as bar:377 for user in bar:378 modify_the_user(user)379380Note that :func:`progressbar` updates the bar *after* each iteration of the381loop. So code like this will render correctly::382383 import time384385 with click.progressbar([1, 2, 3]) as bar:386 for x in bar:387 print(f"sleep({x})...")388 time.sleep(x)389390Another useful feature is to associate a label with the progress bar which391will be shown preceding the progress bar::392393 with 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)398399Sometimes, one may need to iterate over an external iterator, and advance the400progress bar irregularly. To do so, you need to specify the length (and no401iterable), and use the update method on the context return value instead of402iterating directly over it::403404 with click.progressbar(length=total_size,405 label='Unzipping archive') as bar:406 for archive in zip_file:407 archive.extract()408 bar.update(archive.size)