convert from reST to MyST
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by denuoweb · committed by denuoweb · parent c002e08 · Browse files · 2 files·+343 added−376 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+343 added−376 removed
- other:+343 added−376 removed
Provenance
- Commit
29eb946- Tree
e09e7fa- Author
denuoweb <jaron@rosenau.info>- Committer
denuoweb <jaron@rosenau.info>- Parent
c002e08
2 files changed+343 added−376 removed
modified:docs/unicode-support.md+69 added-84 removed
1212434675679101112891014151611121314181920212215162417181920212627222329242526272829303131323334353233343738393536374142433839404546414243484950444546475253545556484950515253596054555662636465665758596068697061627273747563646566676869707177727374798081828384757686878877787980819091828384939485868788899697989091921001011021031041051069394109110111112959697Unicode Support===============# Unicode Support
.. currentmodule:: clickClick has to take extra care to support Unicode text in different environments.
Click has to take extra care to support Unicode text in differentenvironments.- The command line in Unix is traditionally bytes, not Unicode. While there are encoding hints, there are some situations where this can break. The most common one is SSH connections to machines with different locales.
* The command line in Unix is traditionally bytes, not Unicode. While there are encoding hints, there are some situations where this can break. The most common one is SSH connections to machines with different locales. Misconfigured environments can cause a wide range of Unicode problems due to the lack of support for roundtripping surrogate escapes. This will not be fixed in Click itself!
Misconfigured environments can cause a wide range of Unicode problems due to the lack of support for roundtripping surrogate escapes. This will not be fixed in Click itself!- Standard input and output is opened in text mode by default. Click has to reopen the stream in binary mode in certain situations. Because there is no standard way to do this, it might not always work. Primarily this can become a problem when testing command-line applications.
* Standard input and output is opened in text mode by default. Click has to reopen the stream in binary mode in certain situations. Because there is no standard way to do this, it might not always work. Primarily this can become a problem when testing command-line applications. This is not supported:
This is not supported:: ```python sys.stdin = io.StringIO('Input here') sys.stdout = io.StringIO() ```
sys.stdin = io.StringIO('Input here') sys.stdout = io.StringIO() Instead you need to do this:
Instead you need to do this:: ```python input = 'Input here' in_stream = io.BytesIO(input.encode('utf-8')) sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8') out_stream = io.BytesIO() sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8') ```
input = 'Input here' in_stream = io.BytesIO(input.encode('utf-8')) sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8') out_stream = io.BytesIO() sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8') Remember in that case, you need to use `out_stream.getvalue()` and not `sys.stdout.getvalue()` if you want to access the buffer contents as the wrapper will not forward that method.
Remember in that case, you need to use ``out_stream.getvalue()`` and not ``sys.stdout.getvalue()`` if you want to access the buffer contents as the wrapper will not forward that method.- `sys.stdin`, `sys.stdout` and `sys.stderr` are by default text-based. When Click needs a binary stream, it attempts to discover the underlying binary stream.
* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default text-based. When Click needs a binary stream, it attempts to discover the underlying binary stream.- `sys.argv` is always text. This means that the native type for input values to the types in Click is Unicode, not bytes.
* ``sys.argv`` is always text. This means that the native type for input values to the types in Click is Unicode, not bytes. This causes problems if the terminal is incorrectly set and Python does not figure out the encoding. In that case, the Unicode string will contain error bytes encoded as surrogate escapes.
This causes problems if the terminal is incorrectly set and Python does not figure out the encoding. In that case, the Unicode string will contain error bytes encoded as surrogate escapes.- When dealing with files, Click will always use the Unicode file system API by using the operating system's reported or guessed filesystem encoding. Surrogates are supported for filenames, so it should be possible to open files through the {func}`click.File` type even if the environment is misconfigured.
* When dealing with files, Click will always use the Unicode file system API by using the operating system's reported or guessed filesystem encoding. Surrogates are supported for filenames, so it should be possible to open files through the :class:`File` type even if the environment is misconfigured.## Surrogate Handling
Click does all the Unicode handling in the standard library and is subject to its behavior. Unicode requires extra care.The reason for this is that the encoding detection is done in the interpreter, and on Linux and certain other operatingsystems, its encoding handling is problematic.
Surrogate Handling------------------The biggest source of frustration is that Click scripts invoked by init systems, deployment tools, or cron jobs willrefuse to work unless a Unicode locale is exported.
Click does all the Unicode handling in the standard library and issubject to its behavior. Unicode requires extra care. The reason forthis is that the encoding detection is done in the interpreter, and onLinux and certain other operating systems, its encoding handling isproblematic.If Click encounters such an environment it will prevent further execution to force you to set a locale. This is donebecause Click cannot know about the state of the system once it's invoked and restore the values before Python's Unicodehandling kicked in.
The biggest source of frustration is that Click scripts invoked by initsystems, deployment tools, or cron jobs will refuse to work unless aUnicode locale is exported.If you see something like this error:
If Click encounters such an environment it will prevent furtherexecution to force you to set a locale. This is done because Clickcannot know about the state of the system once it's invoked and restorethe values before Python's Unicode handling kicked in.```consoleTraceback (most recent call last): ...RuntimeError: Click will abort further execution because Python was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/unicode-support/ for mitigation steps.```
If you see something like this error::You are dealing with an environment where Python thinks you are restricted to ASCII data. The solution to these problemsis different depending on which locale your computer is running in.
Traceback (most recent call last): ... RuntimeError: Click will abort further execution because Python was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/unicode-support/ for mitigation steps.For instance, if you have a German Linux machine, you can fix the problem by exporting the locale to `de_DE.utf-8`:
You are dealing with an environment where Python thinks you arerestricted to ASCII data. The solution to these problems is differentdepending on which locale your computer is running in.```consoleexport LC_ALL=de_DE.utf-8export LANG=de_DE.utf-8```
For instance, if you have a German Linux machine, you can fix theproblem by exporting the locale to ``de_DE.utf-8``::If you are on a US machine, `en_US.utf-8` is the encoding of choice. On some newer Linux systems, you could also try`C.UTF-8` as the locale:
export LC_ALL=de_DE.utf-8 export LANG=de_DE.utf-8```consoleexport LC_ALL=C.UTF-8export LANG=C.UTF-8```
If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.On some newer Linux systems, you could also try ``C.UTF-8`` as thelocale::On some systems it was reported that `UTF-8` has to be written as `UTF8` and vice versa. To see which locales aresupported you can invoke `locale -a`.
export LC_ALL=C.UTF-8 export LANG=C.UTF-8
On some systems it was reported that ``UTF-8`` has to be written as``UTF8`` and vice versa. To see which locales are supported you caninvoke ``locale -a``.
You need to export the values before you invoke your Python script.
In Python 3.7 and later you will no longer get a ``RuntimeError`` inmany cases thanks to :pep:`538` and :pep:`540`, which changed thedefault assumption in unconfigured environments. This doesn't change thegeneral issue that your locale may be misconfigured.In Python 3.7 and later you will no longer get a `RuntimeError` in many cases thanks to {pep}`538` and {pep}`540`, whichchanged the default assumption in unconfigured environments. This doesn't change the general issue that your locale maybe misconfigured.modified:docs/utils.md+274 added-292 removed
1-Utilities2-=========1+# Utilities2 4-.. currentmodule:: click3+Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunch4+of addon functionality that is useful for writing command line utilities.5 6-Besides the functionality that Click provides to interface with argument7-parsing and handling, it also provides a bunch of addon functionality that8-is useful for writing command line utilities.6+## Printing to Stdout7 8+The most obvious helper is the {func}`click.echo` function, which in many ways works like the Python `print` statement or9+function. The main difference is that it works the same in many different terminal environments.10 11-Printing to Stdout12-------------------11+Example:12 14-The most obvious helper is the :func:`echo` function, which in many ways15-works like the Python ``print`` statement or function. The main difference is16-that it works the same in many different terminal environments.13+```python14+import click15 18-Example::16+click.echo('Hello World!')17+```18 20- import click19+It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by20+passing `nl=False`:21 22- click.echo('Hello World!')22+```python23+click.echo(b'\xe2\x98\x83', nl=False)24+```25 24-It can output both text and binary data. It will emit a trailing newline25-by default, which needs to be suppressed by passing ``nl=False``::26+Last but not least {func}`click.echo` uses click's intelligent internal output streams to stdout and stderr which support27+unicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicode28+characters (there are some limitations on the default font with regards to which characters can be displayed).29 27- click.echo(b'\xe2\x98\x83', nl=False)30+```{versionadded} 6.031+```32 29-Last but not least :func:`echo` uses click's intelligent internal output30-streams to stdout and stderr which support unicode output on the Windows31-console. This means for as long as you are using `click.echo` you can32-output unicode characters (there are some limitations on the default font33-with regards to which characters can be displayed).33+Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more34+information see {doc}`wincmd`.35 35-.. versionadded:: 6.036+```{versionadded} 3.037+```38 37-Click emulates output streams on Windows to support unicode to the38-Windows console through separate APIs. For more information see39-:doc:`wincmd`.39+You can also easily print to standard error by passing `err=True`:40 41-.. versionadded:: 3.041+```python42+click.echo('Hello World!', err=True)43+```44 43-You can also easily print to standard error by passing ``err=True``::45+(ansi-colors)=46 45- click.echo('Hello World!', err=True)47+## ANSI Colors48 49+```{versionadded} 2.050+```51 48-.. _ansi-colors:52+The {func}`click.echo` function supports ANSI colors and styles. On Windows this uses [colorama].53 50-ANSI Colors51------------52-53-.. versionadded:: 2.054-55-The :func:`echo` function supports ANSI colors and styles. On Windows56-this uses `colorama`_.57-54 Primarily this means that:55 60-- Click's :func:`echo` function will automatically strip ANSI color codes61- if the stream is not connected to a terminal.62-- the :func:`echo` function will transparently connect to the terminal on63- Windows and translate ANSI codes to terminal API calls. This means64- that colors will work on Windows the same way they do on other65- operating systems.56+- Click's {func}`click.echo` function will automatically strip ANSI color codes if the stream is not connected to a terminal.57+- the {func}`click.echo` function will transparently connect to the terminal on Windows and translate ANSI codes to terminal58+ API calls. This means that colors will work on Windows the same way they do on other operating systems.59 67-On Windows, Click uses colorama without calling ``colorama.init()``. You68-can still call that in your code, but it's not required for Click.60+On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not61+required for Click.62 70-For styling a string, the :func:`style` function can be used::63+For styling a string, the {func}`click.style` function can be used:64 65+```python72- import click66+import click67 74- click.echo(click.style('Hello World!', fg='green'))75- click.echo(click.style('Some more text', bg='blue', fg='white'))76- click.echo(click.style('ATTENTION', blink=True, bold=True))68+click.echo(click.style('Hello World!', fg='green'))69+click.echo(click.style('Some more text', bg='blue', fg='white'))70+click.echo(click.style('ATTENTION', blink=True, bold=True))71+```72 78-The combination of :func:`echo` and :func:`style` is also available in79-a single function called :func:`secho`::73+The combination of {func}`click.echo` and {func}`click.style` is also available in a single function called {func}`click.secho`:74 75+```python81- click.secho('Hello World!', fg='green')82- click.secho('Some more text', bg='blue', fg='white')83- click.secho('ATTENTION', blink=True, bold=True)76+click.secho('Hello World!', fg='green')77+click.secho('Some more text', bg='blue', fg='white')78+click.secho('ATTENTION', blink=True, bold=True)79+```80 81+## Pager Support82 86-.. _colorama: https://pypi.org/project/colorama/83+In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be84+achieved by using the {func}`click.echo_via_pager` function which works similarly to the {func}`click.echo` function, but always85+writes to stdout and, if possible, through a pager.86 88-Pager Support89--------------90-91-In some situations, you might want to show long texts on the terminal and92-let a user scroll through it. This can be achieved by using the93-:func:`echo_via_pager` function which works similarly to the :func:`echo`94-function, but always writes to stdout and, if possible, through a pager.95-87 Example:88 98-.. click:example::89+```python90+@click.command()91+def less():92+ click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))93+```94 100- @click.command()101- def less():102- click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))95+If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,96+you can pass a generator (or generator function) instead of a string:97 104-If 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:98+```python99+def _generate_output():100+ for idx in range(50000):101+ yield f"Line {idx}\n"102 106-.. click:example::107- def _generate_output():108- for idx in range(50000):109- yield f"Line {idx}\n"103+@click.command()104+def less():105+ click.echo_via_pager(_generate_output())106+```107 111- @click.command()112- def less():113- click.echo_via_pager(_generate_output())108+## Screen Clearing109 110+```{versionadded} 2.0111+```112 116-Screen Clearing117----------------113+To clear the terminal screen, you can use the {func}`click.clear` function that is provided starting with Click 2.0. It does114+what the name suggests: it clears the entire visible screen in a platform-agnostic way:115 119-.. versionadded:: 2.0116+```117+import click118+click.clear()119+```120 121-To clear the terminal screen, you can use the :func:`clear` function that122-is provided starting with Click 2.0. It does what the name suggests: it123-clears the entire visible screen in a platform-agnostic way:121+## Getting Characters from Terminal122 125-::123+```{versionadded} 2.0124+```125 127- import click128- click.clear()126+Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and127+will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead128+read individual characters as they are being written.129 130+For this, Click provides the {func}`click.getchar` function which reads a single character from the terminal buffer and131+returns it as a Unicode character.132 131-Getting Characters from Terminal132---------------------------------133+Note that this function will always read from the terminal, even if stdin is instead a pipe.134 134-.. versionadded:: 2.0135+Example:136 136-Normally, when reading input from the terminal, you would read from137-standard input. However, this is buffered input and will not show up until138-the line has been terminated. In certain circumstances, you might not want139-to do that and instead read individual characters as they are being written.137+```python138+import click139 141-For this, Click provides the :func:`getchar` function which reads a single142-character from the terminal buffer and returns it as a Unicode character.140+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+```150 144-Note that this function will always read from the terminal, even if stdin145-is instead a pipe.146-147-Example::148-149- import click150-151- click.echo('Continue? [yn] ', nl=False)152- c = click.getchar()153- click.echo()154- if c == 'y':155- click.echo('We will go on')156- elif c == 'n':157- click.echo('Abort!')158- else:159- click.echo('Invalid input :(')160-161-Note that this reads raw input, which means that things like arrow keys162-will show up in the platform's native escape format. The only characters163-translated are ``^C`` and ``^D`` which are converted into keyboard164-interrupts and end of file exceptions respectively. This is done because165-otherwise, it's too easy to forget about that and to create scripts that151+Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape152+format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file153+exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that154 cannot be properly exited.155 156+## Waiting for Key Press157 169-Waiting for Key Press170----------------------158+```{versionadded} 2.0159+```160 172-.. versionadded:: 2.0161+Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows162+where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.163 174-Sometimes, it's useful to pause until the user presses any key on the175-keyboard. This is especially useful on Windows where ``cmd.exe`` will176-close the window at the end of the command execution by default, instead177-of waiting.164+In click, this can be accomplished with the {func}`click.pause` function. This function will print a quick message to the165+terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP166+(no operation instruction) if the script is not run interactively.167 179-In click, this can be accomplished with the :func:`pause` function. This180-function will print a quick message to the terminal (which can be181-customized) and wait for the user to press a key. In addition to that,182-it will also become a NOP (no operation instruction) if the script is not183-run interactively.168+Example:169 185-Example::170+```python171+import click172+click.pause()173+```174 187- import click188- click.pause()175+## Launching Editors176 177+```{versionadded} 2.0178+```179 191-Launching Editors192------------------180+Click supports launching editors automatically through {func}`click.edit`. This is very useful for asking users for multi-line181+input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the182+editor without saving, the return value will be `None`, otherwise the entered text.183 194-.. versionadded:: 2.0184+Example usage:185 196-Click supports launching editors automatically through :func:`edit`. This197-is very useful for asking users for multi-line input. It will198-automatically open the user's defined editor or fall back to a sensible199-default. If the user closes the editor without saving, the return value200-will be ``None``, otherwise the entered text.186+```python187+import click188 202-Example usage::189+def get_commit_message():190+ MARKER = '# Everything below is ignored\n'191+ message = click.edit('\n\n' + MARKER)192+ if message is not None:193+ return message.split(MARKER, 1)[0].rstrip('\n')194+```195 204- import click196+Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the197+return value is always `None`.198 206- def get_commit_message():207- MARKER = '# Everything below is ignored\n'208- message = click.edit('\n\n' + MARKER)209- if message is not None:210- return message.split(MARKER, 1)[0].rstrip('\n')199+Example usage:200 212-Alternatively, the function can also be used to launch editors for files by213-a specific filename. In this case, the return value is always `None`.201+```python202+import click203+click.edit(filename='/etc/passwd')204+```205 215-Example usage::206+## Launching Applications207 217- import click218- click.edit(filename='/etc/passwd')208+```{versionadded} 2.0209+```210 211+Click supports launching applications through {func}`click.launch`. This can be used to open the default application212+associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition213+to this, it can also launch the file manager and automatically select the provided file.214 221-Launching Applications222-----------------------215+Example usage:216 224-.. versionadded:: 2.0217+```python218+click.launch("https://click.palletsprojects.com/")219+click.launch("/my/downloaded/file.txt", locate=True)220+```221 226-Click supports launching applications through :func:`launch`. This can be227-used to open the default application associated with a URL or filetype.228-This can be used to launch web browsers or picture viewers, for instance.229-In addition to this, it can also launch the file manager and automatically230-select the provided file.222+## Printing Filenames223 232-Example usage::224+Because filenames might not be Unicode, formatting them can be a bit tricky.225 234- click.launch("https://click.palletsprojects.com/")235- click.launch("/my/downloaded/file.txt", locate=True)226+The way this works with click is through the {func}`click.format_filename` function. It does a best-effort conversion of the227+filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode228+string.229 230+Example:231 238-Printing Filenames239-------------------232+```python233+click.echo(f"Path: {click.format_filename(b'foo.txt')}")234+```235 241-Because filenames might not be Unicode, formatting them can be a bit242-tricky.236+## Standard Streams237 244-The way this works with click is through the :func:`format_filename`245-function. It does a best-effort conversion of the filename to Unicode and246-will never fail. This makes it possible to use these filenames in the247-context of a full Unicode string.238+For command line utilities, it's very important to get access to input and output streams reliably. Python generally239+provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between240+2.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.241 249-Example::242+Because of this, click provides the {func}`click.get_binary_stream` and {func}`click.get_text_stream` functions, which produce243+consistent results with different Python versions and for a wide variety of terminal configurations.244 251- click.echo(f"Path: {click.format_filename(b'foo.txt')}")245+The end result is that these functions will always return a functional stream object (except in very odd cases; see246+{doc}`/unicode-support`).247 248+Example:249 254-Standard Streams255-----------------250+```python251+import click252 257-For command line utilities, it's very important to get access to input and258-output streams reliably. Python generally provides access to these259-streams through ``sys.stdout`` and friends, but unfortunately, there are260-API differences between 2.x and 3.x, especially with regards to how these261-streams respond to Unicode and binary data.253+stdin_text = click.get_text_stream('stdin')254+stdout_binary = click.get_binary_stream('stdout')255+```256 263-Because of this, click provides the :func:`get_binary_stream` and264-:func:`get_text_stream` functions, which produce consistent results with265-different Python versions and for a wide variety of terminal configurations.257+```{versionadded} 6.0258+```259 267-The end result is that these functions will always return a functional268-stream object (except in very odd cases; see :doc:`/unicode-support`).260+Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more261+information see {doc}`wincmd`.262 270-Example::263+## Intelligent File Opening264 272- import click265+```{versionadded} 3.0266+```267 274- stdin_text = click.get_text_stream('stdin')275- stdout_binary = click.get_binary_stream('stdout')268+Starting with Click 3.0 the logic for opening files from the {func}`click.File` type is exposed through the {func}`click.open_file`269+function. It can intelligently open stdin/stdout as well as any other file.270 277-.. versionadded:: 6.0271+Example:272 279-Click now emulates output streams on Windows to support unicode to the280-Windows console through separate APIs. For more information see281-:doc:`wincmd`.273+```python274+import click275 276+stdout = click.open_file('-', 'w')277+test_file = click.open_file('test.txt', 'w')278+```279 284-Intelligent File Opening285-------------------------280+If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent281+the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:282 287-.. versionadded:: 3.0283+```python284+with click.open_file(filename, 'w') as f:285+ f.write('Hello World!\n')286+```287 289-Starting with Click 3.0 the logic for opening files from the :class:`File`290-type is exposed through the :func:`open_file` function. It can291-intelligently open stdin/stdout as well as any other file.288+## Finding Application Folders289 293-Example::290+```{versionadded} 2.0291+```292 295- import click293+Very often, you want to open a configuration file that belongs to your application. However, different operating systems294+store these configuration files in different locations depending on their standards. Click provides a295+{func}`click.get_app_dir` function which returns the most appropriate location for per-user config files for your application296+depending on the OS.297 297- stdout = click.open_file('-', 'w')298- test_file = click.open_file('test.txt', 'w')298+Example usage:299 300-If stdin or stdout are returned, the return value is wrapped in a special301-file where the context manager will prevent the closing of the file. This302-makes the handling of standard streams transparent and you can always use303-it like this::300+```python301+import os302+import click303+import ConfigParser304 305- with click.open_file(filename, 'w') as f:306- f.write('Hello World!\n')305+APP_NAME = 'My Application'306+def read_config():307+cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')308+parser = ConfigParser.RawConfigParser()309+parser.read([cfg])310+rv = {}311+for section in parser.sections():312+ for key, value in parser.items(section):313+ rv[f"{section}.{key}"] = value314+return rv315+```316 317+## Showing Progress Bars318 309-Finding Application Folders310----------------------------319+Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some320+progress about how long that will take. Click supports simple progress bar rendering for that through the321+{func}`click.progressbar` function.322 312-.. versionadded:: 2.0323+```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm].324+```325 314-Very often, you want to open a configuration file that belongs to your315-application. However, different operating systems store these configuration316-files in different locations depending on their standards. Click provides317-a :func:`get_app_dir` function which returns the most appropriate location318-for per-user config files for your application depending on the OS.326+The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the327+iterable it might take some time to do processing. So say you have a loop like this:328 320-Example usage::329+```python330+for user in all_the_users_to_process:331+ modify_the_user(user)332+```333 322- import os323- import click324- import ConfigParser334+To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:335 326- APP_NAME = 'My Application'336+```python337+import click338 328- def read_config():329- cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')330- parser = ConfigParser.RawConfigParser()331- parser.read([cfg])332- rv = {}333- for section in parser.sections():334- for key, value in parser.items(section):335- rv[f"{section}.{key}"] = value336- return rv339+with click.progressbar(all_the_users_to_process) as bar:340+ for user in bar:341+ modify_the_user(user)342+```343 344+Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The345+calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the346+length, you can explicitly provide it:347 339-Showing Progress Bars340----------------------348+```python349+with click.progressbar(all_the_users_to_process,350+ length=number_of_users) as bar:351+ for user in bar:352+ modify_the_user(user)353+```354 342-Sometimes, you have command line scripts that need to process a lot of data,343-but you want to quickly show the user some progress about how long that344-will take. Click supports simple progress bar rendering for that through345-the :func:`progressbar` function.355+Note that {func}`click.progressbar` updates the bar *after* each iteration of the loop. So code like this will render356+correctly:357 347-.. note::358+```python359+import time360 349- If you find that you have requirements beyond what Click's progress350- bar supports, try using `tqdm`_.361+with click.progressbar([1, 2, 3]) as bar:362+ for x in bar:363+ print(f"sleep({x})...")364+ time.sleep(x)365+```366 352- .. _tqdm: https://tqdm.github.io/367+Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:368 354-The basic usage is very simple: the idea is that you have an iterable that355-you want to operate on. For each item in the iterable it might take some356-time to do processing. So say you have a loop like this::357-358- for user in all_the_users_to_process:369+```python370+with click.progressbar(all_the_users_to_process,371+ label='Modifying user accounts',372+ length=number_of_users) as bar:373+ for user in bar:374 modify_the_user(user)375+```376 361-To hook this up with an automatically updating progress bar, all you need362-to do is to change the code to this::377+Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you378+need to specify the length (and no iterable), and use the update method on the context return value instead of iterating379+directly over it:380 364- import click381+```python382+with click.progressbar(length=total_size,383+ label='Unzipping archive') as bar:384+ for archive in zip_file:385+ archive.extract()386+ bar.update(archive.size)387+```388 366- with click.progressbar(all_the_users_to_process) as bar:367- for user in bar:368- modify_the_user(user)369-370-Click will then automatically print a progress bar to the terminal and371-calculate the remaining time for you. The calculation of remaining time372-requires that the iterable has a length. If it does not have a length373-but you know the length, you can explicitly provide it::374-375- with click.progressbar(all_the_users_to_process,376- length=number_of_users) as bar:377- for user in bar:378- modify_the_user(user)379-380-Note that :func:`progressbar` updates the bar *after* each iteration of the381-loop. So code like this will render correctly::382-383- import time384-385- with click.progressbar([1, 2, 3]) as bar:386- for x in bar:387- print(f"sleep({x})...")388- time.sleep(x)389-390-Another useful feature is to associate a label with the progress bar which391-will be shown preceding the progress bar::392-393- with click.progressbar(all_the_users_to_process,394- label='Modifying user accounts',395- length=number_of_users) as bar:396- for user in bar:397- modify_the_user(user)398-399-Sometimes, one may need to iterate over an external iterator, and advance the400-progress bar irregularly. To do so, you need to specify the length (and no401-iterable), and use the update method on the context return value instead of402-iterating directly over it::403-404- with click.progressbar(length=total_size,405- label='Unzipping archive') as bar:406- for archive in zip_file:407- archive.extract()408- bar.update(archive.size)389+[colorama]: https://pypi.org/project/colorama/390+[tqdm]: https://tqdm.github.io/