def test_classic_class(self): class C: "Classic class" c = C() self.assertEqual(pydoc.describe(C), 'class C') self.assertEqual(pydoc.describe(c), 'instance of C') expected = 'instance of C in module %s' % __name__ self.assertIn(expected, pydoc.render_doc(c))
def dump_object(name, tmp_obj): print ">>>>>>>>>>>>>>>>>>>>>>>>>>", name, tmp_obj print describe(tmp_obj) # From line 921, method docmodule: classes = [] for key, value in inspect.getmembers(tmp_obj, inspect.isclass): if (inspect.getmodule(value) or tmp_obj) is tmp_obj: classes.append((key, value)) dump_object(key, value) funcs = [] for key, value in inspect.getmembers(tmp_obj, inspect.isroutine): if inspect.isbuiltin(value) or inspect.getmodule(value) is tmp_obj: funcs.append((key, value)) data = [] for key, value in inspect.getmembers(tmp_obj, isdata): if key not in ['__builtins__', '__doc__']: data.append((key, value)) methods = [] for key, value in inspect.getmembers(tmp_obj, inspect.ismethod): if key not in ['__builtins__', '__doc__']: methods.append((key, value)) print "C:", classes print "\nF:", funcs print "\nD:", data print "\nM:", methods for m in methods: print inspect.getargspec(m[1]), inspect.getdoc(m[1]), inspect.getcomments(m[1]) print "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
def test_classic_class(self): class C: "Classic class" c = C() self.assertEqual(pydoc.describe(C), 'class C') self.assertEqual(pydoc.describe(c), 'C') expected = 'C in module %s' % __name__ self.assertTrue(expected in pydoc.render_doc(c))
def test_class(self): class C(object): "New-style class" c = C() self.assertEqual(pydoc.describe(C), 'class C') self.assertEqual(pydoc.describe(c), 'C') expected = 'C in module %s object' % __name__ self.assertTrue(expected in pydoc.render_doc(c))
def test_classic_class(self): class C: "Classic class" c = C() self.assertEqual(pydoc.describe(C), "class C") self.assertEqual(pydoc.describe(c), "C") expected = "C in module %s" % __name__ self.assert_(expected in pydoc.render_doc(c))
def test_class(self): class C: "New-style class" c = C() self.assertEqual(pydoc.describe(C), "class C") self.assertEqual(pydoc.describe(c), "C") expected = "C in module %s object" % __name__ self.assertIn(expected, pydoc.render_doc(c))
def _generate_assertions_html(self, lang): object = pikzie.assertions.Assertions html_name = "html/assertions.html" translation = None if lang: html_name = "%s.%s" % (html_name, lang) translation = gettext.translation("pikzie", "data/locale", [lang]) print(html_name) original_getdoc = pydoc.getdoc def getdoc(object): document = original_getdoc(object) if document == "": return document else: return translation.gettext(document) if translation: pydoc.getdoc = getdoc page = pydoc.html.page(pydoc.describe(object), pydoc.html.document(object, "assertions")) pydoc.getdoc = original_getdoc html = file(html_name, "w") html.write(page.strip()) html.close()
def getdoc(thing, title='Help on %s', forceload=0): #g.trace(thing) if 1: # Both seem to work. # Redirect stdout to a "file like object". old_stdout = sys.stdout sys.stdout = fo = g.fileLikeObject() # Python's builtin help function writes to stdout. help(str(thing)) # Restore original stdout. sys.stdout = old_stdout # Return what was written to fo. return fo.get() else: # Similar to doc function from pydoc module. from pydoc import resolve, describe, inspect, text, plain object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ doc = title % desc + '\n\n' + text.document(object, name) return plain(doc)
def PrintHtml(name, things): """Print HTML documentation to stdout.""" ambiguous = len(things) > 1 content = "" for thing in things: obj, name = pydoc.resolve(thing, forceload=0) title = pydoc.describe(obj) if ambiguous: if inspect.ismethoddescriptor(obj): content += '\n\n<h2>method %s in class %s</h2>\n' % (obj.__name__, obj.__dict__) else: content += '<h2>%s in module <a href="py:%s">%s</a></h2>\n' % (title, obj.__module__, obj.__module__) content += pydoc.html.document(obj, name) if ambiguous: title = 'Matches for "%s"' % name content = '<h1>%s</h1>\n\n%s' % (title, content) page = pydoc.html.page(title, content) # Note: rewriting the anchors in a form more useful to Evergreen should be in Evergreen, not here. # The rewriting here should be generally useful to anyone or anything that needs Python documentation. # Remove a couple of useless (and seemingly broken) links. page = page.replace('<a href=".">index</a><br>', '') page = re.sub('<br><a href="[^"]+\.html">Module Docs</a>', '', page) # There's a bug in pydoc that makes it output the text of the "Modules" section in cyan instead of white. page = re.sub('"#fffff"', '"#ffffff"', page) # The explicit font specifications are unnecessary manual uglification. page = re.sub(' face="[^"]+"', '', page); sys.stdout.write(page + '\n')
def _writeclientdoc(doc, thing, forceload=0): """Write HTML documentation to a file in the current directory. """ docmodule = pydoc.HTMLDoc.docmodule def strongarm(self, object, name=None, mod=None, *ignored): result = docmodule(self, object, name, mod, *ignored) # Grab all the aliases to pyclasses and create links. nonmembers = [] push = nonmembers.append for k,v in inspect.getmembers(object, inspect.isclass): if inspect.getmodule(v) is not object and getattr(v,'typecode',None) is not None: push('<a href="%s.html">%s</a>: pyclass alias<br/>' %(v.__name__,k)) result += self.bigsection('Aliases', '#ffffff', '#eeaa77', ''.join(nonmembers)) return result pydoc.HTMLDoc.docmodule = strongarm try: object, name = pydoc.resolve(thing, forceload) page = pydoc.html.page(pydoc.describe(object), pydoc.html.document(object, name)) name = os.path.join(doc, name + '.html') file = open(name, 'w') file.write(page) file.close() except (ImportError, pydoc.ErrorDuringImport), value: log.debug(str(value))
def GenerateHTMLForModule(module): html = pydoc.html.page(pydoc.describe(module), pydoc.html.document(module, module.__name__)) # pydoc writes out html with links in a variety of funky ways. We need # to fix them up. assert not telemetry_dir.endswith(os.sep) links = re.findall('(<a href="(.+?)">(.+?)</a>)', html) for link_match in links: link, href, link_text = link_match if not href.startswith('file:'): continue new_href = href.replace('file:', '') new_href = new_href.replace(telemetry_dir, '..') new_href = new_href.replace(os.sep, '/') new_link_text = link_text.replace(telemetry_dir + os.sep, '') new_link = '<a href="%s">%s</a>' % (new_href, new_link_text) html = html.replace(link, new_link) # pydoc writes out html with absolute path file links. This is not suitable # for checked in documentation. So, fix up the HTML after it is generated. #html = re.sub('href="file:%s' % telemetry_dir, 'href="..', html) #html = re.sub(telemetry_dir + os.sep, '', html) return html
def doc2(thing, title="Python Library Documentation: %s", forceload=0): """Display text documentation, given an object or a path to an object.""" import types try: object, name = pydoc.resolve(thing, forceload) desc = pydoc.describe(object) module = mygetmodule(object) if name and "." in name: desc += " in " + name[: name.rfind(".")] elif module and module is not object: desc += " in module " + module.__name__ if not ( inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or isinstance(object, property) ): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. # if this is a instance of used defined old-style class if type(object) == types.InstanceType: object = object.__class__ else: object = type(object) desc += " object" pydoc.pager(title % desc + "\n\n" + pydoc.text.document(object, name)) except (ImportError, pydoc.ErrorDuringImport), value: print value
def writedoc(key,top=False): """Write HTML documentation to a file in the current directory.""" if(type(key) == str and (key == "modules" or key == "/.")): heading = pydoc.html.heading( '<br><big><big><strong> ' 'Python: Index of Modules' '</strong></big></big>', '#ffffff', '#7799ee') builtins = [] for name in sys.builtin_module_names: builtins.append('<a href="%s">%s</a>' % (cgi.escape(name,quote=True), cgi.escape(name))) indices = ['<p>Built-in modules: ' + cgi.escape(join(builtins, ', '))] seen = {} for dir in pydoc.pathdirs(): indices.append(pydoc.html.index(dir, seen)) print cleanlinks(heading + join(indices)) return if(type(key) != types.ModuleType): object = pydoc.locate(key) if(object == None and top): print "could not locate module/object for key " + \ cgi.escape(key) + "<br><a href=\"pydoc:modules\">go to index</a>"; else: object = key if object: print cleanlinks(pydoc.html.page(pydoc.describe(object), pydoc.html.document(object)))
def gethtmldoc(thing, forceload=0): obj, name = pydoc.resolve(thing, forceload) page = pydoc.html.page( pydoc.describe(obj), pydoc.html.document(obj, name) ) return page
def local_docs(word): import pydoc try: obj, name = pydoc.resolve(word) except ImportError: return None desc = pydoc.describe(obj) return [(desc, urljoin(pydoc_url()[0], "%s.html" % word))]
def _writebrokedoc(doc, ex, name, forceload=0): try: fname = os.path.join(doc, name + '.html') page = pydoc.html.page(pydoc.describe(ex), pydoc.html.document(str(ex), fname)) file = open(fname, 'w') file.write(page) file.close() except (ImportError, pydoc.ErrorDuringImport), value: log.debug(str(value))
def helpNonVerbose(thing, title='Python Library Documentation: %s', forceload=0): """ Utility method to return python help in the form of a string (based on the code in pydoc.py) Note: only a string (including unicode) should be passed in for "thing" """ import pydoc as pydocs import inspect import string result="" # Important for converting an incoming c++ unicode character string! thingStr=str(thing) """Display text documentation, given an object or a path to an object.""" try: # Possible two-stage object resolution! # Sometimes we get docs for strings, other times for objects # try: object, name = pydocs.resolve(thingStr, forceload) except: # Get an object from a string thingObj=eval(thingStr) object, name = pydocs.resolve(thingObj, forceload) desc = pydocs.describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or inspect.ismemberdescriptor(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' text = pydocs.TextDoc() result=pydocs.plain(title % desc + '\n\n' + text.document(object, name)) # Remove multiple empty lines result = [ line for line in result.splitlines() if line.strip() ] result = string.join(result,"\n") except: pass return result
def custom_writedoc(thing, forceload=0): """Write HTML documentation to specific directory""" try: object, name = pydoc.resolve(thing, forceload) page = pydoc.html.page(pydoc.describe(object), pydoc.html.document(object, name)) file = open(PYDOC_OUTPUT_DIR + name + '.html', 'w') file.write(page) file.close() print 'wrote', PYDOC_OUTPUT_DIR + name + '.html' except (ImportError, pydoc.ErrorDuringImport), value: print value
def _writedoc(doc, thing, forceload=0): """Write HTML documentation to a file in the current directory. """ try: object, name = pydoc.resolve(thing, forceload) page = pydoc.html.page(pydoc.describe(object), pydoc.html.document(object, name)) fname = os.path.join(doc, name + '.html') file = open(fname, 'w') file.write(page) file.close() except (ImportError, pydoc.ErrorDuringImport), value: traceback.print_exc(sys.stderr)
def insert_formatted(buf, iter, obj, heading_type_tag, inline_type_tag, value_tag): """Insert a nicely-formatted display of obj into a gtk.TextBuffer @param buf: the buffer to insert the formatted display into @param iter: the location to insert the formatted display @param obj: the object to display in the buffer @param heading_type_tag: tag to use for the object type if we are outputting a block @param inline_type_tag: tag to use for the object type if we are outputting a single line @param value_tag: the tag to use for the objects value """ text = format(obj) if text.find("\n") >= 0: insert_with_tag(buf, iter, pydoc.describe(obj), heading_type_tag) buf.insert(iter, "\n") else: insert_with_tag(buf, iter, pydoc.describe(obj), inline_type_tag) buf.insert(iter, ": ") insert_with_tag(buf, iter, text, value_tag)
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
def buildAllDocs(symbol='pyroclast'): """Recursively constructs HTML pages of documentation the given module contents, beginning with pyroclast itself, which are subsequently written to the package's 'docs/' folder. """ dd = getDocDir() obj, name = pydoc.resolve(symbol) page = pydoc.html.page(pydoc.describe(obj), pydoc.html.document(obj,name)) with open(dd + name + '.html', 'w') as f: f.write(page) if hasattr(obj, '__all__'): for a in obj.__all__: identifier = name + '.' + a child = importlib.import_module(identifier) buildAllDocs(child)
def getPython(self, w): """get python documentation This function is a modified version of DocHandler.do_GET() from pydoc.py by Ka-Ping Yee""" path = '/'.join(w) if path.endswith('.html'): path = path[:-5] if path and path != '.': try: obj = pydoc.locate(path, forceload=1) except pydoc.ErrorDuringImport, value: return 'text/html', pydoc.html.page(path, pydoc.html.escape(str(value))) print obj if obj: return 'text/html', pydoc.html.page(pydoc.describe(obj), pydoc.html.document(obj, path)) else: return 'text/html', pydoc.html.page(path, 'no Python documentation found for %s' % repr(path))
def process( self ): """Having added all of the base and/or interesting modules, proceed to generate the appropriate documentation for each module in the appropriate directory, doing the recursion as we go.""" try: while self.pending: try: if self.pending[0] in self.completed: raise AlreadyDone( self.pending[0] ) self.info( """Start %s"""% (repr(self.pending[0]))) object = pydoc.locate ( self.pending[0] ) self.info( """ ... found %s"""% (repr(object.__name__))) except AlreadyDone: pass except pydoc.ErrorDuringImport as value: self.info( """ ... FAILED %s"""% (repr( value))) self.warn( """Unable to import the module %s"""% (repr(self.pending[0]))) except (SystemError, SystemExit) as value: self.info( """ ... FAILED %s"""% (repr( value))) self.warn( """Unable to import the module %s"""% (repr(self.pending[0]))) except Exception as value: self.info( """ ... FAILED %s"""% (repr( value))) self.warn( """Unable to import the module %s"""% (repr(self.pending[0]))) else: page = self.formatter.page( pydoc.describe(object), self.formatter.docmodule( object, object.__name__, packageContext = self, ) ) file = open ( os.path.join( self.destinationDirectory, self.pending[0] + ".html", ), 'w', ) file.write(page) file.close() self.completed[ self.pending[0]] = object del self.pending[0] finally: for item in self.warnings: print(item)
def help(obj): """ Display HTML help for ``obj``, a Python object, module, etc. This help is often more extensive than that given by 'obj?'. This function does not return a value --- it prints HTML as a side effect. .. note:: This a wrapper around the built-in help. If formats the output as HTML without word wrap, which looks better in the notebook. INPUT: - ``obj`` - a Python object, module, etc. TESTS:: sage: import numpy.linalg sage: import os, sage.misc.misc ; current_dir = os.getcwd() sage: os.chdir(sage.misc.misc.tmp_dir('server_doctest')) sage: sage.server.support.help(numpy.linalg.norm) <html><table notracebacks bgcolor="#386074" cellpadding=10 cellspacing=10><tr><td bgcolor="#f5f5f5"><font color="#37546d"> <a target='_new' href='cell://docs-....html'>Click to open help window</a> <br></font></tr></td></table></html> sage: os.chdir(current_dir) """ from pydoc import resolve, html, describe import sagenb.notebook.interact as interact print '<html><table notracebacks bgcolor="#386074" cellpadding=10 cellspacing=10><tr><td bgcolor="#f5f5f5"><font color="#37546d">' object, name = resolve(obj) page = html.page(describe(object), html.document(object, name)) page = page.replace("<a href", "<a ") n = 0 while True: filename = "docs-%s.html" % n if not os.path.exists(filename): break n += 1 open(filename, "w").write(page) print " <a target='_new' href='cell://%s'>Click to open help window</a> " % filename print "<br></font></tr></td></table></html>"
def document(resource, path): print path collections = [] for name in dir(resource): if not "_" in name and callable(getattr(resource, name)) and hasattr( getattr(resource, name), '__is_resource__'): collections.append(name) obj, name = pydoc.resolve(type(resource)) page = pydoc.html.page( pydoc.describe(obj), pydoc.html.document(obj, name)) for name in collections: page = re.sub('strong>(%s)<' % name, r'strong><a href="%s">\1</a><' % (path + name + ".html"), page) for name in collections: document(getattr(resource, name)(), path + name + ".") f = open(os.path.join(BASE, path + 'html'), 'w') f.write(page) f.close()
def help(obj): """ Display help on s. .. note:: This a wrapper around the builtin help. If formats the output as HTML without word wrap, which looks better in the notebook. INPUT: - ``s`` - Python object, module, etc. OUTPUT: prints out help about s; it's often more more extensive than foo? TESTS:: sage: import numpy.linalg sage: sage.server.support.help(numpy.linalg.norm) <html><table notracebacks bgcolor="#386074" cellpadding=10 cellspacing=10><tr><td bgcolor="#f5f5f5"><font color="#37546d"> <a target='_new' href='cell://docs-....html'>Click to open help window</a> <br></font></tr></td></table></html> """ from pydoc import resolve, html, describe import sage.server.notebook.interact as interact print '<html><table notracebacks bgcolor="#386074" cellpadding=10 cellspacing=10><tr><td bgcolor="#f5f5f5"><font color="#37546d">' object, name = resolve(obj) page = html.page(describe(object), html.document(object, name)) page = page.replace('<a href','<a ') n = 0 while True: filename = 'docs-%s.html'%n if not os.path.exists(filename): break n += 1 open(filename, 'w').write(page) print " <a target='_new' href='cell://%s'>Click to open help window</a> "%filename print '<br></font></tr></td></table></html>'
def handler(req): req.content_type = "text/html" html = HTMLDoc() path = req.uri if path[-5:] == '.html': path = path[:-5] path = path.split('/')[-1] if path and path != '.': # Return documentation for an object try: obj = locate(path, forceload=1) except ErrorDuringImport, value: req.write(html.page(path, html.escape(str(value)))) return apache.OK if obj: req.write(html.page(describe(obj), html.document(obj, path))) return apache.OK else: req.write(html.page(path, 'no Python documentation found for %s' % repr(path))) return apache.OK
def doc_asstring(thing, title='Python Library Documentation: %s', forceload=0): """return text documentation as a string, given an object or a path to an object.""" try: object, name = pydoc.resolve(thing, forceload) desc = pydoc.describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or inspect.ismemberdescriptor(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' return title % desc + '\n\n' + pydoc.text.document(object, name) except (ImportError, ErrorDuringImport) as value: print(value)
def _writetypesdoc(doc, thing, forceload=0): """Write HTML documentation to a file in the current directory. """ try: object, name = pydoc.resolve(thing, forceload) name = os.path.join(doc, name + '.html') except (ImportError, pydoc.ErrorDuringImport) as value: log.debug(str(value)) return # inner classes cdict = {} fdict = {} elements_dict = {} types_dict = {} for kname, klass in inspect.getmembers(thing, inspect.isclass): if thing is not inspect.getmodule(klass): continue cdict[kname] = inspect.getmembers(klass, inspect.isclass) for iname, iklass in cdict[kname]: key = (kname, iname) fdict[key] = _writedoc(doc, iklass) if issubclass(iklass, ElementDeclaration): try: typecode = iklass() except (AttributeError, RuntimeError) as ex: elements_dict[iname] = _writebrokedoc(doc, ex, iname) continue elements_dict[iname] = None if typecode.pyclass is not None: elements_dict[iname] = _writedoc(doc, typecode.pyclass) continue if issubclass(iklass, TypeDefinition): try: typecode = iklass(None) except (AttributeError, RuntimeError) as ex: types_dict[iname] = _writebrokedoc(doc, ex, iname) continue types_dict[iname] = None if typecode.pyclass is not None: types_dict[iname] = _writedoc(doc, typecode.pyclass) continue def strongarm(self, object, name=None, mod=None, funcs={}, classes={}, *ignored): """Produce HTML documentation for a class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ object, name = pydoc.resolve(object, forceload) contents = [] push = contents.append if name == realname: title = '<a name="%s">class <strong>%s</strong></a>' % (name, realname) else: title = '<strong>%s</strong> = <a name="%s">class %s</a>' % ( name, name, realname) mdict = {} if bases: parents = [] for base in bases: parents.append(self.classlink(base, object.__module__)) title = title + '(%s)' % pydoc.join(parents, ', ') doc = self.markup(pydoc.getdoc(object), self.preformat, funcs, classes, mdict) doc = doc and '<tt>%s<br> </tt>' % doc for iname, iclass in cdict[name]: fname = fdict[(name, iname)] if iname in elements_dict: push('class <a href="%s">%s</a>: element declaration typecode<br/>'\ %(fname,iname)) pyclass = elements_dict[iname] if pyclass is not None: push('<ul>instance attributes:') push('<li><a href="%s">pyclass</a>: instances serializable to XML<br/></li>'\ %elements_dict[iname]) push('</ul>') elif iname in types_dict: push('class <a href="%s">%s</a>: type definition typecode<br/>' % (fname, iname)) pyclass = types_dict[iname] if pyclass is not None: push('<ul>instance attributes:') push('<li><a href="%s">pyclass</a>: instances serializable to XML<br/></li>'\ %types_dict[iname]) push('</ul>') else: push( 'class <a href="%s">%s</a>: TODO not sure what this is<br/>' % (fname, iname)) contents = ''.join(contents) return self.section(title, '#000000', '#ffc8d8', contents, 3, doc) doclass = pydoc.HTMLDoc.docclass pydoc.HTMLDoc.docclass = strongarm try: page = pydoc.html.page(pydoc.describe(object), pydoc.html.document(object, name)) file = open(name, 'w') file.write(page) file.close() except (ImportError, pydoc.ErrorDuringImport) as value: log.debug(str(value)) pydoc.HTMLDoc.docclass = doclass
def _render(resource): """Use pydoc helpers on an instance to generate the help documentation. """ obj, name = pydoc.resolve(type(resource)) return pydoc.html.page(pydoc.describe(obj), pydoc.html.document(obj, name))
object = pydoc.locate ( self.pending[0] ) self.info( """ ... found %s"""% (repr(object.__name__))) except AlreadyDone: pass except pydoc.ErrorDuringImport, value: self.info( """ ... FAILED %s"""% (repr( value))) self.warn( """Unable to import the module %s"""% (repr(self.pending[0]))) except (SystemError, SystemExit), value: self.info( """ ... FAILED %s"""% (repr( value))) self.warn( """Unable to import the module %s"""% (repr(self.pending[0]))) except Exception, value: self.info( """ ... FAILED %s"""% (repr( value))) self.warn( """Unable to import the module %s"""% (repr(self.pending[0]))) else: page = self.formatter.page( pydoc.describe(object), self.formatter.docmodule( object, object.__name__, packageContext = self, ) ) file = open ( os.path.join( self.destinationDirectory, self.pending[0] + ".html", ), 'w', ) file.write(page) file.close()
push('<li><a href="%s">pyclass</a>: instances serializable to XML<br/></li>'\ %types_dict[iname]) push('</ul>') else: push( 'class <a href="%s">%s</a>: TODO not sure what this is<br/>' % (fname, iname)) contents = ''.join(contents) return self.section(title, '#000000', '#ffc8d8', contents, 3, doc) doclass = pydoc.HTMLDoc.docclass pydoc.HTMLDoc.docclass = strongarm try: page = pydoc.html.page(pydoc.describe(object), pydoc.html.document(object, name)) file = open(name, 'w') file.write(page) file.close() except (ImportError, pydoc.ErrorDuringImport), value: log.debug(str(value)) pydoc.HTMLDoc.docclass = doclass def _writebrokedoc(doc, ex, name, forceload=0): try: fname = os.path.join(doc, name + '.html') page = pydoc.html.page(pydoc.describe(ex), pydoc.html.document(str(ex), fname))
def moduleGetHelp(module): """Fetch HTML documentation on some module.""" return pydoc.html.page(pydoc.describe(module), pydoc.html.document(module, module.__name__))
def fun2(self): '''fun2 description''' print('function2') def doc(self, name): return pydoc.help(name) obj = testclass() aaa = obj.doc(obj.fun1) members = dir(obj) print('#' * 16) pydoc.Doc() des = pydoc.describe(obj) print(des) print('#' * 16) for m in sorted(members): if m.startswith('__'): pass else: print(m + '\n\t') fundef = inspect.getsource(eval('obj.%s' % m)) fundefstr = fundef[:fundef.find(':')] listoffun = fundef.split('\n') print(fundefstr) ret = eval('obj.%s.__doc__' % m) if ret: print('\t' + '\n\t'.join(ret.split('\n')))
def helpNonVerbose(thing, title='Python Library Documentation: %s', forceload=0): """ Utility method to return python help in the form of a string thing - str or unicode name to get help on title - format string for help result forceload - argument to pydoc.resolve, force object's module to be reloaded from file returns formated help string """ result = "" try: thingStr = thing.encode(cmds.about(codeset=True)) except: thingStr = str(thing) try: # Possible two-stage object resolution! # Sometimes we get docs for strings, other times for objects # try: object, name = pydoc.resolve(thingStr, forceload) except: # Get an object from a string thingObj = eval(thingStr, sys.modules['__main__'].__dict__) object, name = pydoc.resolve(thingObj, forceload) desc = pydoc.describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ doc = None text = pydoc.TextDoc() if not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or inspect.ismemberdescriptor(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' # if the object is a maya command without a proper docstring, # then tack on the help for it elif module is cmds and inspect.isroutine(object): try: if len(object.__doc__) == 0: doc = cmds.help(object.__name__) except: pass if not doc: doc = text.document(object, name) result = pydoc.plain(title % desc + '\n\n' + doc) # Remove multiple empty lines result = "\n".join( [line for line in result.splitlines() if line.strip()]) except: pass return result
import os import importlib import morning def getDocDir(): """Returns the absolute path to the documentation directory of the pyroclast package (where this file is located). """ return os.path.dirname(os.path.realpath(__file__)) + os.sep def buildAllDocs(symbol=None): """Recursively constructs HTML pages of documentation the given module contents, beginning with the package itself, which are subsequently written to the package's 'docs/' folder. """ if symbol is None: symbol = morning dd = getDocDir() obj, name = pydoc.resolve(symbol) page = pydoc.html.page(pydoc.describe(obj), pydoc.html.document(obj,name)) with open(dd + name + '.html', 'w') as f: f.write(page) if hasattr(obj, '__all__'): for a in obj.__all__: identifier = name + '.' + a child = importlib.import_module(identifier) buildAllDocs(child) if __name__ == '__main__': buildAllDocs()
def gethtmldoc(thing, forceload=0): obj, name = pydoc.resolve(thing, forceload) page = pydoc.html.page(pydoc.describe(obj), pydoc.html.document(obj, name)) return page
#See inviwo/modules/python3/scripts/documentgenerator.py import inviwopy import pydoc page = pydoc.html.page(pydoc.describe(inviwopy), pydoc.html.document(inviwopy, 'inviwopy')) path = inviwopy.app.getPath(inviwopy.PathType.Help , "/inviwopy.html" ) with open(path,'w') as file: print(page,file=file) page = pydoc.html.page(pydoc.describe(inviwopy.glm), pydoc.html.document(inviwopy.glm, 'inviwopy.glm')) path = inviwopy.app.getPath(inviwopy.PathType.Help , "/inviwopy.glm.html" ) with open(path,'w') as file: print(page,file=file) page = pydoc.html.page(pydoc.describe(inviwopy.qt), pydoc.html.document(inviwopy.glm, 'inviwopy.qt')) path = inviwopy.app.getPath(inviwopy.PathType.Help , "/inviwopy.qt.html" ) with open(path,'w') as file: print(page,file=file) page = pydoc.html.page(pydoc.describe(inviwopy.data), pydoc.html.document(inviwopy.data, 'inviwopy.data')) path = inviwopy.app.getPath(inviwopy.PathType.Help , "/inviwopy.data.html" ) with open(path,'w') as file: print(page,file=file) page = pydoc.html.page(pydoc.describe(inviwopy.data.formats), pydoc.html.document(inviwopy.data.formats, 'inviwopy.data.formats')) path = inviwopy.app.getPath(inviwopy.PathType.Help , "/inviwopy.data.formats.html" ) with open(path,'w') as file: