Exemplo n.º 1
0
def test_indent_lines():
    console = Console(width=100, color_system=None)
    console.begin_capture()
    console.print(Pretty([100, 200], indent_guides=True), width=8)
    expected = """\
[
│   100,
│   200
]
"""
    result = console.end_capture()
    print(repr(result))
    print(result)
    assert result == expected
Exemplo n.º 2
0
def log(log_level: LogLevel, message: str, debug_object: any = None):
    if LogLevel(log_level) == LogLevel.DEBUG:
        console.log(f'[bold green]DEBUG[/]  {message}')
        if debug_object:
            console.log(Panel(Pretty(debug_object), expand=False))
    elif LogLevel(log_level) == LogLevel.INFO:
        console.log(f'[bold blue]INFO[/]  {message}')
    elif LogLevel(log_level) == LogLevel.WARN:
        console.log(f'[bold yellow]WARN[/]  {message}')
    elif LogLevel(log_level) == LogLevel.ERROR:
        console.log(f'[bold red]ERROR[/] {message}')
        console.print_exception()
    elif LogLevel(log_level) == LogLevel.FATAL:
        console.log(f'[bold white on red]FATAL[/] {message}')
        console.print_exception()
Exemplo n.º 3
0
    def list_venvs(self,
                   pattern,
                   venv_pattern,
                   pythons=None,
                   out=sys.stdout,
                   pipe_mode=False):
        table = None
        if not pipe_mode:
            table = Table(
                "No.",
                "Hash",
                "Name",
                "Interpreter",
                "Environment",
                "Packages",
                box=None,
            )

        for n, inst in enumerate(self.venv.instances()):
            if not inst.name or not inst.matches_pattern(pattern):
                continue

            if pythons and inst.py not in pythons:
                continue

            if not inst.match_venv_pattern(venv_pattern):
                continue
            pkgs_str = inst.full_pkg_str
            env_str = env_to_str(inst.env)
            if pipe_mode:
                print(
                    f"[#{n}]  {inst.short_hash}  {inst.name:12} {env_str} {inst.py} Packages({pkgs_str})"
                )
            else:
                table.add_row(
                    f"[cyan]#{n}[/cyan]",
                    f"[bold cyan]{hex(hash(inst))[2:9]}[/bold cyan]",
                    f"[bold]{inst.name}[/bold]",
                    Pretty(inst.py),
                    env_str or "--",
                    f"[italic]{pkgs_str}[/italic]",
                )

        if table:
            rich_print(table)
Exemplo n.º 4
0
def value_type(value: Any, *, split_min: int = DEFAULT_VALUE_TYPE_SPLIT_MIN):
    typ = type(value)
    if hasattr(typ, "__name__"):
        # Just omit the module name for now, it gets to take up too much
        # space...

        # if (
        #     hasattr(typ, "__module__")
        #     and typ.__module__ != "builtins"
        # ):
        #     if len(typ.__module__) + len(typ.__name__) < split_min:
        #         return f"{typ.__module__}.{typ.__name__}"
        #     else:
        #         return f"{typ.__module__}\n.{typ.__name__}"
        # else:
        #     return typ.__name__

        return typ.__name__
    else:
        return Pretty(typ)
    def __rich__(self) -> "Pretty":
        # External
        from rich.pretty import Pretty

        return Pretty({
            "users": len(self.users_timeline),
            "clock": self.clock,
            "iteration": self.iteration,
            "timeline": self.timeline_type.name,
            "topology": self.topology.name,
            "rate": {
                "internal": {
                    "fake": self.internal_fake_transmission_rate,
                    "genuine": self.internal_genuine_transmission_rate,
                },
                "external": {
                    "fake": self.external_fake_transmission_rate,
                    "genuine": self.external_genuine_transmission_rate,
                },
            },
        })
Exemplo n.º 6
0
def refresh_cart() -> bool:
    """
    GUI helper to display carts content.

    *Note:* Before calling this method make sure that `selected_cart != None`.

    :return: `True` if cart data could be fetched, `False` otherwise.
    """
    resp = api_client.get_cart(cart_ids[selected_cart])  # type: ignore
    if resp.status_code != 200:
        # Error processing the request.
        layout["content"].update(Pretty(resp.json()))
        layout["footer"].update(gui.Status(Text("[ERROR] Cannot get cart content", style="danger")))
        return False

    cart_data = resp.json()

    # Update GUI panels
    layout["content"].update(gui.CartDetail(cart_data["products"], cart_data["total"]))

    return True
Exemplo n.º 7
0
def report() -> None:  # pragma: no cover
    """Print a report to the terminal with debugging information"""
    console = Console()
    inspect(console)
    features = get_windows_console_features()
    inspect(features)

    env_names = (
        "TERM",
        "COLORTERM",
        "CLICOLOR",
        "NO_COLOR",
        "TERM_PROGRAM",
        "COLUMNS",
        "LINES",
        "JPY_PARENT_PID",
        "VSCODE_VERBOSE_LOGGING",
    )
    env = {name: os.getenv(name) for name in env_names}
    console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables"))

    console.print(f'platform="{platform.system()}"')
Exemplo n.º 8
0
def add_product(product_index: int) -> None:
    """
    GUI helper to add a product to a cart.

    :param product_index: Product index.
    """
    if selected_cart is None:
        layout["footer"].update(gui.Status(Text("Must create a cart first! ", style="warning")))
        return None

    product = settings.CLIENT_PRODUCT_CODES[product_index - 1]

    resp = api_client.add_product(cart_ids[selected_cart], product)
    if resp.status_code != 200:
        # Error processing the request.
        layout["content"].update(Pretty(resp.json()))
        layout["footer"].update(gui.Status(Text("[ERROR] Cannot add product", style="error")))
        return None

    if refresh_cart():
        # Update GUI panels
        layout["footer"].update(gui.Status(Text("Product added!", style="info")))
Exemplo n.º 9
0
def create_cart() -> None:
    """
    GUI helper to create a new cart.
    """
    global selected_cart

    resp = api_client.create_cart()
    if resp.status_code != 201:
        # Error processing the request.
        layout["content"].update(Pretty(resp.json()))
        layout["footer"].update(gui.Status(Text("[ERROR] Cannot create cart", style="danger")))
        return None

    cart_data = resp.json()

    cart_ids.append(cart_data["id"])
    selected_cart = len(cart_ids) - 1

    # Update GUI panels
    layout["carts"].update(gui.CartList(cart_ids, selected_cart))
    layout["content"].update(gui.CartDetail(cart_data["products"]))
    layout["footer"].update(gui.Status(Text("New cart created!", style="info")))
Exemplo n.º 10
0
def table(mapping: Mapping) -> Table:
    tbl = Table.grid(padding=(0, 1))
    tbl.expand = True
    tbl.add_column(style=Style(color="blue", italic=True))
    tbl.add_column(style=Style(color="#4ec9b0", italic=True))
    tbl.add_column()
    for key in sorted(mapping.keys()):
        value = mapping[key]
        if is_rich(value):
            rich_value_type = None
            rich_value = value
        else:
            rich_value_type = value_type(value)
            if isinstance(value, str):
                rich_value = value
            elif (inspect.isfunction(value) and hasattr(value, "__module__")
                  and hasattr(value, "__name__")):
                rich_value = ReprHighlighter()(
                    f"<function {value.__module__}.{value.__name__}>")
            else:
                rich_value = Pretty(value)
        tbl.add_row(key, rich_value_type, rich_value)
    return tbl
Exemplo n.º 11
0
from rich.console import Console
from rich.panel import Panel
from rich.pretty import Pretty

DATA = {
    "foo": [1, 2, 3, (), {}, (1, 2, 3), {4, 5, 6, (7, 8, 9)}, "Hello, World"],
    "bar": [None, (False, True)] * 2,
}
console = Console()
for w in range(130):
    console.print(Panel(Pretty(DATA), width=w))
Exemplo n.º 12
0
def _what_variable(obj, **kwargs):
    """
    Prints a detailed report of a variable, including
      - name
      - __repr__
      - definition
      - attributes and methods

    Getting the name for builtins is tricky so it finds the
    variable's name by scooping around in the locals stack.
    Then it get's the corresponding locals frame's file
    and in it it looks for the line definition of the variable.
    """
    # Get variable's source
    try:
        # if it's a function or class
        _file = getfile(obj)
        line_no = getsourcelines(obj)[-1]
        name = _name(obj)

    except TypeError:  # doesn't work for builtins
        # Get all locals frames
        locs = [s.frame for s in stack()]
        locs = locs[::-1]  # start from most superficial and ingnore current

        # look for variable in locals stack
        for loc in locs:
            var = [(k, v) for k, v in loc.f_locals.items() if np.all(v == obj)]
            if var:
                name, value = var[0]
                try:
                    _file = loc.f_locals["__file__"]
                except KeyError:
                    while True:
                        loc = loc.f_back
                        if not loc or loc is None:
                            _file = ""

                        if "__file__" in loc.f_locals.keys():
                            _file = loc.f_locals["__file__"]
                            break
                break

        # look for variable definition in the source file
        _got_line = False
        if _file:
            with open(_file, "r") as source:
                for line_no, line in enumerate(source):
                    line = line.replace('"', "'")

                    if name in line and str(value) in line:
                        line_no += 1
                        _got_line = True
                        break  # We got the source line!

            if not _got_line:  # failed to find obj in source code
                _file = ""

    # Create report
    rep = Report(f"Inspecting variable: {name}", accent=salmon)
    rep.width = 150
    rep.add("[dim]Variable content:\n[/]")
    rep.add(Pretty(obj), "rich")
    rep.spacer()

    # add source
    if _file and _file.endswith(".py"):
        rep.add(f"[dim]Defined in:[/] {_file}:[{mocassin}]{line_no}")
        rep.add(
            _file,
            "code file",
            theme=Monokai,
            line_numbers=True,
            line_range=[line_no - 2, line_no + 2],
            highlight_lines=[line_no],
        )
    else:
        rep.add(f"[{orange}]Failed to get source code for variable")
    rep.spacer()

    # add rich inspect
    rep.add(
        Inspect(
            obj,
            help=False,
            methods=True,
            private=True,
            dunder=False,
            sort=True,
            all=False,
        ),
        "rich",
    )

    console.print(rep)
Exemplo n.º 13
0
        try:
            res = qrz.get_bio(bio)
            if args.pretty:
                c.print(
                    Panel.fit(Syntax(res,
                                     "html",
                                     theme="inkpot",
                                     background_color="default"),
                              title=f"Bio: {bio}",
                              border_style=Style(color="green")))
            else:
                print(res)
        except QrzError as e:
            if args.pretty:
                ec.print(
                    Panel.fit(Pretty(e),
                              title=f"Bio: {bio}",
                              border_style=Style(color="red")))
            else:
                print(e)
        print()

if args.dxcc:
    for dxcc in args.dxcc:
        try:
            results = qrz.get_dxcc(dxcc)
            if isinstance(results, list):
                resses = {
                    res.name: tabulate(asdict(res), args.pretty)
                    for res in results
                }
Exemplo n.º 14
0
    def get_operands(self, err: TestAssertionFailure) -> Optional[RenderableType]:
        if err.operator in EQUALITY_COMPARISONS | INEQUALITY_COMPARISONS:
            description = {
                Comparison.Equals: "not equal to",
                Comparison.NotEquals: "equal to",
                Comparison.LessThan: "not less than",
                Comparison.LessThanEqualTo: "not less than or equal to",
                Comparison.GreaterThan: "not greater than",
                Comparison.GreaterThanEqualTo: "not greater than or equal to",
            }[err.operator]

            lhs_msg = Text.assemble(
                ("The ", "default"),
                ("LHS ", "pass.textonly"),
                *self.of_type(err.lhs),
            )
            rhs_msg = Text.assemble(
                (f"was {description} ", "bold default"),
                ("the ", "default"),
                ("RHS ", "fail.textonly"),
                *self.of_type(err.rhs),
            )
        elif err.operator in IN_COMPARISONS:
            lhs_msg = Text.assemble(
                ("The ", "default"),
                ("item ", "pass.textonly"),
                *self.of_type(err.lhs),
            )
            rhs_msg = Text.assemble(
                (
                    "was not " if err.operator is Comparison.In else "was ",
                    "bold default",
                ),
                ("found in the ", "default"),
                ("container ", "fail.textonly"),
                *self.of_type(err.rhs),
            )
        elif err.operator in IS_COMPARISONS:
            lhs_msg = Text.assemble(
                ("The ", "default"),
                ("LHS ", "pass.textonly"),
                *self.of_type(err.lhs),
                (" with ", "default"),
                ("id ", "default"),
                (f"{id(err.lhs)}", "bold default"),
            )
            rhs_msg = Text.assemble(
                (
                    "was not " if err.operator is Comparison.Is else "was ",
                    "bold default",
                ),
                ("the ", "default"),
                ("RHS ", "fail.textonly"),
                *self.of_type(err.rhs),
                (" with ", "default"),
                ("id ", "default"),
                (f"{id(err.rhs)}", "bold default"),
            )
        else:  # pragma: unreachable
            raise Exception(f"Unknown operator: {err.operator!r}")

        lhs = Panel(
            Pretty(err.lhs),
            title=lhs_msg,
            title_align="left",
            border_style="pass.textonly",
            padding=1,
            expand=True,
        )
        rhs = Panel(
            Pretty(err.rhs),
            title=rhs_msg,
            title_align="left",
            border_style="fail.textonly",
            padding=1,
            expand=True,
        )

        return Columns(
            [lhs, rhs],
            expand=True,
            padding=0,
        )
Exemplo n.º 15
0
 def time_pretty_justify_center(self):
     pretty = Pretty(snippets.PYTHON_DICT, justify="center")
     self.console.print(pretty)
Exemplo n.º 16
0
@attr.define
class Model:
    name: str
    triangles: List[Triangle] = attr.Factory(list)


if __name__ == "__main__":
    model = Model(
        name="Alien#1",
        triangles=[
            Triangle(
                Point3D(x=20, y=50),
                Point3D(x=50, y=15, z=-45.34),
                Point3D(3.1426, 83.2323, -16),
            )
        ],
    )

    from rich.console import Console
    from rich.pretty import Pretty
    from rich.table import Column, Table
    from rich.text import Text

    console = Console()

    table = Table("attrs *with* Rich", Column(Text.from_markup("attrs *without* Rich")))

    table.add_row(Pretty(model), repr(model))
    console.print(table)
Exemplo n.º 17
0
 def time_pretty(self):
     pretty = Pretty(snippets.PYTHON_DICT)
     self.console.print(pretty)
Exemplo n.º 18
0
 def time_pretty_indent_guides(self):
     pretty = Pretty(snippets.PYTHON_DICT, indent_guides=True)
     self.console.print(pretty)
Exemplo n.º 19
0
import json
import io
from time import time
from rich.console import Console
from rich.pretty import Pretty

console = Console(file=io.StringIO(), color_system="truecolor", width=100)

with open("cats.json") as fh:
    cats = json.load(fh)

start = time()
pretty = Pretty(cats)
console.print(pretty)
taken = (time() - start) * 1000

print(console.file.getvalue())
print(f"{taken:.1f}")
Exemplo n.º 20
0
def dump(entries, debug=False, eval_lazy=False, trace=False, title_only=False):
    """
    Dump *entries* to stdout

    :param list entries: Entries to be dumped.
    :param bool debug: Print non printable fields as well.
    :param bool eval_lazy: Evaluate lazy fields.
    :param bool trace: Display trace information.
    :param bool title_only: Display only title field
    """
    def sort_key(field):
        # Sort certain fields above the rest
        if field == 'title':
            return (0, )
        if field == 'url':
            return (1, )
        if field == 'original_url':
            return (2, )
        return 3, field

    highlighter = ReprHighlighter()

    for entry in entries:
        entry_table = TerminalTable(
            'field',
            ':',
            'value',
            show_header=False,
            show_edge=False,
            pad_edge=False,
            collapse_padding=True,
            box=None,
            padding=0,
        )
        for field in sorted(entry, key=sort_key):
            if field.startswith('_') and not debug:
                continue
            if title_only and field != 'title':
                continue
            if entry.is_lazy(field) and not eval_lazy:
                renderable = (
                    '[italic]<LazyField - value will be determined when it is accessed>[/italic]'
                )
            else:
                try:
                    value = entry[field]
                except KeyError:
                    renderable = '[italic]<LazyField - lazy lookup failed>[/italic]'
                else:
                    if field.rsplit('_', maxsplit=1)[-1] == 'url':
                        renderable = f'[link={value}][repr.url]{value}[/repr.url][/link]'
                    elif isinstance(value, str):
                        renderable = value.replace('\r', '').replace('\n', '')
                    elif is_expandable(value):
                        renderable = Pretty(value)
                    else:
                        try:
                            renderable = highlighter(str(value))
                        except Exception:
                            renderable = f'[[i]not printable[/i]] ({repr(value)})'
            entry_table.add_row(f'{field}', ': ', renderable)
        console(entry_table)
        if trace:
            console('── Processing trace:', style='italic')
            trace_table = TerminalTable(
                'Plugin',
                'Operation',
                'Message',
                show_edge=False,
                pad_edge=False,
            )
            for item in entry.traces:
                trace_table.add_row(item[0],
                                    '' if item[1] is None else item[1],
                                    item[2])
            console(trace_table)
        if not title_only:
            console('')
def main(
    timeline_spec: str,
    *,
    seed: str,
    fake_rate: str,
    iterations: int,
    genuine_rate: str,
    timeline_type: TimelineType,
    topology_type: TopologyType,
) -> None:
    timeline_spec = tuple(map(int, timeline_spec.split(",")))
    timeline_size = len(timeline_spec) - 1
    if timeline_size < 1:
        raise ValueError("Timeline have at least 2 values")

    fake_rate = tuple(map(float, fake_rate.split(",")))
    genuine_rate = tuple(map(float, genuine_rate.split(",")))
    if len(fake_rate) != 2 or len(genuine_rate) != 2:
        raise ValueError("fake_rate and genuine_rate must have two entries")

    timeline = []
    template = [EventType.Fake for _ in range(timeline_size)]
    for pos, spec in enumerate(timeline_spec):
        timeline += [template[:] for _ in range(spec)]
        template[timeline_size - (pos + 1)] = EventType.Genuine

    simulator = Simulator(
        timeline,
        timeline_type=timeline_type,
        topology_type=topology_type,
        fake_rate_heuristic=lambda _: 1,
        genuine_rate_heuristic=lambda _: 1,
        internal_fake_transmission_rate=fake_rate[0],
        external_fake_transmission_rate=fake_rate[1],
        internal_genuine_transmission_rate=genuine_rate[0],
        external_genuine_transmission_rate=genuine_rate[1],
    )

    if seed:
        simulator.load_seed(seed)

    # === GUI Setup === #
    layout = Layout(name="root")

    layout.split(
        Layout(name="header", ratio=7),
        Layout(name="info", ratio=15),
        Layout(name="stats", ratio=10),
        Layout(name="footer", ratio=1),
    )

    layout["header"].update(Panel(simulator, title="Simulator"))

    infos_table: ReversedTable

    def setup_info_table() -> None:
        nonlocal infos_table
        infos_table = ReversedTable(
            Column("Time", style="dim"),
            "Type",
            "Origin",
            title="Events",
            expand=True,
            show_header=True,
            header_style="bold white",
        )
        layout["info"].update(infos_table)

    setup_info_table()

    stats_table: ReversedTable

    def setup_stats_table(*headers: T.Union[Column, str], ) -> None:
        nonlocal stats_table
        stats_table = ReversedTable(
            *headers,
            title="Timeline Distribution",
            expand=True,
            show_header=True,
        )
        layout["stats"].update(stats_table)

    setup_stats_table()

    if iterations == 0:
        progress: T.Union[str, Progress] = "Press CTRL+C to exit..."
        progress_task: T.Optional[TaskID] = None
    else:
        progress = Progress(expand=True)
        progress_task = progress.add_task("[white]Simulating...",
                                          total=iterations)
    # FIXME: Rich has wrong typing definition
    layout["footer"].update(T.cast(RenderableType, progress))

    with Live(layout,
              refresh_per_second=10,
              screen=True,
              redirect_stdout=False,
              redirect_stderr=False):
        with suppress(KeyboardInterrupt):
            for time, event, stats in simulator:
                if 0 < iterations <= simulator.iteration:
                    break

                infos_table.add_row(str(time), event.type.name,
                                    event.origin.name)

                keys = tuple(sorted(key for key in stats.keys()))
                stats_columns = tuple("".join(key.name[0]
                                              for key in state_keys)
                                      for state_keys in keys)
                if len(stats_columns) != len(stats_table.columns):
                    setup_stats_table(*stats_columns)

                stats_table.add_row(*(Pretty(stats[key]) for key in keys))

                if isinstance(progress,
                              Progress) and progress_task is not None:
                    progress.update(progress_task, advance=1)

            layout["footer"].update("Press enter key to exit...")
            input()

    print("Seed:", simulator.seed)
Exemplo n.º 22
0
 def __rich_console__(self, *args):
     n = len(self._list)
     yield f'[{green}]pyinspect.builtins.List[/{green}] [{mocassin}]containing [{orange}]{n}[/{orange}] item{"s" if n != 1 else ""}{":" if n > 0 else "."}'
     if n > 0:
         yield Pretty(self._list)
Exemplo n.º 23
0
from rich.console import Console
from rich.panel import Panel
from rich.pretty import Pretty

DATA = {
    "foo": [1, 2, 3, (), {}, (1, 2, 3), {4, 5, 6, (7, 8, 9)}, "Hello, World"],
    "bar": [None, (False, True)] * 2,
    "Dune": {
        "names": {
            "Paul Atriedies",
            "Vladimir Harkonnen",
            "Thufir Haway",
            "Duncan Idaho",
        }
    },
}
console = Console()
for w in range(130):
    console.print(Panel(Pretty(DATA, indent_guides=True), width=w))
Exemplo n.º 24
0

if __name__ == "__main__":
    from os.path import dirname, join
    from rich.console import Console
    from rich.pretty import Pretty
    from rich.traceback import Traceback

    console = Console()
    try:
        cfg = ConfigManager(join(dirname(__file__), "examples", "minidaqapp"))
    except Exception as e:
        console.print(Traceback())

    console.print("Boot data :boot:")
    console.print(Pretty(cfg.boot))

    console.print("Init data :boot:")
    console.print(Pretty(cfg.init))

    console.print("Conf data :boot:")
    console.print(Pretty(cfg.conf))

    console.print("Start data :runner:")
    console.print(Pretty(cfg.start))
    console.print("Start order :runner:")
    console.print(Pretty(cfg.start_order))

    console.print("Stop data :busstop:")
    console.print(Pretty(cfg.stop))
    console.print("Stop order :busstop:")
Exemplo n.º 25
0
    def _print_individual_result(
        self,
        result: Result,
        vars: List[str],
        group: bool = False,
    ) -> None:

        title_text = f"{result.name} "

        result_details = []
        if result.changed:
            result_details.append("changed = True")

        if result.severity_level != 20:
            result_details.append(
                f"logging_level = {logging.getLevelName(result.severity_level)}"
            )

        if result.failed:
            result_details.append("failed = True")

        if result_details:
            title_text += "(" + ", ".join(result_details) + ")"

        title = self.highlighter(title_text)
        if group:
            group_title = f"{' ' * self.current_indent}:heavy_check_mark: {title_text}"

        items_table = Table.grid(padding=(0, 1), expand=False)
        items_table.add_column(width=self.current_indent)
        items_table.add_column(justify="right")

        attrs = vars if vars else ["stdout", "result", "stderr", "diff"]

        for attr in attrs:
            x = getattr(result, attr, None)

            if x and attr == "tests":
                for i, test in enumerate(result.tests.tests):
                    status = ":green_circle:" if test.passed else ":red_circle:"
                    items_table.add_row(
                        None,
                        f"{attr} {status} " if i == 0 else f"{status}",
                        Pretty(test, highlighter=self.highlighter),
                    )
            elif x and attr == "exception":
                # TODO - figure out how to add traceback highlighting
                items_table.add_row(None, f"{attr} = ",
                                    Pretty(x, highlighter=self.highlighter))
            elif x:
                items_table.add_row(None, f"{attr} = ",
                                    Pretty(x, highlighter=self.highlighter))

        if items_table.row_count > 0:
            self.console.print(
                Padding(
                    Panel(items_table, title=title, title_align="left"),
                    (0, 0, 0, self.current_indent + 1),
                ))
        else:
            self.console.print(group_title)
Exemplo n.º 26
0
def make_test_card() -> Table:
    """Get a renderable that demonstrates a number of features."""
    table = Table.grid(padding=1, pad_edge=True)
    table.title = "Rich features"
    table.add_column("Feature",
                     no_wrap=True,
                     justify="center",
                     style="bold red")
    table.add_column("Demonstration")

    color_table = Table(
        box=None,
        expand=False,
        show_header=False,
        show_edge=False,
        pad_edge=False,
    )
    color_table.add_row(
        # "[bold yellow]256[/] colors or [bold green]16.7 million[/] colors [blue](if supported by your terminal)[/].",
        ("✓ [bold green]4-bit color[/]\n"
         "✓ [bold blue]8-bit color[/]\n"
         "✓ [bold magenta]Truecolor (16.7 million)[/]\n"
         "✓ [bold yellow]Dumb terminals[/]\n"
         "✓ [bold cyan]Automatic color conversion"),
        ColorBox(),
    )

    table.add_row("Colors", color_table)

    table.add_row(
        "Styles",
        "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].",
    )

    lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus."
    lorem_table = Table.grid(padding=1, collapse_padding=True)
    lorem_table.pad_edge = False
    lorem_table.add_row(
        Text(lorem, justify="left", style="green"),
        Text(lorem, justify="center", style="yellow"),
        Text(lorem, justify="right", style="blue"),
        Text(lorem, justify="full", style="red"),
    )
    table.add_row(
        "Text",
        RenderGroup(
            Text.from_markup(
                """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n"""
            ),
            lorem_table,
        ),
    )

    def comparison(renderable1, renderable2) -> Table:
        table = Table(show_header=False, pad_edge=False, box=None, expand=True)
        table.add_column("1", ratio=1)
        table.add_column("2", ratio=1)
        table.add_row(renderable1, renderable2)
        return table

    table.add_row(
        "Asian languages",
        ":flag_for_china:  该库支持中文,日文和韩文文本!\n:flag_for_japan:  ライブラリは中国語、日本語、韓国語のテキストをサポートしています\n:flag_for_south_korea:  이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다",
    )

    markup_example = (
        "[bold magenta]Rich[/] supports a simple [i]bbcode[/i] like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! "
        ":+1: :apple: :ant: :bear: :baguette_bread: :bus: ")
    table.add_row("Console markup", markup_example)

    example_table = Table(
        show_edge=False,
        show_header=True,
        expand=False,
        row_styles=["none", "dim"],
        box=box.SIMPLE,
    )
    example_table.add_column("[green]Date", style="green", no_wrap=True)
    example_table.add_column("[blue]Title", style="blue")
    example_table.add_column(
        "[cyan]Production Budget",
        style="cyan",
        justify="right",
        no_wrap=True,
    )
    example_table.add_column(
        "[magenta]Box Office",
        style="magenta",
        justify="right",
        no_wrap=True,
    )
    example_table.add_row(
        "Dec 20, 2019",
        "Star Wars: The Rise of Skywalker",
        "$275,000,000",
        "$375,126,118",
    )
    example_table.add_row(
        "May 25, 2018",
        "[b]Solo[/]: A Star Wars Story",
        "$275,000,000",
        "$393,151,347",
    )
    example_table.add_row(
        "Dec 15, 2017",
        "Star Wars Ep. VIII: The Last Jedi",
        "$262,000,000",
        "[bold]$1,332,539,889[/bold]",
    )
    example_table.add_row(
        "May 19, 1999",
        "Star Wars Ep. [b]I[/b]: [i]The phantom Menace",
        "$115,000,000",
        "$1,027,044,677",
    )

    table.add_row("Tables", example_table)

    code = '''\
def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
    """Iterate and generate a tuple with a flag for last value."""
    iter_values = iter(values)
    try:
        previous_value = next(iter_values)
    except StopIteration:
        return
    for value in iter_values:
        yield False, previous_value
        previous_value = value
    yield True, previous_value'''

    pretty_data = {
        "foo": [
            3.1427,
            (
                "Paul Atriedies",
                "Vladimir Harkonnen",
                "Thufir Haway",
            ),
        ],
        "atomic": (False, True, None),
    }
    table.add_row(
        "Syntax\nhighlighting\n&\npretty\nprinting",
        comparison(
            Syntax(code, "python3", line_numbers=True, indent_guides=True),
            Pretty(pretty_data, indent_guides=True),
        ),
    )

    markdown_example = """\
# Markdown

Supports much of the *markdown*, __syntax__!

- Headers
- Basic formatting: **bold**, *italic*, `code`
- Block quotes
- Lists, and more...
    """
    table.add_row(
        "Markdown",
        comparison("[cyan]" + markdown_example, Markdown(markdown_example)))

    table.add_row(
        "And more",
        """Progress bars, columns, styled logging handler, tracebacks, etc...""",
    )
    return table
Exemplo n.º 27
0
 def showkeys(self):
     console.print(f"{len(self._keys)} keys: ", Pretty(self._keys))