Ejemplo n.º 1
0
def cmd_htmldoc(ch, cmd, arg):
    """Creates html documentation for all registered modules. html files will
       be saved to html/pydocs/
    """
    try:
        os.makedirs(HTML_DOC_DIR)
    except: pass
    doc = pydoc.HTMLDoc()
    for modname in suggested_reading:
        todoc = pydoc.locate(modname)
        if todoc != None:
            fname = HTML_DOC_DIR + "/" + modname + ".html"
            fl    = file(fname, "w+")
            fl.write(doc.page(modname, doc.document(todoc)))
            fl.close()

    builtin_index = doc.multicolumn([doc.modulelink(pydoc.locate(modname)) for modname in builtins], lambda x: x)
    
    # build our index page. That includes things in pymodules/ and builtins
    index_contents ="".join([doc.section("<big><strong>builtins</big></strong>",
                                         'white', '#ee77aa', builtin_index),
                             doc.index("../lib/pymodules/")])

    # go over all of our builtins and add them to the index
    index = file(HTML_DOC_DIR + "/index.html", "w+")
    index.write(doc.page("index", index_contents))
    index.close()
    
    ch.send("html documentation generated for all known modules.")
Ejemplo n.º 2
0
    def __init__(self, name, title=None, summary=None):
        """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
        if title == None: title = name
        if summary == None: summary = title

        self.doc = pydoc.HTMLDoc()

        self.html = open('%s.html' % name, 'w')
        self.html.write('<html>\n')
        self.html.write('<head>\n')
        self.html.write('<title>%s</title>\n' % title)
        self.html.write('</head>\n')
        self.html.write('<body>\n')

        self.html_variables = ''
        self.html_functions = ''
        self.html_classes = ''

        self.wiki = open('%s.wiki' % name, 'w')
        self.wiki.write('#summary %s\n\n' % summary)
        self.wiki.write('= %s= \n\n' % title)

        self.wiki_variables = ''
        self.wiki_functions = ''
        self.wiki_classes = ''
Ejemplo n.º 3
0
def get_pydoc_html(module):
    "Returns pydoc generated output as html"
    doc = pydoc.HTMLDoc()
    output = doc.docmodule(module)
    loc = doc.getdocloc(pydoc_mod) or ""
    if loc:
        loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
    return output.strip(), loc
Ejemplo n.º 4
0
def on_init(debugger):
    f = open("zero.html", "w")
    f.write("<html><title>Zero Python Documentation</title><body>")
    doc = pydoc.HTMLDoc()
    f.write(doc.docmodule(zero))
    f.write("</body></html>")
    f.close()
    sys.exit(0)
Ejemplo n.º 5
0
def get_pydoc_html(module):
    """Returns pydoc generated output as html"""
    doc = pydoc.HTMLDoc()
    output = doc.docmodule(module)
    loc = doc.getdocloc(pydoc_mod) or ''
    if loc:
        loc = '<br><a href="' + loc + '">Module Docs</a>'
    return output.strip(), loc
Ejemplo n.º 6
0
 def initUI(self, ui, request):
     openDocument = request.fields.get('load')
     if openDocument:
         ui.display.setVisibleElement(ui.openDocument)
         html = ui.openDocument.addChildElement(self.buildElement('straightHTML'))
         htmlDoc = pydoc.HTMLDoc()
         product = GuiBuilderConfig.Factory.build(openDocument.lower(), "", "")
         if product:
             html.html = htmlDoc.docclass(product.__class__)
             html.html = html.html.replace('href="', 'href="Documentation?load=').replace(".html", "")
Ejemplo n.º 7
0
def document_nx_function(function):
    try:
        nx_function = get_function_from_path(function)
    except AssertionError as e:
        return f"[network.{function}] is not a function", 400
    except Exception as e:
        print(e)
        return f"[network.{function}] not found", 404

    documenter = pydoc.HTMLDoc()
    return documenter.docroutine(nx_function)
Ejemplo n.º 8
0
def docHTML(text):
    """ just testing """
    import pydoc
    try:
        token = text.split()[-1]
        if '(' in token:  #better do regex
            token = token[:-1]
        obj = eval(token)
        #pyobj,name=pydoc.resolve(obj,0)
        ins = pydoc.plain(pydoc.render_doc(obj))
        html = pydoc.HTMLDoc()
        return html.page(pydoc.describe(obj), html.document(obj, name))
    except NameError:
        pass
Ejemplo n.º 9
0
def gen_docs_module(m):
    d = pd.HTMLDoc()
    doc = d.docmodule(m)

    _dir = m.__name__
    os.mkdir(_dir)

    fn = '{}/{}.html'.format(_dir, m.__name__)
    write_docs(fn, doc)

    for item in dir(m):
        if eval("type(m.{})".format(item)) == type(m):
            sub_mod = eval("m.{}".format(item))
            doc = d.docmodule(sub_mod)

            fn = '{}/{}.html'.format(_dir, sub_mod.__name__)
            write_docs(fn, doc)
Ejemplo n.º 10
0
def hgd_mk_pydoc():
    """ Generate HGD Python documentation """

    outdir = "pydoc"
    if (not os.path.exists(outdir)):
        os.mkdir(outdir)

    # HTML doc disabled for now
    #for doctype in ["txt", "html"]:
    for doctype in ["txt"]:

        if (not os.path.exists(outdir + "/" + doctype)):
            os.mkdir(outdir + "/" + doctype)

        if (doctype == ("txt")):
            d = pydoc.TextDoc()
        else:
            d = pydoc.HTMLDoc()

        # first make top level docs
        f = open("%s/%s/index.%s" % (outdir, doctype, doctype), "w")

        if (doctype == "html"):
            content = d.page("HGD Python API", d.docmodule(sys.modules["hgd"]))
        else:
            content = d.docmodule(sys.modules["hgd"])

        f.write(content)
        f.close()

        # now each module in the hgd package which is not builtin
        mods = ["hgd.playlist", "hgd.doccer"]

        for mod in mods:
            f = open("%s/%s/%s.%s" % (outdir, doctype, mod, doctype), "w")

            if (doctype == "html"):
                content = d.page("HGD Python API",
                                 d.docmodule(sys.modules[mod]))
            else:
                content = d.docmodule(sys.modules[mod])

            f.write(content)
            f.close()

    return 0
Ejemplo n.º 11
0
    def test_method_aliases(self):
        class A:
            def tkraise(self, aboveThis=None):
                """Raise this widget in the stacking order."""

            lift = tkraise

            def a_size(self):
                """Return size"""

        class B(A):
            def itemconfigure(self, tagOrId, cnf=None, **kw):
                """Configure resources of an item TAGORID."""

            itemconfig = itemconfigure
            b_size = A.a_size

        doc = pydoc.render_doc(B)
        # clean up the extra text formatting that pydoc performs
        doc = re.sub('\b.', '', doc)
        self.assertEqual(
            doc, '''\
Python Library Documentation: class B in module %s

class B(A)
 |  Method resolution order:
 |      B
 |      A
 |      builtins.object
 |\x20\x20
 |  Methods defined here:
 |\x20\x20
 |  b_size = a_size(self)
 |\x20\x20
 |  itemconfig = itemconfigure(self, tagOrId, cnf=None, **kw)
 |\x20\x20
 |  itemconfigure(self, tagOrId, cnf=None, **kw)
 |      Configure resources of an item TAGORID.
 |\x20\x20
 |  ----------------------------------------------------------------------
 |  Methods inherited from A:
 |\x20\x20
 |  a_size(self)
 |      Return size
 |\x20\x20
 |  lift = tkraise(self, aboveThis=None)
 |\x20\x20
 |  tkraise(self, aboveThis=None)
 |      Raise this widget in the stacking order.
 |\x20\x20
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from A:
 |\x20\x20
 |  __dict__
 |      dictionary for instance variables (if defined)
 |\x20\x20
 |  __weakref__
 |      list of weak references to the object (if defined)
''' % __name__)

        doc = pydoc.render_doc(B, renderer=pydoc.HTMLDoc())
        self.assertEqual(
            doc, '''\
Python Library Documentation: class B in module %s

<p>
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#000000" face="helvetica, arial"><a name="B">class <strong>B</strong></a>(A)</font></td></tr>
\x20\x20\x20\x20
<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%%"><dl><dt>Method resolution order:</dt>
<dd>B</dd>
<dd>A</dd>
<dd><a href="builtins.html#object">builtins.object</a></dd>
</dl>
<hr>
Methods defined here:<br>
<dl><dt><a name="B-b_size"><strong>b_size</strong></a> = <a href="#B-a_size">a_size</a>(self)</dt></dl>

<dl><dt><a name="B-itemconfig"><strong>itemconfig</strong></a> = <a href="#B-itemconfigure">itemconfigure</a>(self, tagOrId, cnf=None, **kw)</dt></dl>

<dl><dt><a name="B-itemconfigure"><strong>itemconfigure</strong></a>(self, tagOrId, cnf=None, **kw)</dt><dd><tt>Configure&nbsp;resources&nbsp;of&nbsp;an&nbsp;item&nbsp;TAGORID.</tt></dd></dl>

<hr>
Methods inherited from A:<br>
<dl><dt><a name="B-a_size"><strong>a_size</strong></a>(self)</dt><dd><tt>Return&nbsp;size</tt></dd></dl>

<dl><dt><a name="B-lift"><strong>lift</strong></a> = <a href="#B-tkraise">tkraise</a>(self, aboveThis=None)</dt></dl>

<dl><dt><a name="B-tkraise"><strong>tkraise</strong></a>(self, aboveThis=None)</dt><dd><tt>Raise&nbsp;this&nbsp;widget&nbsp;in&nbsp;the&nbsp;stacking&nbsp;order.</tt></dd></dl>

<hr>
Data descriptors inherited from A:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
</dl>
</td></tr></table>\
''' % __name__)
Ejemplo n.º 12
0
    <b>Download</b></a><br/>
    <small><em>The source was styled using <a href="http://silvercity.sourceforge.net/">SilverCity</a></em></small>
</p>
</body>
</html>
"""

params = cgi.FieldStorage(keep_blank_values=1)

if "source" not in params:
    import pydoc

    print("Content-type: text/plain")
    print()

    doc = pydoc.HTMLDoc()

    print(doc.page("Docs", doc.preformat(__doc__)))

else:
    source = params["source"].value
    file_name = urllib.parse.unquote(source)

    if "download" in params:
        # The user has asked to download the source, so send it
        # as plain text
        print("Content-type: text/plain")
        print()
        sys.stdout.write(open(file_name, 'r').read())

    else:
Ejemplo n.º 13
0
#!/usr/bin/python3

try:
    from cStringIO import StringIO as BytesIO
except ImportError:
    from io import BytesIO

import pydoc
import lxml.etree

html = pydoc.HTMLDoc()

# Generate the documentation from the pydoc strings
object, name = pydoc.resolve('pycdlib.pycdlib', 0)
page = html.page(pydoc.describe(object), html.document(object, name))

# Now parse that documentation
parser = lxml.etree.HTMLParser()
tree = lxml.etree.parse(BytesIO(page.encode('ascii')), parser)

# Now we remove the "Modules" section, since it contains only links to parts
# of the API that we are not documenting
doc = tree.getroot()
tables = doc.xpath('/html/body/table')
remove_table = None
for table in tables:
    for tr in table.xpath('tr'):
        bgcolor = tr.get('bgcolor')
        if bgcolor == '#aa55cc':
            # We found the 'Modules' section; go back up to the table to remove it
            remove_table = table
Ejemplo n.º 14
0
def api_docs(item,
             skip=[],
             prefix='',
             subclass_of=None,
             write=True,
             members=[
                 pydoc.inspect.ismethod, pydoc.inspect.isfunction,
                 pydoc.inspect.isdatadescriptor
             ]):
    def check_member(item):
        for member in members:
            if member(item):
                return True

        return False

    # item is either a module or class
    stored_fms = []

    for fm in pydoc.inspect.getmembers(item, check_member):
        output = list()

        if fm[0] in skip or (fm[0].startswith('_') and fm[0] != '__init__'):
            continue

        if pydoc.inspect.ismodule(fm[1]) or pydoc.inspect.isclass(fm[1]):
            stored_fms.append(fm[0])
            # don't write its own page, make a manual call to api_docs to do that... but we will create the link
            continue

        path = [
            p for p in prefix.split(".") + [item.__name__.split(".")[-1]]
            if len(p)
        ]
        path_md = ".".join([
            "[{}]({}.md)".format(p, ".".join(path[:i + 1]))
            for i, p in enumerate(path)
        ])
        output.append("### {}.{} ({})\n\n".format(path_md, fm[0],
                                                  get_kind(fm[1])))

        # Get the signature
        if pydoc.inspect.ismethod(fm[1]) or pydoc.inspect.isfunction(fm[1]):
            output.append('```py\n')
            output.append('def %s%s\n' %
                          (fm[0],
                           pydoc.inspect.formatargspec(
                               *pydoc.inspect.getargspec(fm[1]))))
            output.append('```\n')

        # get the docstring
        if pydoc.inspect.getdoc(fm[1]):
            output.append('\n')
            docstring = pydoc.HTMLDoc().markup(pydoc.inspect.getdoc(fm[1]))
            docstring = docstring.replace("&lt;class&gt;", item.__name__)
            docstring = re.sub(r"(?P<name>&lt;[0a-zA-Z_\.]*&gt;)",
                               md_internal_link, docstring)
            output.append(docstring)

        output.append('\n')

        stored_fms.append(fm[0])

        if write:
            path = ".".join([p for p in prefix.split(".") if len(p)] +
                            [item.__name__.split(".")[-1], fm[0]])

            filename = './api/{}.md'.format(path)
            print("writing {}".format(filename))
            f_method = open(filename, 'w')
            f_method.write("\n".join(output))
            f_method.close()

    if write:
        path = [
            p for p in prefix.split(".") + [item.__name__.split(".")[-1]]
            if len(p)
        ]
        path_md = ".".join([
            "[{}]({}.md)".format(p, ".".join(path[:i + 1]))
            for i, p in enumerate(path[:-1])
        ])
        if len(path_md):
            path_md += ".{}".format(item.__name__.split(".")[-1])
        else:
            path_md = item.__name__.split(".")[-1]

        path = ".".join(path)
        filename_class = './api/{}.md'.format(path)
        print("writing {}".format(filename_class))
        f_class = open(filename_class, 'w')
        f_class.write("## {} ({})\n\n".format(path_md, get_kind(item)))
        if subclass_of is not None:
            f_class.write(
                "{} is a subclass of {} and therefore also includes all [{} methods]({}.md)\n\n"
                .format(item.__name__, subclass_of, subclass_of, subclass_of))
        if hasattr(item, '__doc__') and item.__doc__ is not None:
            for l in item.__doc__.split("\n"):
                docstringline = pydoc.HTMLDoc().markup(l.lstrip() + "\n")
                docstring = docstringline.replace("&lt;class&gt;",
                                                  item.__name__)
                docstringline = re.sub(r"(?P<name>&lt;[0a-zA-Z_\.]*&gt;)",
                                       md_internal_link, docstringline)
                f_class.write(docstringline)
            f_class.write("\n\n")
        for fm in stored_fms:
            path_fm = ".".join([p for p in prefix.split(".") if len(p)] +
                               [item.__name__.split(".")[-1], fm])
            f_class.write("* [{}]({}.md)\n".format(fm, path_fm))
        f_class.close()

    return stored_fms
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-

# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
#     http://www.kamaelia.org/AUTHORS - please extend this file,
#     not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import likefile, pydoc

documentation = ''.join([
    "<pre>",
    likefile.__doc__,
    "<br><br><br></pre>",
    pydoc.HTMLDoc().document(likefile.LikeFile),
])

outfile = open("likefile.html", "w+b")
outfile.write(documentation)
Ejemplo n.º 16
0
def doc_generate_html(obj) -> str:
    """Generate formatted fdoc -- UNUSED.

    Args:
        obj (object): The object

    Returns:
        str: Generated html

    Raises:
        TypeError: Objcet is the wrong type
        ValueError: Inspectoin failed
    """
    # Generate formatted fdoc
    # Get docstring
    # doc = inspect.getdoc(obj)
    # if doc:
    #     doc = inspect.cleandoc(doc)
    doc = pydoc.HTMLDoc()
    doc_text = doc.docroutine(obj)

    # Get file
    try:
        file = inspect.getfile(obj)
    except TypeError:
        file = ''

    # Get signature
    try:
        signature = inspect.signature(obj)
        signature_full = str(signature)
    except (ValueError, TypeError):
        signature_full = ''

    objtype = str(type(obj))

    ### Get the souruce code
    import linecache
    linecache.clearcache()
    # Clear the cache. Use this function if you no longer need lines from
    # files previously read using getline().
    source = inspect.getsource(obj)  # TODO: format

    text = """
<style type="text/css">
  p {
  line-height: 1em;   /* within paragraph */
  margin-bottom: 1em; /* between paragraphs */
  }
  .signature_type {
    color:#AA2b01;
    font-weight:bold;
  }
  .myheading{
      font-weight:bold;
      color:#AA2b01;
  }
</style>
""" + f"""
{doc_text}

<p><span class="signature_type"> file:</span> {file}</p>

<hr>
<h5 class="myheading">Source code:</h5>
<p>
{source}
</p>
"""

    return text