Skip to content
Myr

Move Utils and Unicode-support docs from reST to MyST (#2960)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents d548479, fbbcc96 · Browse files · 4 files+490 added−520 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+490 added−520 removed

  • other:+490 added−520 removed

4 files+490 added−520 removed

added:docs/unicode-support.md+100 added
1# Unicode Support23```{currentmodule} click4```56Click has to take extra care to support Unicode text in different environments.78- The command line in Unix is traditionally bytes, not Unicode. While there are encoding hints, there are some9 situations where this can break. The most common one is SSH connections to machines with different locales.1011 Misconfigured environments can cause a wide range of Unicode problems due to the lack of support for roundtripping12 surrogate escapes. This will not be fixed in Click itself!1314- Standard input and output is opened in text mode by default. Click has to reopen the stream in binary mode in certain15 situations. Because there is no standard way to do this, it might not always work. Primarily this can become a problem16 when testing command-line applications.1718 This is not supported:1920 ```python21 sys.stdin = io.StringIO('Input here')22 sys.stdout = io.StringIO()23 ```2425 Instead you need to do this:2627 ```python28 input = 'Input here'29 in_stream = io.BytesIO(input.encode('utf-8'))30 sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')31 out_stream = io.BytesIO()32 sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')33 ```3435 Remember in that case, you need to use `out_stream.getvalue()` and not `sys.stdout.getvalue()` if you want to access36 the buffer contents as the wrapper will not forward that method.3738- `sys.stdin`, `sys.stdout` and `sys.stderr` are by default text-based. When Click needs a binary stream, it attempts to39 discover the underlying binary stream.4041- `sys.argv` is always text. This means that the native type for input values to the types in Click is Unicode, not42 bytes.4344 This causes problems if the terminal is incorrectly set and Python does not figure out the encoding. In that case, the45 Unicode string will contain error bytes encoded as surrogate escapes.4647- When dealing with files, Click will always use the Unicode file system API by using the operating system's reported or48 guessed filesystem encoding. Surrogates are supported for filenames, so it should be possible to open files through49 the {func}`File` type even if the environment is misconfigured.5051## Surrogate Handling5253Click does all the Unicode handling in the standard library and is subject to its behavior. Unicode requires extra care.54The reason for this is that the encoding detection is done in the interpreter, and on Linux and certain other operating55systems, its encoding handling is problematic.5657The biggest source of frustration is that Click scripts invoked by init systems, deployment tools, or cron jobs will58refuse to work unless a Unicode locale is exported.5960If Click encounters such an environment it will prevent further execution to force you to set a locale. This is done61because Click cannot know about the state of the system once it's invoked and restore the values before Python's Unicode62handling kicked in.6364If you see something like this error:6566```console67Traceback (most recent call last):68 ...69RuntimeError: Click will abort further execution because Python was70 configured to use ASCII as encoding for the environment. Consult71 https://click.palletsprojects.com/unicode-support/ for mitigation72 steps.73```7475You are dealing with an environment where Python thinks you are restricted to ASCII data. The solution to these problems76is different depending on which locale your computer is running in.7778For instance, if you have a German Linux machine, you can fix the problem by exporting the locale to `de_DE.utf-8`:7980```console81export LC_ALL=de_DE.utf-882export LANG=de_DE.utf-883```8485If you are on a US machine, `en_US.utf-8` is the encoding of choice. On some newer Linux systems, you could also try86`C.UTF-8` as the locale:8788```console89export LC_ALL=C.UTF-890export LANG=C.UTF-891```9293On some systems it was reported that `UTF-8` has to be written as `UTF8` and vice versa. To see which locales are94supported you can invoke `locale -a`.9596You need to export the values before you invoke your Python script.9798In Python 3.7 and later you will no longer get a `RuntimeError` in many cases thanks to {pep}`538` and {pep}`540`, which99changed the default assumption in unconfigured environments. This doesn't change the general issue that your locale may100be misconfigured.
deleted:docs/unicode-support.rst-112 removed
1Unicode Support2===============34.. currentmodule:: click56Click has to take extra care to support Unicode text in different7environments.89* The command line in Unix is traditionally bytes, not Unicode. While10 there are encoding hints, there are some situations where this can11 break. The most common one is SSH connections to machines with12 different locales.1314 Misconfigured environments can cause a wide range of Unicode15 problems due to the lack of support for roundtripping surrogate16 escapes. This will not be fixed in Click itself!1718* Standard input and output is opened in text mode by default. Click19 has to reopen the stream in binary mode in certain situations.20 Because there is no standard way to do this, it might not always21 work. Primarily this can become a problem when testing command-line22 applications.2324 This is not supported::2526 sys.stdin = io.StringIO('Input here')27 sys.stdout = io.StringIO()2829 Instead you need to do this::3031 input = 'Input here'32 in_stream = io.BytesIO(input.encode('utf-8'))33 sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')34 out_stream = io.BytesIO()35 sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')3637 Remember in that case, you need to use ``out_stream.getvalue()``38 and not ``sys.stdout.getvalue()`` if you want to access the buffer39 contents as the wrapper will not forward that method.4041* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default42 text-based. When Click needs a binary stream, it attempts to43 discover the underlying binary stream.4445* ``sys.argv`` is always text. This means that the native type for46 input values to the types in Click is Unicode, not bytes.4748 This causes problems if the terminal is incorrectly set and Python49 does not figure out the encoding. In that case, the Unicode string50 will contain error bytes encoded as surrogate escapes.5152* When dealing with files, Click will always use the Unicode file53 system API by using the operating system's reported or guessed54 filesystem encoding. Surrogates are supported for filenames, so it55 should be possible to open files through the :class:`File` type even56 if the environment is misconfigured.575859Surrogate Handling60------------------6162Click does all the Unicode handling in the standard library and is63subject to its behavior. Unicode requires extra care. The reason for64this is that the encoding detection is done in the interpreter, and on65Linux and certain other operating systems, its encoding handling is66problematic.6768The biggest source of frustration is that Click scripts invoked by init69systems, deployment tools, or cron jobs will refuse to work unless a70Unicode locale is exported.7172If Click encounters such an environment it will prevent further73execution to force you to set a locale. This is done because Click74cannot know about the state of the system once it's invoked and restore75the values before Python's Unicode handling kicked in.7677If you see something like this error::7879 Traceback (most recent call last):80 ...81 RuntimeError: Click will abort further execution because Python was82 configured to use ASCII as encoding for the environment. Consult83 https://click.palletsprojects.com/unicode-support/ for mitigation84 steps.8586You are dealing with an environment where Python thinks you are87restricted to ASCII data. The solution to these problems is different88depending on which locale your computer is running in.8990For instance, if you have a German Linux machine, you can fix the91problem by exporting the locale to ``de_DE.utf-8``::9293 export LC_ALL=de_DE.utf-894 export LANG=de_DE.utf-89596If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97On some newer Linux systems, you could also try ``C.UTF-8`` as the98locale::99100 export LC_ALL=C.UTF-8101 export LANG=C.UTF-8102103On some systems it was reported that ``UTF-8`` has to be written as104``UTF8`` and vice versa. To see which locales are supported you can105invoke ``locale -a``.106107You need to export the values before you invoke your Python script.108109In Python 3.7 and later you will no longer get a ``RuntimeError`` in110many cases thanks to :pep:`538` and :pep:`540`, which changed the111default assumption in unconfigured environments. This doesn't change the112general issue that your locale may be misconfigured.
added:docs/utils.md+390 added
1# Utilities23```{currentmodule} click4```56Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunch7of addon functionality that is useful for writing command line utilities.89## Printing to Stdout1011The most obvious helper is the {func}`echo` function, which in many ways works like the Python `print` statement or12function. The main difference is that it works the same in many different terminal environments.1314Example:1516```python17import click1819click.echo('Hello World!')20```2122It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by23passing `nl=False`:2425```python26click.echo(b'\xe2\x98\x83', nl=False)27```2829Last but not least {func}`echo` uses click's intelligent internal output streams to stdout and stderr which support30unicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicode31characters (there are some limitations on the default font with regards to which characters can be displayed).3233```{versionadded} 6.034```3536Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more37information see {doc}`wincmd`.3839```{versionadded} 3.040```4142You can also easily print to standard error by passing `err=True`:4344```python45click.echo('Hello World!', err=True)46```4748(ansi-colors)=4950## ANSI Colors5152```{versionadded} 2.053```5455The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/).5657Primarily this means that:5859- Click's {func}`echo` function will automatically strip ANSI color codes if the stream is not connected to a terminal.60- the {func}`echo` function will transparently connect to the terminal on Windows and translate ANSI codes to terminal61 API calls. This means that colors will work on Windows the same way they do on other operating systems.6263On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not64required for Click.6566For styling a string, the {func}`style` function can be used:6768```python69import click7071click.echo(click.style('Hello World!', fg='green'))72click.echo(click.style('Some more text', bg='blue', fg='white'))73click.echo(click.style('ATTENTION', blink=True, bold=True))74```7576The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:7778```python79click.secho('Hello World!', fg='green')80click.secho('Some more text', bg='blue', fg='white')81click.secho('ATTENTION', blink=True, bold=True)82```8384## Pager Support8586In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be87achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always88writes to stdout and, if possible, through a pager.8990Example:9192```python93@click.command()94def less():95 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))96```9798If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,99you can pass a generator (or generator function) instead of a string:100101```python102def _generate_output():103 for idx in range(50000):104 yield f"Line {idx}\n"105106@click.command()107def less():108 click.echo_via_pager(_generate_output())109```110111## Screen Clearing112113```{versionadded} 2.0114```115116To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does117what the name suggests: it clears the entire visible screen in a platform-agnostic way:118119```python120import click121click.clear()122```123124## Getting Characters from Terminal125126```{versionadded} 2.0127```128129Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and130will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead131read individual characters as they are being written.132133For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and134returns it as a Unicode character.135136Note that this function will always read from the terminal, even if stdin is instead a pipe.137138Example:139140```python141import click142143click.echo('Continue? [yn] ', nl=False)144c = click.getchar()145click.echo()146if c == 'y':147 click.echo('We will go on')148elif c == 'n':149 click.echo('Abort!')150else:151 click.echo('Invalid input :(')152```153154Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape155format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file156exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that157cannot be properly exited.158159## Waiting for Key Press160161```{versionadded} 2.0162```163164Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows165where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.166167In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the168terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP169(no operation instruction) if the script is not run interactively.170171Example:172173```python174import click175click.pause()176```177178## Launching Editors179180```{versionadded} 2.0181```182183Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line184input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the185editor without saving, the return value will be `None`, otherwise the entered text.186187Example usage:188189```python190import click191192def get_commit_message():193 MARKER = '# Everything below is ignored\n'194 message = click.edit('\n\n' + MARKER)195 if message is not None:196 return message.split(MARKER, 1)[0].rstrip('\n')197```198199Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the200return value is always `None`.201202Example usage:203204```python205import click206click.edit(filename='/etc/passwd')207```208209## Launching Applications210211```{versionadded} 2.0212```213214Click supports launching applications through {func}`launch`. This can be used to open the default application215associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition216to this, it can also launch the file manager and automatically select the provided file.217218Example usage:219220```python221click.launch("https://click.palletsprojects.com/")222click.launch("/my/downloaded/file.txt", locate=True)223```224225## Printing Filenames226227Because filenames might not be Unicode, formatting them can be a bit tricky.228229The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the230filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode231string.232233Example:234235```python236click.echo(f"Path: {click.format_filename(b'foo.txt')}")237```238239## Standard Streams240241For command line utilities, it's very important to get access to input and output streams reliably. Python generally242provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between2432.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.244245Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce246consistent results with different Python versions and for a wide variety of terminal configurations.247248The end result is that these functions will always return a functional stream object (except in very odd cases; see249{doc}`/unicode-support`).250251Example:252253```python254import click255256stdin_text = click.get_text_stream('stdin')257stdout_binary = click.get_binary_stream('stdout')258```259260```{versionadded} 6.0261```262263Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more264information see {doc}`wincmd`.265266## Intelligent File Opening267268```{versionadded} 3.0269```270271Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`272function. It can intelligently open stdin/stdout as well as any other file.273274Example:275276```python277import click278279stdout = click.open_file('-', 'w')280test_file = click.open_file('test.txt', 'w')281```282283If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent284the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:285286```python287with click.open_file(filename, 'w') as f:288 f.write('Hello World!\n')289```290291## Finding Application Folders292293```{versionadded} 2.0294```295296Very often, you want to open a configuration file that belongs to your application. However, different operating systems297store these configuration files in different locations depending on their standards. Click provides a298{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application299depending on the OS.300301Example usage:302303```python304import os305import click306import ConfigParser307308APP_NAME = 'My Application'309def read_config():310cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')311parser = ConfigParser.RawConfigParser()312parser.read([cfg])313rv = {}314for section in parser.sections():315 for key, value in parser.items(section):316 rv[f"{section}.{key}"] = value317return rv318```319320## Showing Progress Bars321322Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some323progress about how long that will take. Click supports simple progress bar rendering for that through the324{func}`progressbar` function.325326```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).327```328329The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the330iterable it might take some time to do processing. So say you have a loop like this:331332```python333for user in all_the_users_to_process:334 modify_the_user(user)335```336337To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:338339```python340import click341342with click.progressbar(all_the_users_to_process) as bar:343 for user in bar:344 modify_the_user(user)345```346347Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The348calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the349length, you can explicitly provide it:350351```python352with click.progressbar(all_the_users_to_process,353 length=number_of_users) as bar:354 for user in bar:355 modify_the_user(user)356```357358Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render359correctly:360361```python362import time363364with click.progressbar([1, 2, 3]) as bar:365 for x in bar:366 print(f"sleep({x})...")367 time.sleep(x)368```369370Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:371372```python373with click.progressbar(all_the_users_to_process,374 label='Modifying user accounts',375 length=number_of_users) as bar:376 for user in bar:377 modify_the_user(user)378```379380Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you381need to specify the length (and no iterable), and use the update method on the context return value instead of iterating382directly over it:383384```python385with click.progressbar(length=total_size,386 label='Unzipping archive') as bar:387 for archive in zip_file:388 archive.extract()389 bar.update(archive.size)390```
deleted:docs/utils.rst-408 removed
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 many different terminal environments.1718Example::1920 import click2122 click.echo('Hello World!')2324It can output both text and binary data. It will emit a trailing newline25by default, which needs to be suppressed by passing ``nl=False``::2627 click.echo(b'\xe2\x98\x83', nl=False)2829Last but not least :func:`echo` uses click's intelligent internal output30streams to stdout and stderr which support unicode output on the Windows31console. This means for as long as you are using `click.echo` you can32output unicode characters (there are some limitations on the default font33with regards to which characters can be displayed).3435.. versionadded:: 6.03637Click emulates output streams on Windows to support unicode to the38Windows console through separate APIs. For more information see39:doc:`wincmd`.4041.. versionadded:: 3.04243You can also easily print to standard error by passing ``err=True``::4445 click.echo('Hello World!', err=True)464748.. _ansi-colors:4950ANSI Colors51-----------5253.. versionadded:: 2.05455The :func:`echo` function supports ANSI colors and styles. On Windows56this uses `colorama`_.5758Primarily this means that:5960- 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.6667On Windows, Click uses colorama without calling ``colorama.init()``. You68can still call that in your code, but it's not required for Click.6970For styling a string, the :func:`style` function can be used::7172 import click7374 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))7778The combination of :func:`echo` and :func:`style` is also available in79a single function called :func:`secho`::8081 click.secho('Hello World!', fg='green')82 click.secho('Some more text', bg='blue', fg='white')83 click.secho('ATTENTION', blink=True, bold=True)848586.. _colorama: https://pypi.org/project/colorama/8788Pager Support89-------------9091In some situations, you might want to show long texts on the terminal and92let a user scroll through it. This can be achieved by using the93:func:`echo_via_pager` function which works similarly to the :func:`echo`94function, but always writes to stdout and, if possible, through a pager.9596Example:9798.. click:example::99100 @click.command()101 def less():102 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))103104If 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:105106.. click:example::107 def _generate_output():108 for idx in range(50000):109 yield f"Line {idx}\n"110111 @click.command()112 def less():113 click.echo_via_pager(_generate_output())114115116Screen Clearing117---------------118119.. versionadded:: 2.0120121To clear the terminal screen, you can use the :func:`clear` function that122is provided starting with Click 2.0. It does what the name suggests: it123clears the entire visible screen in a platform-agnostic way:124125::126127 import click128 click.clear()129130131Getting Characters from Terminal132--------------------------------133134.. versionadded:: 2.0135136Normally, when reading input from the terminal, you would read from137standard input. However, this is buffered input and will not show up until138the line has been terminated. In certain circumstances, you might not want139to do that and instead read individual characters as they are being written.140141For this, Click provides the :func:`getchar` function which reads a single142character from the terminal buffer and returns it as a Unicode character.143144Note that this function will always read from the terminal, even if stdin145is instead a pipe.146147Example::148149 import click150151 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 :(')160161Note that this reads raw input, which means that things like arrow keys162will show up in the platform's native escape format. The only characters163translated are ``^C`` and ``^D`` which are converted into keyboard164interrupts and end of file exceptions respectively. This is done because165otherwise, it's too easy to forget about that and to create scripts that166cannot be properly exited.167168169Waiting for Key Press170---------------------171172.. versionadded:: 2.0173174Sometimes, it's useful to pause until the user presses any key on the175keyboard. This is especially useful on Windows where ``cmd.exe`` will176close the window at the end of the command execution by default, instead177of waiting.178179In click, this can be accomplished with the :func:`pause` function. This180function will print a quick message to the terminal (which can be181customized) and wait for the user to press a key. In addition to that,182it will also become a NOP (no operation instruction) if the script is not183run interactively.184185Example::186187 import click188 click.pause()189190191Launching Editors192-----------------193194.. versionadded:: 2.0195196Click supports launching editors automatically through :func:`edit`. This197is very useful for asking users for multi-line input. It will198automatically open the user's defined editor or fall back to a sensible199default. If the user closes the editor without saving, the return value200will be ``None``, otherwise the entered text.201202Example usage::203204 import click205206 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')211212Alternatively, the function can also be used to launch editors for files by213a specific filename. In this case, the return value is always `None`.214215Example usage::216217 import click218 click.edit(filename='/etc/passwd')219220221Launching Applications222----------------------223224.. versionadded:: 2.0225226Click supports launching applications through :func:`launch`. This can be227used to open the default application associated with a URL or filetype.228This can be used to launch web browsers or picture viewers, for instance.229In addition to this, it can also launch the file manager and automatically230select the provided file.231232Example usage::233234 click.launch("https://click.palletsprojects.com/")235 click.launch("/my/downloaded/file.txt", locate=True)236237238Printing Filenames239------------------240241Because filenames might not be Unicode, formatting them can be a bit242tricky.243244The way this works with click is through the :func:`format_filename`245function. It does a best-effort conversion of the filename to Unicode and246will never fail. This makes it possible to use these filenames in the247context of a full Unicode string.248249Example::250251 click.echo(f"Path: {click.format_filename(b'foo.txt')}")252253254Standard Streams255----------------256257For command line utilities, it's very important to get access to input and258output streams reliably. Python generally provides access to these259streams through ``sys.stdout`` and friends, but unfortunately, there are260API differences between 2.x and 3.x, especially with regards to how these261streams respond to Unicode and binary data.262263Because of this, click provides the :func:`get_binary_stream` and264:func:`get_text_stream` functions, which produce consistent results with265different Python versions and for a wide variety of terminal configurations.266267The end result is that these functions will always return a functional268stream object (except in very odd cases; see :doc:`/unicode-support`).269270Example::271272 import click273274 stdin_text = click.get_text_stream('stdin')275 stdout_binary = click.get_binary_stream('stdout')276277.. versionadded:: 6.0278279Click now emulates output streams on Windows to support unicode to the280Windows console through separate APIs. For more information see281:doc:`wincmd`.282283284Intelligent File Opening285------------------------286287.. versionadded:: 3.0288289Starting with Click 3.0 the logic for opening files from the :class:`File`290type is exposed through the :func:`open_file` function. It can291intelligently open stdin/stdout as well as any other file.292293Example::294295 import click296297 stdout = click.open_file('-', 'w')298 test_file = click.open_file('test.txt', 'w')299300If stdin or stdout are returned, the return value is wrapped in a special301file where the context manager will prevent the closing of the file. This302makes the handling of standard streams transparent and you can always use303it like this::304305 with click.open_file(filename, 'w') as f:306 f.write('Hello World!\n')307308309Finding Application Folders310---------------------------311312.. versionadded:: 2.0313314Very often, you want to open a configuration file that belongs to your315application. However, different operating systems store these configuration316files in different locations depending on their standards. Click provides317a :func:`get_app_dir` function which returns the most appropriate location318for per-user config files for your application depending on the OS.319320Example usage::321322 import os323 import click324 import ConfigParser325326 APP_NAME = 'My Application'327328 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 rv337338339Showing Progress Bars340---------------------341342Sometimes, you have command line scripts that need to process a lot of data,343but you want to quickly show the user some progress about how long that344will take. Click supports simple progress bar rendering for that through345the :func:`progressbar` function.346347.. note::348349 If you find that you have requirements beyond what Click's progress350 bar supports, try using `tqdm`_.351352 .. _tqdm: https://tqdm.github.io/353354The basic usage is very simple: the idea is that you have an iterable that355you want to operate on. For each item in the iterable it might take some356time to do processing. So say you have a loop like this::357358 for user in all_the_users_to_process:359 modify_the_user(user)360361To hook this up with an automatically updating progress bar, all you need362to do is to change the code to this::363364 import click365366 with click.progressbar(all_the_users_to_process) as bar:367 for user in bar:368 modify_the_user(user)369370Click will then automatically print a progress bar to the terminal and371calculate the remaining time for you. The calculation of remaining time372requires that the iterable has a length. If it does not have a length373but you know the length, you can explicitly provide it::374375 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)379380Note that :func:`progressbar` updates the bar *after* each iteration of the381loop. So code like this will render correctly::382383 import time384385 with click.progressbar([1, 2, 3]) as bar:386 for x in bar:387 print(f"sleep({x})...")388 time.sleep(x)389390Another useful feature is to associate a label with the progress bar which391will be shown preceding the progress bar::392393 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)398399Sometimes, one may need to iterate over an external iterator, and advance the400progress bar irregularly. To do so, you need to specify the length (and no401iterable), and use the update method on the context return value instead of402iterating directly over it::403404 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)