使用Pygments高亮显示代码为html

Friday, January 29, 2010

Pygments —— Python syntax highlighter

pip install pygments

实例代码:

# -*- coding: utf-8 -*-
"""
code2html.py
Created by Eric on 2009-09-14.
Copyright (c) 2009 lxneng@gmail.com. All rights reserved.
"""

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter


def code2html(code, lang):
    lexer = get_lexer_by_name(lang, encoding='utf-8', stripall=True)
    formatter = HtmlFormatter(linenos=True,
                              encoding='utf-8',
                              noclasses="True")
    result = highlight(code, lexer, formatter)
    return result


def main():
    f = open(__file__)
    code = f.read()
    f.close()
    html = """
    <html>
        <head>
            <title>Pygments_example</title>
        </head>
        <body>
        %s
        </body>
    </html>
    """ % code2html(code, 'python')
    ff = open('test.html', 'w')
    ff.write(html)
    ff.close()


if __name__ == '__main__':
    main()

This entry was tagged Django and Python

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top