def export(self, spans: typing.Sequence[ReadableSpan]) -> SpanExportResult: if not spans: return SpanExportResult.SUCCESS tree = Tree( label= f"Trace {opentelemetry.trace.format_trace_id(spans[0].context.trace_id)}" ) parents = {} for span in spans: child = tree.add(label=Text.from_markup( f"[blue][{_ns_to_time(span.start_time)}][/blue] [bold]{span.name}[/bold], span {opentelemetry.trace.format_span_id(span.context.span_id)}" )) parents[span.context.span_id] = child _child_to_tree(child, span) for span in spans: if span.parent and span.parent.span_id in parents: child = parents[span.parent.span_id].add(label=Text.from_markup( f"[blue][{_ns_to_time(span.start_time)}][/blue] [bold]{span.name}[/bold], span {opentelemetry.trace.format_span_id(span.context.span_id)}" )) else: child = tree.add(label=Text.from_markup( f"[blue][{_ns_to_time(span.start_time)}][/blue] [bold]{span.name}[/bold], span {opentelemetry.trace.format_span_id(span.context.span_id)}" )) parents[span.context.span_id] = child _child_to_tree(child, span) self.console.print(tree) return SpanExportResult.SUCCESS
def render(self, task: "Task") -> RenderableType: """Show compute test results.""" results = task.fields.get("results", None) if not results: return Text.from_markup("") output = " ".join( ["[bold green]✔[/]" if i else "[bold red]𐄂[/]" for i in results]) return Text.from_markup(output)
def test_markup_property(): assert Text("").markup == "" assert Text("foo").markup == "foo" assert Text("foo", style="bold").markup == "[bold]foo[/bold]" assert Text.from_markup( "foo [red]bar[/red]").markup == "foo [red]bar[/red]" assert (Text.from_markup( "foo [red]bar[/red]", style="bold").markup == "[bold]foo [red]bar[/red][/bold]") assert (Text.from_markup("[bold]foo [italic]bar[/bold] baz[/italic]"). markup == "[bold]foo [italic]bar[/bold] baz[/italic]") assert Text("[bold]foo").markup == "\\[bold]foo"
def parse_link(self, text, link, dev=None): if dev == 1: dev = ' [B]' elif dev == 2: dev = ' [A]' else: dev = '' if link: obj = Text.from_markup(f'[link={link}]{text}[/link][bold]{dev}[/bold]') else: obj = Text.from_markup(f'{text}[bold]{dev}[/bold]') obj.no_wrap = True return obj
async def show_status(lama): while True: await asyncio.sleep(0) os.system('clear') await asyncio.sleep(0) print(Text.from_markup(str(lama))) await asyncio.sleep(0)
def render(self, task) -> Text: if self._stage != "fit" or self._trainer.sanity_checking: return "" if self._trainer.training and task.id not in self._tasks: self._tasks[task.id] = "None" if self._renderable_cache: self._tasks[ self._current_task_id] = self._renderable_cache[ self._current_task_id][1] self._current_task_id = task.id if self._trainer.training and task.id != self._current_task_id: return self._tasks[task.id] _text = "" # TODO(@daniellepintz): make this code cleaner progress_bar_callback = getattr(self._trainer, "progress_bar_callback", None) if progress_bar_callback: metrics = self._trainer.progress_bar_callback.get_metrics( self._trainer, self._pl_module) else: metrics = self._trainer.progress_bar_metrics for k, v in metrics.items(): _text += f"{k}: {round(v, 3) if isinstance(v, float) else v} " text = Text.from_markup(_text, style=None, justify="left") return text
def display_cmd_info(cmd: Command) -> None: """显示命令的详细信息""" with section('description') as columns: for note in _get_cmd_notes(cmd): columns.append(dim(note)) with section('path') as columns: columns.append(cmd.path) print(bright_blue(cmd.desc)) for c in cmd.cmd: c = bright_yellow(c) console.print(cmd_highlighter(Text.from_markup(c))) with section('variables') as columns: for v in cmd.vars.list: desc = cmd.vars.list[v].desc columns.append(f"{v}: {desc}" if desc else f"{v}") with section('references') as columns: for ref in cmd.refer: columns.append(ref) with section('link to db') as columns: for link in cmd.links: columns.append(link)
def test_divide_complex(): MAP = ( "[on orange4] [on green]XX[on orange4] \n" " \n" " \n" " \n" " [bright_red on black]Y[on orange4] \n" "[on green]X[on orange4] [on green]X[on orange4] \n" " [on green]X[on orange4] [on green]X\n" "[on orange4] \n" " [on green]XX[on orange4] \n") from rich.console import Console from rich.text import Text text = Text.from_markup(MAP) console = Console(color_system="truecolor", width=30, force_terminal=True, file=StringIO()) console.print(text) result = console.file.getvalue() print(repr(result)) expected = "\x1b[48;5;94m \x1b[0m\x1b[42mXX\x1b[0m\x1b[48;5;94m \x1b[0m\n\x1b[48;5;94m \x1b[0m\n\x1b[48;5;94m \x1b[0m\n\x1b[48;5;94m \x1b[0m\n\x1b[48;5;94m \x1b[0m\x1b[91;40mY\x1b[0m\x1b[91;48;5;94m \x1b[0m\n\x1b[91;42mX\x1b[0m\x1b[91;48;5;94m \x1b[0m\x1b[91;42mX\x1b[0m\x1b[91;48;5;94m \x1b[0m\n\x1b[91;48;5;94m \x1b[0m\x1b[91;42mX\x1b[0m\x1b[91;48;5;94m \x1b[0m\x1b[91;42mX\x1b[0m\n\x1b[91;48;5;94m \x1b[0m\n\x1b[91;48;5;94m \x1b[0m\x1b[91;42mXX\x1b[0m\x1b[91;48;5;94m \x1b[0m\n\n" assert result == expected
def print_stations(stations, amount, location): index = 0 grid = Table(box=box.MINIMAL) grid.add_column() grid.add_column(Text('Station name and address', style="grey58"), justify="left", no_wrap=True) grid.add_column(Text('95E10', style="grey58"), justify="center") grid.add_column(Text(f'40l {Emoji("car")}', style="grey58"), justify="center") grid.add_column(Text(f'40l {Emoji("fuelpump")}', style="grey58"), justify="center") grid.add_column(Text('Recorded', style="grey58")) grid.add_column(Text('Dist (m)/Dur (min)', style="grey58")) for i, row in stations.head(amount).iterrows(): style = get_style_for_row(index) price_style = style if row["95E10 Price"] < 1.45 else 'red1' name = (row["Name"][:45] + '...') if len(row["Name"]) > 48 else row["Name"] time_str = _format_timestamp(row["Timestamp"]) grid.add_row( Text(f'{str(index+1)}. ', style=style), Text.from_markup(get_maps_link(row, location) + f'{name}[/link]', style=style), Text(str(row["95E10 Price"]), style=price_style), Text(str(row["Total price"]), style=price_style), Text(str(row["40l price"]), style=price_style), Text(time_str, style=price_style), Text(f'{row["Distance"]}, {row["Duration"]}', style=price_style)) index += 1 console.print(grid)
def write(self): message = tcp.write_multiple_registers(slave_id=1, starting_address=0, values=self._output_regs) # time.sleep(.5) while True: try: print(self._output_regs) print(message) try: response = tcp.send_message(message, self.client) except ValueError as ve: print(response) break except OSError as e: print('No he poodido leer. Error {e}') while True: try: self.client.connect((self.ip, self.port)) print('Socket conectado') break except OSError as e: print('No he poodido conectar. Error {e}') time.sleep(5) continue os.system('clear') print(Text.from_markup(str(self)))
def get_stackoverflow(query): """ Prints the results of interrogating SO with a search query (str). """ # get link to top question questionlink, search_url = _get_link_so_top_answer(query) if questionlink is None: warn( "Failed to find anything on stack overflow, sorry.", "While parsing the URL with the top SO answer, could not detect any answer. Nothing to report", ) return _parse_so_top_answer(questionlink) out = Text.from_markup(f""" [{white}]Link to top [{lightsalmon}]Stack Overflow[/{lightsalmon}] question for the error: [{ls}]{questionlink}[/{ls}] [{white}]To find more related answers on [{lightsalmon}]Stack Overflow[/{lightsalmon}], visit: [{ls}]{search_url}[/{ls}] """) console.print(out)
def print_movies_to_exclude(movies, total_filesize): # Setup console console = Console() # Setup table table = Table(show_footer=True, row_styles=["none", "dim"], box=box.MINIMAL, pad_edge=False) with Live(table, console=console, screen=False): # Setup table columns and totals table.add_column("Release Date") or "Unknown" table.add_column( "Title", Text.from_markup("[b][i]Total Used Diskspace", justify="right")) table.add_column("Used Diskspace", filters.get_filesize_gb(total_filesize)) table.add_column("Streaming Providers") for _, movie in movies.items(): release_date = movie["release_date"] title = movie["title"] diskspace = filters.get_filesize_gb(movie["filesize"]) providers = ", ".join(movie["providers"]) # Add table rows table.add_row(release_date, title, diskspace, providers)
def make_sponsor_message() -> Panel: """Some example content.""" sponsor_message = Table.grid(padding=1) sponsor_message.add_column(style="green", justify="right") sponsor_message.add_column(no_wrap=True) sponsor_message.add_row( "✔ GitHub 🤓 ", "[u blue link=https://github.com/jiaulislam]https://github.com/jiaulislam", ) intro_message = Text.from_markup( """Consider supporting my work via Github 🤘 🤘 🤘. - Jiaul Islam""" ) message = Table.grid(padding=1) message.add_column() message.add_column(no_wrap=True) message.add_row(intro_message, sponsor_message) message_panel = Panel( Align.center( RenderGroup(intro_message, "\n", Align.center(sponsor_message)), vertical="middle", ), box=box.ROUNDED, padding=(1, 2), title="[b red]Thanks for using my application!", border_style="bright_blue", ) return message_panel
def emit(self, record: LogRecord) -> None: """Invoked by logging.""" path = Path(record.pathname).name log_style = f"logging.level.{record.levelname.lower()}" message = self.format(record) time_format = None if self.formatter is None else self.formatter.datefmt log_time = datetime.fromtimestamp(record.created) level = Text() level.append(record.levelname, log_style) use_markup = (getattr(record, "markup") if hasattr(record, "markup") else self.markup) if use_markup: message_text = Text.from_markup(message) else: message_text = Text(message) if self.highlighter: message_text = self.highlighter(message_text) if self.KEYWORDS: message_text.highlight_words(self.KEYWORDS, "logging.keyword") self.console.print( self._log_render( self.console, [message_text], log_time=log_time, time_format=time_format, level=level, path=path, line_no=record.lineno, link_path=record.pathname if self.enable_link_path else None, ))
def test_split_spans(): test = Text.from_markup("[red]Hello\n[b]World") lines = test.split("\n") assert lines[0].plain == "Hello" assert lines[1].plain == "World" assert lines[0].spans == [Span(0, 5, "red")] assert lines[1].spans == [Span(0, 5, "red"), Span(0, 5, "bold")]
def connect_to_devices(self, testbed): """Connect to all the devices""" print( Panel.fit( Text.from_markup( "Hang on tight - we are about to go on a [bold blue]Magic[/bold blue] [bold yellow]Carpet[/bold yellow] ride!\n\n[purple].-.\n[.-''-.,\n| //`~\)\n(<|[/][blue]0[/][purple]|>[/][blue]0[/][purple])\n;\ _/ \\_ _\,\n__\|'._/_ \ '='-,\n/\ \ || )_///_\>>\n( '._ T |\ | _/),-'\n'. '._.-' /'/ |\n| '._ _.'`-.._/\n,\ / '-' |/\n[_/\-----j\n_.--.__[_.--'_\__\n/ `--' '---._\n/ '---. -'. .' _.-- '.\n\_ '--.___ _;.-o /\n'.__ ___/______.__8----'\nc-'----'[/]\n\n", justify="center"))) testbed.connect()
def _rich_atlas_metadata(atlas_name, metadata): orange = "#f59e42" dimorange = "#b56510" gray = "#A9A9A9" mocassin = "#FFE4B5" cit_name, cit_link = metadata["citation"].split(", ") # Create a rich table tb = Table( box=None, show_lines=False, title=atlas_name.replace("_", " ").capitalize(), title_style=f"bold {orange}", ) # Add entries to table tb.add_column( style=f"bold {mocassin}", justify="right", min_width=8, max_width=40, ) tb.add_column(min_width=20, max_width=48) tb.add_row( "name:", Text.from_markup( metadata["name"] + f' [{gray}](v{metadata["version"]})' ), ) tb.add_row("species:", Text.from_markup(f'[i]{metadata["species"]}')) tb.add_row("citation:", Text.from_markup(f"{cit_name} [{gray}]{cit_link}")) tb.add_row("link:", Text.from_markup(metadata["atlas_link"])) tb.add_row("") tb.add_row( "orientation:", Text.from_markup(f"[bold]{metadata['orientation']}"), ) tb.add_row("symmetric:", Pretty(metadata["symmetric"])) tb.add_row("resolution:", Pretty(metadata["resolution"])) tb.add_row("shape:", Pretty(metadata["shape"])) # Fit into panel and yield panel = Panel.fit(tb, border_style=dimorange) return panel
async def main(): #xknx = XKNX(config='xknx.yaml', daemon_mode=True) lama_1 = Lama('192.168.25.101', 502) #init 192.168.25.101:502 print(Text.from_markup(str(lama))) await lama_1.move_to_pos(6) await asyncio.sleep(5) await lama_1.move_to_pos(1) '''
def test_render(): console = Console(width=15, record=True) test = Text.from_markup( "[u][b]Where[/b] there is a [i]Will[/i], there is a Way.[/u]") console.print(test) output = console.export_text(styles=True) expected = "\x1b[1;4mWhere\x1b[0m\x1b[4m there is \x1b[0m\n\x1b[4ma \x1b[0m\x1b[3;4mWill\x1b[0m\x1b[4m, there \x1b[0m\n\x1b[4mis a Way.\x1b[0m\n" assert output == expected
def parse_link(self, text, link, dev=None, authors=None): if dev == 1: dev = ' [bold][B][/bold]' elif dev == 2: dev = ' [bold][A][/bold]' else: dev = '' if authors and self.core.config['ShowAuthors']: authors.sort() authors = f' [bold black]by {", ".join(authors)}[/bold black]' else: authors = '' if link: obj = Text.from_markup(f'[link={link}]{text}[/link]{dev}{authors}') else: obj = Text.from_markup(f'{text}{dev}{authors}') obj.no_wrap = True return obj
def linkify_cve(text_str: TextType) -> Text: """Apply a link to anything that looks like a CVE.""" def make_link(cve: str) -> Style: return Style(link=f"https://nvd.nist.gov/vuln/detail/{cve}") text = Text.from_markup(text_str) if isinstance(text_str, str) else text_str text.highlight_regex(RE_CVE, style=make_link) return text
def display_cmds(cmdlist: CommandList) -> None: """显示命令列表""" idx = 1 for cmd in cmdlist: if type(cmd) == Command: cmd = Text.from_markup(_display_cmd(idx, cmd) + "\n") console.print(cmd_highlighter(cmd)) idx += 1 elif type(cmd) == SplitLine: print(str(cmd) + "\n")
def render(self, task) -> Text: elapsed = task.finished_time if task.finished else task.elapsed remaining = task.time_remaining elapsed_delta = "-:--:--" if elapsed is None else str( timedelta(seconds=int(elapsed))) remaining_delta = "-:--:--" if remaining is None else str( timedelta(seconds=int(remaining))) return Text.from_markup( f"[progress.elapsed]{elapsed_delta} < [progress.remaining]{remaining_delta}" )
def _get_message( self, latest: str, current: str = None, color: str = "yellow", pkg: Optional[str] = None, ) -> "Text": from rich.text import Text current = current or self.current update_message = Text.from_markup( f"You are using dvc version [bold]{current}[/]; " f"however, version [bold]{latest}[/] is available.") instruction = Text.from_markup(self._get_update_instructions(pkg=pkg)) return Text.assemble("\n", update_message, "\n", instruction, style=color)
def menu_select_cmd_var(cmd: "Command") -> None: for _, var in cmd.vars.items(): list = var.get_recommend() title = Text.from_markup( f'{var.name} [cyan][{var.desc}][/]' if var.desc else var.name) select = menu_with_custom_choice(title, list) conf.workspace_set_custom_input(var.name, select) var.select = select
def emit(self, record: LogRecord) -> None: """Invoked by logging.""" path = pathlib.Path(record.pathname).name level = self.get_level_text(record) message = self.format(record) time_format = None if self.formatter is None else self.formatter.datefmt log_time = datetime.fromtimestamp(record.created) traceback = None if self.rich_tracebacks and record.exc_info and record.exc_info != ( None, None, None): exc_type, exc_value, exc_traceback = record.exc_info assert exc_type is not None assert exc_value is not None traceback = RedTraceback.from_exception( exc_type, exc_value, exc_traceback, width=self.tracebacks_width, extra_lines=self.tracebacks_extra_lines, theme=self.tracebacks_theme, word_wrap=self.tracebacks_word_wrap, show_locals=self.tracebacks_show_locals, locals_max_length=self.locals_max_length, locals_max_string=self.locals_max_string, indent_guides=False, ) message = record.getMessage() use_markup = getattr(record, "markup") if hasattr( record, "markup") else self.markup if use_markup: message_text = Text.from_markup(message) else: message_text = Text(message) if self.highlighter: message_text = self.highlighter(message_text) if self.KEYWORDS: message_text.highlight_words(self.KEYWORDS, "logging.keyword") self.console.print( self._log_render( self.console, [message_text], log_time=log_time, time_format=time_format, level=level, path=path, line_no=record.lineno, link_path=record.pathname if self.enable_link_path else None, logger_name=record.name, )) if traceback: self.console.print(traceback)
def render(self, task: "Task") -> Text: _text = self.text_format.format(task=task) if self.markup: text = Text.from_markup(_text, style=self.style, justify=self.justify) else: text = Text(_text, style=self.style, justify=self.justify) if self.highlighter: self.highlighter.highlight(text) text.truncate(max_width=self.width, overflow=self.overflow, pad=True) return text
def menu(title: Text | str, menu_list: list) -> int: """显示菜单,并返回选择的index""" if isinstance(title, str): title = Text.from_markup(title) if is_windows(): idx = menu_windows(title, menu_list) return idx else: menu = TerminalMenu(menu_list, title=title.plain) return menu.show()
def get_statistics_table(self) -> Table: """Converts the statistics into a pretty table. :return: a table containing all statistics """ stats = [] for key, value in self.runtimeStatistics.items(): stats.append(key) if "-" in value: stats.append(Text.from_markup(f"[red]{value}[/red]")) elif any(char.isdigit() and int(char) > 0 for char in value): stats.append(Text.from_markup(f"[green]{value}[/green]")) else: stats.append(value) if len(stats) % 4 != 0: stats.extend(["", ""]) end_of_first_section = len(stats) for key, value in self.statistics.items(): stats.extend([key, value]) if len(stats) % 4 != 0: stats.extend(["", ""]) table = Table(box=box.SQUARE) table.add_column("Statistic") table.add_column("Value") table.add_column("Statistic") table.add_column("Value") for i in range(int(len(stats) / 4)): start = i * 4 end = (i + 1) * 4 table.add_row(*stats[start:end], end_section=end_of_first_section == end) return table
def test_slice(): text = Text.from_markup("[red]foo [bold]bar[/red] baz[/bold]") assert text[0] == Text("f", spans=[Span(0, 1, "red")]) assert text[4] == Text("b", spans=[Span(0, 1, "red"), Span(0, 1, "bold")]) assert text[:3] == Text("foo", spans=[Span(0, 3, "red")]) assert text[:4] == Text("foo ", spans=[Span(0, 4, "red")]) assert text[:5] == Text("foo b", spans=[Span(0, 5, "red"), Span(4, 5, "bold")]) assert text[4:] == Text("bar baz", spans=[Span(0, 3, "red"), Span(0, 7, "bold")]) with pytest.raises(TypeError): text[::-1]