def _make_rich_color_theme(style_name: Optional[str] = None) -> 'Theme': from rich.style import Style from rich.theme import Theme try: PieStyle(style_name) except ValueError: style = Styles.ANSI else: style = Styles.PIE theme = Theme() for color, color_set in ChainMap( GenericColor.__members__, CUSTOM_STYLES ).items(): if isinstance(color_set, _StyledGenericColor): properties = dict.fromkeys(color_set.styles, True) color_set = color_set.color else: properties = {} theme.styles[color.lower()] = Style( color=color_set.apply_style(style, style_name=style_name), **properties, ) # E.g translate GenericColor.BLUE into blue on key access theme.styles = _GenericColorCaster(theme.styles) return theme
def test_from_file(): theme = Theme({"warning": "red"}) text_file = io.StringIO() text_file.write(theme.config) text_file.seek(0) load_theme = Theme.from_file(text_file) assert theme.styles == load_theme.styles
def test_read(): theme = Theme({"warning": "red"}) with tempfile.TemporaryDirectory("richtheme") as name: filename = os.path.join(name, "theme.cfg") with open(filename, "wt") as write_theme: write_theme.write(theme.config) load_theme = Theme.read(filename) assert theme.styles == load_theme.styles
def test_theme_stack(): theme = Theme({"warning": "red"}) stack = ThemeStack(theme) assert stack.get("warning") == Style.parse("red") new_theme = Theme({"warning": "bold yellow"}) stack.push_theme(new_theme) assert stack.get("warning") == Style.parse("bold yellow") stack.pop_theme() assert stack.get("warning") == Style.parse("red") with pytest.raises(ThemeStackError): stack.pop_theme()
def __init__(self, level: int) -> None: super().__init__(level=level) self.console = Console( theme=Theme({"logging.level.warning": Style(color="yellow")})) self._log_render = LogRender(show_level=True, show_time=False, show_path=False)
def save_category(self) -> None: """ Creates and saves a new category if not exists When the task(s) is going to be saved and is created a new category, it will set the id of this new one and store the task(s) in this created category """ if len(self.category_name) <= 30: if not self.category_exists(): sql = f'INSERT INTO {categories.TABLE_NAME} ({categories.COLUMN_NAME}) VALUES (?)' cursor = self.db.exec_sql(sql, (self.category_name, )) self.category_id = cursor.lastrowid self.db.commit() PrintFormatted.print_category_creation(self.category_name) else: custom_theme = Theme({ 'msg': '#31f55f bold', 'name': '#616161 italic' }) PrintFormatted.custom_print( f'[msg]Category selected:[/msg][name]{self.category_name}[/name]', custom_theme) else: self._ask_category()
def _parse_theme(config_logger): theme = dict( zip( [key.replace("_", ".") for key in config_logger.keys()], list(config_logger.values()), )) theme["log.width"] = None if theme["log.width"] == "-1" else int( theme["log.width"]) theme["log.height"] = (None if theme["log.height"] == "-1" else int( theme["log.height"])) theme["log.timestamps"] = False try: customTheme = Theme({ k: v for k, v in theme.items() if k not in ["log.width", "log.height", "log.timestamps"] }) except (color.ColorParseError, errors.StyleSyntaxError): customTheme = None printf( "[logging.level.error]It seems your colour configuration couldn't be parsed. Loading the default color configuration...[/logging.level.error]" ) return customTheme
def parse_theme(config_logger): theme = dict( zip( [key.replace("_", ".") for key in config_logger.keys()], list(config_logger.values()), ) ) theme["log.width"] = None if theme["log.width"] == "-1" else int(theme["log.width"]) theme["log.height"] = ( None if theme["log.height"] == "-1" else int(theme["log.height"]) ) theme["log.timestamps"] = False try: customTheme = Theme( { k: v for k, v in theme.items() if k not in ["log.width", "log.height", "log.timestamps"] } ) except (color.ColorParseError, errors.StyleSyntaxError): printf(WRONG_COLOR_CONFIG_MSG) customTheme = None return customTheme
def __init__(self, theme: dict = None): try: # pylint:disable=import-outside-toplevel from rich.console import Console as RichConsole from rich.theme import Theme if theme is None: if in_notebook(): theme = { 'repr.number': 'bold #87ff00', 'repr.attrib_name': 'bold #ff5fff', 'repr.str': 'italic #FFFF00', } with_jupyter = in_notebook() console = RichConsole(record=False, log_path=False, force_jupyter=with_jupyter, force_terminal=(not with_jupyter), log_time_format='[%X] ', theme=Theme(theme)) #, width=width) except (ImportError, ModuleNotFoundError): console = Console() self.console = console
def parse_theme(fp): config_parser.read(fp) theme = dict(config_parser["logger"]) # replaces `_` by `.` as rich understands it theme = dict( zip([key.replace("_", ".") for key in theme.keys()], list(theme.values()))) theme["log.width"] = None if theme["log.width"] == "-1" else int( theme["log.width"]) theme["log.height"] = (None if theme["log.height"] == "-1" else int( theme["log.height"])) theme["log.timestamps"] = config_parser["logger"].getboolean( "log.timestamps") try: customTheme = Theme({ k: v for k, v in theme.items() if k not in ["log.width", "log.height", "log.timestamps"] }) except (color.ColorParseError, errors.StyleSyntaxError): customTheme = None printf( "[logging.level.error]It seems your colour configuration couldn't be parsed. Loading the default color configuration...[/logging.level.error]" ) return customTheme, theme
def __init__(self, level: int = logging.NOTSET, console: Console = None) -> None: # Add own styles to the default styles and create a new theme for the console ACMEStyles = { 'repr.dim': Style(color='grey70', dim=True), 'repr.request': Style(color='spring_green2'), 'repr.response': Style(color='magenta2'), 'repr.id': Style(color='light_sky_blue1'), 'repr.url': Style(color='sandy_brown', underline=True), 'repr.start': Style(color='orange1'), 'logging.level.debug': Style(color='grey50'), 'logging.level.warning': Style(color='orange3'), 'logging.level.error': Style(color='red', reverse=True), 'logging.console': Style(color='spring_green2'), } _styles = DEFAULT_STYLES.copy() _styles.update(ACMEStyles) super().__init__(level=level, console=Console(theme=Theme(_styles))) # Set own highlights self.highlighter.highlights = [ # type: ignore # r"(?P<brace>[\{\[\(\)\]\}])", #r"(?P<tag_start>\<)(?P<tag_name>\w*)(?P<tag_contents>.*?)(?P<tag_end>\>)", #r"(?P<attrib_name>\w+?)=(?P<attrib_value>\"?\w+\"?)", #r"(?P<bool_true>True)|(?P<bool_false>False)|(?P<none>None)", r"(?P<none>None)", #r"(?P<id>(?<!\w)\-?[0-9]+\.?[0-9]*\b)", # r"(?P<number>\-?[0-9a-f])", r"(?P<number>\-?0x[0-9a-f]+)", #r"(?P<filename>\/\w*\.\w{3,4})\s", r"(?<!\\)(?P<str>b?\'\'\'.*?(?<!\\)\'\'\'|b?\'.*?(?<!\\)\'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")", #r"(?P<id>[\w\-_.]+[0-9]+\.?[0-9])", # ID r"(?P<url>https?:\/\/[0-9a-zA-Z\$\-\_\~\+\!`\(\)\,\.\?\/\;\:\&\=\%]*)", #r"(?P<uuid>[a-fA-F0-9]{8}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{12})", # r"(?P<dim>^[0-9]+\.?[0-9]*\b - )", # thread ident at front r"(?P<dim>^[^ ]*[ ]*- )", # thread ident at front r"(?P<request>==>.*:)", # Incoming request or response r"(?P<request>[^-]+Request ==>:)", # Outgoing request or response r"(?P<response><== [^:]+[(:]+)", # outgoing response or request r"(?P<response>[^-]+Response <== [^ :]+[ :]+)", # Incoming response or request r"(?P<number>\(RSC: [0-9]+\.?[0-9]\))", # Result code #r"(?P<id> [\w/\-_]*/[\w/\-_]+)", # ID r"(?P<number>\nHeaders: )", r"(?P<number> \- Headers: )", r"(?P<number>\nBody: )", r"(?P<number> \- Body: )", r"(?P<number> \- Operation: )", # r"(?P<request>CSE started$)", # CSE startup message # r"(?P<request>CSE shutdown$)", # CSE shutdown message # r"(?P<start>CSE shutting down$)", # CSE shutdown message # r"(?P<start>Starting CSE$)", # CSE shutdown message #r"(?P<id>(acp|ae|bat|cin|cnt|csest|dvi|grp|la|mem|nod|ol|sub)[0-9]+\.?[0-9])", # ID ]
def __init__(self): custom_theme = Theme({ "info": "dim cyan", "warning": "magenta", "danger": "bold red" }) self.console = Console(theme=custom_theme) self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.connect(ADDR)
def get_console(width=None): return Console( width=width, theme=Theme({ "repr.number": "bold cyan", "repr.string": "bold green", "logging.level.info": "dim yellow", "logging.level.warning": "dim red", "logging.level.exception": "bold red" }), )
def __init__(self, config: Config): self.config = config self.node = None custom_theme = Theme({ "info": "dim cyan", "warning": "magenta", "danger": "bold red" }) if config.force_colors: self.console = Console(theme=custom_theme, force_terminal=config.force_colors) else: self.console = Console(theme=custom_theme)
def get_default_console() -> Console: """ Get the default console Returns ------- console : Console console for printing and logging """ return Console(theme=Theme({ "info": "blue", "success": "green", "warning": "yellow", "error": "bold red" }), record=True, highlight=False)
def displayPassport(passport: Passport, console: Console): theme = Theme({ "eyeclr": convertColor(passport.ecl), "hairclr": convertColor(passport.hcl) }) with console.use_theme(theme): table = Table(title="Advent of Code Passport", box=box.ROUNDED, show_header=False, min_width=33) table.add_column("picture", width=11) table.add_column("data", width=15) faceLines = randomFace().split("\n") table.add_row( faceLines[0], f"byr: {passport.byr if passport.byr is not None else '[red]??????????[/red]'}" ) table.add_row( faceLines[1], f"iyr: {passport.iyr if passport.iyr is not None else '[red]??????????[/red]'}" ) table.add_row( faceLines[2], f"eyr: {passport.eyr if passport.eyr is not None else '[red]??????????[/red]'}" ) table.add_row( faceLines[3], f"hgt: {passport.hgt if passport.hgt is not None else '[red]??????????[/red]'}" ) table.add_row( faceLines[4], f"hcl: {passport.hcl if passport.hcl is not None else '[red]??????????[/red]'}" ) table.add_row( faceLines[5], f"ecl: {passport.ecl if passport.ecl is not None else '[red]??????????[/red]'}" ) table.add_row( faceLines[6], f"pid: {passport.pid if passport.pid is not None else '[red]??????????[/red]'}" ) table.add_row( faceLines[7], f"cid: {passport.cid if passport.cid is not None else '??????????'}" ) console.print(table) if passport.isValid(): console.print(":heavy_check_mark: [green]VALID[/green]") else: console.print(":x: [red]INVALID[/red]")
def console(self): if not hasattr(self, "_console"): self._console = Console( file=(AsciiStdout(buffer=self.stdout.buffer, encoding="ascii") if is_celery else self.stdout), theme=Theme({ "info": "dim cyan", "warning": "magenta", "danger": "bold red" }), style=self._style, force_terminal=True, force_interactive=True, ) return self._console
def rich_ipdb_klass(*args, **kwargs): ripdb = rich_pdb_klass(TerminalPdb, show_layouts=False)(*args, **kwargs) # Set frame and stack related self-attributes ripdb.botframe = currentframe.f_back ripdb.setup(currentframe.f_back, None) # Set the console's file to stdout so that we can capture the output _console = Console( file=kwargs.get("stdout", sys.stdout), theme=Theme({ "info": "dim cyan", "warning": "magenta", "danger": "bold red" }), ) ripdb._console = _console return ripdb
def parse_theme(fp): config_parser.read(fp) theme = dict(config_parser["logger"]) # replaces `_` by `.` as rich understands it for key in theme: temp = theme[key] del theme[key] key = key.replace("_", ".") theme[key] = temp try: customTheme = Theme(theme) except (color.ColorParseError, errors.StyleSyntaxError): customTheme = None printf( "[logging.level.error]It seems your colour configuration couldn't be parsed. Loading the default color configuration...[/logging.level.error]" ) return customTheme
def _get_rich_console(stderr: bool = False) -> Console: return Console( theme=Theme( { "option": STYLE_OPTION, "switch": STYLE_SWITCH, "negative_option": STYLE_NEGATIVE_OPTION, "negative_switch": STYLE_NEGATIVE_SWITCH, "metavar": STYLE_METAVAR, "metavar_sep": STYLE_METAVAR_SEPARATOR, "usage": STYLE_USAGE, }, ), highlighter=highlighter, color_system=COLOR_SYSTEM, force_terminal=FORCE_TERMINAL, width=MAX_WIDTH, stderr=stderr, )
def __init__( self, type_, value, traceback, keep_frames, all_locals, relevant_only, hide_locals, ): self.traceback_console = Console( file=sys.stderr, theme=Theme(rich.default_styles.DEFAULT_STYLES)) self.type_ = type_ self.value = value self.traceback = traceback self.keep_frames = keep_frames self.all_locals = all_locals self.relevant_only = relevant_only self.hide_locals = hide_locals
def test_traceback_console_theme_applies(): """ Ensure that themes supplied via Console init work on Tracebacks. Regression test for https://github.com/Textualize/rich/issues/1786 """ r, g, b = 123, 234, 123 console = Console( force_terminal=True, _environ={"COLORTERM": "truecolor"}, theme=Theme({"traceback.title": f"rgb({r},{g},{b})"}), ) console.begin_capture() try: 1 / 0 except Exception: console.print_exception() result = console.end_capture() assert f"\\x1b[38;2;{r};{g};{b}mTraceback \\x1b[0m" in repr(result)
def displayPassport(passport: Passport, console: Console): theme = Theme({ "eyeclr": convertColor(passport.ecl), "hairclr": convertColor(passport.hcl) }) with console.use_theme(theme): table = Table(title="Advent of Code Passport", box=box.ROUNDED, show_header=False, min_width=33) table.add_column("picture", width=11) table.add_column("data", width=15) faceLines = randomFace().split("\n") table.add_row(faceLines[0], f"byr: {formatPassportData(passport.byr)}") table.add_row(faceLines[1], f"iyr: {formatPassportData(passport.iyr)}") table.add_row(faceLines[2], f"eyr: {formatPassportData(passport.eyr)}") table.add_row(faceLines[3], f"hgt: {formatPassportData(passport.hgt)}") table.add_row(faceLines[4], f"hcl: {formatPassportData(passport.hcl)}") table.add_row(faceLines[5], f"ecl: {formatPassportData(passport.ecl)}") table.add_row(faceLines[6], f"pid: {formatPassportData(passport.pid)}") table.add_row(faceLines[7], f"cid: {formatPassportData(passport.cid)}") console.print(table)
def __call__(self, *args, **kwargs): kwargs.setdefault('_stack_offset', 2) if self._log: return self._log(*args, **kwargs) import sys import os from rich.console import Console from rich.theme import Theme PYCHARM_HOSTED = os.getenv('PYCHARM_HOSTED') theme = { 'debug': 'dim', 'warn': 'yellow', 'warning': 'yellow', 'error': 'red', 'fatal': 'bright_red', 'success': 'green', 'prompt': 'b bright_cyan', 'title': 'b bright_white', } # noinspection PyTypeChecker console = Console( # force_terminal=True, # log_time_format='[%d.%m.%Y][%T]', # safe_box=False, # soft_wrap=True, log_time=False, color_system='auto' if PYCHARM_HOSTED else 'truecolor', tab_size=2, log_path=True, file=sys.stdout if PYCHARM_HOSTED else sys.stderr, theme=Theme({ **theme, **{k.upper(): v for k, v in theme.items()} })) if console.width == 80: console.width = 160 self._log = console.log return self._log(*args, **kwargs)
def parse_theme(parser: configparser.ConfigParser) -> Theme: """Configure the rich style of logger and console output. Parameters ---------- parser : :class:`configparser.ConfigParser` A parser containing any .cfg files in use. Returns ------- :class:`rich.Theme` The rich theme to be used by the manim logger. See Also -------- :func:`make_logger`. """ theme = {key.replace("_", "."): parser[key] for key in parser} theme["log.width"] = None if theme["log.width"] == "-1" else int(theme["log.width"]) theme["log.height"] = ( None if theme["log.height"] == "-1" else int(theme["log.height"]) ) theme["log.timestamps"] = False try: custom_theme = Theme( { k: v for k, v in theme.items() if k not in ["log.width", "log.height", "log.timestamps"] }, ) except (color.ColorParseError, errors.StyleSyntaxError): printf(WRONG_COLOR_CONFIG_MSG) custom_theme = None return custom_theme
def _make_rich_console(self, file: IO[str], force_terminal: bool) -> 'Console': from rich.console import Console from rich.theme import Theme from rich.style import Style style = getattr(self.args, 'style', palette.AUTO_STYLE) theme = {} if style in palette.STYLE_SHADES: shade = palette.STYLE_SHADES[style] theme.update({ color: Style(color=palette.get_color( color, shade, palette=palette.RICH_THEME_PALETTE), bold=True) for color in palette.RICH_THEME_PALETTE }) # Rich infers the rest of the knowledge (e.g encoding) # dynamically by looking at the file/stderr. return Console(file=file, force_terminal=force_terminal, no_color=(self.colors == 0), theme=Theme(theme))
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Console used by all processes. We are forcing colors and terminal output as Breeze is supposed to be only run in CI or real development terminal - in both cases we want to have colors on. """ try: from rich.console import Console from rich.theme import Theme custom_theme = Theme({ "info": "blue", "warning": "magenta", "error": "red" }) console = Console(force_terminal=True, color_system="standard", width=180, theme=custom_theme) except ImportError: # We handle the ImportError so that autocomplete works with just click installed custom_theme = None # type: ignore[assignment] console = None # type: ignore[assignment]
JustifyMethod, detect_legacy_windows, OverflowMethod, ) from spotdl.search import SongObject custom_theme = Theme( { "bar.back": "grey23", "bar.complete": "rgb(165,66,129)", "bar.finished": "rgb(114,156,31)", "bar.pulse": "rgb(165,66,129)", "general": "green", "nonimportant": "rgb(40,100,40)", "progress.data.speed": "red", "progress.description": "none", "progress.download": "green", "progress.filesize": "green", "progress.filesize.total": "green", "progress.percentage": "green", "progress.remaining": "rgb(40,100,40)", } ) class YTDLLogger(object): def debug(self, msg): pass def warning(self, msg):
import logging from logging.handlers import TimedRotatingFileHandler from rich.logging import RichHandler from mpm.core.__init__ import LOGGING_DIR, USER_DATA_DIR from rich.console import Console from rich.theme import Theme from rich.style import Style FORMATTER_FULL = logging.Formatter( "[%(levelname)s](%(asctime)s)LINE: %(lineno)d %(pathname)s - %(name)s %(funcName)s - %(message)s" ) FORMATER = logging.Formatter("%(message)s") console = Console( theme=Theme({"logging.level.success": Style(color="green", bold=True)})) def get_logging(): SUCCESS_LEVEL = 25 logging.addLevelName(SUCCESS_LEVEL, "SUCCESS") def success(self, message, *args, **kws): if self.isEnabledFor(SUCCESS_LEVEL): # Yes, logger takes its '*args' as 'args'. self._log(SUCCESS_LEVEL, message, args, **kws) logging.Logger.success = success return logging logging = get_logging()
from platform import system as system_name from pprint import pprint import subprocess from concurrent.futures import ThreadPoolExecutor, as_completed import yaml from scrapli import Scrapli from scrapli.exceptions import ScrapliException from rich.progress import Progress, BarColumn, TimeRemainingColumn from rich.console import Console from rich.theme import Theme custom_theme = Theme({ "success": "bold blue", "fail": "bold red", "error": "bold yellow", "repr.str": "bold white", #"repr.number": "bold green", # defaults: python -m rich.theme }) console = Console(theme=custom_theme) total_dev = 4 progress = Progress( "[progress.description]{task.description}", BarColumn(), "[progress.percentage]{task.percentage:>3.0f}%", TimeRemainingColumn(), "{task.completed} of {task.total}", console=console, ) t1 = progress.add_task("Пингую...", total=total_dev) t2 = progress.add_task("Успешное подключение...", total=total_dev)