utils.rst
This file
Path
docs/utils.rst
398 lines · 12.5 KiB
Last changed by
Documented wincmdArmin Ronacherbefore adoption7e8da4b
History of this fileTake it
1Utilities2=========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 Python 2 and 3, it intelligently detects17misconfigured output streams, and it will never fail (except in Python 3; for18more information see :ref:`python3-limitations`).1920Example::2122 import click2324 click.echo('Hello World!')2526Most importantly, it can print both Unicode and binary data, unlike the27built-in ``print`` function in Python 3, which cannot output any bytes. It28will, however, emit a trailing newline by default, which needs to be29suppressed by passing ``nl=False``::3031 click.echo(b'\xe2\x98\x83', nl=False)3233Last but not least :func:`echo` uses click's intelligent internal output34streams to stdout and stderr which support unicode output on the Windows35console. This means for as long as you are using `click.echo` you can36output unicode character (there are some limitations on the default font37with regards to which characters can be displayed). This functionality is38new in Click 6.0.3940.. versionadded:: 6.04142Click now emulates output streams on Windows to support unicode to the43Windows console through separate APIs. For more information see44`wincmd`_.4546.. versionadded:: 3.04748Starting with Click 3.0 you can also easily print to standard error by49passing ``err=True``::5051 click.echo('Hello World!', err=True)525354.. _ansi-colors:5556ANSI Colors57-----------5859.. versionadded:: 2.06061Starting with Click 2.0, the :func:`echo` function gained extra62functionality to deal with ANSI colors and styles. Note that on Windows,63this functionality is only available if `colorama`_ is installed. If it64is installed, then ANSI codes are intelligently handled.6566Primarily this means that:6768- Click's :func:`echo` function will automatically strip ANSI color codes69 if the stream is not connected to a terminal.70- the :func:`echo` function will transparently connect to the terminal on71 Windows and translate ANSI codes to terminal API calls. This means72 that colors will work on Windows the same way they do on other73 operating systems.7475Note for `colorama` support: Click will automatically detect when `colorama`76is available and use it. Do *not* call ``colorama.init()``!7778To install `colorama`, run this command::7980 $ pip install colorama8182For styling a string, the :func:`style` function can be used::8384 import click8586 click.echo(click.style('Hello World!', fg='green'))87 click.echo(click.style('Some more text', bg='blue', fg='white'))88 click.echo(click.style('ATTENTION', blink=True, bold=True))8990The combination of :func:`echo` and :func:`style` is also available in91a single function called :func:`secho`::9293 click.secho('Hello World!', fg='green')94 click.secho('Some more text', bg='blue', fg='white')95 click.secho('ATTENTION', blink=True, bold=True)969798.. _colorama: https://pypi.python.org/pypi/colorama99100Pager Support101-------------102103In some situations, you might want to show long texts on the terminal and104let a user scroll through it. This can be achieved by using the105:func:`echo_via_pager` function which works similarly to the :func:`echo`106function, but always writes to stdout and, if possible, through a pager.107108Example:109110.. click:example::111112 @click.command()113 def less():114 click.echo_via_pager('\n'.join('Line %d' % idx115 for idx in range(200)))116117118Screen Clearing119---------------120121.. versionadded:: 2.0122123To clear the terminal screen, you can use the :func:`clear` function that124is provided starting with Click 2.0. It does what the name suggests: it125clears the entire visible screen in a platform-agnostic way:126127::128129 import click130 click.clear()131132133Getting Characters from Terminal134--------------------------------135136.. versionadded:: 2.0137138Normally, when reading input from the terminal, you would read from139standard input. However, this is buffered input and will not show up until140the line has been terminated. In certain circumstances, you might not want141to do that and instead read individual characters as they are being written.142143For this, Click provides the :func:`getchar` function which reads a single144character from the terminal buffer and returns it as a Unicode character.145146Note that this function will always read from the terminal, even if stdin147is instead a pipe.148149Example::150151 import click152153 click.echo('Continue? [yn] ', nl=False)154 c = click.getchar()155 click.echo()156 if c == 'y':157 click.echo('We will go on')158 elif c == 'n':159 click.echo('Abort!')160 else:161 click.echo('Invalid input :(')162163Note that this reads raw input, which means that things like arrow keys164will show up in the platform's native escape format. The only characters165translated are ``^C`` and ``^D`` which are converted into keyboard166interrupts and end of file exceptions respectively. This is done because167otherwise, it's too easy to forget about that and to create scripts that168cannot be properly exited.169170171Waiting for Key Press172---------------------173174.. versionadded:: 2.0175176Sometimes, it's useful to pause until the user presses any key on the177keyboard. This is especially useful on Windows where ``cmd.exe`` will178close the window at the end of the command execution by default, instead179of waiting.180181In click, this can be accomplished with the :func:`pause` function. This182function will print a quick message to the terminal (which can be183customized) and wait for the user to press a key. In addition to that,184it will also become a NOP (no operation instruction) if the script is not185run interactively.186187Example::188189 import click190 click.pause()191192193Launching Editors194-----------------195196.. versionadded:: 2.0197198Click supports launching editors automatically through :func:`edit`. This199is very useful for asking users for multi-line input. It will200automatically open the user's defined editor or fall back to a sensible201default. If the user closes the editor without saving, the return value202will be `None` otherwise the entered text.203204Example usage::205206 import click207208 def get_commit_message():209 MARKER = '# Everything below is ignored\n'210 message = click.edit('\n\n' + MARKER)211 if message is not None:212 return message.split(MARKER, 1)[0].rstrip('\n')213214Alternatively, the function can also be used to launch editors for files by215a specific filename. In this case, the return value is always `None`.216217Example usage::218219 import click220 click.edit(filename='/etc/passwd')221222223Launching Applications224----------------------225226.. versionadded:: 2.0227228Click supports launching applications through :func:`launch`. This can be229used to open the default application assocated with a URL or filetype.230This can be used to launch web browsers or picture viewers, for instance.231In addition to this, it can also launch the file manager and automatically232select the provided file.233234Example usage::235236 click.launch('http://click.pocoo.org/')237 click.launch('/my/downloaded/file.txt', locate=True)238239240Printing Filenames241------------------242243Because filenames might not be Unicode, formatting them can be a bit244tricky. Generally, this is easier in Python 2 than on 3, as you can just245write the bytes to stdout with the ``print`` function, but in Python 3, you246will always need to operate in Unicode.247248The way this works with click is through the :func:`format_filename`249function. It does a best-effort conversion of the filename to Unicode and250will never fail. This makes it possible to use these filenames in the251context of a full Unicode string.252253Example::254255 click.echo('Path: %s' % click.format_filename(b'foo.txt'))256257258Standard Streams259----------------260261For command line utilities, it's very important to get access to input and262output streams reliably. Python generally provides access to these263streams through ``sys.stdout`` and friends, but unfortunately, there are264API differences between 2.x and 3.x, especially with regards to how these265streams respond to Unicode and binary data.266267Because of this, click provides the :func:`get_binary_stream` and268:func:`get_text_stream` functions, which produce consistent results with269different Python versions and for a wide variety pf terminal configurations.270271The end result is that these functions will always return a functional272stream object (except in very odd cases in Python 3; see273:ref:`python3-limitations`).274275Example::276277 import click278279 stdin_text = click.get_text_stream('stdin')280 stdout_binary = click.get_binary_stream('stdout')281282.. versionadded:: 6.0283284Click now emulates output streams on Windows to support unicode to the285Windows console through separate APIs. For more information see286`wincmd`_.287288289Intelligent File Opening290------------------------291292.. versionadded:: 3.0293294Starting with Click 3.0 the logic for opening files from the :class:`File`295type is exposed through the :func:`open_file` function. It can296intelligently open stdin/stdout as well as any other file.297298Example::299300 import click301302 stdout = click.open_file('-', 'w')303 test_file = click.open_file('test.txt', 'w')304305If stdin or stdout are returned, the return value is wrapped in a special306file where the context manager will prevent the closing of the file. This307makes the handling of standard streams transparent and you can always use308it like this::309310 with click.open_file(filename, 'w') as f:311 f.write('Hello World!\n')312313314Finding Application Folders315---------------------------316317.. versionadded:: 2.0318319Very often, you want to open a configuration file that belongs to your320application. However, different operating systems store these configuration321files in different locations depending on their standards. Click provides322a :func:`get_app_dir` function which returns the most appropriate location323for per-user config files for your application depending on the OS.324325Example usage::326327 import os328 import click329 import ConfigParser330331 APP_NAME = 'My Application'332333 def read_config():334 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')335 parser = ConfigParser.RawConfigParser()336 parser.read([cfg])337 rv = {}338 for section in parser.sections():339 for key, value in parser.items(section):340 rv['%s.%s' % (section, key)] = value341 return rv342343344Showing Progress Bars345---------------------346347.. versionadded:: 2.0348349Sometimes, you have command line scripts that need to process a lot of data,350but you want to quickly show the user some progress about how long that351will take. Click supports simple progress bar rendering for that through352the :func:`progressbar` function.353354The 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)379380Another useful feature is to associate a label with the progress bar which381will be shown preceding the progress bar::382383 with click.progressbar(all_the_users_to_process,384 label='Modifying user accounts',385 length=number_of_users) as bar:386 for user in bar:387 modify_the_user(user)388389Sometimes, one may need to iterate over an external iterator, and advance the390progress bar irregularly. To do so, you need to specify the length (and no391iterable), and use the update method on the context return value instead of392iterating directly over it::393394 with click.progressbar(length=total_size,395 label='Unzipping archive') as bar:396 for archive in zip_file:397 archive.extract()398 bar.update(archive.size)