當前位置: 首頁>>代碼示例>>Python>>正文


Python lexers.PythonLexer方法代碼示例

本文整理匯總了Python中pygments.lexers.PythonLexer方法的典型用法代碼示例。如果您正苦於以下問題:Python lexers.PythonLexer方法的具體用法?Python lexers.PythonLexer怎麽用?Python lexers.PythonLexer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pygments.lexers的用法示例。


在下文中一共展示了lexers.PythonLexer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: testPython

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def testPython(self):
        """ Does the CompletionLexer work for Python?
        """
        lexer = CompletionLexer(PythonLexer())

        # Test simplest case.
        self.assertEqual(lexer.get_context("foo.bar.baz"),
                          [ "foo", "bar", "baz" ])

        # Test trailing period.
        self.assertEqual(lexer.get_context("foo.bar."), [ "foo", "bar", "" ])

        # Test with prompt present.
        self.assertEqual(lexer.get_context(">>> foo.bar.baz"),
                          [ "foo", "bar", "baz" ])

        # Test spacing in name.
        self.assertEqual(lexer.get_context("foo.bar. baz"), [ "baz" ])

        # Test parenthesis.
        self.assertEqual(lexer.get_context("foo("), []) 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:23,代碼來源:test_completion_lexer.py

示例2: code

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def code(self, session=None):
        all_errors = ""

        try:
            dag_id = request.args.get('dag_id')
            dag_orm = DagModel.get_dagmodel(dag_id, session=session)
            code = DagCode.get_code_by_fileloc(dag_orm.fileloc)
            html_code = Markup(highlight(
                code, lexers.PythonLexer(), HtmlFormatter(linenos=True)))

        except Exception as e:
            all_errors += (
                "Exception encountered during " +
                "dag_id retrieval/dag retrieval fallback/code highlighting:\n\n{}\n".format(e)
            )
            html_code = Markup('<p>Failed to load file.</p><p>Details: {}</p>').format(
                escape(all_errors))

        return self.render_template(
            'airflow/dag_code.html', html_code=html_code, dag=dag_orm, title=dag_id,
            root=request.args.get('root'),
            demo_mode=conf.getboolean('webserver', 'demo_mode'),
            wrapped=conf.getboolean('webserver', 'default_wrap')) 
開發者ID:apache,項目名稱:airflow,代碼行數:25,代碼來源:views.py

示例3: __init__

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def __init__(self, **kwargs):
        stylename = kwargs.get('style_name', 'default')
        style = kwargs['style'] if 'style' in kwargs \
            else styles.get_style_by_name(stylename)
        self.formatter = BBCodeFormatter(style=style)
        self.lexer = lexers.PythonLexer()
        self.text_color = '#000000'
        self._label_cached = Label()
        self.use_text_color = True

        super(CodeInput, self).__init__(**kwargs)

        self._line_options = kw = self._get_line_options()
        self._label_cached = Label(**kw)
        # use text_color as foreground color
        text_color = kwargs.get('foreground_color')
        if text_color:
            self.text_color = get_hex_from_color(text_color)
        # set foreground to white to allow text colors to show
        # use text_color as the default color in bbcodes
        self.use_text_color = False
        self.foreground_color = [1, 1, 1, .999]
        if not kwargs.get('background_color'):
            self.background_color = [.9, .92, .92, 1] 
開發者ID:mahart-studio,項目名稱:kivystudio,代碼行數:26,代碼來源:codeinput.py

示例4: __init__

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def __init__(self, *args, **kwargs):
        super(InterpreterInput, self).__init__(*args, **kwargs)

        self.register_event_type('on_request_completions')
        self.register_event_type('on_clear_completions')
        self.register_event_type('on_get_completions')

        if platform != 'android':
            from pygments.lexers import PythonLexer
            self.lexer = PythonLexer()

        App.get_running_app().bind(on_pause=self.on_pause)

    #     self.text = '''for i in range(5):
    # print(i)
    # time.sleep(1)''' 
開發者ID:inclement,項目名稱:Pyonic-interpreter,代碼行數:18,代碼來源:interpreter.py

示例5: table_definition

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def table_definition(table_name):
    """
    Get the source of a table function.

    If a table is registered DataFrame and not a function then all that is
    returned is {'type': 'dataframe'}.

    If the table is a registered function then the JSON returned has keys
    "type", "filename", "lineno", "text", and "html". "text" is the raw
    text of the function, "html" has been marked up by Pygments.

    """
    if orca.table_type(table_name) == 'dataframe':
        return jsonify(type='dataframe')

    filename, lineno, source = \
        orca.get_raw_table(table_name).func_source_data()

    html = highlight(source, PythonLexer(), HtmlFormatter())

    return jsonify(
        type='function', filename=filename, lineno=lineno, text=source,
        html=html) 
開發者ID:UDST,項目名稱:orca,代碼行數:25,代碼來源:server.py

示例6: column_definition

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def column_definition(table_name, col_name):
    """
    Get the source of a column function.

    If a column is a registered Series and not a function then all that is
    returned is {'type': 'series'}.

    If the column is a registered function then the JSON returned has keys
    "type", "filename", "lineno", "text", and "html". "text" is the raw
    text of the function, "html" has been marked up by Pygments.

    """
    col_type = orca.get_table(table_name).column_type(col_name)

    if col_type != 'function':
        return jsonify(type=col_type)

    filename, lineno, source = \
        orca.get_raw_column(table_name, col_name).func_source_data()

    html = highlight(source, PythonLexer(), HtmlFormatter())

    return jsonify(
        type='function', filename=filename, lineno=lineno, text=source,
        html=html) 
開發者ID:UDST,項目名稱:orca,代碼行數:27,代碼來源:server.py

示例7: injectable_definition

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def injectable_definition(inj_name):
    """
    Get the source of an injectable function.

    If an injectable is a registered Python variable and not a function
    then all that is returned is {'type': 'variable'}.

    If the column is a registered function then the JSON returned has keys
    "type", "filename", "lineno", "text", and "html". "text" is the raw
    text of the function, "html" has been marked up by Pygments.

    """
    inj_type = orca.injectable_type(inj_name)

    if inj_type == 'variable':
        return jsonify(type='variable')
    else:
        filename, lineno, source = \
            orca.get_injectable_func_source_data(inj_name)
        html = highlight(source, PythonLexer(), HtmlFormatter())
        return jsonify(
            type='function', filename=filename, lineno=lineno, text=source,
            html=html) 
開發者ID:UDST,項目名稱:orca,代碼行數:25,代碼來源:server.py

示例8: stacktraces

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def stacktraces():
    code = []
    for threadId, stack in sys._current_frames().items():
        code.append("\n# ThreadID: %s" % threadId)
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line:
                code.append("  %s" % (line.strip()))
 
    return highlight("\n".join(code), PythonLexer(), HtmlFormatter(
      full=False,
      # style="native",
      noclasses=True,
    ))


# This part was made by nagylzs 
開發者ID:vanangamudi,項目名稱:newspaper-crawler-scripts,代碼行數:19,代碼來源:stacktracer.py

示例9: test_formatter_unicode_handling

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def test_formatter_unicode_handling(cls):
    # test that the formatter supports encoding and Unicode
    tokens = list(lexers.PythonLexer(encoding='utf-8').
                  get_tokens("def f(): 'ä'"))

    try:
        inst = cls(encoding=None)
    except (ImportError, FontNotFound) as e:
        # some dependency or font not installed
        pytest.skip(str(e))

    if cls.name != 'Raw tokens':
        out = format(tokens, inst)
        if cls.unicodeoutput:
            assert type(out) is str, '%s: %r' % (cls, out)

        inst = cls(encoding='utf-8')
        out = format(tokens, inst)
        assert type(out) is bytes, '%s: %r' % (cls, out)
        # Cannot test for encoding, since formatters may have to escape
        # non-ASCII characters.
    else:
        inst = cls()
        out = format(tokens, inst)
        assert type(out) is bytes, '%s: %r' % (cls, out) 
開發者ID:pygments,項目名稱:pygments,代碼行數:27,代碼來源:test_basic_api.py

示例10: display

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def display(cells):
    output = []

    for cell in cells:
        execution_count = (
            cell["execution_count"] if cell["execution_count"] is not None else " "
        )
        prompt = (
            Fore.GREEN
            + Style.BRIGHT
            + "In [{}]: ".format(execution_count)
            + Style.RESET_ALL
        )
        code = highlight(cell.source, PythonLexer(), TerminalTrueColorFormatter())
        output.append(prompt + code)

    return output 
開發者ID:vinayak-mehta,項目名稱:nbcommands,代碼行數:19,代碼來源:terminal.py

示例11: get_pygments

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def get_pygments():
    try:
        import pygments
        from pygments.lexers import PythonLexer
        from pygments.formatters import Terminal256Formatter
    except ImportError:  # pragma: no cover
        return None, None, None
    else:
        return pygments, PythonLexer(), Terminal256Formatter(style='vim') 
開發者ID:samuelcolvin,項目名稱:python-devtools,代碼行數:11,代碼來源:prettier.py

示例12: _vendor_wrap

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def _vendor_wrap(self, colour_class, text):
        """Override in reporters that wrap snippet lines in vendor styles, e.g. pygments."""
        if '-line' not in colour_class:
            text = highlight(text, PythonLexer(),
                            HtmlFormatter(nowrap=True, lineseparator='', classprefix='pygments-'))
        return text 
開發者ID:pyta-uoft,項目名稱:pyta,代碼行數:8,代碼來源:html_reporter.py

示例13: __init__

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def __init__(self, parent, lexer=None):
        super(PygmentsHighlighter, self).__init__(parent)

        self._document = self.document()
        self._formatter = HtmlFormatter(nowrap=True)
        self._lexer = lexer if lexer else PythonLexer()
        self.set_style('default') 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:9,代碼來源:pygments_highlighter.py

示例14: __init__

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def __init__(self, code_dir=None, isolate=True, show_vars=True, max_length=120):
        # The directory we're interested in.
        if not code_dir:
            code_dir = os.getcwd()
        self._code_dir = code_dir

        # Whether to print interesting lines in color or not. If False,
        # all lines are printed in color.
        self._isolate = isolate

        # Our current state.
        self._state = State.no_idea

        # The filename of the line we're currently printing.
        self._file = None

        # The buffer that we use to build up the output in.
        self._buffer = ""

        # Whether to print variables for stack frames.
        self._show_vars = show_vars

        # Max length of printed variable lines
        self._max_length = max_length

        self._load_config()

        self.pygments_lexer = PythonLexer()
        self.pygments_formatter = TerminalFormatter(style=self._config.get("style", "color_scheme")) 
開發者ID:skorokithakis,項目名稱:tbvaccine,代碼行數:31,代碼來源:tbv.py

示例15: get_attr_renderer

# 需要導入模塊: from pygments import lexers [as 別名]
# 或者: from pygments.lexers import PythonLexer [as 別名]
def get_attr_renderer():
    """Return Dictionary containing different Pygements Lexers for Rendering & Highlighting"""
    return {
        'bash_command': lambda x: render(x, lexers.BashLexer),
        'hql': lambda x: render(x, lexers.SqlLexer),
        'sql': lambda x: render(x, lexers.SqlLexer),
        'doc': lambda x: render(x, lexers.TextLexer),
        'doc_json': lambda x: render(x, lexers.JsonLexer),
        'doc_rst': lambda x: render(x, lexers.RstLexer),
        'doc_yaml': lambda x: render(x, lexers.YamlLexer),
        'doc_md': wrapped_markdown,
        'python_callable': lambda x: render(get_python_source(x), lexers.PythonLexer),
    } 
開發者ID:apache,項目名稱:airflow,代碼行數:15,代碼來源:utils.py


注:本文中的pygments.lexers.PythonLexer方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。