::-- ZoomQuiet [2008-01-25 06:23:25]

CPUG联盟::

CPUG::门户plone

BPUG

SPUG

ZPUG

SpreadPython Python宣传

1. 拿Pygments做了个在线代码着色工具

realfun <realfun AT gmail.com>
reply-to        [email protected],
to      [email protected],
date    Jan 25, 2008 9:23 AM
subject [python-chinese] 拿Pygments做了个在线代码着色工具

   1 #!/usr/bin/env python
   2 #encoding:utf-8
   3 
   4 import sys
   5 sys.path.insert(0, '/home/twomaom1/lib/python2.3/')
   6 sys.path.insert(0, '/home/twomaom1/lib/python2.3/site-packages/')
   7 
   8 from pygments import highlight
   9 from pygments.lexers import get_lexer_by_name
  10 from pygments.formatters import HtmlFormatter
  11 
  12 import cgi
  13 import cgitb
  14 cgitb.enable()
  15 
  16 print "Content-type:text/html\n"
  17 
  18 def code2html(code, lang):
  19     if lang.lower() == "auto":
  20         #@notworking...
  21         lexer = guess_lexer(code, encoding='utf-8', stripall=True)
  22     else:
  23         lexer = get_lexer_by_name(lang, encoding='utf-8', stripall=True)
  24     formatter = HtmlFormatter(linenos=False, encoding='utf-8', cssclass="source")
  25     result = highlight(code, lexer, formatter)
  26     return result
  27 
  28 def output_head():
  29     print """
  30 <!DOCTYPE html
  31 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  32 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  33 
  34 <html xmlns="http://www.w3.org/1999/xhtml">
  35         <head>
  36                 <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  37                 <title>O_O</title>
  38         <link rel="stylesheet" type="text/css" href="http://www.peerat.com/code/style.css" />
  39         </head>
  40     <body>
  41         """
  42 
  43 def output_end():
  44     print "</body>"
  45     print "</html>"
  46 
  47 def main():
  48     form = cgi.FieldStorage()
  49     code = 'print "Hello World!"'
  50     lang = "AUTO"
  51     name = "浮名乃身外物"
  52     user = "无名氏"
  53     output_head()
  54     if (form.has_key("code") and len(form["code"].value) > 0)\
  55      or (form.has_key("file") and form["file"].file):
  56         if form.has_key("code") and len(form["code"].value) > 0:
  57             code = form["code"].value
  58         else:
  59             fileitem = form["file"].file
  60             data = fileitem.read(0x10000)
  61             if len(data):
  62                 code = data
  63         if form.has_key("lang"):
  64             lang = form["lang"].value
  65         if form.has_key("name"):
  66             name = form["name"].value
  67         if form.has_key("user"):
  68             user = form["name"].value
  69 
  70         result = code2html(code, lang)
  71         print result
  72     else:
  73         print "选择文件,或者粘贴代码,否则啥也没有。:)\n"
  74         print '<a href="http://www.peerat.com/code/">点击此处返回</a> \n'
  75     output_end()
  76 
  77 main()

1.1. 反馈

MiscItems/2008-01-25 (last edited 2009-12-25 07:14:02 by localhost)