utils.rst
This file
Path
docs/utils.rst
336 lines · 10.4 KiB
Last changed by
Added click.pauseArmin Ronacherbefore adoptionc9eb780
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!')25Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 26why, one step back26Most importantly, it can print both Unicode and binary data, unlike theAdded example on how to supress newlines.Armin Ronacherbefore adoptioned9594d
line 27why, one step back27builtin ``print`` function on Python 3 which cannot output any bytes. ItMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 28why, one step back28will, however, emit a trailing newline by default which needs to beAdded example on how to supress newlines.Armin Ronacherbefore adoptioned9594d
lines 29–32why, one step back29supressed 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–79why, one step back7778.. _colorama: https://pypi.python.org/pypi/colorama79Moved pager support in the docsArmin Ronacherbefore adoptionf0b559f
lines 80–82why, one step back80Pager Support81-------------82Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 83why, one step back83In some situations, you might want to show long texts on the terminal andMoved pager support in the docsArmin Ronacherbefore adoptionf0b559f
lines 84–96why, one step back84let a user scroll through it. This can be achieved by using the85:func:`echo_via_pager` function which works similar to the :func:`echo`86function but always writes to stdout and, if possible, through a pager.8788Example:8990.. click:example::9192 @click.command()93 def less():94 click.echo_via_pager('\n'.join('Line %d' % idx95 for idx in range(200)))96Added colorama support into the echo function.Armin Ronacherbefore adoptionba19550
line 97why, one step back97Added support for screen clearing.Armin Ronacherbefore adoption09ba1e9
lines 98–104why, one step back98Screen Clearing99---------------100101.. versionadded:: 2.0102103To clear the terminal screen you can use the :func:`clear` function that104is provided starting with Click 2.0. It does what the name suggests: itMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 105why, one step back105clears the entire visible screen in a platform-agnostic way:Added support for screen clearing.Armin Ronacherbefore adoption09ba1e9
lines 106–112why, one step back106107::108109 import click110 click.clear()111112Added getchar()Armin Ronacherbefore adoption88c97ef
lines 113–118why, one step back113Getting Characters from Terminal114--------------------------------115116.. versionadded:: 2.0117118Normally when reading input from the terminal you would use reading fromMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 119–120why, one step back119standard input. However, this is buffered input and will not show up until120the line has been terminated. In certain circumstances, you might not wantAdded getchar()Armin Ronacherbefore adoption88c97ef
lines 121–124why, one step back121to do that and instead read individual characters as they are being122written.123124For this click provides the :func:`getchar` function which reads a singleMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 125why, one step back125character from the terminal buffer and returns it as a Unicode character.Added getchar()Armin Ronacherbefore adoption88c97ef
lines 126–143why, one step back126127Note that this function will always read from the terminal, even if stdin128is instead a pipe.129130Example::131132 import click133134 click.echo('Continue? [yn] ', nl=False)135 c = click.getchar()136 click.echo()137 if c == 'y':138 click.echo('We will go on')139 elif c == 'n':140 click.echo('Abort!')141 else:142 click.echo('Invalid input :(')143Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 144–150why, one step back144Note that this reads raw input which means that things like arrow keys145will show up in the platform's native escape format. The only characters146translated are ``^C`` and ``^D`` which are converted into keyboard147interrupt and end of file exceptions. This is done because otherwise it's148too easy to forget about that and to create scripts that cannot be149properly exited.150Added getchar()Armin Ronacherbefore adoption88c97ef
line 151why, one step back151Added click.pauseArmin Ronacherbefore adoptionc9eb780
lines 152–172why, one step back152Waiting for Key Press153---------------------154155.. versionadded:: 2.0156157Sometimes it's useful to pause until the user presses any key on the158keyboard. This is especially useful on windows where ``cmd.exe`` by159default will close the window at the end of the command execution instead160of waiting.161162In click this can be accomplished by the :func:`pause` function. This163function will print a quick message to the terminal (which can be164customized) and wait for the user to press a key. In addition to that165it will also become a noop if the script is not run interactively.166167Example::168169 import click170 click.pause()171172Added an edit function.Armin Ronacherbefore adoption721e527
lines 173–193why, one step back173Launching Editors174-----------------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 sensible181default. If the user closes the editor without saving the return value182will 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')193Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 194–195why, one step back194Alternatively, the function can also be used to launch editors for files by195a specific filename. In this case, the return value is always `None`.Added an edit function.Armin Ronacherbefore adoption721e527
lines 196–202why, one step back196197Example usage::198199 import click200 click.edit(filename='/etc/passwd')201202Added click.launchArmin Ronacherbefore adoptionba36392
lines 203–208why, one step back203Launching Applications204----------------------205206.. versionadded:: 2.0207208Click supports launching applications through :func:`launch`. This can beMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 209–212why, one step back209used to open the default application assocated with a URL or filetype.210This for instance can be used to launch web browsers, picture viewers, etc.211In addition to that, it can also launch the file manager and automatically212select the provided file.Added click.launchArmin Ronacherbefore adoptionba36392
lines 213–215why, one step back213214Example usage::215open -> launchArmin Ronacherbefore adoption502c86b
lines 216–217why, one step back216 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 back218219Added filename format functionArmin Ronacherbefore adoption31043c3
lines 220–222why, one step back220Printing Filenames221------------------222Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 223why, one step back223Because filenames might not be Unicode, formatting them can be a bitMerge pull request #88 from julen/doc-fixesArmin Ronacherbefore adoptione45ef4c
lines 224–225why, one step back224tricky. Generally this is easier on Python 2 than on 3 as you can just225write the bytes to stdout with the print function, but at least on PythonMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 226why, one step back2263 you will need to always operate in Unicode.Added filename format functionArmin Ronacherbefore adoption31043c3
lines 227–230why, one step back227228The way this works with click is through the :func:`format_filename`229function. It does a best effort conversion of the filename to Unicode and230will never fail. This makes it possible to use these filenames in theMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 231why, one step back231context of a full Unicode string.Added filename format functionArmin Ronacherbefore adoption31043c3
lines 232–237why, one step back232233Example::234235 click.echo('Path: %s' % click.format_filename(b'foo.txt'))236237Updated docs for streamsArmin Ronacherbefore adoptionfff6b28
lines 238–240why, one step back238Standard Streams239----------------240Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 241why, one step back241For command line utilities, it's very important to get access to input andUpdated docs for streamsArmin Ronacherbefore adoptionfff6b28
lines 242–244why, one step back242output streams reliably. Python generally provides access to these243streams through ``sys.stdout`` and friends, but unfortunately there are244API differences between 2.x and 3.x. Especially in regards to how theseMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 245why, one step back245streams respond to Unicode and binary data there are wide differences.Updated docs for streamsArmin Ronacherbefore adoptionfff6b28
line 246why, one step back246Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 247why, one step back247Because of this, click provides the :func:`get_binary_stream` andUpdated docs for streamsArmin Ronacherbefore adoptionfff6b28
lines 248–250why, one step back248:func:`get_text_stream` which produce consistent results with different249Python versions and for widely misconfigured terminals.250Merge pull request #78 from julen/doc-fixesArmin Ronacherbefore adoption147bd4b
line 251why, one step back251The end result is that these functions will always return a functionalUpdated docs for streamsArmin Ronacherbefore adoptionfff6b28
lines 252–260why, one step back252stream object (except in very odd cases on Python 3, see253: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 back261262263Finding Application Folders264---------------------------265266.. versionadded:: 2.0267Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 268–271why, one step back268Very often you want to open a configuration file that belongs to your269application. However, different operating systems store these configuration270files in different locations depending on their standards. Click provides271a :func:`get_app_dir` function which returns the most appropriate locationMerge branch 'pr/95'Armin Ronacherbefore adoption61e5a16
line 272why, one step back272for per-user config files for your application depending on the OS.Documented new functions in utilsArmin Ronacherbefore adoption397438a
lines 273–329why, one step back273274Example 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.0297298Sometimes you have command line scripts that need to process a lot of data299but you want to quickly show the user some progress about how long that300will 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)309310To hook this up with an automatically updating progress bar all you need311to 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 time321requires that the iterable has a length. If it does not have a length,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 whichMerge branch 'pr/95'Armin Ronacherbefore adoption61e5a16
line 330why, one step back330will be shown preceding the progress bar::Documented new functions in utilsArmin Ronacherbefore adoption397438a
lines 331–336why, one step back331332 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)