Python pygments.formatters.TerminalFormatter() Examples

The following are 30 code examples of pygments.formatters.TerminalFormatter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygments.formatters , or try the search function .
Example #1
Source File: decompiler.py    From dcc with Apache License 2.0 6 votes vote down vote up
def get_source_method(self, m):
        """
        Return the Java source of a single method

        :param m: `EncodedMethod` Object
        :return:
        """
        class_name = m.get_class_name()
        method_name = m.get_name()

        if class_name not in self.classes:
            return ""

        lexer = get_lexer_by_name("java", stripall=True)
        lexer.add_filter(MethodFilter(method_name=method_name))
        formatter = TerminalFormatter()
        result = highlight(self.classes[class_name], lexer, formatter)
        return result 
Example #2
Source File: other.py    From mindpark with GNU General Public License v3.0 6 votes vote down vote up
def color_stack_trace():

    def excepthook(type_, value, trace):
        text = ''.join(traceback.format_exception(type_, value, trace))
        try:
            from pygments import highlight
            from pygments.lexers import get_lexer_by_name
            from pygments.formatters import TerminalFormatter
            lexer = get_lexer_by_name('pytb', stripall=True)
            formatter = TerminalFormatter()
            sys.stderr.write(highlight(text, lexer, formatter))
        except Exception:
            sys.stderr.write(text)
            sys.stderr.write('Failed to colorize the traceback.')

    sys.excepthook = excepthook
    setup_thread_excepthook() 
Example #3
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_source_method(self, method):
        class_name = method.get_class_name()
        method_name = method.get_name()

        if class_name not in self.classes:
            return ""

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            lexer.add_filter(MethodFilter(method_name=method_name))
            formatter = TerminalFormatter()
            result = highlight(self.classes[class_name], lexer, formatter)
            return result

        return self.classes[class_name] 
Example #4
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_source_method(self, method):
        class_name = method.get_class_name()
        method_name = method.get_name()

        if class_name not in self.classes:
            return ""

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            lexer.add_filter(MethodFilter(method_name=method_name))
            formatter = TerminalFormatter()
            result = highlight(self.classes[class_name], lexer, formatter)
            return result

        return self.classes[class_name] 
Example #5
Source File: colors.py    From pappy-proxy with MIT License 5 votes vote down vote up
def pretty_body(msg):
    from .util import printable_data
    to_ret = printable_data(msg.body, colors=False)
    if 'content-type' in msg.headers:
        try:
            lexer = get_lexer_for_mimetype(msg.headers.get('content-type').split(';')[0])
            to_ret = highlight(to_ret, lexer, TerminalFormatter())
        except:
            pass
    return to_ret 
Example #6
Source File: view.py    From pappy-proxy with MIT License 5 votes vote down vote up
def pretty_print_body(fmt, body):
    try:
        bstr = body.decode()
        if fmt.lower() == 'json':
            d = json.loads(bstr.strip())
            s = json.dumps(d, indent=4, sort_keys=True)
            print(pygments.highlight(s, JsonLexer(), TerminalFormatter()))
        elif fmt.lower() == 'form':
            qs = parse_qs(bstr, keep_blank_values=True)
            for k, vs in qs.items():
                for v in vs:
                    s = Colors.GREEN
                    s += '%s: ' % unquote(k)
                    s += Colors.ENDC
                    if v == '':
                        s += Colors.RED
                        s += 'EMPTY'
                        s += Colors.ENDC
                    else:
                        s += unquote(v)
                    print(s)
        elif fmt.lower() == 'text':
            print(bstr)
        elif fmt.lower() == 'xml':
            import xml.dom.minidom
            xml = xml.dom.minidom.parseString(bstr)
            print(pygments.highlight(xml.toprettyxml(), XmlLexer(), TerminalFormatter()))
        else:
            raise CommandError('"%s" is not a valid format' % fmt)
    except CommandError as e:
        raise e
    except Exception as e:
        raise CommandError('Body could not be parsed as "{}": {}'.format(fmt, e)) 
Example #7
Source File: colors.py    From pappy-proxy with MIT License 5 votes vote down vote up
def pretty_headers(msg):
    to_ret = msg.headers_section()
    to_ret = highlight(to_ret, HttpLexer(), TerminalFormatter())
    return to_ret 
Example #8
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_all(self, class_name):
        if class_name not in self.classes:
            return ""

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            formatter = TerminalFormatter()
            result = highlight(self.classes[class_name], lexer, formatter)
            return result
        return self.classes[class_name] 
Example #9
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_all(self, class_name):
        if class_name not in self.classes:
            return ""

        lexer = get_lexer_by_name("java", stripall=True)
        formatter = TerminalFormatter()
        result = highlight(self.classes[class_name], lexer, formatter)
        return result 
Example #10
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_source_method(self, method):
        class_name = method.get_class_name()
        method_name = method.get_name()

        if class_name not in self.classes:
            return ""

        lexer = get_lexer_by_name("java", stripall=True)
        lexer.add_filter(MethodFilter(method_name=method_name))
        formatter = TerminalFormatter()
        result = highlight(self.classes[class_name], lexer, formatter)
        return result 
Example #11
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_all(self, class_name):
        if class_name not in self.classes:
            return ""

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            formatter = TerminalFormatter()
            result = highlight(self.classes[class_name], lexer, formatter)
            return result
        return self.classes[class_name] 
Example #12
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def display_source(self, m):
        result = self.get_source_method(m)

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            formatter = TerminalFormatter()
            result = highlight(result, lexer, formatter)
        print result 
Example #13
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_source_method(self, method):
        class_name = method.get_class_name()
        method_name = method.get_name()

        if class_name not in self.classes:
            return ""

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            lexer.add_filter(MethodFilter(method_name=method_name))
            formatter = TerminalFormatter()
            result = highlight(self.classes[class_name], lexer, formatter)
            return result

        return self.classes[class_name] 
Example #14
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_source_method(self, method):
        class_name = method.get_class_name()
        method_name = method.get_name()

        if class_name not in self.classes:
            return ""

        lexer = get_lexer_by_name("java", stripall=True)
        lexer.add_filter(MethodFilter(method_name=method_name))
        formatter = TerminalFormatter()
        result = highlight(self.classes[class_name], lexer, formatter)
        return result 
Example #15
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_all(self, class_name):
        if class_name not in self.classes:
            return ""

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            formatter = TerminalFormatter()
            result = highlight(self.classes[class_name], lexer, formatter)
            return result
        return self.classes[class_name] 
Example #16
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_source_method(self, method):
        class_name = method.get_class_name()
        method_name = method.get_name()

        if class_name not in self.classes:
            return ""

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            lexer.add_filter(MethodFilter(method_name=method_name))
            formatter = TerminalFormatter()
            result = highlight(self.classes[class_name], lexer, formatter)
            return result

        return self.classes[class_name] 
Example #17
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_all(self, class_name):
        if class_name not in self.classes:
            return ""

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            formatter = TerminalFormatter()
            result = highlight(self.classes[class_name], lexer, formatter)
            return result
        return self.classes[class_name] 
Example #18
Source File: decompiler.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def display_source(self, m):
        result = self.get_source_method(m)

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            formatter = TerminalFormatter()
            result = highlight(result, lexer, formatter)
        print result 
Example #19
Source File: cheat.py    From collection with MIT License 5 votes vote down vote up
def colorize (self, sheet_content):
		""" Colorizes cheatsheet content if so configured """

		# only colorize if so configured
		if not 'CHEATCOLORS' in os.environ:
			return sheet_content

		try:
			from pygments import highlight
			from pygments.lexers import get_lexer_by_name
			from pygments.formatters import TerminalFormatter

		# if pygments can't load, just return the uncolorized text
		except ImportError:
			return sheet_content

		first_line = sheet_content.splitlines()[0]
		lexer      = get_lexer_by_name('bash')
		if first_line.startswith('```'):
			sheet_content = '\n'.join(sheet_content.split('\n')[1:-2])
			try:
				lexer = get_lexer_by_name(first_line[3:])
			except Exception:
				pass

		return highlight(sheet_content, lexer, TerminalFormatter()) 
Example #20
Source File: outputs.py    From crash with Apache License 2.0 5 votes vote down vote up
def __init__(self, writer, is_tty):
        self.is_tty = is_tty
        self._json_lexer = JsonLexer()
        self._formatter = TerminalFormatter()
        self.writer = writer
        self._output_format = 'tabular'
        self._formats = {
            'tabular': self.tabular,
            'json': self.json,
            'csv': self.csv,
            'raw': self.raw,
            'mixed': self.mixed,
            'dynamic': self.dynamic,
            'json_row': self.json_row
        } 
Example #21
Source File: lncli.py    From lndmanage with MIT License 5 votes vote down vote up
def lncli(self, command):
        """
        Invokes the lncli command line interface for lnd.

        :param command: list of command line arguments
        :return:
            int: error code
        """

        cmd = self.lncli_command + command
        logger.debug('executing lncli %s', ' '.join(cmd))
        proc = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        # check if the output can be decoded from valid json
        try:
            json.loads(proc.stdout)
            # convert json into color coded characters
            colorful_json = highlight(
                proc.stdout,
                lexers.JsonLexer(),
                formatters.TerminalFormatter()
            )
            logger.info(colorful_json)

        # usually errors and help are not json, handle them here
        except ValueError:
            logger.info(proc.stdout.decode('utf-8'))
            logger.info(proc.stderr.decode('utf-8'))

        return proc.returncode 
Example #22
Source File: context_view.py    From angrgdb with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __pstr_codeblock(self, ip) -> str:
        """Get the pretty version of a basic block with Pygemnts"""
        try:
            block = self.state.project.factory.block(ip)
            code = self._disassembler.disass_block(block)
            return highlight(code, NasmLexer(), TerminalFormatter())
        except SimEngineError:
            return None 
Example #23
Source File: context_view.py    From angrgdb with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def cap_disasm(self, ip):
        md = capstone.Cs(self.state.project.arch.cs_arch, self.state.project.arch.cs_mode)
        r = ""
        code = self.state.memory.load(ip, MAX_DISASS_LENGHT*10)
        code = self.state.solver.eval(code, cast_to=bytes)
        cnt = 0
        for i in md.disasm(code, MAX_DISASS_LENGHT*10):
            r += "0x%x:\t%s\t%s\n" % (ip + i.address, i.mnemonic, i.op_str)
            cnt += 1
            if cnt == 18: break
        return highlight(r, NasmLexer(), TerminalFormatter()) 
Example #24
Source File: workflow_template.py    From girlfriend with MIT License 5 votes vote down vote up
def do_show(self, line):
        """Show me the code!
        """
        code = autopep8.fix_code("".join(self._generate_workflow_code()))
        if self.options.no_highlight:
            print code
        else:
            print highlight(code, PythonLexer(), TerminalFormatter()) 
Example #25
Source File: misc.py    From nephos with Apache License 2.0 5 votes vote down vote up
def pretty_print(string):
    """Pretty print a JSON string.

    Args:
        string (str): String we want to pretty print.
    """
    return highlight(string, JsonLexer(), TerminalFormatter()) 
Example #26
Source File: display.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _colorize(text, colorize=True):
    if not colorize or not sys.stdout.isatty():
        return text
    try:
        from pygments import highlight
        from pygments.formatters import TerminalFormatter
        from pygments.lexers import PythonLexer
        return highlight(text, PythonLexer(), TerminalFormatter())
    except ImportError:
        return text 
Example #27
Source File: display.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _colorize(text, colorize=True):
    if not colorize or not sys.stdout.isatty():
        return text
    try:
        from pygments import highlight
        from pygments.formatters import TerminalFormatter
        from pygments.lexers import PythonLexer
        return highlight(text, PythonLexer(), TerminalFormatter())
    except ImportError:
        return text 
Example #28
Source File: common.py    From omnibus with MIT License 5 votes vote down vote up
def pp_json(data):
    if data is None:
        warning('No data returned from module.')
    else:
        print(highlight(unicode(json.dumps(data, indent=4, default=jsondate), 'UTF-8'),
            lexers.JsonLexer(), formatters.TerminalFormatter())) 
Example #29
Source File: utils.py    From grafcli with MIT License 5 votes vote down vote up
def json_pretty(data, colorize=False):
    pretty = json.dumps(data,
                        sort_keys=True,
                        indent=4,
                        separators=(',', ': '))

    if colorize:
        pretty = highlight(pretty, lexers.JsonLexer(), formatters.TerminalFormatter())

    return pretty.strip() 
Example #30
Source File: decompiler.py    From AndroBugs_Framework with GNU General Public License v3.0 5 votes vote down vote up
def display_all(self, _class):
        result = self.get_source_class(_class)

        if PYGMENTS:
            lexer = get_lexer_by_name("java", stripall=True)
            formatter = TerminalFormatter()
            result = highlight(result, lexer, formatter)
        print result