Skip to content
Myr

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

2 files+343 added−376 removed

modified:docs/unicode-support.md+69 added-84 removed
modified:docs/utils.md+274 added-292 removed
1Utilities2=========1# Utilities24.. currentmodule:: click3Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunch4of addon functionality that is useful for writing command line utilities.56Besides 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.6## Printing to Stdout78The most obvious helper is the {func}`click.echo` function, which in many ways works like the Python `print` statement or9function. The main difference is that it works the same in many different terminal environments.1011Printing to Stdout12------------------11Example:1214The 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.13```python14import click1518Example::16click.echo('Hello World!')17```1820 import click19It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by20passing `nl=False`:2122 click.echo('Hello World!')22```python23click.echo(b'\xe2\x98\x83', nl=False)24```2524It can output both text and binary data. It will emit a trailing newline25by default, which needs to be suppressed by passing ``nl=False``::26Last but not least {func}`click.echo` uses click's intelligent internal output streams to stdout and stderr which support27unicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicode28characters (there are some limitations on the default font with regards to which characters can be displayed).2927 click.echo(b'\xe2\x98\x83', nl=False)30```{versionadded} 6.031```3229Last 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).33Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more34information see {doc}`wincmd`.3535.. versionadded:: 6.036```{versionadded} 3.037```3837Click emulates output streams on Windows to support unicode to the38Windows console through separate APIs. For more information see39:doc:`wincmd`.39You can also easily print to standard error by passing `err=True`:4041.. versionadded:: 3.041```python42click.echo('Hello World!', err=True)43```4443You can also easily print to standard error by passing ``err=True``::45(ansi-colors)=4645 click.echo('Hello World!', err=True)47## ANSI Colors4849```{versionadded} 2.050```5148.. _ansi-colors:52The {func}`click.echo` function supports ANSI colors and styles. On Windows this uses [colorama].5350ANSI Colors51-----------5253.. versionadded:: 2.05455The :func:`echo` function supports ANSI colors and styles. On Windows56this uses `colorama`_.5754Primarily this means that:5560- 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.5967On Windows, Click uses colorama without calling ``colorama.init()``. You68can still call that in your code, but it's not required for Click.60On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not61required for Click.6270For styling a string, the :func:`style` function can be used::63For styling a string, the {func}`click.style` function can be used:6465```python72 import click66import click6774 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))68click.echo(click.style('Hello World!', fg='green'))69click.echo(click.style('Some more text', bg='blue', fg='white'))70click.echo(click.style('ATTENTION', blink=True, bold=True))71```7278The combination of :func:`echo` and :func:`style` is also available in79a single function called :func:`secho`::73The combination of {func}`click.echo` and {func}`click.style` is also available in a single function called {func}`click.secho`:7475```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)76click.secho('Hello World!', fg='green')77click.secho('Some more text', bg='blue', fg='white')78click.secho('ATTENTION', blink=True, bold=True)79```8081## Pager Support8286.. _colorama: https://pypi.org/project/colorama/83In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be84achieved by using the {func}`click.echo_via_pager` function which works similarly to the {func}`click.echo` function, but always85writes to stdout and, if possible, through a pager.8688Pager 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.9587Example:8898.. click:example::89```python90@click.command()91def less():92 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))93```94100 @click.command()101 def less():102 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))95If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,96you can pass a generator (or generator function) instead of a string:97104If 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```python99def _generate_output():100 for idx in range(50000):101 yield f"Line {idx}\n"102106.. click:example::107 def _generate_output():108 for idx in range(50000):109 yield f"Line {idx}\n"103@click.command()104def less():105 click.echo_via_pager(_generate_output())106```107111 @click.command()112 def less():113 click.echo_via_pager(_generate_output())108## Screen Clearing109110```{versionadded} 2.0111```112116Screen Clearing117---------------113To clear the terminal screen, you can use the {func}`click.clear` function that is provided starting with Click 2.0. It does114what the name suggests: it clears the entire visible screen in a platform-agnostic way:115119.. versionadded:: 2.0116```117import click118click.clear()119```120121To 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:121## Getting Characters from Terminal122125::123```{versionadded} 2.0124```125127 import click128 click.clear()126Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and127will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead128read individual characters as they are being written.129130For this, Click provides the {func}`click.getchar` function which reads a single character from the terminal buffer and131returns it as a Unicode character.132131Getting Characters from Terminal132--------------------------------133Note that this function will always read from the terminal, even if stdin is instead a pipe.134134.. versionadded:: 2.0135Example:136136Normally, 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.137```python138import click139141For this, Click provides the :func:`getchar` function which reads a single142character from the terminal buffer and returns it as a Unicode character.140click.echo('Continue? [yn] ', nl=False)141c = click.getchar()142click.echo()143if c == 'y':144 click.echo('We will go on')145elif c == 'n':146 click.echo('Abort!')147else:148 click.echo('Invalid input :(')149```150144Note 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 that151Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape152format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file153exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that154cannot be properly exited.155156## Waiting for Key Press157169Waiting for Key Press170---------------------158```{versionadded} 2.0159```160172.. versionadded:: 2.0161Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows162where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.163174Sometimes, 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.164In click, this can be accomplished with the {func}`click.pause` function. This function will print a quick message to the165terminal (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.167179In 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.168Example:169185Example::170```python171import click172click.pause()173```174187 import click188 click.pause()175## Launching Editors176177```{versionadded} 2.0178```179191Launching Editors192-----------------180Click supports launching editors automatically through {func}`click.edit`. This is very useful for asking users for multi-line181input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the182editor without saving, the return value will be `None`, otherwise the entered text.183194.. versionadded:: 2.0184Example usage:185196Click 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.186```python187import click188202Example usage::189def 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```195204 import click196Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the197return value is always `None`.198206 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')199Example usage:200212Alternatively, the function can also be used to launch editors for files by213a specific filename. In this case, the return value is always `None`.201```python202import click203click.edit(filename='/etc/passwd')204```205215Example usage::206## Launching Applications207217 import click218 click.edit(filename='/etc/passwd')208```{versionadded} 2.0209```210211Click supports launching applications through {func}`click.launch`. This can be used to open the default application212associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition213to this, it can also launch the file manager and automatically select the provided file.214221Launching Applications222----------------------215Example usage:216224.. versionadded:: 2.0217```python218click.launch("https://click.palletsprojects.com/")219click.launch("/my/downloaded/file.txt", locate=True)220```221226Click 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.222## Printing Filenames223232Example usage::224Because filenames might not be Unicode, formatting them can be a bit tricky.225234 click.launch("https://click.palletsprojects.com/")235 click.launch("/my/downloaded/file.txt", locate=True)226The way this works with click is through the {func}`click.format_filename` function. It does a best-effort conversion of the227filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode228string.229230Example:231238Printing Filenames239------------------232```python233click.echo(f"Path: {click.format_filename(b'foo.txt')}")234```235241Because filenames might not be Unicode, formatting them can be a bit242tricky.236## Standard Streams237244The 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.238For command line utilities, it's very important to get access to input and output streams reliably. Python generally239provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between2402.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.241249Example::242Because of this, click provides the {func}`click.get_binary_stream` and {func}`click.get_text_stream` functions, which produce243consistent results with different Python versions and for a wide variety of terminal configurations.244251 click.echo(f"Path: {click.format_filename(b'foo.txt')}")245The end result is that these functions will always return a functional stream object (except in very odd cases; see246{doc}`/unicode-support`).247248Example:249254Standard Streams255----------------250```python251import click252257For 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.253stdin_text = click.get_text_stream('stdin')254stdout_binary = click.get_binary_stream('stdout')255```256263Because 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.257```{versionadded} 6.0258```259267The end result is that these functions will always return a functional268stream object (except in very odd cases; see :doc:`/unicode-support`).260Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more261information see {doc}`wincmd`.262270Example::263## Intelligent File Opening264272 import click265```{versionadded} 3.0266```267274 stdin_text = click.get_text_stream('stdin')275 stdout_binary = click.get_binary_stream('stdout')268Starting with Click 3.0 the logic for opening files from the {func}`click.File` type is exposed through the {func}`click.open_file`269function. It can intelligently open stdin/stdout as well as any other file.270277.. versionadded:: 6.0271Example:272279Click now emulates output streams on Windows to support unicode to the280Windows console through separate APIs. For more information see281:doc:`wincmd`.273```python274import click275276stdout = click.open_file('-', 'w')277test_file = click.open_file('test.txt', 'w')278```279284Intelligent File Opening285------------------------280If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent281the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:282287.. versionadded:: 3.0283```python284with click.open_file(filename, 'w') as f:285 f.write('Hello World!\n')286```287289Starting 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.288## Finding Application Folders289293Example::290```{versionadded} 2.0291```292295 import click293Very often, you want to open a configuration file that belongs to your application. However, different operating systems294store 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 application296depending on the OS.297297 stdout = click.open_file('-', 'w')298 test_file = click.open_file('test.txt', 'w')298Example usage: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::300```python301import os302import click303import ConfigParser304305 with click.open_file(filename, 'w') as f:306 f.write('Hello World!\n')305APP_NAME = 'My Application'306def read_config():307cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')308parser = ConfigParser.RawConfigParser()309parser.read([cfg])310rv = {}311for section in parser.sections():312 for key, value in parser.items(section):313 rv[f"{section}.{key}"] = value314return rv315```316317## Showing Progress Bars318309Finding Application Folders310---------------------------319Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some320progress about how long that will take. Click supports simple progress bar rendering for that through the321{func}`click.progressbar` function.322312.. versionadded:: 2.0323```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm].324```325314Very 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.326The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the327iterable it might take some time to do processing. So say you have a loop like this:328320Example usage::329```python330for user in all_the_users_to_process:331 modify_the_user(user)332```333322 import os323 import click324 import ConfigParser334To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:335326 APP_NAME = 'My Application'336```python337import click338328 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 rv339with click.progressbar(all_the_users_to_process) as bar:340 for user in bar:341 modify_the_user(user)342```343344Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The345calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the346length, you can explicitly provide it:347339Showing Progress Bars340---------------------348```python349with 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```354342Sometimes, 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.355Note that {func}`click.progressbar` updates the bar *after* each iteration of the loop. So code like this will render356correctly:357347.. note::358```python359import time360349 If you find that you have requirements beyond what Click's progress350 bar supports, try using `tqdm`_.361with click.progressbar([1, 2, 3]) as bar:362 for x in bar:363 print(f"sleep({x})...")364 time.sleep(x)365```366352 .. _tqdm: https://tqdm.github.io/367Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:368354The 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:369```python370with 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```376361To hook this up with an automatically updating progress bar, all you need362to do is to change the code to this::377Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you378need to specify the length (and no iterable), and use the update method on the context return value instead of iterating379directly over it:380364 import click381```python382with 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```388366 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)389[colorama]: https://pypi.org/project/colorama/390[tqdm]: https://tqdm.github.io/