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
Updated docs for streamsArmin Ronacherbefore adoptionfff6b28
lines 1–5why, one step back1Utilities2=========34.. currentmodule:: click5Merge pull request #78 from julen/doc-fixesArmin Ronacherbefore adoption147bd4b
line 6why, one step back6Besides the functionality that click provides to interface with argumentUpdated docs for streamsArmin Ronacherbefore adoptionfff6b28
lines 7–10why, one step back7parsing and handling, it also provides a bunch of addon functionality that8is useful for writing command line utilities.910Merge pull request #80 from dirn/patch-1Armin Ronacherbefore adoptionc7846b3
lines 11–12why, one step back11Printing to Stdout12------------------Updated docs for streamsArmin Ronacherbefore adoptionfff6b28
lines 13–25why, one step back1314The 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!')25Added example on how to supress newlines.Armin Ronacherbefore adoptioned9594d
lines 26–32why, one step back26Most 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)32Updated docs for streamsArmin Ronacherbefore adoptionfff6b28
line 33why, one step back33Cross link for ansi colors.Armin Ronacherbefore adoptionc5d53f8
lines 34–35why, one step back34.. _ansi-colors:35Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550
lines 36–40why, one step back36ANSI Colors37-----------3839.. versionadded:: 2.040Added style helpers and added deeper ansi color support. Colorama now optional.Armin Ronacherbefore adoptionf516eee
lines 41–44why, one step back41Starting 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.Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550
lines 45–54why, one step back4546Primarily 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.54Added style helpers and added deeper ansi color support. Colorama now optional.Armin Ronacherbefore adoptionf516eee
lines 55–56why, one step back55Note for colorama support: click will automatically detect when `colorama`56is available and use it. Do *not* call ``colorama.init()``!Added note on colorama installation.Armin Ronacherbefore adoption398e43c
lines 57–61why, one step back5758To install colorama run this command::5960 $ pip install colorama61Added style helpers and added deeper ansi color support. Colorama now optional.Armin Ronacherbefore adoptionf516eee
line 62why, one step back62For styling a string the :func:`style` function can be used::Added colorama exampleArmin Ronacherbefore adoption3d19d7f
lines 63–65why, one step back6364 import click65Added style helpers and added deeper ansi color support. Colorama now optional.Armin Ronacherbefore adoptionf516eee
lines 66–68why, one step back66 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))Added colorama exampleArmin Ronacherbefore adoption3d19d7f
line 69why, one step back69Added sechoArmin Ronacherbefore adoption97f942c
lines 70–76why, one step back70The 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)76Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550
lines 77–80why, one step back7778.. _colorama: https://pypi.python.org/pypi/colorama7980Added support for screen clearing.Armin Ronacherbefore adoption09ba1e9
lines 81–95why, one step back81Screen 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()9495Added an edit function.Armin Ronacherbefore adoption721e527
lines 96–125why, one step back96Launching 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')124125Added click.launchArmin Ronacherbefore adoptionba36392
lines 126–142why, one step back126Launching 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)141142Added filename format functionArmin Ronacherbefore adoption31043c3
lines 143–145why, one step back143Printing Filenames144------------------145Merge pull request #88 from julen/doc-fixesArmin Ronacherbefore adoptione45ef4c
lines 146–149why, one step back146Because 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.Added filename format functionArmin Ronacherbefore adoption31043c3
lines 150–160why, one step back150151The 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'))159160Updated docs for streamsArmin Ronacherbefore adoptionfff6b28
lines 161–173why, one step back161Standard 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.173Merge pull request #78 from julen/doc-fixesArmin Ronacherbefore adoption147bd4b
line 174why, one step back174The end result is that these functions will always return a functionalUpdated docs for streamsArmin Ronacherbefore adoptionfff6b28
lines 175–183why, one step back175stream 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')Documented new functions in utilsArmin Ronacherbefore adoption397438a
lines 184–191why, one step back184185186Finding Application Folders187---------------------------188189.. versionadded:: 2.0190191Very often you want to open a config file that belongs to yourMerge branch 'pr/95'Armin Ronacherbefore adoption61e5a16
line 192why, one step back192application. However different operating systems store these configDocumented new functions in utilsArmin Ronacherbefore adoption397438a
lines 193–194why, one step back193files by their policy in different places. Click provides a194:func:`get_app_dir` function which returns the most appropriate locationMerge branch 'pr/95'Armin Ronacherbefore adoption61e5a16
line 195why, one step back195for per-user config files for your application depending on the OS.Documented new functions in utilsArmin Ronacherbefore adoption397438a
lines 196–252why, one step back196197Example 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 whichMerge branch 'pr/95'Armin Ronacherbefore adoption61e5a16
line 253why, one step back253will be shown preceding the progress bar::Documented new functions in utilsArmin Ronacherbefore adoption397438a
lines 254–259why, one step back254255 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)