Skip to content
Myr

utils.rst

This file

Path

docs/utils.rst

336 lines · 10.5 KiB

Last changed by

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

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 #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

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

line 13why, one step back
13

Documentation fixesKevin Yapbefore adoption67523af

line 14why, one step back
14The most obvious helper is the :func:`echo` function, which in many ways

Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4

line 15why, one step back
15works like the Python ``print`` statement or function. The main difference is

Merge pull request #113 from iKevinY/doc-fixesArmin Ronacherbefore adoptione0ea94a

line 16why, one step back
16that it works the same in Python 2 and 3, it intelligently detects

Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4

line 17why, one step back
17misconfigured output streams, and it will never fail (except in Python 3; for

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

lines 18–25why, one step back
18more information see :ref:`python3-limitations`).
1920Example::2122 import click2324 click.echo('Hello World!')25

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 26why, one step back
26Most importantly, it can print both Unicode and binary data, unlike the

Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4

lines 27–29why, one step back
27built-in ``print`` function in Python 3, which cannot output any bytes. It
28will, however, emit a trailing newline by default, which needs to be29suppressed by passing ``nl=False``::

Added example on how to supress newlines.Armin Ronacherbefore adoptioned9594d

lines 30–32why, one step back
30
31 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

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 41why, one step back
41Starting with Click 2.0, the :func:`echo` function gained extra

Documentation fixesKevin Yapbefore adoption67523af

line 42why, one step back
42functionality to deal with ANSI colors and styles. Note that on Windows,

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

line 43why, one step back
43this functionality is only available if `colorama`_ is installed. If it

Documentation fixesKevin Yapbefore adoption67523af

line 44why, one step back
44is installed, then ANSI codes are intelligently handled.

Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550

lines 45–47why, one step back
45
46Primarily this means that:47

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 48why, one step back
48- Click's :func:`echo` function will automatically strip ANSI color codes

Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4

lines 49–50why, one step back
49 if the stream is not connected to a terminal.
50- the :func:`echo` function will transparently connect to the terminal on

Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550

lines 51–54why, one step back
51 Windows and translate ANSI codes to terminal API calls. This means
52 that colors will work on Windows the same way they do on other53 operating systems.54

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 55why, one step back
55Note for `colorama` support: Click will automatically detect when `colorama`

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

line 56why, one step back
56is available and use it. Do *not* call ``colorama.init()``!

Added note on colorama installation.Armin Ronacherbefore adoption398e43c

line 57why, one step back
57

Documentation fixesKevin Yapbefore adoption67523af

line 58why, one step back
58To install `colorama`, run this command::

Added note on colorama installation.Armin Ronacherbefore adoption398e43c

lines 59–61why, one step back
59
60 $ pip install colorama61

Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4

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–67why, one step back
66 click.echo(click.style('Hello World!', fg='green'))
67 click.echo(click.style('Some more text', bg='blue', fg='white'))

Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4

line 68why, one step back
68 click.echo(click.style('ATTENTION', blink=True, bold=True))

Added colorama exampleArmin Ronacherbefore adoption3d19d7f

line 69why, one step back
69

Added sechoArmin Ronacherbefore adoption97f942c

lines 70–74why, 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')

Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4

line 75why, one step back
75 click.secho('ATTENTION', blink=True, bold=True)

Added sechoArmin Ronacherbefore adoption97f942c

line 76why, one step back
76

Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550

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

Moved pager support in the docsArmin Ronacherbefore adoptionf0b559f

lines 80–82why, one step back
80Pager Support
81-------------82

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 83why, one step back
83In some situations, you might want to show long texts on the terminal and

Moved pager support in the docsArmin Ronacherbefore adoptionf0b559f

line 84why, one step back
84let a user scroll through it. This can be achieved by using the

Documentation fixesKevin Yapbefore adoption67523af

lines 85–86why, one step back
85:func:`echo_via_pager` function which works similarly to the :func:`echo`
86function, but always writes to stdout and, if possible, through a pager.

Moved pager support in the docsArmin Ronacherbefore adoptionf0b559f

lines 87–96why, one step back
87
88Example:8990.. click:example::9192 @click.command()93 def less():94 click.echo_via_pager('\n'.join('Line %d' % idx95 for idx in range(200)))96

Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550

line 97why, one step back
97

Added support for screen clearing.Armin Ronacherbefore adoption09ba1e9

lines 98–102why, one step back
98Screen Clearing
99---------------100101.. versionadded:: 2.0102

Documentation fixesKevin Yapbefore adoption67523af

line 103why, one step back
103To clear the terminal screen, you can use the :func:`clear` function that

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 104why, one step back
104is provided starting with Click 2.0. It does what the name suggests: it

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 105why, one step back
105clears the entire visible screen in a platform-agnostic way:

Added support for screen clearing.Armin Ronacherbefore adoption09ba1e9

lines 106–112why, one step back
106
107::108109 import click110 click.clear()111112

Added getchar()Armin Ronacherbefore adoption88c97ef

lines 113–117why, one step back
113Getting Characters from Terminal
114--------------------------------115116.. versionadded:: 2.0117

Documentation fixesKevin Yapbefore adoption67523af

line 118why, one step back
118Normally, when reading input from the terminal, you would read from

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 119–120why, one step back
119standard input. However, this is buffered input and will not show up until
120the line has been terminated. In certain circumstances, you might not want

Documentation fixesKevin Yapbefore adoption67523af

line 121why, one step back
121to do that and instead read individual characters as they are being written.

Added getchar()Armin Ronacherbefore adoption88c97ef

line 122why, one step back
122

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 123why, one step back
123For this, Click provides the :func:`getchar` function which reads a single

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 124why, one step back
124character from the terminal buffer and returns it as a Unicode character.

Added getchar()Armin Ronacherbefore adoption88c97ef

lines 125–142why, one step back
125
126Note 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 :(')142

Documentation fixesKevin Yapbefore adoption67523af

line 143why, one step back
143Note that this reads raw input, which means that things like arrow keys

Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4

lines 144–145why, one step back
144will show up in the platform's native escape format. The only characters
145translated are ``^C`` and ``^D`` which are converted into keyboard

Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4

lines 146–148why, one step back
146interrupts and end of file exceptions respectively. This is done because
147otherwise, it's too easy to forget about that and to create scripts that148cannot be properly exited.

Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4

line 149why, one step back
149

Added getchar()Armin Ronacherbefore adoption88c97ef

line 150why, one step back
150

Added click.pauseArmin Ronacherbefore adoptionc9eb780

lines 151–155why, one step back
151Waiting for Key Press
152---------------------153154.. versionadded:: 2.0155

Documentation fixesKevin Yapbefore adoption67523af

lines 156–158why, one step back
156Sometimes, it's useful to pause until the user presses any key on the
157keyboard. This is especially useful on Windows where ``cmd.exe`` will158close the window at the end of the command execution by default, instead

Added click.pauseArmin Ronacherbefore adoptionc9eb780

lines 159–160why, one step back
159of waiting.
160

Documentation fixesKevin Yapbefore adoption67523af

line 161why, one step back
161In click, this can be accomplished with the :func:`pause` function. This

Added click.pauseArmin Ronacherbefore adoptionc9eb780

line 162why, one step back
162function will print a quick message to the terminal (which can be

Documentation fixesKevin Yapbefore adoption67523af

lines 163–165why, one step back
163customized) 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.

Added click.pauseArmin Ronacherbefore adoptionc9eb780

lines 166–172why, one step back
166
167Example::168169 import click170 click.pause()171172

Added an edit function.Armin Ronacherbefore adoption721e527

lines 173–180why, one step back
173Launching Editors
174-----------------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 sensible

Documentation fixesKevin Yapbefore adoption67523af

line 181why, one step back
181default. If the user closes the editor without saving, the return value

Added an edit function.Armin Ronacherbefore adoption721e527

lines 182–193why, one step back
182will 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')193

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 194–195why, one step back
194Alternatively, the function can also be used to launch editors for files by
195a specific filename. In this case, the return value is always `None`.

Added an edit function.Armin Ronacherbefore adoption721e527

lines 196–202why, one step back
196
197Example usage::198199 import click200 click.edit(filename='/etc/passwd')201202

Added click.launchArmin Ronacherbefore adoptionba36392

lines 203–208why, one step back
203Launching Applications
204----------------------205206.. versionadded:: 2.0207208Click supports launching applications through :func:`launch`. This can be

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 209why, one step back
209used to open the default application assocated with a URL or filetype.

Documentation fixesKevin Yapbefore adoption67523af

lines 210–211why, one step back
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 automatically

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 212why, one step back
212select the provided file.

Added click.launchArmin Ronacherbefore adoptionba36392

lines 213–215why, one step back
213
214Example usage::215

open -> launchArmin Ronacherbefore adoption502c86b

lines 216–217why, one step back
216 click.launch('http://click.pocoo.org/')
217 click.launch('/my/downloaded/file.txt', locate=True)

Added click.launchArmin Ronacherbefore adoptionba36392

lines 218–219why, one step back
218
219

Added filename format functionArmin Ronacherbefore adoption31043c3

lines 220–222why, one step back
220Printing Filenames
221------------------222

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 223why, one step back
223Because filenames might not be Unicode, formatting them can be a bit

Merge pull request #113 from iKevinY/doc-fixesArmin Ronacherbefore adoptione0ea94a

line 224why, one step back
224tricky. Generally, this is easier in Python 2 than on 3, as you can just

Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4

lines 225–226why, one step back
225write the bytes to stdout with the ``print`` function, but in Python 3, you
226will always need to operate in Unicode.

Added filename format functionArmin Ronacherbefore adoption31043c3

lines 227–228why, one step back
227
228The way this works with click is through the :func:`format_filename`

Documentation fixesKevin Yapbefore adoption67523af

line 229why, one step back
229function. It does a best-effort conversion of the filename to Unicode and

Added filename format functionArmin Ronacherbefore adoption31043c3

line 230why, one step back
230will never fail. This makes it possible to use these filenames in the

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 231why, one step back
231context of a full Unicode string.

Added filename format functionArmin Ronacherbefore adoption31043c3

lines 232–237why, one step back
232
233Example::234235 click.echo('Path: %s' % click.format_filename(b'foo.txt'))236237

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

lines 238–240why, one step back
238Standard Streams
239----------------240

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 241why, one step back
241For command line utilities, it's very important to get access to input and

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

line 242why, one step back
242output streams reliably. Python generally provides access to these

Documentation fixesKevin Yapbefore adoption67523af

lines 243–245why, one step back
243streams through ``sys.stdout`` and friends, but unfortunately, there are
244API differences between 2.x and 3.x, especially with regards to how these245streams respond to Unicode and binary data.

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

line 246why, one step back
246

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 247why, one step back
247Because of this, click provides the :func:`get_binary_stream` and

Documentation fixesKevin Yapbefore adoption67523af

lines 248–249why, one step back
248:func:`get_text_stream` functions, which produce consistent results with
249different Python versions and for a wide variety pf terminal configurations.

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

line 250why, one step back
250

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

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

Merge pull request #113 from iKevinY/doc-fixesArmin Ronacherbefore adoptione0ea94a

line 252why, one step back
252stream object (except in very odd cases in Python 3; see

Updated docs for streamsArmin Ronacherbefore adoptionfff6b28

lines 253–260why, one step back
253:ref:`python3-limitations`).
254255Example::256257 import click258259 stdin_text = click.get_text_stream('stdin')260 stdout_binary = click.get_binary_stream('stdout')

Documented new functions in utilsArmin Ronacherbefore adoption397438a

lines 261–267why, one step back
261
262263Finding Application Folders264---------------------------265266.. versionadded:: 2.0267

Documentation fixesKevin Yapbefore adoption67523af

line 268why, one step back
268Very often, you want to open a configuration file that belongs to your

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 269–271why, one step back
269application. However, different operating systems store these configuration
270files in different locations depending on their standards. Click provides271a :func:`get_app_dir` function which returns the most appropriate location

Merge branch 'pr/95'Armin Ronacherbefore adoption61e5a16

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

Documented new functions in utilsArmin Ronacherbefore adoption397438a

lines 273–297why, one step back
273
274Example 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.0297

Documentation fixesKevin Yapbefore adoption67523af

line 298why, one step back
298Sometimes, you have command line scripts that need to process a lot of data,

Documented new functions in utilsArmin Ronacherbefore adoption397438a

lines 299–309why, one step back
299but you want to quickly show the user some progress about how long that
300will 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)309

Documentation fixesKevin Yapbefore adoption67523af

line 310why, one step back
310To hook this up with an automatically updating progress bar, all you need

Documented new functions in utilsArmin Ronacherbefore adoption397438a

lines 311–320why, one step back
311to 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 time

Documentation fixesKevin Yapbefore adoption67523af

line 321why, one step back
321requires that the iterable has a length. If it does not have a length

Documented new functions in utilsArmin Ronacherbefore adoption397438a

lines 322–329why, one step back
322but 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 which

Merge branch 'pr/95'Armin Ronacherbefore adoption61e5a16

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

Documented new functions in utilsArmin Ronacherbefore adoption397438a

lines 331–336why, one step back
331
332 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)