utils.rst
This file
Path
docs/utils.rst
403 lines · 12.4 KiB
Last changed by
Merge pull request #1784 from pallets/windows-requires-coloramaDavid Lordbefore adoption890e984
History of this fileTake it
The walk stopped after 200 commits: lines older than 31d19ba point at it.
add changelog for #1014David Lordbefore adoption31d19ba
lines 1–15why, one step back1Utilities2=========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 isMerge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 16why, one step back16that it works the same in many different terminal environments.add changelog for #1014David Lordbefore adoption31d19ba
lines 17–23why, one step back1718Example::1920 import click2122 click.echo('Hello World!')23Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 24–25why, one step back24It can output both text and binary data. It will emit a trailing newline25by default, which needs to be suppressed by passing ``nl=False``::add changelog for #1014David Lordbefore adoption31d19ba
lines 26–31why, one step back2627 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 canMerge branch '7.x'David Lordbefore adoptionc6ef735
line 32why, one step back32output unicode characters (there are some limitations on the default fontMerge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 33why, one step back33with regards to which characters can be displayed).add changelog for #1014David Lordbefore adoption31d19ba
lines 34–36why, one step back3435.. versionadded:: 6.036Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 37why, one step back37Click emulates output streams on Windows to support unicode to theadd changelog for #1014David Lordbefore adoption31d19ba
lines 38–42why, one step back38Windows console through separate APIs. For more information see39:doc:`wincmd`.4041.. versionadded:: 3.042Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 43why, one step back43You can also easily print to standard error by passing ``err=True``::add changelog for #1014David Lordbefore adoption31d19ba
lines 44–54why, one step back4445 click.echo('Hello World!', err=True)464748.. _ansi-colors:4950ANSI Colors51-----------5253.. versionadded:: 2.054Merge pull request #1784 from pallets/windows-requires-coloramaDavid Lordbefore adoption890e984
lines 55–56why, one step back55The :func:`echo` function supports ANSI colors and styles. On Windows56this uses `colorama`_.add changelog for #1014David Lordbefore adoption31d19ba
lines 57–66why, one step back5758Primarily 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.66Merge pull request #1784 from pallets/windows-requires-coloramaDavid Lordbefore adoption890e984
lines 67–68why, one step back67On Windows, Click uses colorama without calling ``colorama.init()``. You68can still call that in your code, but it's not required for Click.add changelog for #1014David Lordbefore adoption31d19ba
lines 69–101why, one step back6970For 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():Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 102why, one step back102 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))add changelog for #1014David Lordbefore adoption31d19ba
lines 103–108why, one step back103104If 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 109why, one step back109 yield f"Line {idx}\n"add changelog for #1014David Lordbefore adoption31d19ba
lines 110–199why, one step back110111 @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 valueMerge branch '7.x'David Lordbefore adoptionc6ef735
line 200why, one step back200will be ``None``, otherwise the entered text.add changelog for #1014David Lordbefore adoption31d19ba
lines 201–233why, one step back201202Example 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::233new docs linksDavid Lordbefore adoption7818f30
lines 234–235why, one step back234 click.launch("https://click.palletsprojects.com/")235 click.launch("/my/downloaded/file.txt", locate=True)add changelog for #1014David Lordbefore adoption31d19ba
lines 236–241why, one step back236237238Printing Filenames239------------------240241Because filenames might not be Unicode, formatting them can be a bitMerge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 242why, one step back242tricky.add changelog for #1014David Lordbefore adoption31d19ba
lines 243–250why, one step back243244The 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::250Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 251why, one step back251 click.echo(f"Path: {click.format_filename(b'foo.txt')}")add changelog for #1014David Lordbefore adoption31d19ba
lines 252–267why, one step back252253254Standard 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 functionalMerge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 268why, one step back268stream object (except in very odd cases; see :doc:`/unicode-support`).add changelog for #1014David Lordbefore adoption31d19ba
lines 269–334why, one step back269270Example::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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 335why, one step back335 rv[f"{section}.{key}"] = valueadd changelog for #1014David Lordbefore adoption31d19ba
lines 336–374why, one step back336 return rv337338339Showing Progress Bars340---------------------341342.. versionadded:: 2.0343344Sometimes, you have command line scripts that need to process a lot of data,345but you want to quickly show the user some progress about how long that346will take. Click supports simple progress bar rendering for that through347the :func:`progressbar` function.348349The basic usage is very simple: the idea is that you have an iterable that350you want to operate on. For each item in the iterable it might take some351time to do processing. So say you have a loop like this::352353 for user in all_the_users_to_process:354 modify_the_user(user)355356To hook this up with an automatically updating progress bar, all you need357to do is to change the code to this::358359 import click360361 with click.progressbar(all_the_users_to_process) as bar:362 for user in bar:363 modify_the_user(user)364365Click will then automatically print a progress bar to the terminal and366calculate the remaining time for you. The calculation of remaining time367requires that the iterable has a length. If it does not have a length368but you know the length, you can explicitly provide it::369370 with click.progressbar(all_the_users_to_process,371 length=number_of_users) as bar:372 for user in bar:373 modify_the_user(user)374Merge branch '7.x'David Lordbefore adoption2269786
lines 375–381why, one step back375Note that :func:`progressbar` updates the bar *after* each iteration of the376loop. So code like this will render correctly::377378 import time379380 with click.progressbar([1, 2, 3]) as bar:381 for x in bar:Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 382why, one step back382 print(f"sleep({x})...")Merge branch '7.x'David Lordbefore adoption2269786
lines 383–384why, one step back383 time.sleep(x)384add changelog for #1014David Lordbefore adoption31d19ba
lines 385–403why, one step back385Another useful feature is to associate a label with the progress bar which386will be shown preceding the progress bar::387388 with click.progressbar(all_the_users_to_process,389 label='Modifying user accounts',390 length=number_of_users) as bar:391 for user in bar:392 modify_the_user(user)393394Sometimes, one may need to iterate over an external iterator, and advance the395progress bar irregularly. To do so, you need to specify the length (and no396iterable), and use the update method on the context return value instead of397iterating directly over it::398399 with click.progressbar(length=total_size,400 label='Unzipping archive') as bar:401 for archive in zip_file:402 archive.extract()403 bar.update(archive.size)