async def state(ctx, dev: SmartDevice): """Print out device state and versions.""" await dev.update() click.echo(click.style(f"== {dev.alias} - {dev.model} ==", bold=True)) click.echo( click.style( "Device state: {}".format("ON" if dev.is_on else "OFF"), fg="green" if dev.is_on else "red", ) ) if dev.is_strip: for plug in dev.plugs: # type: ignore is_on = plug.is_on alias = plug.alias click.echo( click.style( " * Socket '{}' state: {} on_since: {}".format( alias, ("ON" if is_on else "OFF"), plug.on_since ), fg="green" if is_on else "red", ) ) click.echo(f"Host/IP: {dev.host}") for k, v in dev.state_information.items(): click.echo(f"{k}: {v}") click.echo(click.style("== Generic information ==", bold=True)) click.echo(f"Time: {await dev.get_time()}") click.echo(f"Hardware: {dev.hw_info['hw_ver']}") click.echo(f"Software: {dev.hw_info['sw_ver']}") click.echo(f"MAC (rssi): {dev.mac} ({dev.rssi})") click.echo(f"Location: {dev.location}") await ctx.invoke(emeter)
def progress(count): """Demonstrates the progress bar.""" items = range_type(count) def process_slowly(item): time.sleep(0.002 * random.random()) def filter(items): for item in items: if random.random() > 0.3: yield item with click.progressbar(items, label='Processing accounts', fill_char=click.style('#', fg='green')) as bar: for item in bar: process_slowly(item) def show_item(item): if item is not None: return 'Item #%d' % item with click.progressbar(filter(items), label='Committing transaction', fill_char=click.style('#', fg='yellow'), item_show_func=show_item) as bar: for item in bar: process_slowly(item) with click.progressbar(length=count, label='Counting', bar_template='%(label)s %(bar)s | %(info)s', fill_char=click.style(u'█', fg='cyan'), empty_char=' ') as bar: for item in bar: process_slowly(item) with click.progressbar(length=count, width=0, show_percent=False, show_eta=False, fill_char=click.style('#', fg='magenta')) as bar: for item in bar: process_slowly(item) # 'Non-linear progress bar' steps = [math.exp( x * 1. / 20) - 1 for x in range(20)] count = int(sum(steps)) with click.progressbar(length=count, show_percent=False, label='Slowing progress bar', fill_char=click.style(u'█', fg='green')) as bar: for item in steps: time.sleep(item) bar.update(item)
async def emeter(dev, year, month, erase): """Query emeter for historical consumption.""" click.echo(click.style("== Emeter ==", bold=True)) await dev.update() if not dev.has_emeter: click.echo("Device has no emeter") return if erase: click.echo("Erasing emeter statistics..") click.echo(await dev.erase_emeter_stats()) return if year: click.echo(f"== For year {year.year} ==") emeter_status = await dev.get_emeter_monthly(year.year) elif month: click.echo(f"== For month {month.month} of {month.year} ==") emeter_status = await dev.get_emeter_daily(year=month.year, month=month.month) else: emeter_status = await dev.get_emeter_realtime() click.echo("== Current State ==") if isinstance(emeter_status, list): for plug in emeter_status: index = emeter_status.index(plug) + 1 click.echo(f"Plug {index}: {plug}") else: click.echo(str(emeter_status))
def test_echo_color_flag(monkeypatch, capfd): isatty = True monkeypatch.setattr(click._compat, "isatty", lambda x: isatty) text = "foo" styled_text = click.style(text, fg="red") assert styled_text == "\x1b[31mfoo\x1b[0m" click.echo(styled_text, color=False) out, err = capfd.readouterr() assert out == f"{text}\n" click.echo(styled_text, color=True) out, err = capfd.readouterr() assert out == f"{styled_text}\n" isatty = True click.echo(styled_text) out, err = capfd.readouterr() assert out == f"{styled_text}\n" isatty = False click.echo(styled_text) out, err = capfd.readouterr() assert out == f"{text}\n"
def test_echo_color_flag(monkeypatch, capfd): isatty = True monkeypatch.setattr(click._compat, 'isatty', lambda x: isatty) text = 'foo' styled_text = click.style(text, fg='red') assert styled_text == '\x1b[31mfoo\x1b[0m' click.echo(styled_text, color=False) out, err = capfd.readouterr() assert out == text + '\n' click.echo(styled_text, color=True) out, err = capfd.readouterr() assert out == styled_text + '\n' isatty = True click.echo(styled_text) out, err = capfd.readouterr() assert out == styled_text + '\n' isatty = False click.echo(styled_text) out, err = capfd.readouterr() assert out == text + '\n'
def test_styling(): examples = [ ('x', dict(fg='black'), '\x1b[30mx\x1b[0m'), ('x', dict(fg='red'), '\x1b[31mx\x1b[0m'), ('x', dict(fg='green'), '\x1b[32mx\x1b[0m'), ('x', dict(fg='yellow'), '\x1b[33mx\x1b[0m'), ('x', dict(fg='blue'), '\x1b[34mx\x1b[0m'), ('x', dict(fg='magenta'), '\x1b[35mx\x1b[0m'), ('x', dict(fg='cyan'), '\x1b[36mx\x1b[0m'), ('x', dict(fg='white'), '\x1b[37mx\x1b[0m'), ('x', dict(bg='black'), '\x1b[40mx\x1b[0m'), ('x', dict(bg='red'), '\x1b[41mx\x1b[0m'), ('x', dict(bg='green'), '\x1b[42mx\x1b[0m'), ('x', dict(bg='yellow'), '\x1b[43mx\x1b[0m'), ('x', dict(bg='blue'), '\x1b[44mx\x1b[0m'), ('x', dict(bg='magenta'), '\x1b[45mx\x1b[0m'), ('x', dict(bg='cyan'), '\x1b[46mx\x1b[0m'), ('x', dict(bg='white'), '\x1b[47mx\x1b[0m'), ('foo bar', dict(blink=True), '\x1b[5mfoo bar\x1b[0m'), ('foo bar', dict(underline=True), '\x1b[4mfoo bar\x1b[0m'), ('foo bar', dict(bold=True), '\x1b[1mfoo bar\x1b[0m'), ('foo bar', dict(dim=True), '\x1b[2mfoo bar\x1b[0m'), ] for text, styles, ref in examples: assert click.style(text, **styles) == ref assert click.unstyle(ref) == text
def pager(): """Demonstrates using the pager.""" lines = [] for x in range(200): lines.append("{}. Hello World!".format(click.style(str(x), fg="green"))) click.echo_via_pager("\n".join(lines))
async def emeter(dev: SmartDevice, year, month, erase): """Query emeter for historical consumption.""" click.echo(click.style("== Emeter ==", bold=True)) await dev.update() if not dev.has_emeter: click.echo("Device has no emeter") return if erase: click.echo("Erasing emeter statistics..") click.echo(await dev.erase_emeter_stats()) return if year: click.echo(f"== For year {year.year} ==") emeter_status = await dev.get_emeter_monthly(year.year) elif month: click.echo(f"== For month {month.month} of {month.year} ==") emeter_status = await dev.get_emeter_daily(year=month.year, month=month.month) else: emeter_status = dev.emeter_realtime if isinstance(emeter_status, list): for plug in emeter_status: index = emeter_status.index(plug) + 1 click.echo(f"Plug {index}: {plug}") else: click.echo("Current: %s A" % emeter_status["current"]) click.echo("Voltage: %s V" % emeter_status["voltage"]) click.echo("Power: %s W" % emeter_status["power"]) click.echo("Total consumption: %s kWh" % emeter_status["total"]) click.echo("Today: %s kWh" % dev.emeter_today) click.echo("This month: %s kWh" % dev.emeter_this_month)
def cli(): """This script prints some colors. If colorama is installed this will also work on Windows. It will also automatically remove all ANSI styles if data is piped into a file. Give it a try! """ for color in all_colors: click.echo(click.style('I am colored %s' % color, fg=color)) for color in all_colors: click.echo(click.style('I am colored %s and bold' % color, fg=color, bold=True)) for color in all_colors: click.echo(click.style('I am reverse colored %s' % color, fg=color, reverse=True)) click.echo(click.style('I am blinking', blink=True)) click.echo(click.style('I am underlined', underline=True))
def cli(): """This script prints some colors. It will also automatically remove all ANSI styles if data is piped into a file. Give it a try! """ for color in all_colors: click.echo(click.style(f"I am colored {color}", fg=color)) for color in all_colors: click.echo( click.style(f"I am colored {color} and bold", fg=color, bold=True)) for color in all_colors: click.echo( click.style(f"I am reverse colored {color}", fg=color, reverse=True)) click.echo(click.style("I am blinking", blink=True)) click.echo(click.style("I am underlined", underline=True))
async def test_with_color(): @click.command() def cli(): click.secho('hello world', fg='blue') runner = CliRunner() result = await runner.invoke(cli) assert result.output == 'hello world\n' assert not result.exception result = await runner.invoke(cli, color=True) assert result.output == click.style('hello world', fg='blue') + '\n' assert not result.exception
async def emeter(dev: SmartDevice, year, month, erase): """Query emeter for historical consumption. Daily and monthly data provided in CSV format. """ click.echo(click.style("== Emeter ==", bold=True)) await dev.update() if not dev.has_emeter: click.echo("Device has no emeter") return if erase: click.echo("Erasing emeter statistics..") click.echo(await dev.erase_emeter_stats()) return if year: click.echo(f"== For year {year.year} ==") click.echo("Month, usage (kWh)") usage_data = await dev.get_emeter_monthly(year.year) elif month: click.echo(f"== For month {month.month} of {month.year} ==") click.echo("Day, usage (kWh)") usage_data = await dev.get_emeter_daily(year=month.year, month=month.month) else: # Call with no argument outputs summary data and returns usage_data = {} emeter_status = dev.emeter_realtime click.echo("Current: %s A" % emeter_status["current"]) click.echo("Voltage: %s V" % emeter_status["voltage"]) click.echo("Power: %s W" % emeter_status["power"]) click.echo("Total consumption: %s kWh" % emeter_status["total"]) click.echo("Today: %s kWh" % dev.emeter_today) click.echo("This month: %s kWh" % dev.emeter_this_month) return # output any detailed usage data for index, usage in usage_data.items(): click.echo(f"{index}, {usage}")
async def state(ctx, dev: SmartDevice): """Print out device state and versions.""" await dev.update() click.echo(click.style(f"== {dev.alias} - {dev.model} ==", bold=True)) click.echo(f"\tHost: {dev.host}") click.echo( click.style( "\tDevice state: {}\n".format("ON" if dev.is_on else "OFF"), fg="green" if dev.is_on else "red", ) ) if dev.is_strip: click.echo(click.style("\t== Plugs ==", bold=True)) for plug in dev.children: # type: ignore is_on = plug.is_on alias = plug.alias click.echo( click.style( "\t* Socket '{}' state: {} on_since: {}".format( alias, ("ON" if is_on else "OFF"), plug.on_since ), fg="green" if is_on else "red", ) ) click.echo() click.echo(click.style("\t== Generic information ==", bold=True)) click.echo(f"\tTime: {await dev.get_time()}") click.echo(f"\tHardware: {dev.hw_info['hw_ver']}") click.echo(f"\tSoftware: {dev.hw_info['sw_ver']}") click.echo(f"\tMAC (rssi): {dev.mac} ({dev.rssi})") click.echo(f"\tLocation: {dev.location}") click.echo(click.style("\n\t== Device specific information ==", bold=True)) for k, v in dev.state_information.items(): click.echo(f"\t{k}: {v}") click.echo() if dev.has_emeter: click.echo(click.style("\n\t== Current State ==", bold=True)) emeter_status = dev.emeter_realtime click.echo(f"\t{emeter_status}")
async def sysinfo(dev): """Print out full system information.""" await dev.update() click.echo(click.style("== System info ==", bold=True)) click.echo(pf(dev.sys_info))
async def sysinfo(dev): """Print out full system information.""" click.echo(click.style("== System info ==", bold=True)) click.echo(pf(dev.sys_info)) return dev.sys_info
def colordemo(): """Demonstrates ANSI color support.""" for color in "red", "green", "blue": click.echo(click.style(f"I am colored {color}", fg=color)) click.echo(click.style(f"I am background colored {color}", bg=color))
def progress(count): """Demonstrates the progress bar.""" items = range(count) def process_slowly(item): time.sleep(0.002 * random.random()) def filter(items): for item in items: if random.random() > 0.3: yield item with click.progressbar( items, label="Processing accounts", fill_char=click.style("#", fg="green") ) as bar: for item in bar: process_slowly(item) def show_item(item): if item is not None: return f"Item #{item}" with click.progressbar( filter(items), label="Committing transaction", fill_char=click.style("#", fg="yellow"), item_show_func=show_item, ) as bar: for item in bar: process_slowly(item) with click.progressbar( length=count, label="Counting", bar_template="%(label)s %(bar)s | %(info)s", fill_char=click.style("█", fg="cyan"), empty_char=" ", ) as bar: for item in bar: process_slowly(item) with click.progressbar( length=count, width=0, show_percent=False, show_eta=False, fill_char=click.style("#", fg="magenta"), ) as bar: for item in bar: process_slowly(item) # 'Non-linear progress bar' steps = [math.exp(x * 1.0 / 20) - 1 for x in range(20)] count = int(sum(steps)) with click.progressbar( length=count, show_percent=False, label="Slowing progress bar", fill_char=click.style("█", fg="green"), ) as bar: for item in steps: time.sleep(item) bar.update(item)
def pager(): """Demonstrates using the pager.""" lines = [] for x in range_type(200): lines.append('%s. Hello World!' % click.style(str(x), fg='green')) click.echo_via_pager('\n'.join(lines))
def colordemo(): """Demonstrates ANSI color support.""" for color in 'red', 'green', 'blue': click.echo(click.style('I am colored %s' % color, fg=color)) click.echo(click.style('I am background colored %s' % color, bg=color))
def test_styling(styles, ref): assert click.style("x y", **styles) == ref assert click.unstyle(ref) == "x y"
def write_heading(self, heading): heading = click.style(heading, fg="yellow") return super().write_heading(heading)