def output_file(filepath, title='', subtitle=''): syntax = Syntax.from_path(filepath, line_numbers=True, word_wrap=True, theme='monokai') panel = Panel(syntax, title=title, subtitle=subtitle) console.print(panel)
def _add_code_file(self, obj, language="python", theme=None, **kwargs): """ Add a Syntax entry to the table by parsing a file with the code """ if theme is None: theme = self._syntax_theme self.tb.add_row(Syntax.from_path(obj, theme=theme, **kwargs))
def test_from_file_unknown_lexer(): fh, path = tempfile.mkstemp("example.nosuchtype") try: os.write(fh, b"import this\n") syntax = Syntax.from_path(path) assert syntax.lexer_name == "default" assert syntax.code == "import this\n" finally: os.remove(path)
def test_from_file(): fh, path = tempfile.mkstemp("example.py") try: os.write(fh, b"import this\n") syntax = Syntax.from_path(path) assert syntax.lexer_name == "Python" assert syntax.code == "import this\n" finally: os.remove(path)
def test_from_path_lexer_override_invalid_lexer(): fh, path = tempfile.mkstemp("example.nosuchtype") try: os.write(fh, b"import this\n") syntax = Syntax.from_path(path, lexer="blah") assert syntax.lexer is None assert syntax.code == "import this\n" finally: os.remove(path)
def test_from_path_lexer_override(): fh, path = tempfile.mkstemp("example.nosuchtype") try: os.write(fh, b"import this\n") syntax = Syntax.from_path(path, lexer="rust") assert syntax.lexer.name == "Rust" assert syntax.code == "import this\n" finally: os.remove(path)
def on_mouse_click_callback(example_name): examples_dir = TaichiMain._get_examples_dir() script = list(examples_dir.rglob(f"{example_name}.py"))[0] print("Demo source code:") print() content = Syntax.from_path(script, line_numbers=True) console = rich.console.Console() console.print(content) self._exec_python_file(script)
def test(args): # parse model-index.yml model_index_file = MMCLS_ROOT / 'model-index.yml' model_index = load(str(model_index_file)) model_index.build_models_with_collections() models = OrderedDict({model.name: model for model in model_index.models}) script_name = osp.join('tools', 'test.py') port = args.port commands = [] if args.models: patterns = [re.compile(pattern) for pattern in args.models] filter_models = {} for k, v in models.items(): if any([re.match(pattern, k) for pattern in patterns]): filter_models[k] = v if len(filter_models) == 0: print('No model found, please specify models in:') print('\n'.join(models.keys())) return models = filter_models preview_script = '' for model_info in models.values(): if model_info.results is None: continue script_path = create_test_job_batch(commands, model_info, args, port, script_name) preview_script = script_path or preview_script port += 1 command_str = '\n'.join(commands) preview = Table() preview.add_column(str(preview_script)) preview.add_column('Shell command preview') preview.add_row( Syntax.from_path(preview_script, background_color='default', line_numbers=True, word_wrap=True), Syntax(command_str, 'bash', background_color='default', line_numbers=True, word_wrap=True)) console.print(preview) if args.run: os.system(command_str) else: console.print('Please set "--run" to start the job')
def train(args): models_cfg = load(str(Path(__file__).parent / 'bench_train.yml')) models_cfg.build_models_with_collections() models = {model.name: model for model in models_cfg.models} script_name = osp.join('tools', 'train.py') port = args.port commands = [] if args.models: patterns = [re.compile(pattern) for pattern in args.models] filter_models = {} for k, v in models.items(): if any([re.match(pattern, k) for pattern in patterns]): filter_models[k] = v if len(filter_models) == 0: print('No model found, please specify models in:') print('\n'.join(models.keys())) return models = filter_models for model_info in models.values(): months = model_info.data.get('Months', range(1, 13)) if datetime.now().month in months: script_path = create_train_job_batch(commands, model_info, args, port, script_name) port += 1 command_str = '\n'.join(commands) preview = Table() preview.add_column(str(script_path)) preview.add_column('Shell command preview') preview.add_row( Syntax.from_path(script_path, background_color='default', line_numbers=True, word_wrap=True), Syntax(command_str, 'bash', background_color='default', line_numbers=True, word_wrap=True)) console.print(preview) if args.run: os.system(command_str) else: console.print('Please set "--run" to start the job')
def _get_syntax_for_list(self, with_line_range=False): line_range = None if with_line_range: first = max(1, self.curframe.f_lineno - 5) line_range = first, first + 10 filename = self.curframe.f_code.co_filename highlight_lines = {self.curframe.f_lineno} return Syntax.from_path( filename, line_numbers=True, theme=self._theme or DEFAULT_THEME, line_range=line_range, highlight_lines=highlight_lines, )
async def handle_file_click(self, message: FileClick) -> None: """A message sent by the directory tree when a file is clicked.""" syntax: RenderableType try: # Construct a Syntax object for the path in the message syntax = Syntax.from_path( message.path, line_numbers=True, word_wrap=True, indent_guides=True, theme="monokai", ) except Exception: # Possibly a binary file # For demonstration purposes we will show the traceback syntax = Traceback(theme="monokai", width=None, show_locals=True) self.app.sub_title = os.path.basename(message.path) await self.body.update(syntax)
def render2syntax(file_path, options={}): "Render syntax to the console with Rich" if not is_path_file(file_path): return line_numbers = options.get("line_numbers", False) word_wrap = options.get("word_wrap", False) soft_wrap = options.get("soft_wrap", False) code_theme = options.get("code_theme", "monokai") background_color = options.get("background_color") syntax = Syntax.from_path( file_path, line_numbers=line_numbers, word_wrap=word_wrap, theme=code_theme, background_color=background_color, ) print_output(syntax, soft_wrap=soft_wrap)
def inspect_traceback(tb, keep_frames=2, all_locals=False, relevant_only=False): """ Get the whole traceback stack with locals at each frame and expand the local with additional info that may be useful. :param tb: traceback object :param keep_frames: int. Keep only the last N frames for traceback :all_locals: bool, False. If True all locals (e.g. including imported modules) are shown. Otherwise only variables are shown """ # Get the whole traceback stack stack = _extract_traceback_stack(tb) if len(stack) > keep_frames: if keep_frames > 1: stack = [stack[0]] + list(stack[-keep_frames:]) else: stack = [stack[-1]] # Make a locals panel for each frame panels = [] for f in stack: # get filepath fpath = f.f_code.co_filename # Get error line as text eline = read_single_line(fpath, f.f_lineno - 1) # get error line as Syntax synt = Syntax.from_path( fpath, line_numbers=True, line_range=[f.f_lineno, f.f_lineno], code_width=PANEL_WIDTH, theme=Monokai, ) # make clickable filepath text = Text(fpath + f":{f.f_lineno}", style="bold white underline") text.stylize(f"link file://{fpath}") # Get locals locs = {} for k, v in f.f_locals.items(): _type, info, _ = _get_type_info(v, all_locals=all_locals) if _type is None: continue # Store all info locs[k] = local( k, v, _type, info, eline, ) # make panel title = f"[i #D3D3D3]file: [bold underline]{text}[/bold underline] line {f.f_lineno}" panels.append( render_scope(locs, synt=synt, title=title, relevant_only=relevant_only)) return panels
def print_code_with_syntax(file: str): syntax = Syntax.from_path(file, theme='monokai', line_numbers=True) console = Console() console.print(syntax)