utils.rst
This file
Path
docs/utils.rst
409 lines · 12.9 KiB
Last changed by
Merge branch 'master' into upstreamJosiahDubbefore adoptiona4b6bbd
History of this fileTake it
1Utilities2=========34.. currentmodule:: click56Besides the functionality that Click provides to interface with argument7parsing and handling, it also provides a bunch of addon functionality that8is useful for writing command line utilities.91011Printing to Stdout12------------------1314The 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 in Python 2 and 3, it intelligently detects17misconfigured output streams, and it will never fail (except in Python 3; for18more information see :ref:`python3-limitations`).1920Example::2122 import click2324 click.echo('Hello World!')2526Most importantly, it can print both Unicode and binary data, unlike the27built-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``::3031 click.echo(b'\xe2\x98\x83', nl=False)3233Last but not least :func:`echo` uses click's intelligent internal output34streams to stdout and stderr which support unicode output on the Windows35console. This means for as long as you are using `click.echo` you can36output unicode character (there are some limitations on the default font37with regards to which characters can be displayed). This functionality is38new in Click 6.0.3940.. versionadded:: 6.04142Click now emulates output streams on Windows to support unicode to the43Windows console through separate APIs. For more information see44:doc:`wincmd`.4546.. versionadded:: 3.04748Starting with Click 3.0 you can also easily print to standard error by49passing ``err=True``::5051 click.echo('Hello World!', err=True)525354.. _ansi-colors:5556ANSI Colors57-----------5859.. versionadded:: 2.06061Starting with Click 2.0, the :func:`echo` function gained extra62functionality to deal with ANSI colors and styles. Note that on Windows,63this functionality is only available if `colorama`_ is installed. If it64is installed, then ANSI codes are intelligently handled.6566Primarily this means that:6768- Click's :func:`echo` function will automatically strip ANSI color codes69 if the stream is not connected to a terminal.70- the :func:`echo` function will transparently connect to the terminal on71 Windows and translate ANSI codes to terminal API calls. This means72 that colors will work on Windows the same way they do on other73 operating systems.7475Note for `colorama` support: Click will automatically detect when `colorama`76is available and use it. Do *not* call ``colorama.init()``!7778To install `colorama`, run this command::7980 $ pip install colorama8182For styling a string, the :func:`style` function can be used::8384 import click8586 click.echo(click.style('Hello World!', fg='green'))87 click.echo(click.style('Some more text', bg='blue', fg='white'))88 click.echo(click.style('ATTENTION', blink=True, bold=True))8990The combination of :func:`echo` and :func:`style` is also available in91a single function called :func:`secho`::9293 click.secho('Hello World!', fg='green')94 click.secho('Some more text', bg='blue', fg='white')95 click.secho('ATTENTION', blink=True, bold=True)969798.. _colorama: https://pypi.org/project/colorama/99100Pager Support101-------------102103In some situations, you might want to show long texts on the terminal and104let a user scroll through it. This can be achieved by using the105:func:`echo_via_pager` function which works similarly to the :func:`echo`106function, but always writes to stdout and, if possible, through a pager.107108Example:109110.. click:example::111112 @click.command()113 def less():114 click.echo_via_pager('\n'.join('Line %d' % idx115 for idx in range(200)))116117If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:118119.. click:example::120 def _generate_output():121 for idx in range(50000):122 yield "Line %d\n" % idx123124 @click.command()125 def less():126 click.echo_via_pager(_generate_output())127128129Screen Clearing130---------------131132.. versionadded:: 2.0133134To clear the terminal screen, you can use the :func:`clear` function that135is provided starting with Click 2.0. It does what the name suggests: it136clears the entire visible screen in a platform-agnostic way:137138::139140 import click141 click.clear()142143144Getting Characters from Terminal145--------------------------------146147.. versionadded:: 2.0148149Normally, when reading input from the terminal, you would read from150standard input. However, this is buffered input and will not show up until151the line has been terminated. In certain circumstances, you might not want152to do that and instead read individual characters as they are being written.153154For this, Click provides the :func:`getchar` function which reads a single155character from the terminal buffer and returns it as a Unicode character.156157Note that this function will always read from the terminal, even if stdin158is instead a pipe.159160Example::161162 import click163164 click.echo('Continue? [yn] ', nl=False)165 c = click.getchar()166 click.echo()167 if c == 'y':168 click.echo('We will go on')169 elif c == 'n':170 click.echo('Abort!')171 else:172 click.echo('Invalid input :(')173174Note that this reads raw input, which means that things like arrow keys175will show up in the platform's native escape format. The only characters176translated are ``^C`` and ``^D`` which are converted into keyboard177interrupts and end of file exceptions respectively. This is done because178otherwise, it's too easy to forget about that and to create scripts that179cannot be properly exited.180181182Waiting for Key Press183---------------------184185.. versionadded:: 2.0186187Sometimes, it's useful to pause until the user presses any key on the188keyboard. This is especially useful on Windows where ``cmd.exe`` will189close the window at the end of the command execution by default, instead190of waiting.191192In click, this can be accomplished with the :func:`pause` function. This193function will print a quick message to the terminal (which can be194customized) and wait for the user to press a key. In addition to that,195it will also become a NOP (no operation instruction) if the script is not196run interactively.197198Example::199200 import click201 click.pause()202203204Launching Editors205-----------------206207.. versionadded:: 2.0208209Click supports launching editors automatically through :func:`edit`. This210is very useful for asking users for multi-line input. It will211automatically open the user's defined editor or fall back to a sensible212default. If the user closes the editor without saving, the return value213will be `None` otherwise the entered text.214215Example usage::216217 import click218219 def get_commit_message():220 MARKER = '# Everything below is ignored\n'221 message = click.edit('\n\n' + MARKER)222 if message is not None:223 return message.split(MARKER, 1)[0].rstrip('\n')224225Alternatively, the function can also be used to launch editors for files by226a specific filename. In this case, the return value is always `None`.227228Example usage::229230 import click231 click.edit(filename='/etc/passwd')232233234Launching Applications235----------------------236237.. versionadded:: 2.0238239Click supports launching applications through :func:`launch`. This can be240used to open the default application associated with a URL or filetype.241This can be used to launch web browsers or picture viewers, for instance.242In addition to this, it can also launch the file manager and automatically243select the provided file.244245Example usage::246247 click.launch('http://click.pocoo.org/')248 click.launch('/my/downloaded/file.txt', locate=True)249250251Printing Filenames252------------------253254Because filenames might not be Unicode, formatting them can be a bit255tricky. Generally, this is easier in Python 2 than on 3, as you can just256write the bytes to stdout with the ``print`` function, but in Python 3, you257will always need to operate in Unicode.258259The way this works with click is through the :func:`format_filename`260function. It does a best-effort conversion of the filename to Unicode and261will never fail. This makes it possible to use these filenames in the262context of a full Unicode string.263264Example::265266 click.echo('Path: %s' % click.format_filename(b'foo.txt'))267268269Standard Streams270----------------271272For command line utilities, it's very important to get access to input and273output streams reliably. Python generally provides access to these274streams through ``sys.stdout`` and friends, but unfortunately, there are275API differences between 2.x and 3.x, especially with regards to how these276streams respond to Unicode and binary data.277278Because of this, click provides the :func:`get_binary_stream` and279:func:`get_text_stream` functions, which produce consistent results with280different Python versions and for a wide variety of terminal configurations.281282The end result is that these functions will always return a functional283stream object (except in very odd cases in Python 3; see284:ref:`python3-limitations`).285286Example::287288 import click289290 stdin_text = click.get_text_stream('stdin')291 stdout_binary = click.get_binary_stream('stdout')292293.. versionadded:: 6.0294295Click now emulates output streams on Windows to support unicode to the296Windows console through separate APIs. For more information see297:doc:`wincmd`.298299300Intelligent File Opening301------------------------302303.. versionadded:: 3.0304305Starting with Click 3.0 the logic for opening files from the :class:`File`306type is exposed through the :func:`open_file` function. It can307intelligently open stdin/stdout as well as any other file.308309Example::310311 import click312313 stdout = click.open_file('-', 'w')314 test_file = click.open_file('test.txt', 'w')315316If stdin or stdout are returned, the return value is wrapped in a special317file where the context manager will prevent the closing of the file. This318makes the handling of standard streams transparent and you can always use319it like this::320321 with click.open_file(filename, 'w') as f:322 f.write('Hello World!\n')323324325Finding Application Folders326---------------------------327328.. versionadded:: 2.0329330Very often, you want to open a configuration file that belongs to your331application. However, different operating systems store these configuration332files in different locations depending on their standards. Click provides333a :func:`get_app_dir` function which returns the most appropriate location334for per-user config files for your application depending on the OS.335336Example usage::337338 import os339 import click340 import ConfigParser341342 APP_NAME = 'My Application'343344 def read_config():345 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')346 parser = ConfigParser.RawConfigParser()347 parser.read([cfg])348 rv = {}349 for section in parser.sections():350 for key, value in parser.items(section):351 rv['%s.%s' % (section, key)] = value352 return rv353354355Showing Progress Bars356---------------------357358.. versionadded:: 2.0359360Sometimes, you have command line scripts that need to process a lot of data,361but you want to quickly show the user some progress about how long that362will take. Click supports simple progress bar rendering for that through363the :func:`progressbar` function.364365The basic usage is very simple: the idea is that you have an iterable that366you want to operate on. For each item in the iterable it might take some367time to do processing. So say you have a loop like this::368369 for user in all_the_users_to_process:370 modify_the_user(user)371372To hook this up with an automatically updating progress bar, all you need373to do is to change the code to this::374375 import click376377 with click.progressbar(all_the_users_to_process) as bar:378 for user in bar:379 modify_the_user(user)380381Click will then automatically print a progress bar to the terminal and382calculate the remaining time for you. The calculation of remaining time383requires that the iterable has a length. If it does not have a length384but you know the length, you can explicitly provide it::385386 with click.progressbar(all_the_users_to_process,387 length=number_of_users) as bar:388 for user in bar:389 modify_the_user(user)390391Another useful feature is to associate a label with the progress bar which392will be shown preceding the progress bar::393394 with click.progressbar(all_the_users_to_process,395 label='Modifying user accounts',396 length=number_of_users) as bar:397 for user in bar:398 modify_the_user(user)399400Sometimes, one may need to iterate over an external iterator, and advance the401progress bar irregularly. To do so, you need to specify the length (and no402iterable), and use the update method on the context return value instead of403iterating directly over it::404405 with click.progressbar(length=total_size,406 label='Unzipping archive') as bar:407 for archive in zip_file:408 archive.extract()409 bar.update(archive.size)