Python to html
by
admin
—
last modified
2008-02-11 05:20
Præsenter din pythonkode pænt på din plone site.
Size 4.7 kB - File type text/python-sourceFile contents
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
MoinMoin - Python Source Parser
"""
# Imports
import cgi, string, sys, cStringIO
import keyword, token, tokenize
import os
##############################################
### Python Source Parser (does Hilighting) ###
##############################################
_KEYWORD = token.NT_OFFSET + 1
_TEXT = token.NT_OFFSET + 2
_colors = {
token.NUMBER: '#0080C0',
token.OP: '#0000C0',
token.STRING: '#004080',
tokenize.COMMENT: '#008000',
token.NAME: '#000000',
token.ERRORTOKEN: '#FF8080',
_KEYWORD: '#C00000',
_TEXT: '#000000',
}
class Parser:
""" Send colored python source.
"""
def __init__(self, raw, out = sys.stdout):
""" Store the source text.
"""
self.raw = string.strip(string.expandtabs(raw))
self.out = out
self.imports = False
self.froms = False
self.module = ""
def format(self, formatter, form):
""" Parse and send the colored source.
"""
# store line offsets in self.lines
self.lines = [0, 0]
pos = 0
while 1:
pos = string.find(self.raw, '\n', pos) + 1
if not pos: break
self.lines.append(pos)
self.lines.append(len(self.raw))
# parse the source and write it
self.pos = 0
text = cStringIO.StringIO(self.raw)
self.out.write('<pre><font face="Lucida,Courier New">')
try:
tokenize.tokenize(text.readline, self)
except tokenize.TokenError, ex:
msg = ex[0]
line = ex[1][0]
self.out.write("<h3>ERROR: %s</h3>%s\n" % (
msg, self.raw[self.lines[line]:]))
self.out.write('</font></pre>')
def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line):
""" Token handler.
"""
baseurl = 'http://www.python.org/doc/current/lib/module-'
if toktype == token.NAME and toktext == 'from':
self.froms = True
self.module = ""
elif self.froms and toktype == token.NAME:
self.module = toktext+"."
elif toktype == token.NEWLINE:
self.imports = False
self.module = ""
elif toktype == token.NAME and toktext == 'import':
self.imports = True
ext = ""
if toktext+".py" in localfiles:
baseurl = 'http://www.databassen.dk:8090/bauerdata/python-program-eksempler/'
ext = ".py"
baseurl = 'http://localhost:9999/'
ext = ""
baseurl = 'http://localhost:9999/'
module = self.module
if 1: # XXX
print "type", toktype, token.tok_name[toktype], "text", toktext,
print "start", srow,scol, "end", erow,ecol, "<br>"
# calculate new positions
oldpos = self.pos
newpos = self.lines[srow] + scol
self.pos = newpos + len(toktext)
# handle newlines
if toktype in [token.NEWLINE, tokenize.NL]:
self.out.write('\n')
return
# send the original whitespace, if needed
if newpos > oldpos:
self.out.write(self.raw[oldpos:newpos])
# skip indenting tokens
if toktype in [token.INDENT, token.DEDENT]:
self.pos = newpos
return
# map token type to a color group
if token.LPAR <= toktype and toktype <= token.OP:
toktype = token.OP
elif toktype == token.NAME and keyword.iskeyword(toktext):
toktype = _KEYWORD
color = _colors.get(toktype, _colors[_TEXT])
style = ''
if toktype == token.ERRORTOKEN:
style = ' style="border: solid 1.5pt #FF0000;"'
# send text
self.out.write('<font color="%s"%s>' % (color, style))
if self.froms and toktype == token.NAME and toktext != 'from':
self.out.write( '<a href="%(baseurl)s%(toktext)s%(ext)s">%(toktext)s</a>' % vars() )
self.froms = False
elif self.imports and toktype == token.NAME and toktext != 'import':
self.out.write( '<a href="%(baseurl)s%(module)s%(toktext)s%(ext)s">%(toktext)s</a>' % vars() )
else:
self.out.write(cgi.escape(toktext))
self.out.write('</font>')
localfiles = os.popen("ls *.py").read()
if __name__ == "__main__":
import os, sys
print "Formatting..."
print localfiles
# open own source
fnames = sys.argv[1:]
for fname in [ os.path.splitext( fn )[0] for fn in fnames ]:
source = open( fname + ".py" ).read()
# write colorized version to "<fname>.html"
Parser(source, open('%(fname)s.html' % vars(), 'wt')).format(None, None)
Click here to get the file