root/stuff/sandbox/pythondoc/linedemo.py

Revision 217 (by effbot, 04/06/06 15:30:31)

added pythondoc line annotation demo

# $Id$
# example: add source code links to pythondoc markup

import pythondoc
import cgi

ET = pythondoc.ElementTree

##
# Converts a Python script to a (unstyled) HTML page.

def makehtml(file):
    out = open(file + ".html", "w")
    out.write("<html><body><pre>\n")
    for ix, line in enumerate(open(file)):
        line = cgi.escape(line.expandtabs())
        out.write("<b id='line%d'>%05d</b> %s" % (ix+1, ix+1, line))
    out.write("</pre></body></html>")

##
# Generates a PythonDoc page for the given module, and add source
# code links to the descriptions.

def makedoc(file, prefix):

    parser = pythondoc.ModuleParser(file)
    module = parser.parse(docstring=1)

    for elem in module.getiterator():

        lineno = elem.get("lineno")
        if not lineno:
            continue

        description = elem.find("info/description")
        if len(description) == 0 and description.text:
            # wrap it in a paragraph
            p = ET.SubElement(description, "p")
            p.text = description.text
            description.text = None

        # insert hyperlink
        href = file + ".html" + "#line" + lineno # FIXME
        p = ET.SubElement(description, "p")
        a = ET.SubElement(p, "a", href=href)
        a.set("class", "sourcelink")
        a.text = "View source code..."

    # ET.ElementTree(module).write("out.xml")

    formatter = pythondoc.CompactHTML()
    print formatter.save(module, prefix), "ok"

file = "examples/docstring.py"
makehtml("examples/docstring.py")
makedoc("examples/docstring.py", "pythondoc-docstring")
Note: See TracBrowser for help on using the browser.