Skip to content
Myr

utils.rst

This file

Path

docs/utils.rst

259 lines · 8.0 KiB

Last changed by

Added click.launchArmin Ronacherbefore adoptionba36392

History of this file

Take it

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

lines 1–5why, one step back
1Utilities
2=========34.. currentmodule:: click5

Merge pull request #78 from julen/doc-fixesArmin Ronacherbefore adoption147bd4b

line 6why, one step back
6Besides the functionality that click provides to interface with argument

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

lines 7–10why, one step back
7parsing and handling, it also provides a bunch of addon functionality that
8is useful for writing command line utilities.910

Merge pull request #80 from dirn/patch-1Armin Ronacherbefore adoptionc7846b3

lines 11–12why, one step back
11Printing to Stdout
12------------------

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

lines 13–25why, one step back
13
14The 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!')25

Added example on how to supress newlines.Armin Ronacherbefore adoptioned9594d

lines 26–32why, one step back
26Most importantly it can print both unicode and binary data, unlike the
27builtin ``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)32

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

line 33why, one step back
33

Cross link for ansi colors.Armin Ronacherbefore adoptionc5d53f8

lines 34–35why, one step back
34.. _ansi-colors:
35

Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550

lines 36–40why, one step back
36ANSI Colors
37-----------3839.. versionadded:: 2.040

Added style helpers and added deeper ansi color support. Colorama now optional.Armin Ronacherbefore adoptionf516eee

lines 41–44why, one step back
41Starting with click 2.0 the :func:`echo` function gained extra
42functionality 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 back
45
46Primarily 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.54

Added style helpers and added deeper ansi color support. Colorama now optional.Armin Ronacherbefore adoptionf516eee

lines 55–56why, one step back
55Note 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 back
57
58To install colorama run this command::5960 $ pip install colorama61

Added style helpers and added deeper ansi color support. Colorama now optional.Armin Ronacherbefore adoptionf516eee

line 62why, one step back
62For styling a string the :func:`style` function can be used::

Added colorama exampleArmin Ronacherbefore adoption3d19d7f

lines 63–65why, one step back
63
64 import click65

Added style helpers and added deeper ansi color support. Colorama now optional.Armin Ronacherbefore adoptionf516eee

lines 66–68why, one step back
66 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 back
69

Added sechoArmin Ronacherbefore adoption97f942c

lines 70–76why, one step back
70The combination of :func:`echo` and :func:`style` is also available in
71a 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)76

Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550

lines 77–80why, one step back
77
78.. _colorama: https://pypi.python.org/pypi/colorama7980

Added support for screen clearing.Armin Ronacherbefore adoption09ba1e9

lines 81–95why, one step back
81Screen Clearing
82---------------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()9495

Added an edit function.Armin Ronacherbefore adoption721e527

lines 96–125why, one step back
96Launching Editors
97-----------------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')124125

Added click.launchArmin Ronacherbefore adoptionba36392

lines 126–142why, one step back
126Launching Applications
127----------------------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)141142

Added filename format functionArmin Ronacherbefore adoption31043c3

lines 143–145why, one step back
143Printing Filenames
144------------------145

Merge pull request #88 from julen/doc-fixesArmin Ronacherbefore adoptione45ef4c

lines 146–149why, one step back
146Because filenames might not be unicode, formatting them can be a bit
147tricky. 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 back
150
151The 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'))159160

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

lines 161–173why, one step back
161Standard Streams
162----------------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.173

Merge pull request #78 from julen/doc-fixesArmin Ronacherbefore adoption147bd4b

line 174why, one step back
174The end result is that these functions will always return a functional

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

lines 175–183why, one step back
175stream object (except in very odd cases on Python 3, see
176: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 back
184
185186Finding Application Folders187---------------------------188189.. versionadded:: 2.0190191Very often you want to open a config file that belongs to your

Merge branch 'pr/95'Armin Ronacherbefore adoption61e5a16

line 192why, one step back
192application. However different operating systems store these config

Documented new functions in utilsArmin Ronacherbefore adoption397438a

lines 193–194why, one step back
193files by their policy in different places. Click provides a
194:func:`get_app_dir` function which returns the most appropriate location

Merge branch 'pr/95'Armin Ronacherbefore adoption61e5a16

line 195why, one step back
195for per-user config files for your application depending on the OS.

Documented new functions in utilsArmin Ronacherbefore adoption397438a

lines 196–252why, one step back
196
197Example 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 which

Merge branch 'pr/95'Armin Ronacherbefore adoption61e5a16

line 253why, one step back
253will be shown preceding the progress bar::

Documented new functions in utilsArmin Ronacherbefore adoption397438a

lines 254–259why, one step back
254
255 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)