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


Python lexers.get_lexer_for_filename方法代码示例

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


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

示例1: view_source

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def view_source(context, web_view, filename):
    from base64 import b64encode
    from os.path import join
    from pygments import highlight
    from pygments.formatters import HtmlFormatter
    from pygments.lexers import get_lexer_for_filename

    from java.io import BufferedReader, InputStreamReader

    stream = context.getAssets().open(join(ASSET_SOURCE_DIR, filename))
    reader = BufferedReader(InputStreamReader(stream))
    text = "\n".join(iter(reader.readLine, None))

    formatter = HtmlFormatter()
    body = highlight(text, get_lexer_for_filename(filename), formatter)
    html = ("<html><head><style>{}\n{}</style></head><body>{}</body></html>"
            .format(formatter.get_style_defs(), EXTRA_CSS, body)).encode()
    web_view.loadData(b64encode(html).decode(), "text/html", "base64") 
开发者ID:chaquo,项目名称:chaquopy,代码行数:20,代码来源:ui_demo.py

示例2: set_lexer_from_filename

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def set_lexer_from_filename(self, filename):
        """
        Change the lexer based on the filename (actually only the extension is
        needed)

        :param filename: Filename or extension
        """
        self._lexer = None
        if filename.endswith("~"):
            filename = filename[0:len(filename) - 1]
        try:
            self._lexer = get_lexer_for_filename(filename)
        except (ClassNotFound, ImportError):
            print('class not found for url', filename)
            try:
                m = mimetypes.guess_type(filename)
                print(m)
                self._lexer = get_lexer_for_mimetype(m[0])
            except (ClassNotFound, IndexError, ImportError):
                self._lexer = get_lexer_for_mimetype('text/plain')
        if self._lexer is None:
            _logger().warning('failed to get lexer from filename: %s, using '
                              'plain text instead...', filename)
            self._lexer = TextLexer() 
开发者ID:TuringApp,项目名称:Turing,代码行数:26,代码来源:pygments_sh.py

示例3: from_filename

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def from_filename(
        cls, filename: str, sync_from_start: FilterOrBool = True
    ) -> "Lexer":
        """
        Create a `Lexer` from a filename.
        """
        # Inline imports: the Pygments dependency is optional!
        from pygments.util import ClassNotFound
        from pygments.lexers import get_lexer_for_filename

        try:
            pygments_lexer = get_lexer_for_filename(filename)
        except ClassNotFound:
            return SimpleLexer()
        else:
            return cls(pygments_lexer.__class__, sync_from_start=sync_from_start) 
开发者ID:prompt-toolkit,项目名称:python-prompt-toolkit,代码行数:18,代码来源:pygments.py

示例4: highlight_file

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [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

示例5: set_lexer

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def set_lexer(self):
        """
        Try to detect the lexer by filename if it fails
        then try to guess the lex by shebang statement.
        
        The shebang statement should be placed in the first
        20 lines of the file.
        """

        try:
            self.lexer = get_lexer_for_filename(self.area.filename, '')
        except Exception as e:
            self.lexer = guess_lexer(self.area.get('1.0', '20.0')) 
开发者ID:vyapp,项目名称:vy,代码行数:15,代码来源:spider.py

示例6: get_lexer_for_file

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def get_lexer_for_file(filename):
    ext = os.path.splitext(filename)[1]
    try:
        lexer = lexers.get_lexer_for_filename(filename)
    except lexers.ClassNotFound:
        if ext == '.kv':
            lexer = KivyLexer()
        else:
            lexer = lexers.TextLexer()
    # print('found {} for {}'.format(lexer, filename))
    return lexer 
开发者ID:mahart-studio,项目名称:kivystudio,代码行数:13,代码来源:codeplace.py

示例7: view_file

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def view_file(filename):
    """ Views file with syntax highlighting (if applicable)

    Args:
        filename (str): Full path to filename to render view response for.
    """
    folder = filename.split(_AEON_TOPDIR).pop().strip('/')
    filename = os.path.join(_AEON_TOPDIR, filename)
    try:
        with open(filename, 'r') as f:
            data = f.read()

            # lexer = guess_lexer_for_filename(filename, data)
            formatter = HtmlFormatter(linenos=True)
        try:
            lexer = get_lexer_for_filename(filename)
            code = highlight(data, lexer, formatter)
        except ClassNotFound:
            lexer = TextLexer()
            code = highlight(data, lexer, formatter)
        stat = os.stat(filename)
        return render_template('view.html', content=code, folder=folder, stat=stat, filename=filename)

    except (OSError, IOError) as e:
        code = e[0]
        reason = e[1]
        flash('Error: Could not view file {filename}: {reason} ({code})'.format(filename=filename, reason=reason,
                                                                                code=code), 'danger')
        return render_template('view.html') 
开发者ID:Apstra,项目名称:aeon-ztps,代码行数:31,代码来源:views.py

示例8: __init__

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def __init__(self, raw, request, **kw):
        self.raw = raw
        self.req = request
        if "format_args" in kw:
            # called from a {{{ }}} block
            try:
                self.lexer = get_lexer_by_name(kw['format_args'].strip())
            except ClassNotFound:
                self.lexer = textlexer
            return
        if "filename" in kw:
            # called for an attachment
            filename = kw['filename']
        else:
            # called for an attachment by an older moin
            # HACK: find out the filename by peeking into the execution
            #       frame which might not always work
            try:
                frame = sys._getframe(1)
                filename = frame.f_locals['filename']
            except:
                filename = 'x.txt'
        try:
            self.lexer = get_lexer_for_filename(filename)
        except ClassNotFound:
            self.lexer = textlexer 
开发者ID:pygments,项目名称:pygments,代码行数:28,代码来源:moin-parser.py

示例9: test_get_lexers

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def test_get_lexers():
    # test that the lexers functions work
    for func, args in [(lexers.get_lexer_by_name, ("python",)),
                       (lexers.get_lexer_for_filename, ("test.py",)),
                       (lexers.get_lexer_for_mimetype, ("text/x-python",)),
                       (lexers.guess_lexer, ("#!/usr/bin/python3 -O\nprint",)),
                       (lexers.guess_lexer_for_filename, ("a.py", "<%= @foo %>"))
                       ]:
        x = func(opt='val', *args)
        assert isinstance(x, lexers.PythonLexer)
        assert x.options["opt"] == "val"

    for cls, (_, lname, aliases, _, mimetypes) in lexers.LEXERS.items():
        assert cls == lexers.find_lexer_class(lname).__name__

        for alias in aliases:
            assert cls == lexers.get_lexer_by_name(alias).__class__.__name__

        for mimetype in mimetypes:
            assert cls == lexers.get_lexer_for_mimetype(mimetype).__class__.__name__

    try:
        lexers.get_lexer_by_name(None)
    except ClassNotFound:
        pass
    else:
        raise Exception 
开发者ID:pygments,项目名称:pygments,代码行数:29,代码来源:test_basic_api.py

示例10: test_render

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def test_render(self):
        code = '#!/usr/bin/env python\n'\
               'print "Hello, world!"'

        formatter = utils.LineAnchorCodeHtmlFormatter(cssclass='codehilite',
                                                      linenos='inline')
        lexer = get_lexer_for_filename("some.py", encoding='chardet')
        hl_code = highlight(code, lexer, formatter)
        assert '<div class="codehilite">' in hl_code
        assert '<div id="l1" class="code_block">' in hl_code
        assert_in('<span class="lineno">1 </span>', hl_code) 
开发者ID:apache,项目名称:allura,代码行数:13,代码来源:test_utils.py

示例11: from_filename

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def from_filename(cls, filename, sync_from_start=True):
        """
        Create a `Lexer` from a filename.
        """
        # Inline imports: the Pygments dependency is optional!
        from pygments.util import ClassNotFound
        from pygments.lexers import get_lexer_for_filename

        try:
            pygments_lexer = get_lexer_for_filename(filename)
        except ClassNotFound:
            return SimpleLexer()
        else:
            return cls(pygments_lexer.__class__, sync_from_start=sync_from_start) 
开发者ID:bkerler,项目名称:android_universal,代码行数:16,代码来源:lexers.py

示例12: fetch_lexer

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def fetch_lexer(
        source: str,
        language: str = None,
        filename: str = None,
        mime_type: str = None
) -> Lexer:
    """

    :param source:
    :param language:
    :param filename:
    :param mime_type:
    :return:
    """

    environ.abort_thread()

    try:
        if language:
            return get_lexer_by_name(language, stripall=True)
    except ClassNotFound:
        pass

    if filename:
        try:
            return get_lexer_for_filename(filename, stripall=True)
        except ClassNotFound:
            pass

        try:
            return guess_lexer_for_filename(filename, source, stripall=True)
        except ClassNotFound:
            pass

    try:
        if mime_type:
            return get_lexer_for_mimetype(mime_type, stripall=True)
    except ClassNotFound:
        pass

    try:
        return guess_lexer(source, stripall=True)
    except ClassNotFound:
        return TextLexer() 
开发者ID:sernst,项目名称:cauldron,代码行数:46,代码来源:syntax_highlighting.py

示例13: print_lines

# 需要导入模块: from pygments import lexers [as 别名]
# 或者: from pygments.lexers import get_lexer_for_filename [as 别名]
def print_lines(console_printer,
                file_dict,
                sourcerange):
    """
    Prints the lines between the current and the result line. If needed
    they will be shortened.

    :param console_printer: Object to print messages on the console.
    :param file_dict:       A dictionary containing all files as values with
                            filenames as key.
    :param sourcerange:     The SourceRange object referring to the related
                            lines to print.
    """
    no_color = not console_printer.print_colored
    for i in range(sourcerange.start.line, sourcerange.end.line + 1):
        # Print affected file's line number in the sidebar.
        console_printer.print(format_lines(lines='', line_nr=i, symbol='['),
                              color=FILE_LINES_COLOR,
                              end='')

        line = file_dict[sourcerange.file][i - 1].rstrip('\n')
        try:
            lexer = get_lexer_for_filename(sourcerange.file)
        except ClassNotFound:
            lexer = TextLexer()
        lexer.add_filter(VisibleWhitespaceFilter(
            spaces=True, tabs=True,
            tabsize=SpacingHelper.DEFAULT_TAB_WIDTH))
        # highlight() combines lexer and formatter to output a ``str``
        # object.
        printed_chars = 0
        if i == sourcerange.start.line and sourcerange.start.column:
            console_printer.print(highlight_text(
                no_color, line[:sourcerange.start.column - 1],
                BackgroundMessageStyle, lexer), end='')

            printed_chars = sourcerange.start.column - 1

        if i == sourcerange.end.line and sourcerange.end.column:
            console_printer.print(highlight_text(
                no_color, line[printed_chars:sourcerange.end.column - 1],
                BackgroundSourceRangeStyle, lexer), end='')

            console_printer.print(highlight_text(
               no_color, line[sourcerange.end.column - 1:],
               BackgroundSourceRangeStyle, lexer), end='')
            console_printer.print('')
        else:
            console_printer.print(highlight_text(
                no_color, line[printed_chars:], BackgroundMessageStyle, lexer),
                                  end='')
            console_printer.print('') 
开发者ID:coala,项目名称:coala,代码行数:54,代码来源:ConsoleInteraction.py


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