当前位置: 首页>>代码示例>>Python>>正文


Python lexers.get_lexer_by_name方法代码示例

本文整理汇总了Python中pygments.lexers.get_lexer_by_name方法的典型用法代码示例。如果您正苦于以下问题:Python lexers.get_lexer_by_name方法的具体用法?Python lexers.get_lexer_by_name怎么用?Python lexers.get_lexer_by_name使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pygments.lexers的用法示例。


在下文中一共展示了lexers.get_lexer_by_name方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: androaxml_main

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def androaxml_main(inp, outp=None, resource=None):
    ret_type = androconf.is_android(inp)
    if ret_type == "APK":
        a = apk.APK(inp)
        if resource:
            if resource not in a.files:
                print("The APK does not contain a file called '{}'".format(resource), file=sys.stderr)
                sys.exit(1)

            axml = AXMLPrinter(a.get_file(resource)).get_xml_obj()
        else:
            axml = a.get_android_manifest_xml()
    elif ".xml" in inp:
        axml = AXMLPrinter(read(inp)).get_xml_obj()
    else:
        print("Unknown file type")
        sys.exit(1)

    buff = etree.tostring(axml, pretty_print=True, encoding="utf-8")
    if outp:
        with open(outp, "wb") as fd:
            fd.write(buff)
    else:
        sys.stdout.write(highlight(buff.decode("UTF-8"), get_lexer_by_name("xml"), TerminalFormatter())) 
开发者ID:amimo,项目名称:dcc,代码行数:26,代码来源:main.py

示例2: get_source_method

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
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 
开发者ID:amimo,项目名称:dcc,代码行数:20,代码来源:decompiler.py

示例3: __init__

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def __init__(self, code, language, tokennames='short'):
        """
        Set up a lexical analyzer for `code` in `language`.
        """
        self.code = code
        self.language = language
        self.tokennames = tokennames
        self.lexer = None
        # get lexical analyzer for `language`:
        if language in ('', 'text') or tokennames == 'none':
            return
        if not with_pygments:
            raise LexerError('Cannot analyze code. '
                                    'Pygments package not found.')
        try:
            self.lexer = get_lexer_by_name(self.language)
        except pygments.util.ClassNotFound:
            raise LexerError('Cannot analyze code. '
                'No Pygments lexer found for "%s".' % language)

    # Since version 1.2. (released Jan 01, 2010) Pygments has a
    # TokenMergeFilter. However, this requires Python >= 2.4. When Docutils
    # requires same minimal version,  ``self.merge(tokens)`` in __iter__ can
    # be replaced by ``self.lexer.add_filter('tokenmerge')`` in __init__. 
开发者ID:skarlekar,项目名称:faces,代码行数:26,代码来源:code_analyzer.py

示例4: _pygment_highlight

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def _pygment_highlight(source, output_formatter, language='ipython'):
    """
    Return a syntax-highlighted version of the input source
    
    Parameters
    ----------
    source : str
        Source code to highlight the syntax of.
    output_formatter : Pygments formatter
    language : str
        Language to highlight the syntax of.
    """
    
    if language == 'ipython':
        lexer = IPythonLexer()
    else:
        lexer = get_lexer_by_name(language, stripall=True)

    return pygements_highlight(source, lexer, output_formatter) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:21,代码来源:highlight.py

示例5: color_stack_trace

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
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() 
开发者ID:danijar,项目名称:mindpark,代码行数:19,代码来源:other.py

示例6: _get_lexer

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def _get_lexer(self, lang):
        if lang.lower() == 'sql':
            return get_lexer_by_name('postgresql', **self.options)

        tries = [lang]
        if lang.startswith('pl'):
            tries.append(lang[2:])
        if lang.endswith('u'):
            tries.append(lang[:-1])
        if lang.startswith('pl') and lang.endswith('u'):
            tries.append(lang[2:-1])

        for l in tries:
            try:
                return get_lexer_by_name(l, **self.options)
            except ClassNotFound:
                pass
        else:
            # TODO: better logging
            # print >>sys.stderr, "language not found:", lang
            return None 
开发者ID:joxeankoret,项目名称:pigaios,代码行数:23,代码来源:sql.py

示例7: block_code

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def block_code(self, code, lang=None):
        """Rendering block level code. ``pre > code``.

        :param code: text content of the code block.
        :param lang: language of the given code.
        """
        code = code.rstrip('\n')  # 去掉尾部的换行符
        # 如果没有lang, 就返回代码块
        if not lang:
            code = mistune.escape(code)
            return '<pre><code>%s\n</code></pre>\n' % code

        # 给代码加上高亮  例如: lang='python'的话
        # ```python
        #   print('666')
        # ```
        try:
            lexer = get_lexer_by_name(lang, stripall=True)
        except ClassNotFound:
            # 如果lang是不合法, 没有匹配到, 就设置为python
            lexer = get_lexer_by_name('python', stripall=True)
        formatter = html.HtmlFormatter()  # linenos=True
        return highlight(code, lexer, formatter) 
开发者ID:enjoy-binbin,项目名称:Django-blog,代码行数:25,代码来源:mistune_markdown.py

示例8: block_code

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def block_code(text, lang, inlinestyles=False, linenos=False):
    if not lang:
        text = text.strip()
        return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)

    try:
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter(
            noclasses=inlinestyles, linenos=linenos
        )
        code = highlight(text, lexer, formatter)
        if linenos:
            return '<div class="highlight-wrapper">%s</div>\n' % code
        return code
    except:
        return '<pre class="%s"><code>%s</code></pre>\n' % (
            lang, mistune.escape(text)
        ) 
开发者ID:lepture,项目名称:mistune-contrib,代码行数:20,代码来源:highlight.py

示例9: _handle_kernel_info_reply

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def _handle_kernel_info_reply(self, rep):
        """Handle kernel info replies."""
        content = rep['content']
        language_name = content['language_info']['name']
        pygments_lexer = content['language_info'].get('pygments_lexer', '')

        try:
            # Other kernels with pygments_lexer info will have to be
            # added here by hand.
            if pygments_lexer == 'ipython3':
                lexer = IPython3Lexer()
            elif pygments_lexer == 'ipython2':
                lexer = IPythonLexer()
            else:
                lexer = get_lexer_by_name(language_name)
            self._highlighter._lexer = lexer
        except ClassNotFound:
            pass

        self.kernel_banner = content.get('banner', '')
        if self._starting:
            # finish handling started channels
            self._starting = False
            super(JupyterWidget, self)._started_channels() 
开发者ID:luckystarufo,项目名称:pySINDy,代码行数:26,代码来源:jupyter_widget.py

示例10: highlighted_operations

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def highlighted_operations(self):
        from pygments.lexers import get_lexer_by_name
        from pygments.util import ClassNotFound
        from pygments import highlight
        from pygments.formatters import get_formatter_by_name
        from wordinserter import parse
        import warnings

        try:
            formatter = get_formatter_by_name("html")
            lexer = get_lexer_by_name(self.highlight)
        except ClassNotFound:
            warnings.warn("Lexer {0} or formatter html not found, not highlighting".format(self.highlight))
            return None

        formatter.noclasses = True

        highlighted_code = highlight(self.text, lexer=lexer, formatter=formatter)
        return parse(highlighted_code, parser="html") 
开发者ID:orf,项目名称:wordinserter,代码行数:21,代码来源:operations.py

示例11: highlight_file

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def highlight_file(self, linenos=True, style='default'):
        """ Highlight the input file, and return HTML as a string. """
        try:
            lexer = lexers.get_lexer_for_filename(self.input_file)
        except pygments.util.ClassNotFound:
            # Try guessing the lexer (file type) later.
            lexer = None

        try:
            formatter = formatters.HtmlFormatter(
                linenos=linenos,
                style=style,
                full=True)
        except pygments.util.ClassNotFound:
            logging.error("\nInvalid style name: {}\nExpecting one of:\n \
                {}".format(style, "\n    ".join(sorted(styles.STYLE_MAP))))
            sys.exit(1)

        try:
            with open(self.input_file, "r") as f:
                content = f.read()
                try:
                    lexer = lexer or lexers.guess_lexer(content)
                except pygments.util.ClassNotFound:
                    # No lexer could be guessed.
                    lexer = lexers.get_lexer_by_name("text")
        except EnvironmentError as exread:
            fmt = "\nUnable to read file: {}\n{}"
            logging.error(fmt.format(self.input_file, exread))
            sys.exit(2)

        return pygments.highlight(content, lexer, formatter) 
开发者ID:tushar-rishav,项目名称:code2pdf,代码行数:34,代码来源:code2pdf.py

示例12: androarsc_main

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def androarsc_main(arscobj, outp=None, package=None, typ=None, locale=None):
    package = package or arscobj.get_packages_names()[0]
    ttype = typ or "public"
    locale = locale or '\x00\x00'

    # TODO: be able to dump all locales of a specific type
    # TODO: be able to recreate the structure of files when developing, eg a
    # res folder with all the XML files

    if not hasattr(arscobj, "get_{}_resources".format(ttype)):
        print("No decoder found for type: '{}'! Please open a bug report."
              .format(ttype),
              file=sys.stderr)
        sys.exit(1)

    x = getattr(arscobj, "get_" + ttype + "_resources")(package, locale)

    buff = etree.tostring(etree.fromstring(x),
                          pretty_print=True,
                          encoding="UTF-8")

    if outp:
        with open(outp, "wb") as fd:
            fd.write(buff)
    else:
        sys.stdout.write(highlight(buff.decode("UTF-8"), get_lexer_by_name("xml"), TerminalFormatter())) 
开发者ID:amimo,项目名称:dcc,代码行数:28,代码来源:main.py

示例13: get_all

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
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 
开发者ID:amimo,项目名称:dcc,代码行数:10,代码来源:decompiler.py

示例14: display_source

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def display_source(self, m):
        result = self.get_source_method(m)

        lexer = get_lexer_by_name("java", stripall=True)
        formatter = TerminalFormatter()
        result = highlight(result, lexer, formatter)
        print(result) 
开发者ID:amimo,项目名称:dcc,代码行数:9,代码来源:decompiler.py

示例15: get_lexer

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_by_name [as 别名]
def get_lexer(text, lang):
    """Tries to get lexer for the text whether the lang is provided or not"""
    if lang:
        try:
            return get_lexer_by_name(lang, stripall=False)
        except:
            pass
        return None

    # No language provided, try to guess
    mime = getMagicMimeFromBuffer(text.strip())
    if mime:
        try:
            return get_lexer_for_mimetype(mime, stripall=False)
        except:
            pass

        # The pygments data sometimes miss mime options provided by python magic
        # library
        if mime.startswith('text/'):
            try:
                return get_lexer_for_mimetype(mime.replace('text/',
                                                           'application/'),
                                              stripall=False)
            except:
                pass

    return None


# The start/end tags could be:
# @startuml / @enduml
# @startgantt / @endgantt
# @startsalt / @endsalt
# @startmindmap / @endmindmap
# @startwbs / @endwbs
# @startditaa / @endditaa
# @startjcckit / @endjcckit 
开发者ID:SergeySatskiy,项目名称:codimension,代码行数:40,代码来源:md.py


注:本文中的pygments.lexers.get_lexer_by_name方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。