utils.rst
This file
Path
docs/utils.rst
336 lines · 10.5 KiB
Last changed by
Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4
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)323334.. _ansi-colors:3536ANSI Colors37-----------3839.. versionadded:: 2.04041Starting with click 2.0, the :func:`echo` function gained extra42functionality to deal with ANSI colors and styles. Note that on Windows,43this functionality is only available if `colorama`_ is installed. If it44is installed, then ANSI codes are intelligently handled.4546Primarily this means that:4748- click's :func:`echo` function will automatically strip ANSI color codes49 if the stream is not connected to a terminal.50- the :func:`echo` function will transparently connect to the terminal on51 Windows and translate ANSI codes to terminal API calls. This means52 that colors will work on Windows the same way they do on other53 operating systems.5455Note for `colorama` support: click will automatically detect when `colorama`56is available and use it. Do *not* call ``colorama.init()``!5758To install `colorama`, run this command::5960 $ pip install colorama6162For styling a string, the :func:`style` function can be used::6364 import click6566 click.echo(click.style('Hello World!', fg='green'))67 click.echo(click.style('Some more text', bg='blue', fg='white'))68 click.echo(click.style('ATTENTION', blink=True, bold=True))6970The combination of :func:`echo` and :func:`style` is also available in71a single function called :func:`secho`::7273 click.secho('Hello World!', fg='green')74 click.secho('Some more text', bg='blue', fg='white')75 click.secho('ATTENTION', blink=True, bold=True)767778.. _colorama: https://pypi.python.org/pypi/colorama7980Pager Support81-------------8283In some situations, you might want to show long texts on the terminal and84let a user scroll through it. This can be achieved by using the85:func:`echo_via_pager` function which works similarly to the :func:`echo`86function, but always writes to stdout and, if possible, through a pager.8788Example:8990.. click:example::9192 @click.command()93 def less():94 click.echo_via_pager('\n'.join('Line %d' % idx95 for idx in range(200)))969798Screen Clearing99---------------100101.. versionadded:: 2.0102103To clear the terminal screen, you can use the :func:`clear` function that104is provided starting with click 2.0. It does what the name suggests: it105clears the entire visible screen in a platform-agnostic way:106107::108109 import click110 click.clear()111112113Getting Characters from Terminal114--------------------------------115116.. versionadded:: 2.0117118Normally, when reading input from the terminal, you would read from119standard input. However, this is buffered input and will not show up until120the line has been terminated. In certain circumstances, you might not want121to do that and instead read individual characters as they are being written.122123For this, click provides the :func:`getchar` function which reads a single124character from the terminal buffer and returns it as a Unicode character.125126Note that this function will always read from the terminal, even if stdin127is instead a pipe.128129Example::130131 import click132133 click.echo('Continue? [yn] ', nl=False)134 c = click.getchar()135 click.echo()136 if c == 'y':137 click.echo('We will go on')138 elif c == 'n':139 click.echo('Abort!')140 else:141 click.echo('Invalid input :(')142143Note that this reads raw input, which means that things like arrow keys144will show up in the platform's native escape format. The only characters145translated are ``^C`` and ``^D`` which are converted into keyboard146interrupts and end of file exceptions respectively. This is done because147otherwise, it's too easy to forget about that and to create scripts that148cannot be properly exited.149150151Waiting for Key Press152---------------------153154.. versionadded:: 2.0155156Sometimes, it's useful to pause until the user presses any key on the157keyboard. This is especially useful on Windows where ``cmd.exe`` will158close the window at the end of the command execution by default, instead159of waiting.160161In click, this can be accomplished with the :func:`pause` function. This162function will print a quick message to the terminal (which can be163customized) and wait for the user to press a key. In addition to that,164it will also become a NOP (no operation instruction) if the script is not165run interactively.166167Example::168169 import click170 click.pause()171172173Launching Editors174-----------------175176.. versionadded:: 2.0177178Click supports launching editors automatically through :func:`edit`. This179is very useful for asking users for multi-line input. It will180automatically open the user's defined editor or fall back to a sensible181default. If the user closes the editor without saving, the return value182will be `None` otherwise the entered text.183184Example usage::185186 import click187188 def get_commit_message():189 MARKER = '# Everything below is ignored\n'190 message = click.edit('\n\n' + MARKER)191 if message is not None:192 return message.split(MARKER, 1)[0].rstrip('\n')193194Alternatively, the function can also be used to launch editors for files by195a specific filename. In this case, the return value is always `None`.196197Example usage::198199 import click200 click.edit(filename='/etc/passwd')201202203Launching Applications204----------------------205206.. versionadded:: 2.0207208Click supports launching applications through :func:`launch`. This can be209used to open the default application assocated with a URL or filetype.210This can be used to launch web browsers or picture viewers, for instance.211In addition to this, it can also launch the file manager and automatically212select the provided file.213214Example usage::215216 click.launch('http://click.pocoo.org/')217 click.launch('/my/downloaded/file.txt', locate=True)218219220Printing Filenames221------------------222223Because filenames might not be Unicode, formatting them can be a bit224tricky. Generally, this is easier in Python 2 than on 3, as you can just225write the bytes to stdout with the ``print`` function, but in Python 3, you226will always need to operate in Unicode.227228The way this works with click is through the :func:`format_filename`229function. It does a best-effort conversion of the filename to Unicode and230will never fail. This makes it possible to use these filenames in the231context of a full Unicode string.232233Example::234235 click.echo('Path: %s' % click.format_filename(b'foo.txt'))236237238Standard Streams239----------------240241For command line utilities, it's very important to get access to input and242output streams reliably. Python generally provides access to these243streams through ``sys.stdout`` and friends, but unfortunately, there are244API differences between 2.x and 3.x, especially with regards to how these245streams respond to Unicode and binary data.246247Because of this, click provides the :func:`get_binary_stream` and248:func:`get_text_stream` functions, which produce consistent results with249different Python versions and for a wide variety pf terminal configurations.250251The end result is that these functions will always return a functional252stream object (except in very odd cases in Python 3; see253:ref:`python3-limitations`).254255Example::256257 import click258259 stdin_text = click.get_text_stream('stdin')260 stdout_binary = click.get_binary_stream('stdout')261262263Finding Application Folders264---------------------------265266.. versionadded:: 2.0267268Very often, you want to open a configuration file that belongs to your269application. However, different operating systems store these configuration270files in different locations depending on their standards. Click provides271a :func:`get_app_dir` function which returns the most appropriate location272for per-user config files for your application depending on the OS.273274Example usage::275276 import os277 import click278 import ConfigParser279280 APP_NAME = 'My Application'281282 def read_config():283 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')284 parser = ConfigParser.RawConfigParser()285 parser.read([cfg])286 rv = {}287 for section in parser.sections():288 for key, value in parser.items(section):289 rv['%s.%s' % (section, key)] = value290 return rv291292293Showing Progress Bars294---------------------295296.. versionadded:: 2.0297298Sometimes, you have command line scripts that need to process a lot of data,299but you want to quickly show the user some progress about how long that300will take. Click supports simple progress bar rendering for that through301the :func:`progressbar` function.302303The basic usage is very simple: the idea is that you have an iterable that304you want to operate on. For each item in the iterable it might take some305time to do processing. So say you have a loop like this::306307 for user in all_the_users_to_process:308 modify_the_user(user)309310To hook this up with an automatically updating progress bar, all you need311to do is to change the code to this::312313 import click314315 with click.progressbar(all_the_users_to_process) as bar:316 for user in bar:317 modify_the_user(user)318319Click will then automatically print a progress bar to the terminal and320calculate the remaining time for you. The calculation of remaining time321requires that the iterable has a length. If it does not have a length322but you know the length, you can explicitly provide it::323324 with click.progressbar(all_the_users_to_process,325 length=number_of_users) as bar:326 for user in bar:327 modify_the_user(user)328329Another useful feature is to associate a label with the progress bar which330will be shown preceding the progress bar::331332 with click.progressbar(all_the_users_to_process,333 label='Modifying user accounts',334 length=number_of_users) as bar:335 for user in bar:336 modify_the_user(user)