def test(foo: float, bar: float) -> None: list_of_things = [1, 2, 3, None, 4, True, False, "Hello World"] dict_of_things = { "version": "1.1", "method": "confirmFruitPurchase", "params": [["apple", "orange", "mangoes", "pomelo"], 1.123], "id": "194521489", } print(render_scope(locals(), title="[i]locals", sort_keys=False))
from mudrich import print from mudrich.padding import Padding test = Padding("Hello", (2, 4), style="on blue", expand=False) print(test)
class Styled: """Apply a style to a renderable. Args: renderable (RenderableType): Any renderable. style (StyleType): A style to apply across the entire renderable. """ def __init__(self, renderable: "RenderableType", style: "StyleType") -> None: self.renderable = renderable self.style = style def __rich_console__(self, console: "Console", options: "ConsoleOptions") -> "RenderResult": style = console.get_style(self.style) rendered_segments = console.render(self.renderable, options) segments = Segment.apply_style(rendered_segments, style) return segments def __rich_measure__(self, console: "Console", options: "ConsoleOptions") -> Measurement: return Measurement.get(console, options, self.renderable) if __name__ == "__main__": # pragma: no cover from mudrich import print from mudrich.panel import Panel panel = Styled(Panel("hello"), "on blue") print(panel)
from mudrich import print print( "If your terminal supports links, the following text should be clickable:") print( "[link=https://www.willmcgugan.com][i]Visit [red]my[/red][/i] [yellow]Blog[/]" )
return value == self.choices[0] if __name__ == "__main__": # pragma: no cover from mudrich import print if Confirm.ask("Run [i]prompt[/i] tests?", default=True): while True: result = IntPrompt.ask( ":rocket: Enter a number between [b]1[/b] and [b]10[/b]", default=5) if result >= 1 and result <= 10: break print( ":pile_of_poo: [prompt.invalid]Number must be between 1 and 10" ) print(f"number={result}") while True: password = Prompt.ask( "Please enter a password [cyan](must be at least 5 characters)", password=True, ) if len(password) >= 5: break print("[prompt.invalid]password too short") print(f"password={password!r}") fruit = Prompt.ask("Enter a fruit", choices=["apple", "orange", "pear"])
""" This example demonstrates how to write a custom highlighter. """ from random import randint from mudrich import print from mudrich.highlighter import Highlighter class RainbowHighlighter(Highlighter): def highlight(self, text): for index in range(len(text)): text.stylize(f"color({randint(16, 255)})", index, index + 1) rainbow = RainbowHighlighter() print(rainbow("I must not fear. Fear is the mind-killer."))
from mudrich.repr import rich_repr @rich_repr class Bird: def __init__(self, name, eats=None, fly=True, extinct=False): self.name = name self.eats = list(eats) if eats else [] self.fly = fly self.extinct = extinct def __rich_repr__(self): yield self.name yield "eats", self.eats yield "fly", self.fly, True yield "extinct", self.extinct, False # __rich_repr__.angular = True from mudrich import print BIRDS = { "gull": Bird("gull", eats=["fish", "chips", "ice cream", "sausage rolls"]), "penguin": Bird("penguin", eats=["fish"], fly=False), "dodo": Bird("dodo", eats=["fruit"], fly=False, extinct=True), } print(BIRDS)
""" Use Bar to renderer a sort-of circle. """ import math from mudrich.align import Align from mudrich.bar import Bar from mudrich.color import Color from mudrich import print SIZE = 40 for row in range(SIZE): y = (row / (SIZE - 1)) * 2 - 1 x = math.sqrt(1 - y * y) color = Color.from_rgb((1 + y) * 127.5, 0, 0) bar = Bar(2, width=SIZE * 2, begin=1 - x, end=1 + x, color=color) print(Align.center(bar))
_GetStdHandle.restype = wintypes.HANDLE def get_windows_console_features() -> WindowsConsoleFeatures: """Get windows console features. Returns: WindowsConsoleFeatures: An instance of WindowsConsoleFeatures. """ handle = _GetStdHandle(STDOUT) console_mode = wintypes.DWORD() result = _GetConsoleMode(handle, console_mode) vt = bool(result and console_mode.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING) truecolor = False if vt: win_version = sys.getwindowsversion() truecolor = win_version.major > 10 or (win_version.major == 10 and win_version.build >= 15063) features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor) return features if __name__ == "__main__": import platform features = get_windows_console_features() from mudrich import print print(f'platform="{platform.system()}"') print(repr(features))
from mudrich import print from mudrich.console import RenderGroup from mudrich.panel import Panel panel_group = RenderGroup( Panel("Hello", style="on blue"), Panel("World", style="on red"), ) print(Panel(panel_group))
for line in lines: yield left yield from line yield from right else: for line in lines: yield from line yield from right if self.bottom: blank_line = blank_line or [_Segment(f'{" " * width}\n', style)] yield from blank_line * self.bottom def __rich_measure__(self, console: "Console", options: "ConsoleOptions") -> "Measurement": max_width = options.max_width extra_width = self.left + self.right if max_width - extra_width < 1: return Measurement(max_width, max_width) measure_min, measure_max = Measurement.get(console, options, self.renderable) measurement = Measurement(measure_min + extra_width, measure_max + extra_width) measurement = measurement.with_maximum(max_width) return measurement if __name__ == "__main__": # pragma: no cover from mudrich import print print(Padding("Hello, World", (2, 4), style="on blue"))
"Hello World!", 100.123, 323.232, 432324.0, {5, 6, 7, (1, 2, 3, 4), 8}, ], "bar": frozenset({1, 2, 3}), "defaultdict": defaultdict( list, {"crumble": ["apple", "rhubarb", "butter", "sugar", "flour"]}), "counter": Counter([ "apple", "orange", "pear", "kumquat", "kumquat", "durian" * 100, ]), "atomic": (False, True, None), "Broken": BrokenRepr(), } data["foo"].append(data) # type: ignore from mudrich import print print(Pretty(data, indent_guides=True, max_string=20))
If your terminal supports hyperlinks you should be able to launch files by clicking the filename (usually with cmd / ctrl). """ import os import sys from mudrich import print from mudrich.columns import Columns from mudrich.text import Text try: root_path = sys.argv[1] except IndexError: print("Usage: python listdir.py DIRECTORY") else: def make_filename_text(filename): path = os.path.abspath(os.path.join(root_path, filename)) text = Text(filename, style="bold blue" if os.path.isdir(path) else "default") text.stylize(f"link file://{path}") text.highlight_regex(r"\..*?$", "bold") return text filenames = [ filename for filename in os.listdir(root_path) if not filename.startswith(".") ] filenames.sort(key=lambda filename: filename.lower())
from mudrich import print from mudrich.console import render_group from mudrich.panel import Panel @render_group() def get_panels(): yield Panel("Hello", style="on blue") yield Panel("World", style="on red") print(Panel(get_panels()))
indent_guides=indent_guides, max_length=max_length, max_string=max_string, ), ) return Panel.fit( items_table, title=title, border_style="scope.border", padding=(0, 1), ) if __name__ == "__main__": # pragma: no cover from mudrich import print print() def test(foo: float, bar: float) -> None: list_of_things = [1, 2, 3, None, 4, True, False, "Hello World"] dict_of_things = { "version": "1.1", "method": "confirmFruitPurchase", "params": [["apple", "orange", "mangoes", "pomelo"], 1.123], "id": "194521489", } print(render_scope(locals(), title="[i]locals", sort_keys=False)) test(20.3423, 3.1427) print()
continue if path.is_dir(): style = "dim" if path.name.startswith("__") else "" branch = tree.add( f"[bold magenta]:open_file_folder: [link file://{path}]{escape(path.name)}", style=style, guide_style=style, ) walk_directory(path, branch) else: text_filename = Text(path.name, "green") text_filename.highlight_regex(r"\..*$", "bold red") text_filename.stylize(f"link file://{path}") file_size = path.stat().st_size text_filename.append(f" ({decimal(file_size)})", "blue") icon = "🐍 " if path.suffix == ".py" else "📄 " tree.add(Text(icon) + text_filename) try: directory = os.path.abspath(sys.argv[1]) except IndexError: print("[b]Usage:[/] python tree.py <DIRECTORY>") else: tree = Tree( f":open_file_folder: [link file://{directory}]{directory}", guide_style="bold bright_blue", ) walk_directory(pathlib.Path(directory), tree) print(tree)
text_length = len(text) while style_stack: start, tag = style_stack.pop() style = str(tag) if style: append_span(_Span(start, text_length, style)) text.spans = sorted(spans) return text if __name__ == "__main__": # pragma: no cover from mudrich.console import Console from mudrich.text import Text console = Console(highlight=False) console.print("Hello [1], [1,2,3] ['hello']") console.print("foo") console.print( "Hello [link=https://www.willmcgugan.com]W[b red]o[/]rld[/]!") from mudrich import print print(escape("[red]")) print(escape(r"\[red]")) print(escape(r"\\[red]")) print(escape(r"\\\[red]"))