Skip to content
Myr

utils.rst

This file

Path

docs/utils.rst

379 lines · 11.8 KiB

Last changed by

Fix some typosMarkus Unterwaditzerbefore adoption46b22d0

History of this file

Take it

The walk stopped after 200 commits: lines older than 13ab804 point at it.

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 7–13why, one step back
7parsing and handling, it also provides a bunch of addon functionality that
8is useful for writing command line utilities.91011Printing to Stdout12------------------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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 18–26why, one step back
18more information see :ref:`python3-limitations`).
1920Example::2122 import click2324 click.echo('Hello World!')2526Most 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``::

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 30–32why, one step back
30
31 click.echo(b'\xe2\x98\x83', nl=False)32

Added err to click echo docsArmin Ronacherbefore adoption1b3a822

lines 33–39why, one step back
33.. versionadded:: 3.0
3435Starting with Click 3.0 you can also easily print to standard error by36passing ``err=True``::3738 click.echo('Hello World!', err=True)39

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 40–47why, one step back
40
41.. _ansi-colors:4243ANSI Colors44-----------4546.. versionadded:: 2.047

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

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

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

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

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 52–54why, one step back
52
53Primarily this means that:54

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

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

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

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 58–61why, one step back
58 Windows and translate ANSI codes to terminal API calls. This means
59 that colors will work on Windows the same way they do on other60 operating systems.61

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

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 63–64why, one step back
63is available and use it. Do *not* call ``colorama.init()``!
64

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 66–68why, one step back
66
67 $ pip install colorama68

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

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 70–74why, one step back
70
71 import click7273 click.echo(click.style('Hello World!', fg='green'))74 click.echo(click.style('Some more text', bg='blue', fg='white'))

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

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 76–81why, one step back
76
77The combination of :func:`echo` and :func:`style` is also available in78a single function called :func:`secho`::7980 click.secho('Hello World!', fg='green')81 click.secho('Some more text', bg='blue', fg='white')

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

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 83–91why, one step back
83
8485.. _colorama: https://pypi.python.org/pypi/colorama8687Pager Support88-------------8990In some situations, you might want to show long texts on the terminal and91let a user scroll through it. This can be achieved by using the

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 94–109why, one step back
94
95Example:9697.. click:example::9899 @click.command()100 def less():101 click.echo_via_pager('\n'.join('Line %d' % idx102 for idx in range(200)))103104105Screen Clearing106---------------107108.. versionadded:: 2.0109

Documentation fixesKevin Yapbefore adoption67523af

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

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

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 112–124why, one step back
112clears the entire visible screen in a platform-agnostic way:
113114::115116 import click117 click.clear()118119120Getting Characters from Terminal121--------------------------------122123.. versionadded:: 2.0124

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

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

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

line 129why, one step back
129

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

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 131–149why, one step back
131character from the terminal buffer and returns it as a Unicode character.
132133Note that this function will always read from the terminal, even if stdin134is instead a pipe.135136Example::137138 import click139140 click.echo('Continue? [yn] ', nl=False)141 c = click.getchar()142 click.echo()143 if c == 'y':144 click.echo('We will go on')145 elif c == 'n':146 click.echo('Abort!')147 else:148 click.echo('Invalid input :(')149

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

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

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

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 156–162why, one step back
156
157158Waiting for Key Press159---------------------160161.. versionadded:: 2.0162

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 166–167why, one step back
166of waiting.
167

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

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

Documentation fixesKevin Yapbefore adoption67523af

lines 170–172why, one step back
170customized) and wait for the user to press a key. In addition to that,
171it will also become a NOP (no operation instruction) if the script is not172run interactively.

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 173–187why, one step back
173
174Example::175176 import click177 click.pause()178179180Launching Editors181-----------------182183.. versionadded:: 2.0184185Click supports launching editors automatically through :func:`edit`. This186is very useful for asking users for multi-line input. It will187automatically open the user's defined editor or fall back to a sensible

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 189–216why, one step back
189will be `None` otherwise the entered text.
190191Example usage::192193 import click194195 def get_commit_message():196 MARKER = '# Everything below is ignored\n'197 message = click.edit('\n\n' + MARKER)198 if message is not None:199 return message.split(MARKER, 1)[0].rstrip('\n')200201Alternatively, the function can also be used to launch editors for files by202a specific filename. In this case, the return value is always `None`.203204Example usage::205206 import click207 click.edit(filename='/etc/passwd')208209210Launching Applications211----------------------212213.. versionadded:: 2.0214215Click supports launching applications through :func:`launch`. This can be216used to open the default application assocated with a URL or filetype.

Documentation fixesKevin Yapbefore adoption67523af

lines 217–218why, one step back
217This can be used to launch web browsers or picture viewers, for instance.
218In addition to this, it can also launch the file manager and automatically

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 219–230why, one step back
219select the provided file.
220221Example usage::222223 click.launch('http://click.pocoo.org/')224 click.launch('/my/downloaded/file.txt', locate=True)225226227Printing Filenames228------------------229230Because filenames might not be Unicode, formatting them can be a bit

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

line 231why, one step back
231tricky. 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 232–233why, one step back
232write the bytes to stdout with the ``print`` function, but in Python 3, you
233will always need to operate in Unicode.

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

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

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 237–249why, one step back
237will never fail. This makes it possible to use these filenames in the
238context of a full Unicode string.239240Example::241242 click.echo('Path: %s' % click.format_filename(b'foo.txt'))243244245Standard Streams246----------------247248For command line utilities, it's very important to get access to input and249output streams reliably. Python generally provides access to these

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 253–254why, one step back
253
254Because of this, click provides the :func:`get_binary_stream` and

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 257–258why, one step back
257
258The end result is that these functions will always return a functional

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

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 260–269why, one step back
260:ref:`python3-limitations`).
261262Example::263264 import click265266 stdin_text = click.get_text_stream('stdin')267 stdout_binary = click.get_binary_stream('stdout')268269

Added open_file function.Armin Ronacherbefore adoption075a77b

lines 270–294why, one step back
270Intelligent File Opening
271------------------------272273.. versionadded:: 3.0274275Starting with Click 3.0 the logic for opening files from the :class:`File`276type is exposed through the :func:`open_file` function. It can277intelligently open stdin/stdout as well as any other file.278279Example::280281 import click282283 stdout = click.open_file('-', 'w')284 test_file = click.open_file('test.txt', 'w')285286If stdin or stdout are returned, the return value is wrapped in a special287file where the context manager will prevent the closing of the file. This288makes the handling of standard streams transparent and you can always use289it like this::290291 with click.open_file(filename, 'w') as f:292 f.write('Hello World!\n')293294

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 295–299why, one step back
295Finding Application Folders
296---------------------------297298.. versionadded:: 2.0299

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 301–329why, one step back
301application. However, different operating systems store these configuration
302files in different locations depending on their standards. Click provides303a :func:`get_app_dir` function which returns the most appropriate location304for per-user config files for your application depending on the OS.305306Example usage::307308 import os309 import click310 import ConfigParser311312 APP_NAME = 'My Application'313314 def read_config():315 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')316 parser = ConfigParser.RawConfigParser()317 parser.read([cfg])318 rv = {}319 for section in parser.sections():320 for key, value in parser.items(section):321 rv['%s.%s' % (section, key)] = value322 return rv323324325Showing Progress Bars326---------------------327328.. versionadded:: 2.0329

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 331–341why, one step back
331but you want to quickly show the user some progress about how long that
332will take. Click supports simple progress bar rendering for that through333the :func:`progressbar` function.334335The basic usage is very simple: the idea is that you have an iterable that336you want to operate on. For each item in the iterable it might take some337time to do processing. So say you have a loop like this::338339 for user in all_the_users_to_process:340 modify_the_user(user)341

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 343–352why, one step back
343to do is to change the code to this::
344345 import click346347 with click.progressbar(all_the_users_to_process) as bar:348 for user in bar:349 modify_the_user(user)350351Click will then automatically print a progress bar to the terminal and352calculate the remaining time for you. The calculation of remaining time

Documentation fixesKevin Yapbefore adoption67523af

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

Add test to ensure click does not import too muchArmin Ronacherbefore adoption13ab804

lines 354–368why, one step back
354but you know the length, you can explicitly provide it::
355356 with click.progressbar(all_the_users_to_process,357 length=number_of_users) as bar:358 for user in bar:359 modify_the_user(user)360361Another useful feature is to associate a label with the progress bar which362will be shown preceding the progress bar::363364 with click.progressbar(all_the_users_to_process,365 label='Modifying user accounts',366 length=number_of_users) as bar:367 for user in bar:368 modify_the_user(user)

Added support for manually advancing progressbars.Armin Ronacherbefore adoption90d7ee9

lines 369–370why, one step back
369
370Sometimes, one may need to iterate over an external iterator, and advance the

Fix some typosMarkus Unterwaditzerbefore adoption46b22d0

line 371why, one step back
371progress bar irregularly. To do so, you need to specify the length (and no

Added support for manually advancing progressbars.Armin Ronacherbefore adoption90d7ee9

lines 372–379why, one step back
372iterable), and use the update method on the context return value instead of
373iterating directly over it::374375 with click.progressbar(length=total_size,376 label='Unzipping archive') as bar:377 for archive in zip_file:378 archive.extract()379 bar.update(archive.size)