change extension to .md
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by denuoweb · committed by denuoweb · parent 60b9c0e · Browse files · 4 files·+520 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+520 added−520 removed
- other:+520 added−520 removed
Provenance
- Commit
c002e08- Tree
1475bde- Author
denuoweb <jaron@rosenau.info>- Committer
denuoweb <jaron@rosenau.info>- Parent
60b9c0e
4 files changed+520 added−520 removed
added:docs/unicode-support.md+112 added
1+Unicode Support2+===============3+4+.. currentmodule:: click5+6+Click has to take extra care to support Unicode text in different7+environments.8+9+* 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.13+14+ 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!17+18+* 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.23+24+ This is not supported::25+26+ sys.stdin = io.StringIO('Input here')27+ sys.stdout = io.StringIO()28+29+ Instead you need to do this::30+31+ 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')36+37+ 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.40+41+* ``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.44+45+* ``sys.argv`` is always text. This means that the native type for46+ input values to the types in Click is Unicode, not bytes.47+48+ 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.51+52+* 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.57+58+59+Surrogate Handling60+------------------61+62+Click does all the Unicode handling in the standard library and is63+subject to its behavior. Unicode requires extra care. The reason for64+this is that the encoding detection is done in the interpreter, and on65+Linux and certain other operating systems, its encoding handling is66+problematic.67+68+The biggest source of frustration is that Click scripts invoked by init69+systems, deployment tools, or cron jobs will refuse to work unless a70+Unicode locale is exported.71+72+If Click encounters such an environment it will prevent further73+execution to force you to set a locale. This is done because Click74+cannot know about the state of the system once it's invoked and restore75+the values before Python's Unicode handling kicked in.76+77+If you see something like this error::78+79+ 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.85+86+You are dealing with an environment where Python thinks you are87+restricted to ASCII data. The solution to these problems is different88+depending on which locale your computer is running in.89+90+For instance, if you have a German Linux machine, you can fix the91+problem by exporting the locale to ``de_DE.utf-8``::92+93+ export LC_ALL=de_DE.utf-894+ export LANG=de_DE.utf-895+96+If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97+On some newer Linux systems, you could also try ``C.UTF-8`` as the98+locale::99+100+ export LC_ALL=C.UTF-8101+ export LANG=C.UTF-8102+103+On some systems it was reported that ``UTF-8`` has to be written as104+``UTF8`` and vice versa. To see which locales are supported you can105+invoke ``locale -a``.106+107+You need to export the values before you invoke your Python script.108+109+In Python 3.7 and later you will no longer get a ``RuntimeError`` in110+many cases thanks to :pep:`538` and :pep:`540`, which changed the111+default assumption in unconfigured environments. This doesn't change the112+general issue that your locale may be misconfigured.deleted:docs/unicode-support.rst-112 removed
1-Unicode Support2-===============3-4-.. currentmodule:: click5-6-Click has to take extra care to support Unicode text in different7-environments.8-9-* 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.13-14- 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!17-18-* 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.23-24- This is not supported::25-26- sys.stdin = io.StringIO('Input here')27- sys.stdout = io.StringIO()28-29- Instead you need to do this::30-31- 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')36-37- 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.40-41-* ``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.44-45-* ``sys.argv`` is always text. This means that the native type for46- input values to the types in Click is Unicode, not bytes.47-48- 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.51-52-* 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.57-58-59-Surrogate Handling60-------------------61-62-Click does all the Unicode handling in the standard library and is63-subject to its behavior. Unicode requires extra care. The reason for64-this is that the encoding detection is done in the interpreter, and on65-Linux and certain other operating systems, its encoding handling is66-problematic.67-68-The biggest source of frustration is that Click scripts invoked by init69-systems, deployment tools, or cron jobs will refuse to work unless a70-Unicode locale is exported.71-72-If Click encounters such an environment it will prevent further73-execution to force you to set a locale. This is done because Click74-cannot know about the state of the system once it's invoked and restore75-the values before Python's Unicode handling kicked in.76-77-If you see something like this error::78-79- 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.85-86-You are dealing with an environment where Python thinks you are87-restricted to ASCII data. The solution to these problems is different88-depending on which locale your computer is running in.89-90-For instance, if you have a German Linux machine, you can fix the91-problem by exporting the locale to ``de_DE.utf-8``::92-93- export LC_ALL=de_DE.utf-894- export LANG=de_DE.utf-895-96-If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97-On some newer Linux systems, you could also try ``C.UTF-8`` as the98-locale::99-100- export LC_ALL=C.UTF-8101- export LANG=C.UTF-8102-103-On some systems it was reported that ``UTF-8`` has to be written as104-``UTF8`` and vice versa. To see which locales are supported you can105-invoke ``locale -a``.106-107-You need to export the values before you invoke your Python script.108-109-In Python 3.7 and later you will no longer get a ``RuntimeError`` in110-many cases thanks to :pep:`538` and :pep:`540`, which changed the111-default assumption in unconfigured environments. This doesn't change the112-general issue that your locale may be misconfigured.added:docs/utils.md+408 added
1+Utilities2+=========3+4+.. currentmodule:: click5+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.9+10+11+Printing to Stdout12+------------------13+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.17+18+Example::19+20+ import click21+22+ click.echo('Hello World!')23+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+27+ click.echo(b'\xe2\x98\x83', nl=False)28+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).34+35+.. versionadded:: 6.036+37+Click emulates output streams on Windows to support unicode to the38+Windows console through separate APIs. For more information see39+:doc:`wincmd`.40+41+.. versionadded:: 3.042+43+You can also easily print to standard error by passing ``err=True``::44+45+ click.echo('Hello World!', err=True)46+47+48+.. _ansi-colors:49+50+ANSI Colors51+-----------52+53+.. versionadded:: 2.054+55+The :func:`echo` function supports ANSI colors and styles. On Windows56+this uses `colorama`_.57+58+Primarily this means that:59+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.66+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.69+70+For styling a string, the :func:`style` function can be used::71+72+ import click73+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))77+78+The combination of :func:`echo` and :func:`style` is also available in79+a single function called :func:`secho`::80+81+ click.secho('Hello World!', fg='green')82+ click.secho('Some more text', bg='blue', fg='white')83+ click.secho('ATTENTION', blink=True, bold=True)84+85+86+.. _colorama: https://pypi.org/project/colorama/87+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+96+Example:97+98+.. click:example::99+100+ @click.command()101+ def less():102+ click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))103+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:105+106+.. click:example::107+ def _generate_output():108+ for idx in range(50000):109+ yield f"Line {idx}\n"110+111+ @click.command()112+ def less():113+ click.echo_via_pager(_generate_output())114+115+116+Screen Clearing117+---------------118+119+.. versionadded:: 2.0120+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:124+125+::126+127+ import click128+ click.clear()129+130+131+Getting Characters from Terminal132+--------------------------------133+134+.. versionadded:: 2.0135+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.140+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.143+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 that166+cannot be properly exited.167+168+169+Waiting for Key Press170+---------------------171+172+.. versionadded:: 2.0173+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.178+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.184+185+Example::186+187+ import click188+ click.pause()189+190+191+Launching Editors192+-----------------193+194+.. versionadded:: 2.0195+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.201+202+Example usage::203+204+ import click205+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')211+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`.214+215+Example usage::216+217+ import click218+ click.edit(filename='/etc/passwd')219+220+221+Launching Applications222+----------------------223+224+.. versionadded:: 2.0225+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.231+232+Example usage::233+234+ click.launch("https://click.palletsprojects.com/")235+ click.launch("/my/downloaded/file.txt", locate=True)236+237+238+Printing Filenames239+------------------240+241+Because filenames might not be Unicode, formatting them can be a bit242+tricky.243+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.248+249+Example::250+251+ click.echo(f"Path: {click.format_filename(b'foo.txt')}")252+253+254+Standard Streams255+----------------256+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.262+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.266+267+The end result is that these functions will always return a functional268+stream object (except in very odd cases; see :doc:`/unicode-support`).269+270+Example::271+272+ import click273+274+ stdin_text = click.get_text_stream('stdin')275+ stdout_binary = click.get_binary_stream('stdout')276+277+.. versionadded:: 6.0278+279+Click now emulates output streams on Windows to support unicode to the280+Windows console through separate APIs. For more information see281+:doc:`wincmd`.282+283+284+Intelligent File Opening285+------------------------286+287+.. versionadded:: 3.0288+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.292+293+Example::294+295+ import click296+297+ stdout = click.open_file('-', 'w')298+ test_file = click.open_file('test.txt', 'w')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::304+305+ with click.open_file(filename, 'w') as f:306+ f.write('Hello World!\n')307+308+309+Finding Application Folders310+---------------------------311+312+.. versionadded:: 2.0313+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.319+320+Example usage::321+322+ import os323+ import click324+ import ConfigParser325+326+ APP_NAME = 'My Application'327+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 rv337+338+339+Showing Progress Bars340+---------------------341+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.346+347+.. note::348+349+ If you find that you have requirements beyond what Click's progress350+ bar supports, try using `tqdm`_.351+352+ .. _tqdm: https://tqdm.github.io/353+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:359+ modify_the_user(user)360+361+To hook this up with an automatically updating progress bar, all you need362+to do is to change the code to this::363+364+ import click365+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)deleted:docs/utils.rst-408 removed
1-Utilities2-=========3-4-.. currentmodule:: click5-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.9-10-11-Printing to Stdout12-------------------13-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.17-18-Example::19-20- import click21-22- click.echo('Hello World!')23-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-27- click.echo(b'\xe2\x98\x83', nl=False)28-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).34-35-.. versionadded:: 6.036-37-Click emulates output streams on Windows to support unicode to the38-Windows console through separate APIs. For more information see39-:doc:`wincmd`.40-41-.. versionadded:: 3.042-43-You can also easily print to standard error by passing ``err=True``::44-45- click.echo('Hello World!', err=True)46-47-48-.. _ansi-colors:49-50-ANSI Colors51------------52-53-.. versionadded:: 2.054-55-The :func:`echo` function supports ANSI colors and styles. On Windows56-this uses `colorama`_.57-58-Primarily this means that:59-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.66-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.69-70-For styling a string, the :func:`style` function can be used::71-72- import click73-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))77-78-The combination of :func:`echo` and :func:`style` is also available in79-a single function called :func:`secho`::80-81- click.secho('Hello World!', fg='green')82- click.secho('Some more text', bg='blue', fg='white')83- click.secho('ATTENTION', blink=True, bold=True)84-85-86-.. _colorama: https://pypi.org/project/colorama/87-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-96-Example:97-98-.. click:example::99-100- @click.command()101- def less():102- click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))103-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:105-106-.. click:example::107- def _generate_output():108- for idx in range(50000):109- yield f"Line {idx}\n"110-111- @click.command()112- def less():113- click.echo_via_pager(_generate_output())114-115-116-Screen Clearing117----------------118-119-.. versionadded:: 2.0120-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:124-125-::126-127- import click128- click.clear()129-130-131-Getting Characters from Terminal132---------------------------------133-134-.. versionadded:: 2.0135-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.140-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.143-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 that166-cannot be properly exited.167-168-169-Waiting for Key Press170----------------------171-172-.. versionadded:: 2.0173-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.178-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.184-185-Example::186-187- import click188- click.pause()189-190-191-Launching Editors192------------------193-194-.. versionadded:: 2.0195-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.201-202-Example usage::203-204- import click205-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')211-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`.214-215-Example usage::216-217- import click218- click.edit(filename='/etc/passwd')219-220-221-Launching Applications222-----------------------223-224-.. versionadded:: 2.0225-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.231-232-Example usage::233-234- click.launch("https://click.palletsprojects.com/")235- click.launch("/my/downloaded/file.txt", locate=True)236-237-238-Printing Filenames239-------------------240-241-Because filenames might not be Unicode, formatting them can be a bit242-tricky.243-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.248-249-Example::250-251- click.echo(f"Path: {click.format_filename(b'foo.txt')}")252-253-254-Standard Streams255-----------------256-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.262-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.266-267-The end result is that these functions will always return a functional268-stream object (except in very odd cases; see :doc:`/unicode-support`).269-270-Example::271-272- import click273-274- stdin_text = click.get_text_stream('stdin')275- stdout_binary = click.get_binary_stream('stdout')276-277-.. versionadded:: 6.0278-279-Click now emulates output streams on Windows to support unicode to the280-Windows console through separate APIs. For more information see281-:doc:`wincmd`.282-283-284-Intelligent File Opening285-------------------------286-287-.. versionadded:: 3.0288-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.292-293-Example::294-295- import click296-297- stdout = click.open_file('-', 'w')298- test_file = click.open_file('test.txt', 'w')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::304-305- with click.open_file(filename, 'w') as f:306- f.write('Hello World!\n')307-308-309-Finding Application Folders310----------------------------311-312-.. versionadded:: 2.0313-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.319-320-Example usage::321-322- import os323- import click324- import ConfigParser325-326- APP_NAME = 'My Application'327-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 rv337-338-339-Showing Progress Bars340----------------------341-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.346-347-.. note::348-349- If you find that you have requirements beyond what Click's progress350- bar supports, try using `tqdm`_.351-352- .. _tqdm: https://tqdm.github.io/353-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:359- modify_the_user(user)360-361-To hook this up with an automatically updating progress bar, all you need362-to do is to change the code to this::363-364- import click365-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)