Hi, I'm Eric Lo. 中文

使用Pyments高亮显示代码为html

Friday, January 29, 2010

Pygments —— Python syntax highlighter (http://pygments.org/)

easy_install pygments

实例代码:

encoding: utf-8
"""
code2html.py
Created by Eric on 2009-09-14.
Copyright (c) 2009 lxneng@gmail.com. All rights reserved.
"""
import sys
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=False,
            encoding='utf-8',
            noclasses="True")
    result = highlight(code, lexer, formatter)
    return result
def demo():
    f = open(file)
    code = f.read()
    f.close()
    html = """
    <html>
        <head>
            <title>Pygments_example</title>
        </head>
        <body>
        %s
        </body>
    </html>
    """%code2html(code, 'python')
    print html
    ff = open('test.html','w')
    ff.write(html)
    ff.close()
if name == 'main':
    demo()

This entry was tagged Python and Django

« Previous Next »

go to Top