utils.rst
This file
Path
docs/utils.rst
259 lines · 8.0 KiB
Last changed by
Added click.launchArmin Ronacherbefore adoptionba36392
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 on Python 2 and 3 and it intelligently detects17misconfigured output streams and will never fail (except on 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 the27builtin ``print`` function on Python 3 which cannot output any bytes. It28will however emit a trailing newline by default which needs to be29supressed 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 Windows43this functionality is only available if `colorama`_ is installed. If it44is installed then ANSI codes are intelligently handled.4546Primarily this means that:4748- click's echo function will automatically strip ANSI color codes if the49 stream is not connected to a terminal.50- the 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))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)767778.. _colorama: https://pypi.python.org/pypi/colorama798081Screen Clearing82---------------8384.. versionadded:: 2.08586To clear the terminal screen you can use the :func:`clear` function that87is provided starting with Click 2.0. It does what the name suggests: it88clears the entire visible screen in a platform agnostic way:8990::9192 import click93 click.clear()949596Launching Editors97-----------------9899.. versionadded:: 2.0100101Click supports launching editors automatically through :func:`edit`. This102is very useful for asking users for multi-line input. It will103automatically open the user's defined editor or fall back to a sensible104default. If the user closes the editor without saving the return value105will be `None` otherwise the entered text.106107Example usage::108109 import click110111 def get_commit_message():112 MARKER = '# Everything below is ignored\n'113 message = click.edit('\n\n' + MARKER)114 if message is not None:115 return message.split(MARKER, 1)[0].rstrip('\n')116117Alternatively the function can also be used to launch editors for files by118a specific filename. In that case the return value is always `None`.119120Example usage::121122 import click123 click.edit(filename='/etc/passwd')124125126Launching Applications127----------------------128129.. versionadded:: 2.0130131Click supports launching applications through :func:`launch`. This can be132used to open the default application assocated with a URL or file type.133This for instance can be used to both launch web browsers as well as134picture viewers etc. In addition to that it can also launch the file135manager and automatically select the provided file.136137Example usage::138139 click.open('http://click.pocoo.org/')140 click.open('/my/downloaded/file.txt', locate=True)141142143Printing Filenames144------------------145146Because filenames might not be unicode, formatting them can be a bit147tricky. Generally this is easier on Python 2 than on 3 as you can just148write the bytes to stdout with the print function, but at least on Python1493 you will need to always operate in unicode.150151The way this works with click is through the :func:`format_filename`152function. It does a best effort conversion of the filename to Unicode and153will never fail. This makes it possible to use these filenames in the154context of a full unicode string.155156Example::157158 click.echo('Path: %s' % click.format_filename(b'foo.txt'))159160161Standard Streams162----------------163164For command line utilities it's very important to get access to input and165output streams reliably. Python generally provides access to these166streams through ``sys.stdout`` and friends, but unfortunately there are167API differences between 2.x and 3.x. Especially in regards to how these168streams respond to unicode and binary data there are wide differences.169170Because of this click provides the :func:`get_binary_stream` and171:func:`get_text_stream` which produce consistent results with different172Python versions and for widely misconfigured terminals.173174The end result is that these functions will always return a functional175stream object (except in very odd cases on Python 3, see176:ref:`python3-limitations`).177178Example::179180 import click181182 stdin_text = click.get_text_stream('stdin')183 stdout_binary = click.get_binary_stream('stdout')184185186Finding Application Folders187---------------------------188189.. versionadded:: 2.0190191Very often you want to open a config file that belongs to your192application. However different operating systems store these config193files by their policy in different places. Click provides a194:func:`get_app_dir` function which returns the most appropriate location195for per-user config files for your application depending on the OS.196197Example usage::198199 import os200 import click201 import ConfigParser202203 APP_NAME = 'My Application'204205 def read_config():206 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')207 parser = ConfigParser.RawConfigParser()208 parser.read([cfg])209 rv = {}210 for section in parser.sections():211 for key, value in parser.items(section):212 rv['%s.%s' % (section, key)] = value213 return rv214215216Showing Progress Bars217---------------------218219.. versionadded:: 2.0220221Sometimes you have command line scripts that need to process a lot of data222but you want to quickly show the user some progress about how long that223will take. Click supports simple progress bar rendering for that through224the :func:`progressbar` function.225226The basic usage is very simple: the idea is that you have an iterable that227you want to operate on. For each item in the iterable it might take some228time to do processing. So say you have a loop like this::229230 for user in all_the_users_to_process:231 modify_the_user(user)232233To hook this up with an automatically updating progress bar all you need234to do is to change the code to this::235236 import click237238 with click.progressbar(all_the_users_to_process) as bar:239 for user in bar:240 modify_the_user(user)241242Click will then automatically print a progress bar to the terminal and243calculate the remaining time for you. The calculation of remaining time244requires that the iterable has a length. If it does not have a length,245but you know the length, you can explicitly provide it::246247 with click.progressbar(all_the_users_to_process,248 length=number_of_users) as bar:249 for user in bar:250 modify_the_user(user)251252Another useful feature is to associate a label with the progress bar which253will be shown preceding the progress bar::254255 with click.progressbar(all_the_users_to_process,256 label='Modifying user accounts',257 length=number_of_users) as bar:258 for user in bar:259 modify_the_user(user)