Skip to content
Myr

termui.py

This file

Path

examples/termui/termui.py

169 lines · 4.1 KiB · Python

Last changed by

Not known.

History of this file

Take it

1import math2import random3import time45import click678@click.group()9def cli():10    """This script showcases different terminal UI helpers in Click."""11    pass121314@cli.command()15def colordemo():16    """Demonstrates ANSI color support."""17    for color in "red", "green", "blue":18        click.echo(click.style(f"I am colored {color}", fg=color))19        click.echo(click.style(f"I am background colored {color}", bg=color))202122@cli.command()23def pager():24    """Demonstrates using the pager."""25    lines = []26    for x in range(200):27        lines.append(f"{click.style(str(x), fg='green')}. Hello World!")28    click.echo_via_pager("\n".join(lines))293031@cli.command()32@click.option(33    "--count",34    default=8000,35    type=click.IntRange(1, 100000),36    help="The number of items to process.",37)38def progress(count):39    """Demonstrates the progress bar."""40    items = range(count)4142    def process_slowly(item):43        time.sleep(0.002 * random.random())4445    def filter(items):46        for item in items:47            if random.random() > 0.3:48                yield item4950    with click.progressbar(51        items, label="Processing accounts", fill_char=click.style("#", fg="green")52    ) as bar:53        for item in bar:54            process_slowly(item)5556    def show_item(item):57        if item is not None:58            return f"Item #{item}"5960    with click.progressbar(61        filter(items),62        label="Committing transaction",63        fill_char=click.style("#", fg="yellow"),64        item_show_func=show_item,65    ) as bar:66        for item in bar:67            process_slowly(item)6869    with click.progressbar(70        length=count,71        label="Counting",72        bar_template="%(label)s  %(bar)s | %(info)s",73        fill_char=click.style("█", fg="cyan"),74        empty_char=" ",75    ) as bar:76        for item in bar:77            process_slowly(item)7879    with click.progressbar(80        length=count,81        width=0,82        show_percent=False,83        show_eta=False,84        fill_char=click.style("#", fg="magenta"),85    ) as bar:86        for item in bar:87            process_slowly(item)8889    # 'Non-linear progress bar'90    steps = [math.exp(x * 1.0 / 20) - 1 for x in range(20)]91    count = int(sum(steps))92    with click.progressbar(93        length=count,94        show_percent=False,95        label="Slowing progress bar",96        fill_char=click.style("█", fg="green"),97    ) as bar:98        for item in steps:99            time.sleep(item)100            bar.update(item)101102103@cli.command()104@click.argument("url")105def open(url):106    """Opens a file or URL In the default application."""107    click.launch(url)108109110@cli.command()111@click.argument("url")112def locate(url):113    """Opens a file or URL In the default application."""114    click.launch(url, locate=True)115116117@cli.command()118def edit():119    """Opens an editor with some text in it."""120    MARKER = "# Everything below is ignored\n"121    message = click.edit(f"\n\n{MARKER}")122    if message is not None:123        msg = message.split(MARKER, 1)[0].rstrip("\n")124        if not msg:125            click.echo("Empty message!")126        else:127            click.echo(f"Message:\n{msg}")128    else:129        click.echo("You did not enter anything!")130131132@cli.command()133def clear():134    """Clears the entire screen."""135    click.clear()136137138@cli.command()139def pause():140    """Waits for the user to press a button."""141    click.pause()142143144@cli.command()145def menu():146    """Shows a simple menu."""147    menu = "main"148    while True:149        if menu == "main":150            click.echo("Main menu:")151            click.echo("  d: debug menu")152            click.echo("  q: quit")153            char = click.getchar()154            if char == "d":155                menu = "debug"156            elif char == "q":157                menu = "quit"158            else:159                click.echo("Invalid input")160        elif menu == "debug":161            click.echo("Debug menu")162            click.echo("  b: back")163            char = click.getchar()164            if char == "b":165                menu = "main"166            else:167                click.echo("Invalid input")168        elif menu == "quit":169            return