utils.rst
This file
Path
docs/utils.rst
184 lines · 5.9 KiB
Last changed by
Cross link for ansi colors.Armin Ronacherbefore adoptionc5d53f8
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 a bit of extra42functionality to deal with ANSI colors. This functionality is only43available if `colorama`_ is installed. If it is installed then ANSI codes44are 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.5455Click will automatically detect when `colorama` is available and use it.56You do not have to call ``colorama.init()``. In fact, it's strongly57recommended you not doing that as colorama will change the default output58streams which is not a good idea.5960To install colorama run this command::6162 $ pip install colorama636465.. _colorama: https://pypi.python.org/pypi/colorama666768Printing Filenames69------------------7071Because filenames might not be unicode, formatting them can be a bit72tricky. Generally this is easier on Python 2 than on 3 as you can just73write the bytes to stdout with the print function, but at least on Python743 you will need to always operate in unicode.7576The way this works with click is through the :func:`format_filename`77function. It does a best effort conversion of the filename to Unicode and78will never fail. This makes it possible to use these filenames in the79context of a full unicode string.8081Example::8283 click.echo('Path: %s' % click.format_filename(b'foo.txt'))848586Standard Streams87----------------8889For command line utilities it's very important to get access to input and90output streams reliably. Python generally provides access to these91streams through ``sys.stdout`` and friends, but unfortunately there are92API differences between 2.x and 3.x. Especially in regards to how these93streams respond to unicode and binary data there are wide differences.9495Because of this click provides the :func:`get_binary_stream` and96:func:`get_text_stream` which produce consistent results with different97Python versions and for widely misconfigured terminals.9899The end result is that these functions will always return a functional100stream object (except in very odd cases on Python 3, see101:ref:`python3-limitations`).102103Example::104105 import click106107 stdin_text = click.get_text_stream('stdin')108 stdout_binary = click.get_binary_stream('stdout')109110111Finding Application Folders112---------------------------113114.. versionadded:: 2.0115116Very often you want to open a config file that belongs to your117application. However different operationg systems store these config118files by their policy in different places. Click provides a119:func:`get_app_dir` function which returns the most appropriate location120for per user config files for your application depending on the OS.121122Example usage::123124 import os125 import click126 import ConfigParser127128 APP_NAME = 'My Application'129130 def read_config():131 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')132 parser = ConfigParser.RawConfigParser()133 parser.read([cfg])134 rv = {}135 for section in parser.sections():136 for key, value in parser.items(section):137 rv['%s.%s' % (section, key)] = value138 return rv139140141Showing Progress Bars142---------------------143144.. versionadded:: 2.0145146Sometimes you have command line scripts that need to process a lot of data147but you want to quickly show the user some progress about how long that148will take. Click supports simple progress bar rendering for that through149the :func:`progressbar` function.150151The basic usage is very simple: the idea is that you have an iterable that152you want to operate on. For each item in the iterable it might take some153time to do processing. So say you have a loop like this::154155 for user in all_the_users_to_process:156 modify_the_user(user)157158To hook this up with an automatically updating progress bar all you need159to do is to change the code to this::160161 import click162163 with click.progressbar(all_the_users_to_process) as bar:164 for user in bar:165 modify_the_user(user)166167Click will then automatically print a progress bar to the terminal and168calculate the remaining time for you. The calculation of remaining time169requires that the iterable has a length. If it does not have a length,170but you know the length, you can explicitly provide it::171172 with click.progressbar(all_the_users_to_process,173 length=number_of_users) as bar:174 for user in bar:175 modify_the_user(user)176177Another useful feature is to associate a label with the progress bar which178will be shown before next to the progress bar::179180 with click.progressbar(all_the_users_to_process,181 label='Modifying user accounts',182 length=number_of_users) as bar:183 for user in bar:184 modify_the_user(user)