utils.rst
This file
Path
docs/utils.rst
379 lines · 11.8 KiB
Last changed by
Fix some typosMarkus Unterwaditzerbefore adoption46b22d0
History of this fileTake it
The walk stopped after 200 commits: lines older than 5cae326 point at it.
Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 1–5why, one step back1Utilities2=========34.. currentmodule:: click5Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 6why, one step back6Besides the functionality that Click provides to interface with argumentMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 7–13why, one step back7parsing and handling, it also provides a bunch of addon functionality that8is useful for writing command line utilities.91011Printing to Stdout12------------------13Documentation fixesKevin Yapbefore adoption67523af
line 14why, one step back14The most obvious helper is the :func:`echo` function, which in many waysMerge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4
line 15why, one step back15works like the Python ``print`` statement or function. The main difference isMerge pull request #113 from iKevinY/doc-fixesArmin Ronacherbefore adoptione0ea94a
line 16why, one step back16that it works the same in Python 2 and 3, it intelligently detectsMerge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4
line 17why, one step back17misconfigured output streams, and it will never fail (except in Python 3; forMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 18–26why, one step back18more information see :ref:`python3-limitations`).1920Example::2122 import click2324 click.echo('Hello World!')2526Most importantly, it can print both Unicode and binary data, unlike theMerge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4
lines 27–29why, one step back27built-in ``print`` function in Python 3, which cannot output any bytes. It28will, however, emit a trailing newline by default, which needs to be29suppressed by passing ``nl=False``::Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 30–32why, one step back3031 click.echo(b'\xe2\x98\x83', nl=False)32Added err to click echo docsArmin Ronacherbefore adoption1b3a822
lines 33–39why, one step back33.. versionadded:: 3.03435Starting with Click 3.0 you can also easily print to standard error by36passing ``err=True``::3738 click.echo('Hello World!', err=True)39Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 40–47why, one step back4041.. _ansi-colors:4243ANSI Colors44-----------4546.. versionadded:: 2.047Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 48why, one step back48Starting with Click 2.0, the :func:`echo` function gained extraDocumentation fixesKevin Yapbefore adoption67523af
line 49why, one step back49functionality to deal with ANSI colors and styles. Note that on Windows,Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
line 50why, one step back50this functionality is only available if `colorama`_ is installed. If itDocumentation fixesKevin Yapbefore adoption67523af
line 51why, one step back51is installed, then ANSI codes are intelligently handled.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 52–54why, one step back5253Primarily this means that:54Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 55why, one step back55- Click's :func:`echo` function will automatically strip ANSI color codesMerge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4
lines 56–57why, one step back56 if the stream is not connected to a terminal.57- the :func:`echo` function will transparently connect to the terminal onMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 58–61why, one step back58 Windows and translate ANSI codes to terminal API calls. This means59 that colors will work on Windows the same way they do on other60 operating systems.61Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 62why, one step back62Note for `colorama` support: Click will automatically detect when `colorama`Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 63–64why, one step back63is available and use it. Do *not* call ``colorama.init()``!64Documentation fixesKevin Yapbefore adoption67523af
line 65why, one step back65To install `colorama`, run this command::Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 66–68why, one step back6667 $ pip install colorama68Merge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4
line 69why, one step back69For styling a string, the :func:`style` function can be used::Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 70–74why, one step back7071 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 back75 click.echo(click.style('ATTENTION', blink=True, bold=True))Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 76–81why, one step back7677The 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 back82 click.secho('ATTENTION', blink=True, bold=True)Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 83–91why, one step back838485.. _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 theDocumentation fixesKevin Yapbefore adoption67523af
lines 92–93why, one step back92:func:`echo_via_pager` function which works similarly to the :func:`echo`93function, but always writes to stdout and, if possible, through a pager.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 94–109why, one step back9495Example: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.0109Documentation fixesKevin Yapbefore adoption67523af
line 110why, one step back110To clear the terminal screen, you can use the :func:`clear` function thatMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 111why, one step back111is provided starting with Click 2.0. It does what the name suggests: itMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 112–124why, one step back112clears the entire visible screen in a platform-agnostic way:113114::115116 import click117 click.clear()118119120Getting Characters from Terminal121--------------------------------122123.. versionadded:: 2.0124Documentation fixesKevin Yapbefore adoption67523af
line 125why, one step back125Normally, when reading input from the terminal, you would read fromMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 126–127why, one step back126standard input. However, this is buffered input and will not show up until127the line has been terminated. In certain circumstances, you might not wantDocumentation fixesKevin Yapbefore adoption67523af
line 128why, one step back128to do that and instead read individual characters as they are being written.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
line 129why, one step back129Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 130why, one step back130For this, Click provides the :func:`getchar` function which reads a singleMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 131–149why, one step back131character 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 :(')149Documentation fixesKevin Yapbefore adoption67523af
line 150why, one step back150Note that this reads raw input, which means that things like arrow keysMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 151–152why, one step back151will show up in the platform's native escape format. The only characters152translated are ``^C`` and ``^D`` which are converted into keyboardMerge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4
lines 153–155why, one step back153interrupts and end of file exceptions respectively. This is done because154otherwise, it's too easy to forget about that and to create scripts that155cannot be properly exited.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 156–157why, one step back156157Added click.pauseArmin Ronacherbefore adoptionc9eb780
lines 158–162why, one step back158Waiting for Key Press159---------------------160161.. versionadded:: 2.0162Documentation fixesKevin Yapbefore adoption67523af
lines 163–165why, one step back163Sometimes, it's useful to pause until the user presses any key on the164keyboard. This is especially useful on Windows where ``cmd.exe`` will165close the window at the end of the command execution by default, insteadAdded click.pauseArmin Ronacherbefore adoptionc9eb780
lines 166–167why, one step back166of waiting.167Documentation fixesKevin Yapbefore adoption67523af
line 168why, one step back168In click, this can be accomplished with the :func:`pause` function. ThisAdded click.pauseArmin Ronacherbefore adoptionc9eb780
line 169why, one step back169function will print a quick message to the terminal (which can beDocumentation fixesKevin Yapbefore adoption67523af
lines 170–172why, one step back170customized) 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.Added click.pauseArmin Ronacherbefore adoptionc9eb780
lines 173–179why, one step back173174Example::175176 import click177 click.pause()178179Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 180–187why, one step back180Launching 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 sensibleDocumentation fixesKevin Yapbefore adoption67523af
line 188why, one step back188default. If the user closes the editor without saving, the return valueMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 189–216why, one step back189will 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 back217This can be used to launch web browsers or picture viewers, for instance.218In addition to this, it can also launch the file manager and automaticallyMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 219–230why, one step back219select 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 bitMerge pull request #113 from iKevinY/doc-fixesArmin Ronacherbefore adoptione0ea94a
line 231why, one step back231tricky. Generally, this is easier in Python 2 than on 3, as you can justMerge pull request #114 from iKevinY/doc-fixesArmin Ronacherbefore adoptiona6136b4
lines 232–233why, one step back232write the bytes to stdout with the ``print`` function, but in Python 3, you233will always need to operate in Unicode.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 234–235why, one step back234235The way this works with click is through the :func:`format_filename`Documentation fixesKevin Yapbefore adoption67523af
line 236why, one step back236function. It does a best-effort conversion of the filename to Unicode andMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 237–249why, one step back237will never fail. This makes it possible to use these filenames in the238context 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 theseDocumentation fixesKevin Yapbefore adoption67523af
lines 250–252why, one step back250streams through ``sys.stdout`` and friends, but unfortunately, there are251API differences between 2.x and 3.x, especially with regards to how these252streams respond to Unicode and binary data.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 253–254why, one step back253254Because of this, click provides the :func:`get_binary_stream` andDocumentation fixesKevin Yapbefore adoption67523af
lines 255–256why, one step back255:func:`get_text_stream` functions, which produce consistent results with256different Python versions and for a wide variety pf terminal configurations.Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 257–258why, one step back257258The end result is that these functions will always return a functionalMerge pull request #113 from iKevinY/doc-fixesArmin Ronacherbefore adoptione0ea94a
line 259why, one step back259stream object (except in very odd cases in Python 3; seeMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 260–269why, one step back260:ref:`python3-limitations`).261262Example::263264 import click265266 stdin_text = click.get_text_stream('stdin')267 stdout_binary = click.get_binary_stream('stdout')268269Added open_file function.Armin Ronacherbefore adoption075a77b
lines 270–294why, one step back270Intelligent File Opening271------------------------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')293294Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 295–299why, one step back295Finding Application Folders296---------------------------297298.. versionadded:: 2.0299Documentation fixesKevin Yapbefore adoption67523af
line 300why, one step back300Very often, you want to open a configuration file that belongs to yourMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 301–329why, one step back301application. However, different operating systems store these configuration302files 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.0329Documentation fixesKevin Yapbefore adoption67523af
line 330why, one step back330Sometimes, you have command line scripts that need to process a lot of data,Merge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 331–341why, one step back331but you want to quickly show the user some progress about how long that332will 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)341Documentation fixesKevin Yapbefore adoption67523af
line 342why, one step back342To hook this up with an automatically updating progress bar, all you needMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 343–352why, one step back343to 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 timeDocumentation fixesKevin Yapbefore adoption67523af
line 353why, one step back353requires that the iterable has a length. If it does not have a lengthMerge pull request #110 from krockode/patch-1Armin Ronacherbefore adoption5cae326
lines 354–368why, one step back354but 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 back369370Sometimes, one may need to iterate over an external iterator, and advance theFix some typosMarkus Unterwaditzerbefore adoption46b22d0
line 371why, one step back371progress bar irregularly. To do so, you need to specify the length (and noAdded support for manually advancing progressbars.Armin Ronacherbefore adoption90d7ee9
lines 372–379why, one step back372iterable), and use the update method on the context return value instead of373iterating 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)