utils.rst
This file
Path
docs/utils.rst
410 lines · 13.0 KiB
Last changed by
new docs linksDavid Lordbefore adoption7818f30
History of this fileTake it
The walk stopped after 200 commits: lines older than ae5412d point at it.
Catch unicode errors as bad value.Armin Ronacherbefore adoptionae5412d
lines 1–32why, one step back1Utilities2=========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)32Documented wincmdArmin Ronacherbefore adoption7e8da4b
lines 33–43why, one step back33Last 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 seeMerge pull request #883 from jacobtolar/doc-cleanupZachery Birbefore adoptionfb0a7a7
line 44why, one step back44:doc:`wincmd`.Documented wincmdArmin Ronacherbefore adoption7e8da4b
line 45why, one step back45Catch unicode errors as bad value.Armin Ronacherbefore adoptionae5412d
lines 46–63why, one step back46.. 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 itMerge pull request #1010 from rpgraham84/masterDan Sullybefore adoption692cb32
lines 64–65why, one step back64is installed, then ANSI codes are intelligently handled. Note that in Python652, the echo function doesn't parse color code information from bytearrays.Catch unicode errors as bad value.Armin Ronacherbefore adoptionae5412d
lines 66–98why, one step back6667Primarily this means that:6869- Click's :func:`echo` function will automatically strip ANSI color codes70 if the stream is not connected to a terminal.71- the :func:`echo` function will transparently connect to the terminal on72 Windows and translate ANSI codes to terminal API calls. This means73 that colors will work on Windows the same way they do on other74 operating systems.7576Note for `colorama` support: Click will automatically detect when `colorama`77is available and use it. Do *not* call ``colorama.init()``!7879To install `colorama`, run this command::8081 $ pip install colorama8283For styling a string, the :func:`style` function can be used::8485 import click8687 click.echo(click.style('Hello World!', fg='green'))88 click.echo(click.style('Some more text', bg='blue', fg='white'))89 click.echo(click.style('ATTENTION', blink=True, bold=True))9091The combination of :func:`echo` and :func:`style` is also available in92a single function called :func:`secho`::9394 click.secho('Hello World!', fg='green')95 click.secho('Some more text', bg='blue', fg='white')96 click.secho('ATTENTION', blink=True, bold=True)9798Merge pull request #989 from ettanany/pypiDavid Lordbefore adoptionef93b49
line 99why, one step back99.. _colorama: https://pypi.org/project/colorama/Catch unicode errors as bad value.Armin Ronacherbefore adoptionae5412d
lines 100–117why, one step back100101Pager Support102-------------103104In some situations, you might want to show long texts on the terminal and105let a user scroll through it. This can be achieved by using the106:func:`echo_via_pager` function which works similarly to the :func:`echo`107function, but always writes to stdout and, if possible, through a pager.108109Example:110111.. click:example::112113 @click.command()114 def less():115 click.echo_via_pager('\n'.join('Line %d' % idx116 for idx in range(200)))117Merge pull request #889 from stefreak/masterDan Sullybefore adoptionb1b4449
lines 118–128why, one step back118If 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:119120.. click:example::121 def _generate_output():122 for idx in range(50000):123 yield "Line %d\n" % idx124125 @click.command()126 def less():127 click.echo_via_pager(_generate_output())128Catch unicode errors as bad value.Armin Ronacherbefore adoptionae5412d
lines 129–240why, one step back129130Screen Clearing131---------------132133.. versionadded:: 2.0134135To clear the terminal screen, you can use the :func:`clear` function that136is provided starting with Click 2.0. It does what the name suggests: it137clears the entire visible screen in a platform-agnostic way:138139::140141 import click142 click.clear()143144145Getting Characters from Terminal146--------------------------------147148.. versionadded:: 2.0149150Normally, when reading input from the terminal, you would read from151standard input. However, this is buffered input and will not show up until152the line has been terminated. In certain circumstances, you might not want153to do that and instead read individual characters as they are being written.154155For this, Click provides the :func:`getchar` function which reads a single156character from the terminal buffer and returns it as a Unicode character.157158Note that this function will always read from the terminal, even if stdin159is instead a pipe.160161Example::162163 import click164165 click.echo('Continue? [yn] ', nl=False)166 c = click.getchar()167 click.echo()168 if c == 'y':169 click.echo('We will go on')170 elif c == 'n':171 click.echo('Abort!')172 else:173 click.echo('Invalid input :(')174175Note that this reads raw input, which means that things like arrow keys176will show up in the platform's native escape format. The only characters177translated are ``^C`` and ``^D`` which are converted into keyboard178interrupts and end of file exceptions respectively. This is done because179otherwise, it's too easy to forget about that and to create scripts that180cannot be properly exited.181182183Waiting for Key Press184---------------------185186.. versionadded:: 2.0187188Sometimes, it's useful to pause until the user presses any key on the189keyboard. This is especially useful on Windows where ``cmd.exe`` will190close the window at the end of the command execution by default, instead191of waiting.192193In click, this can be accomplished with the :func:`pause` function. This194function will print a quick message to the terminal (which can be195customized) and wait for the user to press a key. In addition to that,196it will also become a NOP (no operation instruction) if the script is not197run interactively.198199Example::200201 import click202 click.pause()203204205Launching Editors206-----------------207208.. versionadded:: 2.0209210Click supports launching editors automatically through :func:`edit`. This211is very useful for asking users for multi-line input. It will212automatically open the user's defined editor or fall back to a sensible213default. If the user closes the editor without saving, the return value214will be `None` otherwise the entered text.215216Example usage::217218 import click219220 def get_commit_message():221 MARKER = '# Everything below is ignored\n'222 message = click.edit('\n\n' + MARKER)223 if message is not None:224 return message.split(MARKER, 1)[0].rstrip('\n')225226Alternatively, the function can also be used to launch editors for files by227a specific filename. In this case, the return value is always `None`.228229Example usage::230231 import click232 click.edit(filename='/etc/passwd')233234235Launching Applications236----------------------237238.. versionadded:: 2.0239240Click supports launching applications through :func:`launch`. This can beFix typos in docs (#623)Radovan Bastbefore adoptionb5239af
line 241why, one step back241used to open the default application associated with a URL or filetype.Catch unicode errors as bad value.Armin Ronacherbefore adoptionae5412d
lines 242–247why, one step back242This can be used to launch web browsers or picture viewers, for instance.243In addition to this, it can also launch the file manager and automatically244select the provided file.245246Example usage::247new docs linksDavid Lordbefore adoption7818f30
lines 248–249why, one step back248 click.launch("https://click.palletsprojects.com/")249 click.launch("/my/downloaded/file.txt", locate=True)Catch unicode errors as bad value.Armin Ronacherbefore adoptionae5412d
lines 250–280why, one step back250251252Printing Filenames253------------------254255Because filenames might not be Unicode, formatting them can be a bit256tricky. Generally, this is easier in Python 2 than on 3, as you can just257write the bytes to stdout with the ``print`` function, but in Python 3, you258will always need to operate in Unicode.259260The way this works with click is through the :func:`format_filename`261function. It does a best-effort conversion of the filename to Unicode and262will never fail. This makes it possible to use these filenames in the263context of a full Unicode string.264265Example::266267 click.echo('Path: %s' % click.format_filename(b'foo.txt'))268269270Standard Streams271----------------272273For command line utilities, it's very important to get access to input and274output streams reliably. Python generally provides access to these275streams through ``sys.stdout`` and friends, but unfortunately, there are276API differences between 2.x and 3.x, especially with regards to how these277streams respond to Unicode and binary data.278279Because of this, click provides the :func:`get_binary_stream` and280:func:`get_text_stream` functions, which produce consistent results withMerge pull request #476 from taleinat/patch-1Armin Ronacherbefore adoptiond5f7713
line 281why, one step back281different Python versions and for a wide variety of terminal configurations.Catch unicode errors as bad value.Armin Ronacherbefore adoptionae5412d
lines 282–292why, one step back282283The end result is that these functions will always return a functional284stream object (except in very odd cases in Python 3; see285:ref:`python3-limitations`).286287Example::288289 import click290291 stdin_text = click.get_text_stream('stdin')292 stdout_binary = click.get_binary_stream('stdout')Documented wincmdArmin Ronacherbefore adoption7e8da4b
lines 293–297why, one step back293294.. versionadded:: 6.0295296Click now emulates output streams on Windows to support unicode to the297Windows console through separate APIs. For more information seeMerge pull request #883 from jacobtolar/doc-cleanupZachery Birbefore adoptionfb0a7a7
line 298why, one step back298:doc:`wincmd`.Catch unicode errors as bad value.Armin Ronacherbefore adoptionae5412d
lines 299–410why, one step back299300301Intelligent File Opening302------------------------303304.. versionadded:: 3.0305306Starting with Click 3.0 the logic for opening files from the :class:`File`307type is exposed through the :func:`open_file` function. It can308intelligently open stdin/stdout as well as any other file.309310Example::311312 import click313314 stdout = click.open_file('-', 'w')315 test_file = click.open_file('test.txt', 'w')316317If stdin or stdout are returned, the return value is wrapped in a special318file where the context manager will prevent the closing of the file. This319makes the handling of standard streams transparent and you can always use320it like this::321322 with click.open_file(filename, 'w') as f:323 f.write('Hello World!\n')324325326Finding Application Folders327---------------------------328329.. versionadded:: 2.0330331Very often, you want to open a configuration file that belongs to your332application. However, different operating systems store these configuration333files in different locations depending on their standards. Click provides334a :func:`get_app_dir` function which returns the most appropriate location335for per-user config files for your application depending on the OS.336337Example usage::338339 import os340 import click341 import ConfigParser342343 APP_NAME = 'My Application'344345 def read_config():346 cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')347 parser = ConfigParser.RawConfigParser()348 parser.read([cfg])349 rv = {}350 for section in parser.sections():351 for key, value in parser.items(section):352 rv['%s.%s' % (section, key)] = value353 return rv354355356Showing Progress Bars357---------------------358359.. versionadded:: 2.0360361Sometimes, you have command line scripts that need to process a lot of data,362but you want to quickly show the user some progress about how long that363will take. Click supports simple progress bar rendering for that through364the :func:`progressbar` function.365366The basic usage is very simple: the idea is that you have an iterable that367you want to operate on. For each item in the iterable it might take some368time to do processing. So say you have a loop like this::369370 for user in all_the_users_to_process:371 modify_the_user(user)372373To hook this up with an automatically updating progress bar, all you need374to do is to change the code to this::375376 import click377378 with click.progressbar(all_the_users_to_process) as bar:379 for user in bar:380 modify_the_user(user)381382Click will then automatically print a progress bar to the terminal and383calculate the remaining time for you. The calculation of remaining time384requires that the iterable has a length. If it does not have a length385but you know the length, you can explicitly provide it::386387 with click.progressbar(all_the_users_to_process,388 length=number_of_users) as bar:389 for user in bar:390 modify_the_user(user)391392Another useful feature is to associate a label with the progress bar which393will be shown preceding the progress bar::394395 with click.progressbar(all_the_users_to_process,396 label='Modifying user accounts',397 length=number_of_users) as bar:398 for user in bar:399 modify_the_user(user)400401Sometimes, one may need to iterate over an external iterator, and advance the402progress bar irregularly. To do so, you need to specify the length (and no403iterable), and use the update method on the context return value instead of404iterating directly over it::405406 with click.progressbar(length=total_size,407 label='Unzipping archive') as bar:408 for archive in zip_file:409 archive.extract()410 bar.update(archive.size)