Skip to content
Myr

termui.py

This file

Path

examples/termui/termui.py

145 lines · 3.8 KiB · Python

Last changed by

Merge branch '2.x-maintenance'Armin Ronacherbefore adoption9740a74

History of this file

Take it

1# coding: utf-82import click3import time4import random56try:7    range_type = xrange8except NameError:9    range_type = range101112@click.group()13def cli():14    """This script showcases different terminal UI helpers in Click."""15    pass161718@cli.command()19def colordemo():20    """Demonstrates ANSI color support."""21    for color in 'red', 'green', 'blue':22        click.echo(click.style('I am colored %s' % color, fg=color))23        click.echo(click.style('I am background colored %s' % color, bg=color))242526@cli.command()27def pager():28    """Demonstrates using the pager."""29    lines = []30    for x in range_type(200):31        lines.append('%s. Hello World!' % click.style(str(x), fg='green'))32    click.echo_via_pager('\n'.join(lines))333435@cli.command()36@click.option('--count', default=8000, type=click.IntRange(1, 100000),37              help='The number of items to process.')38def progress(count):39    """Demonstrates the progress bar."""40    items = range_type(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(items, label='Processing accounts',51                           fill_char=click.style('#', fg='green')) as bar:52        for item in bar:53            process_slowly(item)5455    def show_item(item):56        if item is not None:57            return 'Item #%d' % item5859    with click.progressbar(filter(items), label='Committing transaction',60                           fill_char=click.style('#', fg='yellow'),61                           item_show_func=show_item) as bar:62        for item in bar:63            process_slowly(item)6465    with click.progressbar(length=count, label='Counting',66                           bar_template='%(label)s  %(bar)s | %(info)s',67                           fill_char=click.style(u'█', fg='cyan'),68                           empty_char=' ') as bar:69        for item in bar:70            process_slowly(item)7172    with click.progressbar(length=count, width=0, show_percent=False,73                           show_eta=False,74                           fill_char=click.style('#', fg='magenta')) as bar:75        for item in bar:76            process_slowly(item)777879@cli.command()80@click.argument('url')81def open(url):82    """Opens a file or URL In the default application."""83    click.launch(url)848586@cli.command()87@click.argument('url')88def locate(url):89    """Opens a file or URL In the default application."""90    click.launch(url, locate=True)919293@cli.command()94def edit():95    """Opens an editor with some text in it."""96    MARKER = '# Everything below is ignored\n'97    message = click.edit('\n\n' + MARKER)98    if message is not None:99        msg = message.split(MARKER, 1)[0].rstrip('\n')100        if not msg:101            click.echo('Empty message!')102        else:103            click.echo('Message:\n' + msg)104    else:105        click.echo('You did not enter anything!')106107108@cli.command()109def clear():110    """Clears the entire screen."""111    click.clear()112113114@cli.command()115def pause():116    """Waits for the user to press a button."""117    click.pause()118119120@cli.command()121def menu():122    """Shows a simple menu."""123    menu = 'main'124    while 1:125        if menu == 'main':126            click.echo('Main menu:')127            click.echo('  d: debug menu')128            click.echo('  q: quit')129            char = click.getchar()130            if char == 'd':131                menu = 'debug'132            elif char == 'q':133                menu = 'quit'134            else:135                click.echo('Invalid input')136        elif menu == 'debug':137            click.echo('Debug menu')138            click.echo('  b: back')139            char = click.getchar()140            if char == 'b':141                menu = 'main'142            else:143                click.echo('Invalid input')144        elif menu == 'quit':145            return