utils.md
This file
Path
docs/utils.md
392 lines · 12.2 KiB · Markdown
Last changed by
restore “eval-rst … click:example::” directivesdenuowebbefore adoption3b5ee71
History of this fileTake it
move header to top ofJaron Rosenaubefore adoption8231bdf
lines 1–2why, one step back1# Utilities2add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
lines 3–5why, one step back3```{currentmodule} click4```5convert from reST to MySTdenuowebbefore adoption29eb946
lines 6–7why, one step back6Besides 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.change extension to .mddenuowebbefore adoptionc002e08
line 8why, one step back8convert from reST to MySTdenuowebbefore adoption29eb946
line 9why, one step back9## Printing to Stdoutchange extension to .mddenuowebbefore adoptionc002e08
line 10why, one step back10add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 11why, one step back11The most obvious helper is the {func}`echo` function, which in many ways works like the Python `print` statement orconvert from reST to MySTdenuowebbefore adoption29eb946
line 12why, one step back12function. The main difference is that it works the same in many different terminal environments.change extension to .mddenuowebbefore adoptionc002e08
line 13why, one step back13convert from reST to MySTdenuowebbefore adoption29eb946
line 14why, one step back14Example:change extension to .mddenuowebbefore adoptionc002e08
line 15why, one step back15convert from reST to MySTdenuowebbefore adoption29eb946
lines 16–17why, one step back16```python17import clickchange extension to .mddenuowebbefore adoptionc002e08
line 18why, one step back18convert from reST to MySTdenuowebbefore adoption29eb946
lines 19–20why, one step back19click.echo('Hello World!')20```change extension to .mddenuowebbefore adoptionc002e08
line 21why, one step back21convert from reST to MySTdenuowebbefore adoption29eb946
lines 22–23why, one step back22It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by23passing `nl=False`:change extension to .mddenuowebbefore adoptionc002e08
line 24why, one step back24convert from reST to MySTdenuowebbefore adoption29eb946
lines 25–27why, one step back25```python26click.echo(b'\xe2\x98\x83', nl=False)27```change extension to .mddenuowebbefore adoptionc002e08
line 28why, one step back28add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 29why, one step back29Last but not least {func}`echo` uses click's intelligent internal output streams to stdout and stderr which supportconvert from reST to MySTdenuowebbefore adoption29eb946
lines 30–31why, one step back30unicode 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).change extension to .mddenuowebbefore adoptionc002e08
line 32why, one step back32convert from reST to MySTdenuowebbefore adoption29eb946
lines 33–34why, one step back33```{versionadded} 6.034```change extension to .mddenuowebbefore adoptionc002e08
line 35why, one step back35convert from reST to MySTdenuowebbefore adoption29eb946
lines 36–37why, one step back36Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more37information see {doc}`wincmd`.change extension to .mddenuowebbefore adoptionc002e08
line 38why, one step back38convert from reST to MySTdenuowebbefore adoption29eb946
lines 39–40why, one step back39```{versionadded} 3.040```change extension to .mddenuowebbefore adoptionc002e08
line 41why, one step back41convert from reST to MySTdenuowebbefore adoption29eb946
line 42why, one step back42You can also easily print to standard error by passing `err=True`:change extension to .mddenuowebbefore adoptionc002e08
line 43why, one step back43convert from reST to MySTdenuowebbefore adoption29eb946
lines 44–46why, one step back44```python45click.echo('Hello World!', err=True)46```change extension to .mddenuowebbefore adoptionc002e08
line 47why, one step back47convert from reST to MySTdenuowebbefore adoption29eb946
line 48why, one step back48(ansi-colors)=change extension to .mddenuowebbefore adoptionc002e08
line 49why, one step back49convert from reST to MySTdenuowebbefore adoption29eb946
line 50why, one step back50## ANSI Colorschange extension to .mddenuowebbefore adoptionc002e08
line 51why, one step back51convert from reST to MySTdenuowebbefore adoption29eb946
lines 52–53why, one step back52```{versionadded} 2.053```change extension to .mddenuowebbefore adoptionc002e08
line 54why, one step back54move header to top ofJaron Rosenaubefore adoption8231bdf
line 55why, one step back55The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/).change extension to .mddenuowebbefore adoptionc002e08
lines 56–58why, one step back5657Primarily this means that:58add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
lines 59–60why, one step back59- 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 terminalconvert from reST to MySTdenuowebbefore adoption29eb946
line 61why, one step back61 API calls. This means that colors will work on Windows the same way they do on other operating systems.change extension to .mddenuowebbefore adoptionc002e08
line 62why, one step back62convert from reST to MySTdenuowebbefore adoption29eb946
lines 63–64why, one step back63On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not64required for Click.change extension to .mddenuowebbefore adoptionc002e08
line 65why, one step back65add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 66why, one step back66For styling a string, the {func}`style` function can be used:change extension to .mddenuowebbefore adoptionc002e08
line 67why, one step back67convert from reST to MySTdenuowebbefore adoption29eb946
lines 68–69why, one step back68```python69import clickchange extension to .mddenuowebbefore adoptionc002e08
line 70why, one step back70convert from reST to MySTdenuowebbefore adoption29eb946
lines 71–74why, one step back71click.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```change extension to .mddenuowebbefore adoptionc002e08
line 75why, one step back75add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 76why, one step back76The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:change extension to .mddenuowebbefore adoptionc002e08
line 77why, one step back77convert from reST to MySTdenuowebbefore adoption29eb946
lines 78–82why, one step back78```python79click.secho('Hello World!', fg='green')80click.secho('Some more text', bg='blue', fg='white')81click.secho('ATTENTION', blink=True, bold=True)82```change extension to .mddenuowebbefore adoptionc002e08
line 83why, one step back83convert from reST to MySTdenuowebbefore adoption29eb946
line 84why, one step back84## Pager Supportchange extension to .mddenuowebbefore adoptionc002e08
line 85why, one step back85convert from reST to MySTdenuowebbefore adoption29eb946
line 86why, one step back86In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can beadd currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 87why, one step back87achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but alwaysconvert from reST to MySTdenuowebbefore adoption29eb946
line 88why, one step back88writes to stdout and, if possible, through a pager.change extension to .mddenuowebbefore adoptionc002e08
lines 89–91why, one step back8990Example:91restore “eval-rst … click:example::” directivesdenuowebbefore adoption3b5ee71
lines 92–96why, one step back92```{eval-rst}93.. click:example::94 @click.command()95 def less():96 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))convert from reST to MySTdenuowebbefore adoption29eb946
line 97why, one step back97```change extension to .mddenuowebbefore adoptionc002e08
line 98why, one step back98convert from reST to MySTdenuowebbefore adoption29eb946
lines 99–100why, one step back99If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,100you can pass a generator (or generator function) instead of a string:change extension to .mddenuowebbefore adoptionc002e08
line 101why, one step back101restore “eval-rst … click:example::” directivesdenuowebbefore adoption3b5ee71
lines 102–106why, one step back102```{eval-rst}103.. click:example::104 def _generate_output():105 for idx in range(50000):106 yield f"Line {idx}\n"change extension to .mddenuowebbefore adoptionc002e08
line 107why, one step back107restore “eval-rst … click:example::” directivesdenuowebbefore adoption3b5ee71
lines 108–110why, one step back108 @click.command()109 def less():110 click.echo_via_pager(_generate_output())convert from reST to MySTdenuowebbefore adoption29eb946
line 111why, one step back111```change extension to .mddenuowebbefore adoptionc002e08
line 112why, one step back112convert from reST to MySTdenuowebbefore adoption29eb946
line 113why, one step back113## Screen Clearingchange extension to .mddenuowebbefore adoptionc002e08
line 114why, one step back114convert from reST to MySTdenuowebbefore adoption29eb946
lines 115–116why, one step back115```{versionadded} 2.0116```change extension to .mddenuowebbefore adoptionc002e08
line 117why, one step back117add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 118why, one step back118To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It doesconvert from reST to MySTdenuowebbefore adoption29eb946
line 119why, one step back119what the name suggests: it clears the entire visible screen in a platform-agnostic way:change extension to .mddenuowebbefore adoptionc002e08
line 120why, one step back120add python label in codeblockdenuowebbefore adoptionba20b21
line 121why, one step back121```pythonconvert from reST to MySTdenuowebbefore adoption29eb946
lines 122–124why, one step back122import click123click.clear()124```change extension to .mddenuowebbefore adoptionc002e08
line 125why, one step back125convert from reST to MySTdenuowebbefore adoption29eb946
line 126why, one step back126## Getting Characters from Terminalchange extension to .mddenuowebbefore adoptionc002e08
line 127why, one step back127convert from reST to MySTdenuowebbefore adoption29eb946
lines 128–129why, one step back128```{versionadded} 2.0129```change extension to .mddenuowebbefore adoptionc002e08
line 130why, one step back130convert from reST to MySTdenuowebbefore adoption29eb946
lines 131–133why, one step back131Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and132will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead133read individual characters as they are being written.change extension to .mddenuowebbefore adoptionc002e08
line 134why, one step back134add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 135why, one step back135For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer andconvert from reST to MySTdenuowebbefore adoption29eb946
line 136why, one step back136returns it as a Unicode character.change extension to .mddenuowebbefore adoptionc002e08
line 137why, one step back137convert from reST to MySTdenuowebbefore adoption29eb946
line 138why, one step back138Note that this function will always read from the terminal, even if stdin is instead a pipe.change extension to .mddenuowebbefore adoptionc002e08
line 139why, one step back139convert from reST to MySTdenuowebbefore adoption29eb946
line 140why, one step back140Example:change extension to .mddenuowebbefore adoptionc002e08
line 141why, one step back141convert from reST to MySTdenuowebbefore adoption29eb946
lines 142–143why, one step back142```python143import clickchange extension to .mddenuowebbefore adoptionc002e08
line 144why, one step back144convert from reST to MySTdenuowebbefore adoption29eb946
lines 145–154why, one step back145click.echo('Continue? [yn] ', nl=False)146c = click.getchar()147click.echo()148if c == 'y':149 click.echo('We will go on')150elif c == 'n':151 click.echo('Abort!')152else:153 click.echo('Invalid input :(')154```change extension to .mddenuowebbefore adoptionc002e08
line 155why, one step back155convert from reST to MySTdenuowebbefore adoption29eb946
lines 156–158why, one step back156Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape157format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file158exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts thatchange extension to .mddenuowebbefore adoptionc002e08
lines 159–160why, one step back159cannot be properly exited.160convert from reST to MySTdenuowebbefore adoption29eb946
line 161why, one step back161## Waiting for Key Presschange extension to .mddenuowebbefore adoptionc002e08
line 162why, one step back162convert from reST to MySTdenuowebbefore adoption29eb946
lines 163–164why, one step back163```{versionadded} 2.0164```change extension to .mddenuowebbefore adoptionc002e08
line 165why, one step back165convert from reST to MySTdenuowebbefore adoption29eb946
lines 166–167why, one step back166Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows167where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.change extension to .mddenuowebbefore adoptionc002e08
line 168why, one step back168add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 169why, one step back169In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to theconvert from reST to MySTdenuowebbefore adoption29eb946
lines 170–171why, one step back170terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP171(no operation instruction) if the script is not run interactively.change extension to .mddenuowebbefore adoptionc002e08
line 172why, one step back172convert from reST to MySTdenuowebbefore adoption29eb946
line 173why, one step back173Example:change extension to .mddenuowebbefore adoptionc002e08
line 174why, one step back174convert from reST to MySTdenuowebbefore adoption29eb946
lines 175–178why, one step back175```python176import click177click.pause()178```change extension to .mddenuowebbefore adoptionc002e08
line 179why, one step back179convert from reST to MySTdenuowebbefore adoption29eb946
line 180why, one step back180## Launching Editorschange extension to .mddenuowebbefore adoptionc002e08
line 181why, one step back181convert from reST to MySTdenuowebbefore adoption29eb946
lines 182–183why, one step back182```{versionadded} 2.0183```change extension to .mddenuowebbefore adoptionc002e08
line 184why, one step back184add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 185why, one step back185Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-lineconvert from reST to MySTdenuowebbefore adoption29eb946
lines 186–187why, one step back186input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the187editor without saving, the return value will be `None`, otherwise the entered text.change extension to .mddenuowebbefore adoptionc002e08
line 188why, one step back188convert from reST to MySTdenuowebbefore adoption29eb946
line 189why, one step back189Example usage:change extension to .mddenuowebbefore adoptionc002e08
line 190why, one step back190convert from reST to MySTdenuowebbefore adoption29eb946
lines 191–192why, one step back191```python192import clickchange extension to .mddenuowebbefore adoptionc002e08
line 193why, one step back193convert from reST to MySTdenuowebbefore adoption29eb946
lines 194–199why, one step back194def get_commit_message():195 MARKER = '# Everything below is ignored\n'196 message = click.edit('\n\n' + MARKER)197 if message is not None:198 return message.split(MARKER, 1)[0].rstrip('\n')199```change extension to .mddenuowebbefore adoptionc002e08
line 200why, one step back200convert from reST to MySTdenuowebbefore adoption29eb946
lines 201–202why, one step back201Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the202return value is always `None`.change extension to .mddenuowebbefore adoptionc002e08
line 203why, one step back203convert from reST to MySTdenuowebbefore adoption29eb946
line 204why, one step back204Example usage:change extension to .mddenuowebbefore adoptionc002e08
line 205why, one step back205convert from reST to MySTdenuowebbefore adoption29eb946
lines 206–209why, one step back206```python207import click208click.edit(filename='/etc/passwd')209```change extension to .mddenuowebbefore adoptionc002e08
line 210why, one step back210convert from reST to MySTdenuowebbefore adoption29eb946
line 211why, one step back211## Launching Applicationschange extension to .mddenuowebbefore adoptionc002e08
line 212why, one step back212convert from reST to MySTdenuowebbefore adoption29eb946
lines 213–214why, one step back213```{versionadded} 2.0214```change extension to .mddenuowebbefore adoptionc002e08
line 215why, one step back215add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 216why, one step back216Click supports launching applications through {func}`launch`. This can be used to open the default applicationconvert from reST to MySTdenuowebbefore adoption29eb946
lines 217–218why, one step back217associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition218to this, it can also launch the file manager and automatically select the provided file.change extension to .mddenuowebbefore adoptionc002e08
line 219why, one step back219convert from reST to MySTdenuowebbefore adoption29eb946
line 220why, one step back220Example usage:change extension to .mddenuowebbefore adoptionc002e08
line 221why, one step back221convert from reST to MySTdenuowebbefore adoption29eb946
lines 222–225why, one step back222```python223click.launch("https://click.palletsprojects.com/")224click.launch("/my/downloaded/file.txt", locate=True)225```change extension to .mddenuowebbefore adoptionc002e08
line 226why, one step back226convert from reST to MySTdenuowebbefore adoption29eb946
line 227why, one step back227## Printing Filenameschange extension to .mddenuowebbefore adoptionc002e08
line 228why, one step back228convert from reST to MySTdenuowebbefore adoption29eb946
line 229why, one step back229Because filenames might not be Unicode, formatting them can be a bit tricky.change extension to .mddenuowebbefore adoptionc002e08
line 230why, one step back230add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 231why, one step back231The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of theconvert from reST to MySTdenuowebbefore adoption29eb946
lines 232–233why, one step back232filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode233string.change extension to .mddenuowebbefore adoptionc002e08
line 234why, one step back234convert from reST to MySTdenuowebbefore adoption29eb946
line 235why, one step back235Example:change extension to .mddenuowebbefore adoptionc002e08
line 236why, one step back236convert from reST to MySTdenuowebbefore adoption29eb946
lines 237–239why, one step back237```python238click.echo(f"Path: {click.format_filename(b'foo.txt')}")239```change extension to .mddenuowebbefore adoptionc002e08
line 240why, one step back240convert from reST to MySTdenuowebbefore adoption29eb946
line 241why, one step back241## Standard Streamschange extension to .mddenuowebbefore adoptionc002e08
line 242why, one step back242convert from reST to MySTdenuowebbefore adoption29eb946
lines 243–245why, one step back243For command line utilities, it's very important to get access to input and output streams reliably. Python generally244provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between2452.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.change extension to .mddenuowebbefore adoptionc002e08
line 246why, one step back246add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 247why, one step back247Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produceconvert from reST to MySTdenuowebbefore adoption29eb946
line 248why, one step back248consistent results with different Python versions and for a wide variety of terminal configurations.change extension to .mddenuowebbefore adoptionc002e08
line 249why, one step back249convert from reST to MySTdenuowebbefore adoption29eb946
lines 250–251why, one step back250The end result is that these functions will always return a functional stream object (except in very odd cases; see251{doc}`/unicode-support`).change extension to .mddenuowebbefore adoptionc002e08
line 252why, one step back252convert from reST to MySTdenuowebbefore adoption29eb946
line 253why, one step back253Example:change extension to .mddenuowebbefore adoptionc002e08
line 254why, one step back254convert from reST to MySTdenuowebbefore adoption29eb946
lines 255–256why, one step back255```python256import clickchange extension to .mddenuowebbefore adoptionc002e08
line 257why, one step back257convert from reST to MySTdenuowebbefore adoption29eb946
lines 258–260why, one step back258stdin_text = click.get_text_stream('stdin')259stdout_binary = click.get_binary_stream('stdout')260```change extension to .mddenuowebbefore adoptionc002e08
line 261why, one step back261convert from reST to MySTdenuowebbefore adoption29eb946
lines 262–263why, one step back262```{versionadded} 6.0263```change extension to .mddenuowebbefore adoptionc002e08
line 264why, one step back264convert from reST to MySTdenuowebbefore adoption29eb946
lines 265–266why, one step back265Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more266information see {doc}`wincmd`.change extension to .mddenuowebbefore adoptionc002e08
line 267why, one step back267convert from reST to MySTdenuowebbefore adoption29eb946
line 268why, one step back268## Intelligent File Openingchange extension to .mddenuowebbefore adoptionc002e08
line 269why, one step back269convert from reST to MySTdenuowebbefore adoption29eb946
lines 270–271why, one step back270```{versionadded} 3.0271```change extension to .mddenuowebbefore adoptionc002e08
line 272why, one step back272add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 273why, one step back273Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`convert from reST to MySTdenuowebbefore adoption29eb946
line 274why, one step back274function. It can intelligently open stdin/stdout as well as any other file.change extension to .mddenuowebbefore adoptionc002e08
line 275why, one step back275convert from reST to MySTdenuowebbefore adoption29eb946
line 276why, one step back276Example:change extension to .mddenuowebbefore adoptionc002e08
line 277why, one step back277convert from reST to MySTdenuowebbefore adoption29eb946
lines 278–279why, one step back278```python279import clickchange extension to .mddenuowebbefore adoptionc002e08
line 280why, one step back280convert from reST to MySTdenuowebbefore adoption29eb946
lines 281–283why, one step back281stdout = click.open_file('-', 'w')282test_file = click.open_file('test.txt', 'w')283```change extension to .mddenuowebbefore adoptionc002e08
line 284why, one step back284convert from reST to MySTdenuowebbefore adoption29eb946
lines 285–286why, one step back285If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent286the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:change extension to .mddenuowebbefore adoptionc002e08
line 287why, one step back287convert from reST to MySTdenuowebbefore adoption29eb946
lines 288–291why, one step back288```python289with click.open_file(filename, 'w') as f:290 f.write('Hello World!\n')291```change extension to .mddenuowebbefore adoptionc002e08
line 292why, one step back292convert from reST to MySTdenuowebbefore adoption29eb946
line 293why, one step back293## Finding Application Folderschange extension to .mddenuowebbefore adoptionc002e08
line 294why, one step back294convert from reST to MySTdenuowebbefore adoption29eb946
lines 295–296why, one step back295```{versionadded} 2.0296```change extension to .mddenuowebbefore adoptionc002e08
line 297why, one step back297convert from reST to MySTdenuowebbefore adoption29eb946
lines 298–299why, one step back298Very often, you want to open a configuration file that belongs to your application. However, different operating systems299store these configuration files in different locations depending on their standards. Click provides aadd currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 300why, one step back300{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your applicationconvert from reST to MySTdenuowebbefore adoption29eb946
line 301why, one step back301depending on the OS.change extension to .mddenuowebbefore adoptionc002e08
line 302why, one step back302convert from reST to MySTdenuowebbefore adoption29eb946
line 303why, one step back303Example usage:change extension to .mddenuowebbefore adoptionc002e08
line 304why, one step back304convert from reST to MySTdenuowebbefore adoption29eb946
lines 305–308why, one step back305```python306import os307import click308import ConfigParserchange extension to .mddenuowebbefore adoptionc002e08
line 309why, one step back309convert from reST to MySTdenuowebbefore adoption29eb946
lines 310–320why, one step back310APP_NAME = 'My Application'311def read_config():312cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')313parser = ConfigParser.RawConfigParser()314parser.read([cfg])315rv = {}316for section in parser.sections():317 for key, value in parser.items(section):318 rv[f"{section}.{key}"] = value319return rv320```change extension to .mddenuowebbefore adoptionc002e08
line 321why, one step back321convert from reST to MySTdenuowebbefore adoption29eb946
line 322why, one step back322## Showing Progress Barschange extension to .mddenuowebbefore adoptionc002e08
line 323why, one step back323convert from reST to MySTdenuowebbefore adoption29eb946
lines 324–325why, one step back324Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some325progress about how long that will take. Click supports simple progress bar rendering for that through theadd currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 326why, one step back326{func}`progressbar` function.change extension to .mddenuowebbefore adoptionc002e08
line 327why, one step back327move header to top ofJaron Rosenaubefore adoption8231bdf
line 328why, one step back328```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).convert from reST to MySTdenuowebbefore adoption29eb946
line 329why, one step back329```change extension to .mddenuowebbefore adoptionc002e08
line 330why, one step back330convert from reST to MySTdenuowebbefore adoption29eb946
lines 331–332why, one step back331The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the332iterable it might take some time to do processing. So say you have a loop like this:change extension to .mddenuowebbefore adoptionc002e08
line 333why, one step back333convert from reST to MySTdenuowebbefore adoption29eb946
lines 334–337why, one step back334```python335for user in all_the_users_to_process:336 modify_the_user(user)337```change extension to .mddenuowebbefore adoptionc002e08
line 338why, one step back338convert from reST to MySTdenuowebbefore adoption29eb946
line 339why, one step back339To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:change extension to .mddenuowebbefore adoptionc002e08
line 340why, one step back340convert from reST to MySTdenuowebbefore adoption29eb946
lines 341–342why, one step back341```python342import clickchange extension to .mddenuowebbefore adoptionc002e08
line 343why, one step back343convert from reST to MySTdenuowebbefore adoption29eb946
lines 344–347why, one step back344with click.progressbar(all_the_users_to_process) as bar:345 for user in bar:346 modify_the_user(user)347```change extension to .mddenuowebbefore adoptionc002e08
line 348why, one step back348convert from reST to MySTdenuowebbefore adoption29eb946
lines 349–351why, one step back349Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The350calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the351length, you can explicitly provide it:change extension to .mddenuowebbefore adoptionc002e08
line 352why, one step back352convert from reST to MySTdenuowebbefore adoption29eb946
lines 353–358why, one step back353```python354with click.progressbar(all_the_users_to_process,355 length=number_of_users) as bar:356 for user in bar:357 modify_the_user(user)358```change extension to .mddenuowebbefore adoptionc002e08
line 359why, one step back359add currentmodule back in myst form and remove click. additionsdenuowebbefore adoptionbea2a2e
line 360why, one step back360Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will renderconvert from reST to MySTdenuowebbefore adoption29eb946
line 361why, one step back361correctly:change extension to .mddenuowebbefore adoptionc002e08
line 362why, one step back362convert from reST to MySTdenuowebbefore adoption29eb946
lines 363–364why, one step back363```python364import timechange extension to .mddenuowebbefore adoptionc002e08
line 365why, one step back365convert from reST to MySTdenuowebbefore adoption29eb946
lines 366–370why, one step back366with click.progressbar([1, 2, 3]) as bar:367 for x in bar:368 print(f"sleep({x})...")369 time.sleep(x)370```change extension to .mddenuowebbefore adoptionc002e08
line 371why, one step back371convert from reST to MySTdenuowebbefore adoption29eb946
line 372why, one step back372Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:change extension to .mddenuowebbefore adoptionc002e08
line 373why, one step back373convert from reST to MySTdenuowebbefore adoption29eb946
lines 374–378why, one step back374```python375with click.progressbar(all_the_users_to_process,376 label='Modifying user accounts',377 length=number_of_users) as bar:378 for user in bar:change extension to .mddenuowebbefore adoptionc002e08
line 379why, one step back379 modify_the_user(user)convert from reST to MySTdenuowebbefore adoption29eb946
line 380why, one step back380```change extension to .mddenuowebbefore adoptionc002e08
line 381why, one step back381convert from reST to MySTdenuowebbefore adoption29eb946
lines 382–384why, one step back382Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you383need to specify the length (and no iterable), and use the update method on the context return value instead of iterating384directly over it:change extension to .mddenuowebbefore adoptionc002e08
line 385why, one step back385convert from reST to MySTdenuowebbefore adoption29eb946
lines 386–392why, one step back386```python387with click.progressbar(length=total_size,388 label='Unzipping archive') as bar:389 for archive in zip_file:390 archive.extract()391 bar.update(archive.size)392```