+++ /dev/null
-#!/usr/bin/env python\r
-# -*- coding: latin-1 -*-\r
-"""Generate Python documentation in HTML or text for interactive use.\r
-\r
-In the Python interpreter, do "from pydoc import help" to provide online\r
-help. Calling help(thing) on a Python object documents the object.\r
-\r
-Or, at the shell command line outside of Python:\r
-\r
-Run "pydoc <name>" to show documentation on something. <name> may be\r
-the name of a function, module, package, or a dotted reference to a\r
-class or function within a module or module in a package. If the\r
-argument contains a path segment delimiter (e.g. slash on Unix,\r
-backslash on Windows) it is treated as the path to a Python source file.\r
-\r
-Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines\r
-of all available modules.\r
-\r
-Run "pydoc -p <port>" to start an HTTP server on a given port on the\r
-local machine to generate documentation web pages.\r
-\r
-For platforms without a command line, "pydoc -g" starts the HTTP server\r
-and also pops up a little window for controlling it.\r
-\r
-Run "pydoc -w <name>" to write out the HTML documentation for a module\r
-to a file named "<name>.html".\r
-\r
-Module docs for core modules are assumed to be in\r
-\r
- http://docs.python.org/library/\r
-\r
-This can be overridden by setting the PYTHONDOCS environment variable\r
-to a different URL or to a local directory containing the Library\r
-Reference Manual pages.\r
-"""\r
-\r
-__author__ = "Ka-Ping Yee <ping@lfw.org>"\r
-__date__ = "26 February 2001"\r
-\r
-__version__ = "$Revision$"\r
-__credits__ = """Guido van Rossum, for an excellent programming language.\r
-Tommy Burnette, the original creator of manpy.\r
-Paul Prescod, for all his work on onlinehelp.\r
-Richard Chamberlain, for the first implementation of textdoc.\r
-"""\r
-\r
-# Known bugs that can't be fixed here:\r
-# - imp.load_module() cannot be prevented from clobbering existing\r
-# loaded modules, so calling synopsis() on a binary module file\r
-# changes the contents of any existing module with the same name.\r
-# - If the __file__ attribute on a module is a relative path and\r
-# the current directory is changed with os.chdir(), an incorrect\r
-# path will be displayed.\r
-\r
-import sys, imp, os, re, types, inspect, __builtin__, pkgutil\r
-from repr import Repr\r
-from string import expandtabs, find, join, lower, split, strip, rfind, rstrip\r
-from traceback import extract_tb\r
-try:\r
- from collections import deque\r
-except ImportError:\r
- # Python 2.3 compatibility\r
- class deque(list):\r
- def popleft(self):\r
- return self.pop(0)\r
-\r
-# --------------------------------------------------------- common routines\r
-\r
-def pathdirs():\r
- """Convert sys.path into a list of absolute, existing, unique paths."""\r
- dirs = []\r
- normdirs = []\r
- for dir in sys.path:\r
- dir = os.path.abspath(dir or '.')\r
- normdir = os.path.normcase(dir)\r
- if normdir not in normdirs and os.path.isdir(dir):\r
- dirs.append(dir)\r
- normdirs.append(normdir)\r
- return dirs\r
-\r
-def getdoc(object):\r
- """Get the doc string or comments for an object."""\r
- result = inspect.getdoc(object) or inspect.getcomments(object)\r
- return result and re.sub('^ *\n', '', rstrip(result)) or ''\r
-\r
-def splitdoc(doc):\r
- """Split a doc string into a synopsis line (if any) and the rest."""\r
- lines = split(strip(doc), '\n')\r
- if len(lines) == 1:\r
- return lines[0], ''\r
- elif len(lines) >= 2 and not rstrip(lines[1]):\r
- return lines[0], join(lines[2:], '\n')\r
- return '', join(lines, '\n')\r
-\r
-def classname(object, modname):\r
- """Get a class name and qualify it with a module name if necessary."""\r
- name = object.__name__\r
- if object.__module__ != modname:\r
- name = object.__module__ + '.' + name\r
- return name\r
-\r
-def isdata(object):\r
- """Check if an object is of a type that probably means it's data."""\r
- return not (inspect.ismodule(object) or inspect.isclass(object) or\r
- inspect.isroutine(object) or inspect.isframe(object) or\r
- inspect.istraceback(object) or inspect.iscode(object))\r
-\r
-def replace(text, *pairs):\r
- """Do a series of global replacements on a string."""\r
- while pairs:\r
- text = join(split(text, pairs[0]), pairs[1])\r
- pairs = pairs[2:]\r
- return text\r
-\r
-def cram(text, maxlen):\r
- """Omit part of a string if needed to make it fit in a maximum length."""\r
- if len(text) > maxlen:\r
- pre = max(0, (maxlen-3)//2)\r
- post = max(0, maxlen-3-pre)\r
- return text[:pre] + '...' + text[len(text)-post:]\r
- return text\r
-\r
-_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)\r
-def stripid(text):\r
- """Remove the hexadecimal id from a Python object representation."""\r
- # The behaviour of %p is implementation-dependent in terms of case.\r
- return _re_stripid.sub(r'\1', text)\r
-\r
-def _is_some_method(obj):\r
- return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)\r
-\r
-def allmethods(cl):\r
- methods = {}\r
- for key, value in inspect.getmembers(cl, _is_some_method):\r
- methods[key] = 1\r
- for base in cl.__bases__:\r
- methods.update(allmethods(base)) # all your base are belong to us\r
- for key in methods.keys():\r
- methods[key] = getattr(cl, key)\r
- return methods\r
-\r
-def _split_list(s, predicate):\r
- """Split sequence s via predicate, and return pair ([true], [false]).\r
-\r
- The return value is a 2-tuple of lists,\r
- ([x for x in s if predicate(x)],\r
- [x for x in s if not predicate(x)])\r
- """\r
-\r
- yes = []\r
- no = []\r
- for x in s:\r
- if predicate(x):\r
- yes.append(x)\r
- else:\r
- no.append(x)\r
- return yes, no\r
-\r
-def visiblename(name, all=None, obj=None):\r
- """Decide whether to show documentation on a variable."""\r
- # Certain special names are redundant.\r
- _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__',\r
- '__module__', '__name__', '__slots__', '__package__')\r
- if name in _hidden_names: return 0\r
- # Private names are hidden, but special names are displayed.\r
- if name.startswith('__') and name.endswith('__'): return 1\r
- # Namedtuples have public fields and methods with a single leading underscore\r
- if name.startswith('_') and hasattr(obj, '_fields'):\r
- return 1\r
- if all is not None:\r
- # only document that which the programmer exported in __all__\r
- return name in all\r
- else:\r
- return not name.startswith('_')\r
-\r
-def classify_class_attrs(object):\r
- """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""\r
- def fixup(data):\r
- name, kind, cls, value = data\r
- if inspect.isdatadescriptor(value):\r
- kind = 'data descriptor'\r
- return name, kind, cls, value\r
- return map(fixup, inspect.classify_class_attrs(object))\r
-\r
-# ----------------------------------------------------- module manipulation\r
-\r
-def ispackage(path):\r
- """Guess whether a path refers to a package directory."""\r
- if os.path.isdir(path):\r
- for ext in ('.py', '.pyc', '.pyo'):\r
- if os.path.isfile(os.path.join(path, '__init__' + ext)):\r
- return True\r
- return False\r
-\r
-def source_synopsis(file):\r
- line = file.readline()\r
- while line[:1] == '#' or not strip(line):\r
- line = file.readline()\r
- if not line: break\r
- line = strip(line)\r
- if line[:4] == 'r"""': line = line[1:]\r
- if line[:3] == '"""':\r
- line = line[3:]\r
- if line[-1:] == '\\': line = line[:-1]\r
- while not strip(line):\r
- line = file.readline()\r
- if not line: break\r
- result = strip(split(line, '"""')[0])\r
- else: result = None\r
- return result\r
-\r
-def synopsis(filename, cache={}):\r
- """Get the one-line summary out of a module file."""\r
- mtime = os.stat(filename).st_mtime\r
- lastupdate, result = cache.get(filename, (0, None))\r
- if lastupdate < mtime:\r
- info = inspect.getmoduleinfo(filename)\r
- try:\r
- file = open(filename)\r
- except IOError:\r
- # module can't be opened, so skip it\r
- return None\r
- if info and 'b' in info[2]: # binary modules have to be imported\r
- try: module = imp.load_module('__temp__', file, filename, info[1:])\r
- except: return None\r
- result = (module.__doc__ or '').splitlines()[0]\r
- del sys.modules['__temp__']\r
- else: # text modules can be directly examined\r
- result = source_synopsis(file)\r
- file.close()\r
- cache[filename] = (mtime, result)\r
- return result\r
-\r
-class ErrorDuringImport(Exception):\r
- """Errors that occurred while trying to import something to document it."""\r
- def __init__(self, filename, exc_info):\r
- exc, value, tb = exc_info\r
- self.filename = filename\r
- self.exc = exc\r
- self.value = value\r
- self.tb = tb\r
-\r
- def __str__(self):\r
- exc = self.exc\r
- if type(exc) is types.ClassType:\r
- exc = exc.__name__\r
- return 'problem in %s - %s: %s' % (self.filename, exc, self.value)\r
-\r
-def importfile(path):\r
- """Import a Python source file or compiled file given its path."""\r
- magic = imp.get_magic()\r
- file = open(path, 'r')\r
- if file.read(len(magic)) == magic:\r
- kind = imp.PY_COMPILED\r
- else:\r
- kind = imp.PY_SOURCE\r
- file.close()\r
- filename = os.path.basename(path)\r
- name, ext = os.path.splitext(filename)\r
- file = open(path, 'r')\r
- try:\r
- module = imp.load_module(name, file, path, (ext, 'r', kind))\r
- except:\r
- raise ErrorDuringImport(path, sys.exc_info())\r
- file.close()\r
- return module\r
-\r
-def safeimport(path, forceload=0, cache={}):\r
- """Import a module; handle errors; return None if the module isn't found.\r
-\r
- If the module *is* found but an exception occurs, it's wrapped in an\r
- ErrorDuringImport exception and reraised. Unlike __import__, if a\r
- package path is specified, the module at the end of the path is returned,\r
- not the package at the beginning. If the optional 'forceload' argument\r
- is 1, we reload the module from disk (unless it's a dynamic extension)."""\r
- try:\r
- # If forceload is 1 and the module has been previously loaded from\r
- # disk, we always have to reload the module. Checking the file's\r
- # mtime isn't good enough (e.g. the module could contain a class\r
- # that inherits from another module that has changed).\r
- if forceload and path in sys.modules:\r
- if path not in sys.builtin_module_names:\r
- # Avoid simply calling reload() because it leaves names in\r
- # the currently loaded module lying around if they're not\r
- # defined in the new source file. Instead, remove the\r
- # module from sys.modules and re-import. Also remove any\r
- # submodules because they won't appear in the newly loaded\r
- # module's namespace if they're already in sys.modules.\r
- subs = [m for m in sys.modules if m.startswith(path + '.')]\r
- for key in [path] + subs:\r
- # Prevent garbage collection.\r
- cache[key] = sys.modules[key]\r
- del sys.modules[key]\r
- module = __import__(path)\r
- except:\r
- # Did the error occur before or after the module was found?\r
- (exc, value, tb) = info = sys.exc_info()\r
- if path in sys.modules:\r
- # An error occurred while executing the imported module.\r
- raise ErrorDuringImport(sys.modules[path].__file__, info)\r
- elif exc is SyntaxError:\r
- # A SyntaxError occurred before we could execute the module.\r
- raise ErrorDuringImport(value.filename, info)\r
- elif exc is ImportError and extract_tb(tb)[-1][2]=='safeimport':\r
- # The import error occurred directly in this function,\r
- # which means there is no such module in the path.\r
- return None\r
- else:\r
- # Some other error occurred during the importing process.\r
- raise ErrorDuringImport(path, sys.exc_info())\r
- for part in split(path, '.')[1:]:\r
- try: module = getattr(module, part)\r
- except AttributeError: return None\r
- return module\r
-\r
-# ---------------------------------------------------- formatter base class\r
-\r
-class Doc:\r
- def document(self, object, name=None, *args):\r
- """Generate documentation for an object."""\r
- args = (object, name) + args\r
- # 'try' clause is to attempt to handle the possibility that inspect\r
- # identifies something in a way that pydoc itself has issues handling;\r
- # think 'super' and how it is a descriptor (which raises the exception\r
- # by lacking a __name__ attribute) and an instance.\r
- if inspect.isgetsetdescriptor(object): return self.docdata(*args)\r
- if inspect.ismemberdescriptor(object): return self.docdata(*args)\r
- try:\r
- if inspect.ismodule(object): return self.docmodule(*args)\r
- if inspect.isclass(object): return self.docclass(*args)\r
- if inspect.isroutine(object): return self.docroutine(*args)\r
- except AttributeError:\r
- pass\r
- if isinstance(object, property): return self.docproperty(*args)\r
- return self.docother(*args)\r
-\r
- def fail(self, object, name=None, *args):\r
- """Raise an exception for unimplemented types."""\r
- message = "don't know how to document object%s of type %s" % (\r
- name and ' ' + repr(name), type(object).__name__)\r
- raise TypeError, message\r
-\r
- docmodule = docclass = docroutine = docother = docproperty = docdata = fail\r
-\r
- def getdocloc(self, object):\r
- """Return the location of module docs or None"""\r
-\r
- try:\r
- file = inspect.getabsfile(object)\r
- except TypeError:\r
- file = '(built-in)'\r
-\r
- docloc = os.environ.get("PYTHONDOCS",\r
- "http://docs.python.org/library")\r
- basedir = os.path.join(sys.exec_prefix, "lib",\r
- "python"+sys.version[0:3])\r
- if (isinstance(object, type(os)) and\r
- (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',\r
- 'marshal', 'posix', 'signal', 'sys',\r
- 'thread', 'zipimport') or\r
- (file.startswith(basedir) and\r
- not file.startswith(os.path.join(basedir, 'site-packages')))) and\r
- object.__name__ not in ('xml.etree', 'test.pydoc_mod')):\r
- if docloc.startswith("http://"):\r
- docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)\r
- else:\r
- docloc = os.path.join(docloc, object.__name__ + ".html")\r
- else:\r
- docloc = None\r
- return docloc\r
-\r
-# -------------------------------------------- HTML documentation generator\r
-\r
-class HTMLRepr(Repr):\r
- """Class for safely making an HTML representation of a Python object."""\r
- def __init__(self):\r
- Repr.__init__(self)\r
- self.maxlist = self.maxtuple = 20\r
- self.maxdict = 10\r
- self.maxstring = self.maxother = 100\r
-\r
- def escape(self, text):\r
- return replace(text, '&', '&', '<', '<', '>', '>')\r
-\r
- def repr(self, object):\r
- return Repr.repr(self, object)\r
-\r
- def repr1(self, x, level):\r
- if hasattr(type(x), '__name__'):\r
- methodname = 'repr_' + join(split(type(x).__name__), '_')\r
- if hasattr(self, methodname):\r
- return getattr(self, methodname)(x, level)\r
- return self.escape(cram(stripid(repr(x)), self.maxother))\r
-\r
- def repr_string(self, x, level):\r
- test = cram(x, self.maxstring)\r
- testrepr = repr(test)\r
- if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):\r
- # Backslashes are only literal in the string and are never\r
- # needed to make any special characters, so show a raw string.\r
- return 'r' + testrepr[0] + self.escape(test) + testrepr[0]\r
- return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',\r
- r'<font color="#c040c0">\1</font>',\r
- self.escape(testrepr))\r
-\r
- repr_str = repr_string\r
-\r
- def repr_instance(self, x, level):\r
- try:\r
- return self.escape(cram(stripid(repr(x)), self.maxstring))\r
- except:\r
- return self.escape('<%s instance>' % x.__class__.__name__)\r
-\r
- repr_unicode = repr_string\r
-\r
-class HTMLDoc(Doc):\r
- """Formatter class for HTML documentation."""\r
-\r
- # ------------------------------------------- HTML formatting utilities\r
-\r
- _repr_instance = HTMLRepr()\r
- repr = _repr_instance.repr\r
- escape = _repr_instance.escape\r
-\r
- def page(self, title, contents):\r
- """Format an HTML page."""\r
- return '''\r
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
-<html><head><title>Python: %s</title>\r
-</head><body bgcolor="#f0f0f8">\r
-%s\r
-</body></html>''' % (title, contents)\r
-\r
- def heading(self, title, fgcol, bgcol, extras=''):\r
- """Format a page heading."""\r
- return '''\r
-<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">\r
-<tr bgcolor="%s">\r
-<td valign=bottom> <br>\r
-<font color="%s" face="helvetica, arial"> <br>%s</font></td\r
-><td align=right valign=bottom\r
-><font color="%s" face="helvetica, arial">%s</font></td></tr></table>\r
- ''' % (bgcol, fgcol, title, fgcol, extras or ' ')\r
-\r
- def section(self, title, fgcol, bgcol, contents, width=6,\r
- prelude='', marginalia=None, gap=' '):\r
- """Format a section with a heading."""\r
- if marginalia is None:\r
- marginalia = '<tt>' + ' ' * width + '</tt>'\r
- result = '''<p>\r
-<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">\r
-<tr bgcolor="%s">\r
-<td colspan=3 valign=bottom> <br>\r
-<font color="%s" face="helvetica, arial">%s</font></td></tr>\r
- ''' % (bgcol, fgcol, title)\r
- if prelude:\r
- result = result + '''\r
-<tr bgcolor="%s"><td rowspan=2>%s</td>\r
-<td colspan=2>%s</td></tr>\r
-<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)\r
- else:\r
- result = result + '''\r
-<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)\r
-\r
- return result + '\n<td width="100%%">%s</td></tr></table>' % contents\r
-\r
- def bigsection(self, title, *args):\r
- """Format a section with a big heading."""\r
- title = '<big><strong>%s</strong></big>' % title\r
- return self.section(title, *args)\r
-\r
- def preformat(self, text):\r
- """Format literal preformatted text."""\r
- text = self.escape(expandtabs(text))\r
- return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',\r
- ' ', ' ', '\n', '<br>\n')\r
-\r
- def multicolumn(self, list, format, cols=4):\r
- """Format a list of items into a multi-column list."""\r
- result = ''\r
- rows = (len(list)+cols-1)//cols\r
- for col in range(cols):\r
- result = result + '<td width="%d%%" valign=top>' % (100//cols)\r
- for i in range(rows*col, rows*col+rows):\r
- if i < len(list):\r
- result = result + format(list[i]) + '<br>\n'\r
- result = result + '</td>'\r
- return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result\r
-\r
- def grey(self, text): return '<font color="#909090">%s</font>' % text\r
-\r
- def namelink(self, name, *dicts):\r
- """Make a link for an identifier, given name-to-URL mappings."""\r
- for dict in dicts:\r
- if name in dict:\r
- return '<a href="%s">%s</a>' % (dict[name], name)\r
- return name\r
-\r
- def classlink(self, object, modname):\r
- """Make a link for a class."""\r
- name, module = object.__name__, sys.modules.get(object.__module__)\r
- if hasattr(module, name) and getattr(module, name) is object:\r
- return '<a href="%s.html#%s">%s</a>' % (\r
- module.__name__, name, classname(object, modname))\r
- return classname(object, modname)\r
-\r
- def modulelink(self, object):\r
- """Make a link for a module."""\r
- return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)\r
-\r
- def modpkglink(self, data):\r
- """Make a link for a module or package to display in an index."""\r
- name, path, ispackage, shadowed = data\r
- if shadowed:\r
- return self.grey(name)\r
- if path:\r
- url = '%s.%s.html' % (path, name)\r
- else:\r
- url = '%s.html' % name\r
- if ispackage:\r
- text = '<strong>%s</strong> (package)' % name\r
- else:\r
- text = name\r
- return '<a href="%s">%s</a>' % (url, text)\r
-\r
- def markup(self, text, escape=None, funcs={}, classes={}, methods={}):\r
- """Mark up some plain text, given a context of symbols to look for.\r
- Each context dictionary maps object names to anchor names."""\r
- escape = escape or self.escape\r
- results = []\r
- here = 0\r
- pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'\r
- r'RFC[- ]?(\d+)|'\r
- r'PEP[- ]?(\d+)|'\r
- r'(self\.)?(\w+))')\r
- while True:\r
- match = pattern.search(text, here)\r
- if not match: break\r
- start, end = match.span()\r
- results.append(escape(text[here:start]))\r
-\r
- all, scheme, rfc, pep, selfdot, name = match.groups()\r
- if scheme:\r
- url = escape(all).replace('"', '"')\r
- results.append('<a href="%s">%s</a>' % (url, url))\r
- elif rfc:\r
- url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)\r
- results.append('<a href="%s">%s</a>' % (url, escape(all)))\r
- elif pep:\r
- url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)\r
- results.append('<a href="%s">%s</a>' % (url, escape(all)))\r
- elif text[end:end+1] == '(':\r
- results.append(self.namelink(name, methods, funcs, classes))\r
- elif selfdot:\r
- results.append('self.<strong>%s</strong>' % name)\r
- else:\r
- results.append(self.namelink(name, classes))\r
- here = end\r
- results.append(escape(text[here:]))\r
- return join(results, '')\r
-\r
- # ---------------------------------------------- type-specific routines\r
-\r
- def formattree(self, tree, modname, parent=None):\r
- """Produce HTML for a class tree as given by inspect.getclasstree()."""\r
- result = ''\r
- for entry in tree:\r
- if type(entry) is type(()):\r
- c, bases = entry\r
- result = result + '<dt><font face="helvetica, arial">'\r
- result = result + self.classlink(c, modname)\r
- if bases and bases != (parent,):\r
- parents = []\r
- for base in bases:\r
- parents.append(self.classlink(base, modname))\r
- result = result + '(' + join(parents, ', ') + ')'\r
- result = result + '\n</font></dt>'\r
- elif type(entry) is type([]):\r
- result = result + '<dd>\n%s</dd>\n' % self.formattree(\r
- entry, modname, c)\r
- return '<dl>\n%s</dl>\n' % result\r
-\r
- def docmodule(self, object, name=None, mod=None, *ignored):\r
- """Produce HTML documentation for a module object."""\r
- name = object.__name__ # ignore the passed-in name\r
- try:\r
- all = object.__all__\r
- except AttributeError:\r
- all = None\r
- parts = split(name, '.')\r
- links = []\r
- for i in range(len(parts)-1):\r
- links.append(\r
- '<a href="%s.html"><font color="#ffffff">%s</font></a>' %\r
- (join(parts[:i+1], '.'), parts[i]))\r
- linkedname = join(links + parts[-1:], '.')\r
- head = '<big><big><strong>%s</strong></big></big>' % linkedname\r
- try:\r
- path = inspect.getabsfile(object)\r
- url = path\r
- if sys.platform == 'win32':\r
- import nturl2path\r
- url = nturl2path.pathname2url(path)\r
- filelink = '<a href="file:%s">%s</a>' % (url, path)\r
- except TypeError:\r
- filelink = '(built-in)'\r
- info = []\r
- if hasattr(object, '__version__'):\r
- version = str(object.__version__)\r
- if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':\r
- version = strip(version[11:-1])\r
- info.append('version %s' % self.escape(version))\r
- if hasattr(object, '__date__'):\r
- info.append(self.escape(str(object.__date__)))\r
- if info:\r
- head = head + ' (%s)' % join(info, ', ')\r
- docloc = self.getdocloc(object)\r
- if docloc is not None:\r
- docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()\r
- else:\r
- docloc = ''\r
- result = self.heading(\r
- head, '#ffffff', '#7799ee',\r
- '<a href=".">index</a><br>' + filelink + docloc)\r
-\r
- modules = inspect.getmembers(object, inspect.ismodule)\r
-\r
- classes, cdict = [], {}\r
- for key, value in inspect.getmembers(object, inspect.isclass):\r
- # if __all__ exists, believe it. Otherwise use old heuristic.\r
- if (all is not None or\r
- (inspect.getmodule(value) or object) is object):\r
- if visiblename(key, all, object):\r
- classes.append((key, value))\r
- cdict[key] = cdict[value] = '#' + key\r
- for key, value in classes:\r
- for base in value.__bases__:\r
- key, modname = base.__name__, base.__module__\r
- module = sys.modules.get(modname)\r
- if modname != name and module and hasattr(module, key):\r
- if getattr(module, key) is base:\r
- if not key in cdict:\r
- cdict[key] = cdict[base] = modname + '.html#' + key\r
- funcs, fdict = [], {}\r
- for key, value in inspect.getmembers(object, inspect.isroutine):\r
- # if __all__ exists, believe it. Otherwise use old heuristic.\r
- if (all is not None or\r
- inspect.isbuiltin(value) or inspect.getmodule(value) is object):\r
- if visiblename(key, all, object):\r
- funcs.append((key, value))\r
- fdict[key] = '#-' + key\r
- if inspect.isfunction(value): fdict[value] = fdict[key]\r
- data = []\r
- for key, value in inspect.getmembers(object, isdata):\r
- if visiblename(key, all, object):\r
- data.append((key, value))\r
-\r
- doc = self.markup(getdoc(object), self.preformat, fdict, cdict)\r
- doc = doc and '<tt>%s</tt>' % doc\r
- result = result + '<p>%s</p>\n' % doc\r
-\r
- if hasattr(object, '__path__'):\r
- modpkgs = []\r
- for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):\r
- modpkgs.append((modname, name, ispkg, 0))\r
- modpkgs.sort()\r
- contents = self.multicolumn(modpkgs, self.modpkglink)\r
- result = result + self.bigsection(\r
- 'Package Contents', '#ffffff', '#aa55cc', contents)\r
- elif modules:\r
- contents = self.multicolumn(\r
- modules, lambda key_value, s=self: s.modulelink(key_value[1]))\r
- result = result + self.bigsection(\r
- 'Modules', '#ffffff', '#aa55cc', contents)\r
-\r
- if classes:\r
- classlist = map(lambda key_value: key_value[1], classes)\r
- contents = [\r
- self.formattree(inspect.getclasstree(classlist, 1), name)]\r
- for key, value in classes:\r
- contents.append(self.document(value, key, name, fdict, cdict))\r
- result = result + self.bigsection(\r
- 'Classes', '#ffffff', '#ee77aa', join(contents))\r
- if funcs:\r
- contents = []\r
- for key, value in funcs:\r
- contents.append(self.document(value, key, name, fdict, cdict))\r
- result = result + self.bigsection(\r
- 'Functions', '#ffffff', '#eeaa77', join(contents))\r
- if data:\r
- contents = []\r
- for key, value in data:\r
- contents.append(self.document(value, key))\r
- result = result + self.bigsection(\r
- 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))\r
- if hasattr(object, '__author__'):\r
- contents = self.markup(str(object.__author__), self.preformat)\r
- result = result + self.bigsection(\r
- 'Author', '#ffffff', '#7799ee', contents)\r
- if hasattr(object, '__credits__'):\r
- contents = self.markup(str(object.__credits__), self.preformat)\r
- result = result + self.bigsection(\r
- 'Credits', '#ffffff', '#7799ee', contents)\r
-\r
- return result\r
-\r
- def docclass(self, object, name=None, mod=None, funcs={}, classes={},\r
- *ignored):\r
- """Produce HTML documentation for a class object."""\r
- realname = object.__name__\r
- name = name or realname\r
- bases = object.__bases__\r
-\r
- contents = []\r
- push = contents.append\r
-\r
- # Cute little class to pump out a horizontal rule between sections.\r
- class HorizontalRule:\r
- def __init__(self):\r
- self.needone = 0\r
- def maybe(self):\r
- if self.needone:\r
- push('<hr>\n')\r
- self.needone = 1\r
- hr = HorizontalRule()\r
-\r
- # List the mro, if non-trivial.\r
- mro = deque(inspect.getmro(object))\r
- if len(mro) > 2:\r
- hr.maybe()\r
- push('<dl><dt>Method resolution order:</dt>\n')\r
- for base in mro:\r
- push('<dd>%s</dd>\n' % self.classlink(base,\r
- object.__module__))\r
- push('</dl>\n')\r
-\r
- def spill(msg, attrs, predicate):\r
- ok, attrs = _split_list(attrs, predicate)\r
- if ok:\r
- hr.maybe()\r
- push(msg)\r
- for name, kind, homecls, value in ok:\r
- push(self.document(getattr(object, name), name, mod,\r
- funcs, classes, mdict, object))\r
- push('\n')\r
- return attrs\r
-\r
- def spilldescriptors(msg, attrs, predicate):\r
- ok, attrs = _split_list(attrs, predicate)\r
- if ok:\r
- hr.maybe()\r
- push(msg)\r
- for name, kind, homecls, value in ok:\r
- push(self._docdescriptor(name, value, mod))\r
- return attrs\r
-\r
- def spilldata(msg, attrs, predicate):\r
- ok, attrs = _split_list(attrs, predicate)\r
- if ok:\r
- hr.maybe()\r
- push(msg)\r
- for name, kind, homecls, value in ok:\r
- base = self.docother(getattr(object, name), name, mod)\r
- if (hasattr(value, '__call__') or\r
- inspect.isdatadescriptor(value)):\r
- doc = getattr(value, "__doc__", None)\r
- else:\r
- doc = None\r
- if doc is None:\r
- push('<dl><dt>%s</dl>\n' % base)\r
- else:\r
- doc = self.markup(getdoc(value), self.preformat,\r
- funcs, classes, mdict)\r
- doc = '<dd><tt>%s</tt>' % doc\r
- push('<dl><dt>%s%s</dl>\n' % (base, doc))\r
- push('\n')\r
- return attrs\r
-\r
- attrs = filter(lambda data: visiblename(data[0], obj=object),\r
- classify_class_attrs(object))\r
- mdict = {}\r
- for key, kind, homecls, value in attrs:\r
- mdict[key] = anchor = '#' + name + '-' + key\r
- value = getattr(object, key)\r
- try:\r
- # The value may not be hashable (e.g., a data attr with\r
- # a dict or list value).\r
- mdict[value] = anchor\r
- except TypeError:\r
- pass\r
-\r
- while attrs:\r
- if mro:\r
- thisclass = mro.popleft()\r
- else:\r
- thisclass = attrs[0][2]\r
- attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)\r
-\r
- if thisclass is __builtin__.object:\r
- attrs = inherited\r
- continue\r
- elif thisclass is object:\r
- tag = 'defined here'\r
- else:\r
- tag = 'inherited from %s' % self.classlink(thisclass,\r
- object.__module__)\r
- tag += ':<br>\n'\r
-\r
- # Sort attrs by name.\r
- try:\r
- attrs.sort(key=lambda t: t[0])\r
- except TypeError:\r
- attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) # 2.3 compat\r
-\r
- # Pump out the attrs, segregated by kind.\r
- attrs = spill('Methods %s' % tag, attrs,\r
- lambda t: t[1] == 'method')\r
- attrs = spill('Class methods %s' % tag, attrs,\r
- lambda t: t[1] == 'class method')\r
- attrs = spill('Static methods %s' % tag, attrs,\r
- lambda t: t[1] == 'static method')\r
- attrs = spilldescriptors('Data descriptors %s' % tag, attrs,\r
- lambda t: t[1] == 'data descriptor')\r
- attrs = spilldata('Data and other attributes %s' % tag, attrs,\r
- lambda t: t[1] == 'data')\r
- assert attrs == []\r
- attrs = inherited\r
-\r
- contents = ''.join(contents)\r
-\r
- if name == realname:\r
- title = '<a name="%s">class <strong>%s</strong></a>' % (\r
- name, realname)\r
- else:\r
- title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (\r
- name, name, realname)\r
- if bases:\r
- parents = []\r
- for base in bases:\r
- parents.append(self.classlink(base, object.__module__))\r
- title = title + '(%s)' % join(parents, ', ')\r
- doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)\r
- doc = doc and '<tt>%s<br> </tt>' % doc\r
-\r
- return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)\r
-\r
- def formatvalue(self, object):\r
- """Format an argument default value as text."""\r
- return self.grey('=' + self.repr(object))\r
-\r
- def docroutine(self, object, name=None, mod=None,\r
- funcs={}, classes={}, methods={}, cl=None):\r
- """Produce HTML documentation for a function or method object."""\r
- realname = object.__name__\r
- name = name or realname\r
- anchor = (cl and cl.__name__ or '') + '-' + name\r
- note = ''\r
- skipdocs = 0\r
- if inspect.ismethod(object):\r
- imclass = object.im_class\r
- if cl:\r
- if imclass is not cl:\r
- note = ' from ' + self.classlink(imclass, mod)\r
- else:\r
- if object.im_self is not None:\r
- note = ' method of %s instance' % self.classlink(\r
- object.im_self.__class__, mod)\r
- else:\r
- note = ' unbound %s method' % self.classlink(imclass,mod)\r
- object = object.im_func\r
-\r
- if name == realname:\r
- title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)\r
- else:\r
- if (cl and realname in cl.__dict__ and\r
- cl.__dict__[realname] is object):\r
- reallink = '<a href="#%s">%s</a>' % (\r
- cl.__name__ + '-' + realname, realname)\r
- skipdocs = 1\r
- else:\r
- reallink = realname\r
- title = '<a name="%s"><strong>%s</strong></a> = %s' % (\r
- anchor, name, reallink)\r
- if inspect.isfunction(object):\r
- args, varargs, varkw, defaults = inspect.getargspec(object)\r
- argspec = inspect.formatargspec(\r
- args, varargs, varkw, defaults, formatvalue=self.formatvalue)\r
- if realname == '<lambda>':\r
- title = '<strong>%s</strong> <em>lambda</em> ' % name\r
- argspec = argspec[1:-1] # remove parentheses\r
- else:\r
- argspec = '(...)'\r
-\r
- decl = title + argspec + (note and self.grey(\r
- '<font face="helvetica, arial">%s</font>' % note))\r
-\r
- if skipdocs:\r
- return '<dl><dt>%s</dt></dl>\n' % decl\r
- else:\r
- doc = self.markup(\r
- getdoc(object), self.preformat, funcs, classes, methods)\r
- doc = doc and '<dd><tt>%s</tt></dd>' % doc\r
- return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)\r
-\r
- def _docdescriptor(self, name, value, mod):\r
- results = []\r
- push = results.append\r
-\r
- if name:\r
- push('<dl><dt><strong>%s</strong></dt>\n' % name)\r
- if value.__doc__ is not None:\r
- doc = self.markup(getdoc(value), self.preformat)\r
- push('<dd><tt>%s</tt></dd>\n' % doc)\r
- push('</dl>\n')\r
-\r
- return ''.join(results)\r
-\r
- def docproperty(self, object, name=None, mod=None, cl=None):\r
- """Produce html documentation for a property."""\r
- return self._docdescriptor(name, object, mod)\r
-\r
- def docother(self, object, name=None, mod=None, *ignored):\r
- """Produce HTML documentation for a data object."""\r
- lhs = name and '<strong>%s</strong> = ' % name or ''\r
- return lhs + self.repr(object)\r
-\r
- def docdata(self, object, name=None, mod=None, cl=None):\r
- """Produce html documentation for a data descriptor."""\r
- return self._docdescriptor(name, object, mod)\r
-\r
- def index(self, dir, shadowed=None):\r
- """Generate an HTML index for a directory of modules."""\r
- modpkgs = []\r
- if shadowed is None: shadowed = {}\r
- for importer, name, ispkg in pkgutil.iter_modules([dir]):\r
- modpkgs.append((name, '', ispkg, name in shadowed))\r
- shadowed[name] = 1\r
-\r
- modpkgs.sort()\r
- contents = self.multicolumn(modpkgs, self.modpkglink)\r
- return self.bigsection(dir, '#ffffff', '#ee77aa', contents)\r
-\r
-# -------------------------------------------- text documentation generator\r
-\r
-class TextRepr(Repr):\r
- """Class for safely making a text representation of a Python object."""\r
- def __init__(self):\r
- Repr.__init__(self)\r
- self.maxlist = self.maxtuple = 20\r
- self.maxdict = 10\r
- self.maxstring = self.maxother = 100\r
-\r
- def repr1(self, x, level):\r
- if hasattr(type(x), '__name__'):\r
- methodname = 'repr_' + join(split(type(x).__name__), '_')\r
- if hasattr(self, methodname):\r
- return getattr(self, methodname)(x, level)\r
- return cram(stripid(repr(x)), self.maxother)\r
-\r
- def repr_string(self, x, level):\r
- test = cram(x, self.maxstring)\r
- testrepr = repr(test)\r
- if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):\r
- # Backslashes are only literal in the string and are never\r
- # needed to make any special characters, so show a raw string.\r
- return 'r' + testrepr[0] + test + testrepr[0]\r
- return testrepr\r
-\r
- repr_str = repr_string\r
-\r
- def repr_instance(self, x, level):\r
- try:\r
- return cram(stripid(repr(x)), self.maxstring)\r
- except:\r
- return '<%s instance>' % x.__class__.__name__\r
-\r
-class TextDoc(Doc):\r
- """Formatter class for text documentation."""\r
-\r
- # ------------------------------------------- text formatting utilities\r
-\r
- _repr_instance = TextRepr()\r
- repr = _repr_instance.repr\r
-\r
- def bold(self, text):\r
- """Format a string in bold by overstriking."""\r
- return join(map(lambda ch: ch + '\b' + ch, text), '')\r
-\r
- def indent(self, text, prefix=' '):\r
- """Indent text by prepending a given prefix to each line."""\r
- if not text: return ''\r
- lines = split(text, '\n')\r
- lines = map(lambda line, prefix=prefix: prefix + line, lines)\r
- if lines: lines[-1] = rstrip(lines[-1])\r
- return join(lines, '\n')\r
-\r
- def section(self, title, contents):\r
- """Format a section with a given heading."""\r
- return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'\r
-\r
- # ---------------------------------------------- type-specific routines\r
-\r
- def formattree(self, tree, modname, parent=None, prefix=''):\r
- """Render in text a class tree as returned by inspect.getclasstree()."""\r
- result = ''\r
- for entry in tree:\r
- if type(entry) is type(()):\r
- c, bases = entry\r
- result = result + prefix + classname(c, modname)\r
- if bases and bases != (parent,):\r
- parents = map(lambda c, m=modname: classname(c, m), bases)\r
- result = result + '(%s)' % join(parents, ', ')\r
- result = result + '\n'\r
- elif type(entry) is type([]):\r
- result = result + self.formattree(\r
- entry, modname, c, prefix + ' ')\r
- return result\r
-\r
- def docmodule(self, object, name=None, mod=None):\r
- """Produce text documentation for a given module object."""\r
- name = object.__name__ # ignore the passed-in name\r
- synop, desc = splitdoc(getdoc(object))\r
- result = self.section('NAME', name + (synop and ' - ' + synop))\r
-\r
- try:\r
- all = object.__all__\r
- except AttributeError:\r
- all = None\r
-\r
- try:\r
- file = inspect.getabsfile(object)\r
- except TypeError:\r
- file = '(built-in)'\r
- result = result + self.section('FILE', file)\r
-\r
- docloc = self.getdocloc(object)\r
- if docloc is not None:\r
- result = result + self.section('MODULE DOCS', docloc)\r
-\r
- if desc:\r
- result = result + self.section('DESCRIPTION', desc)\r
-\r
- classes = []\r
- for key, value in inspect.getmembers(object, inspect.isclass):\r
- # if __all__ exists, believe it. Otherwise use old heuristic.\r
- if (all is not None\r
- or (inspect.getmodule(value) or object) is object):\r
- if visiblename(key, all, object):\r
- classes.append((key, value))\r
- funcs = []\r
- for key, value in inspect.getmembers(object, inspect.isroutine):\r
- # if __all__ exists, believe it. Otherwise use old heuristic.\r
- if (all is not None or\r
- inspect.isbuiltin(value) or inspect.getmodule(value) is object):\r
- if visiblename(key, all, object):\r
- funcs.append((key, value))\r
- data = []\r
- for key, value in inspect.getmembers(object, isdata):\r
- if visiblename(key, all, object):\r
- data.append((key, value))\r
-\r
- modpkgs = []\r
- modpkgs_names = set()\r
- if hasattr(object, '__path__'):\r
- for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):\r
- modpkgs_names.add(modname)\r
- if ispkg:\r
- modpkgs.append(modname + ' (package)')\r
- else:\r
- modpkgs.append(modname)\r
-\r
- modpkgs.sort()\r
- result = result + self.section(\r
- 'PACKAGE CONTENTS', join(modpkgs, '\n'))\r
-\r
- # Detect submodules as sometimes created by C extensions\r
- submodules = []\r
- for key, value in inspect.getmembers(object, inspect.ismodule):\r
- if value.__name__.startswith(name + '.') and key not in modpkgs_names:\r
- submodules.append(key)\r
- if submodules:\r
- submodules.sort()\r
- result = result + self.section(\r
- 'SUBMODULES', join(submodules, '\n'))\r
-\r
- if classes:\r
- classlist = map(lambda key_value: key_value[1], classes)\r
- contents = [self.formattree(\r
- inspect.getclasstree(classlist, 1), name)]\r
- for key, value in classes:\r
- contents.append(self.document(value, key, name))\r
- result = result + self.section('CLASSES', join(contents, '\n'))\r
-\r
- if funcs:\r
- contents = []\r
- for key, value in funcs:\r
- contents.append(self.document(value, key, name))\r
- result = result + self.section('FUNCTIONS', join(contents, '\n'))\r
-\r
- if data:\r
- contents = []\r
- for key, value in data:\r
- contents.append(self.docother(value, key, name, maxlen=70))\r
- result = result + self.section('DATA', join(contents, '\n'))\r
-\r
- if hasattr(object, '__version__'):\r
- version = str(object.__version__)\r
- if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':\r
- version = strip(version[11:-1])\r
- result = result + self.section('VERSION', version)\r
- if hasattr(object, '__date__'):\r
- result = result + self.section('DATE', str(object.__date__))\r
- if hasattr(object, '__author__'):\r
- result = result + self.section('AUTHOR', str(object.__author__))\r
- if hasattr(object, '__credits__'):\r
- result = result + self.section('CREDITS', str(object.__credits__))\r
- return result\r
-\r
- def docclass(self, object, name=None, mod=None, *ignored):\r
- """Produce text documentation for a given class object."""\r
- realname = object.__name__\r
- name = name or realname\r
- bases = object.__bases__\r
-\r
- def makename(c, m=object.__module__):\r
- return classname(c, m)\r
-\r
- if name == realname:\r
- title = 'class ' + self.bold(realname)\r
- else:\r
- title = self.bold(name) + ' = class ' + realname\r
- if bases:\r
- parents = map(makename, bases)\r
- title = title + '(%s)' % join(parents, ', ')\r
-\r
- doc = getdoc(object)\r
- contents = doc and [doc + '\n'] or []\r
- push = contents.append\r
-\r
- # List the mro, if non-trivial.\r
- mro = deque(inspect.getmro(object))\r
- if len(mro) > 2:\r
- push("Method resolution order:")\r
- for base in mro:\r
- push(' ' + makename(base))\r
- push('')\r
-\r
- # Cute little class to pump out a horizontal rule between sections.\r
- class HorizontalRule:\r
- def __init__(self):\r
- self.needone = 0\r
- def maybe(self):\r
- if self.needone:\r
- push('-' * 70)\r
- self.needone = 1\r
- hr = HorizontalRule()\r
-\r
- def spill(msg, attrs, predicate):\r
- ok, attrs = _split_list(attrs, predicate)\r
- if ok:\r
- hr.maybe()\r
- push(msg)\r
- for name, kind, homecls, value in ok:\r
- push(self.document(getattr(object, name),\r
- name, mod, object))\r
- return attrs\r
-\r
- def spilldescriptors(msg, attrs, predicate):\r
- ok, attrs = _split_list(attrs, predicate)\r
- if ok:\r
- hr.maybe()\r
- push(msg)\r
- for name, kind, homecls, value in ok:\r
- push(self._docdescriptor(name, value, mod))\r
- return attrs\r
-\r
- def spilldata(msg, attrs, predicate):\r
- ok, attrs = _split_list(attrs, predicate)\r
- if ok:\r
- hr.maybe()\r
- push(msg)\r
- for name, kind, homecls, value in ok:\r
- if (hasattr(value, '__call__') or\r
- inspect.isdatadescriptor(value)):\r
- doc = getdoc(value)\r
- else:\r
- doc = None\r
- push(self.docother(getattr(object, name),\r
- name, mod, maxlen=70, doc=doc) + '\n')\r
- return attrs\r
-\r
- attrs = filter(lambda data: visiblename(data[0], obj=object),\r
- classify_class_attrs(object))\r
- while attrs:\r
- if mro:\r
- thisclass = mro.popleft()\r
- else:\r
- thisclass = attrs[0][2]\r
- attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)\r
-\r
- if thisclass is __builtin__.object:\r
- attrs = inherited\r
- continue\r
- elif thisclass is object:\r
- tag = "defined here"\r
- else:\r
- tag = "inherited from %s" % classname(thisclass,\r
- object.__module__)\r
-\r
- # Sort attrs by name.\r
- attrs.sort()\r
-\r
- # Pump out the attrs, segregated by kind.\r
- attrs = spill("Methods %s:\n" % tag, attrs,\r
- lambda t: t[1] == 'method')\r
- attrs = spill("Class methods %s:\n" % tag, attrs,\r
- lambda t: t[1] == 'class method')\r
- attrs = spill("Static methods %s:\n" % tag, attrs,\r
- lambda t: t[1] == 'static method')\r
- attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,\r
- lambda t: t[1] == 'data descriptor')\r
- attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,\r
- lambda t: t[1] == 'data')\r
- assert attrs == []\r
- attrs = inherited\r
-\r
- contents = '\n'.join(contents)\r
- if not contents:\r
- return title + '\n'\r
- return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n'\r
-\r
- def formatvalue(self, object):\r
- """Format an argument default value as text."""\r
- return '=' + self.repr(object)\r
-\r
- def docroutine(self, object, name=None, mod=None, cl=None):\r
- """Produce text documentation for a function or method object."""\r
- realname = object.__name__\r
- name = name or realname\r
- note = ''\r
- skipdocs = 0\r
- if inspect.ismethod(object):\r
- imclass = object.im_class\r
- if cl:\r
- if imclass is not cl:\r
- note = ' from ' + classname(imclass, mod)\r
- else:\r
- if object.im_self is not None:\r
- note = ' method of %s instance' % classname(\r
- object.im_self.__class__, mod)\r
- else:\r
- note = ' unbound %s method' % classname(imclass,mod)\r
- object = object.im_func\r
-\r
- if name == realname:\r
- title = self.bold(realname)\r
- else:\r
- if (cl and realname in cl.__dict__ and\r
- cl.__dict__[realname] is object):\r
- skipdocs = 1\r
- title = self.bold(name) + ' = ' + realname\r
- if inspect.isfunction(object):\r
- args, varargs, varkw, defaults = inspect.getargspec(object)\r
- argspec = inspect.formatargspec(\r
- args, varargs, varkw, defaults, formatvalue=self.formatvalue)\r
- if realname == '<lambda>':\r
- title = self.bold(name) + ' lambda '\r
- argspec = argspec[1:-1] # remove parentheses\r
- else:\r
- argspec = '(...)'\r
- decl = title + argspec + note\r
-\r
- if skipdocs:\r
- return decl + '\n'\r
- else:\r
- doc = getdoc(object) or ''\r
- return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n')\r
-\r
- def _docdescriptor(self, name, value, mod):\r
- results = []\r
- push = results.append\r
-\r
- if name:\r
- push(self.bold(name))\r
- push('\n')\r
- doc = getdoc(value) or ''\r
- if doc:\r
- push(self.indent(doc))\r
- push('\n')\r
- return ''.join(results)\r
-\r
- def docproperty(self, object, name=None, mod=None, cl=None):\r
- """Produce text documentation for a property."""\r
- return self._docdescriptor(name, object, mod)\r
-\r
- def docdata(self, object, name=None, mod=None, cl=None):\r
- """Produce text documentation for a data descriptor."""\r
- return self._docdescriptor(name, object, mod)\r
-\r
- def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):\r
- """Produce text documentation for a data object."""\r
- repr = self.repr(object)\r
- if maxlen:\r
- line = (name and name + ' = ' or '') + repr\r
- chop = maxlen - len(line)\r
- if chop < 0: repr = repr[:chop] + '...'\r
- line = (name and self.bold(name) + ' = ' or '') + repr\r
- if doc is not None:\r
- line += '\n' + self.indent(str(doc))\r
- return line\r
-\r
-# --------------------------------------------------------- user interfaces\r
-\r
-def pager(text):\r
- """The first time this is called, determine what kind of pager to use."""\r
- global pager\r
- pager = getpager()\r
- pager(text)\r
-\r
-def getpager():\r
- """Decide what method to use for paging through text."""\r
- if type(sys.stdout) is not types.FileType:\r
- return plainpager\r
- if not sys.stdin.isatty() or not sys.stdout.isatty():\r
- return plainpager\r
- if 'PAGER' in os.environ:\r
- if sys.platform == 'win32': # pipes completely broken in Windows\r
- return lambda text: tempfilepager(plain(text), os.environ['PAGER'])\r
- elif sys.platform == 'uefi':\r
- return lambda text: tempfilepager(plain(text), os.environ['PAGER'])\r
- elif os.environ.get('TERM') in ('dumb', 'emacs'):\r
- return lambda text: pipepager(plain(text), os.environ['PAGER'])\r
- else:\r
- return lambda text: pipepager(text, os.environ['PAGER'])\r
- if os.environ.get('TERM') in ('dumb', 'emacs'):\r
- return plainpager\r
- if sys.platform == 'uefi':\r
- return plainpager\r
- if sys.platform == 'win32' or sys.platform.startswith('os2'):\r
- return lambda text: tempfilepager(plain(text), 'more <')\r
- if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:\r
- return lambda text: pipepager(text, 'less')\r
-\r
- import tempfile\r
- (fd, filename) = tempfile.mkstemp()\r
- os.close(fd)\r
- try:\r
- if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:\r
- return lambda text: pipepager(text, 'more')\r
- else:\r
- return ttypager\r
- finally:\r
- os.unlink(filename)\r
-\r
-def plain(text):\r
- """Remove boldface formatting from text."""\r
- return re.sub('.\b', '', text)\r
-\r
-def pipepager(text, cmd):\r
- """Page through text by feeding it to another program."""\r
- pipe = os.popen(cmd, 'w')\r
- try:\r
- pipe.write(text)\r
- pipe.close()\r
- except IOError:\r
- pass # Ignore broken pipes caused by quitting the pager program.\r
-\r
-def tempfilepager(text, cmd):\r
- """Page through text by invoking a program on a temporary file."""\r
- import tempfile\r
- filename = tempfile.mktemp()\r
- file = open(filename, 'w')\r
- file.write(text)\r
- file.close()\r
- try:\r
- os.system(cmd + ' "' + filename + '"')\r
- finally:\r
- os.unlink(filename)\r
-\r
-def ttypager(text):\r
- """Page through text on a text terminal."""\r
- lines = split(plain(text), '\n')\r
- try:\r
- import tty\r
- fd = sys.stdin.fileno()\r
- old = tty.tcgetattr(fd)\r
- tty.setcbreak(fd)\r
- getchar = lambda: sys.stdin.read(1)\r
- except (ImportError, AttributeError):\r
- tty = None\r
- getchar = lambda: sys.stdin.readline()[:-1][:1]\r
-\r
- try:\r
- r = inc = os.environ.get('LINES', 25) - 1\r
- sys.stdout.write(join(lines[:inc], '\n') + '\n')\r
- while lines[r:]:\r
- sys.stdout.write('-- more --')\r
- sys.stdout.flush()\r
- c = getchar()\r
-\r
- if c in ('q', 'Q'):\r
- sys.stdout.write('\r \r')\r
- break\r
- elif c in ('\r', '\n'):\r
- sys.stdout.write('\r \r' + lines[r] + '\n')\r
- r = r + 1\r
- continue\r
- if c in ('b', 'B', '\x1b'):\r
- r = r - inc - inc\r
- if r < 0: r = 0\r
- sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')\r
- r = r + inc\r
-\r
- finally:\r
- if tty:\r
- tty.tcsetattr(fd, tty.TCSAFLUSH, old)\r
-\r
-def plainpager(text):\r
- """Simply print unformatted text. This is the ultimate fallback."""\r
- sys.stdout.write(plain(text))\r
-\r
-def describe(thing):\r
- """Produce a short description of the given thing."""\r
- if inspect.ismodule(thing):\r
- if thing.__name__ in sys.builtin_module_names:\r
- return 'built-in module ' + thing.__name__\r
- if hasattr(thing, '__path__'):\r
- return 'package ' + thing.__name__\r
- else:\r
- return 'module ' + thing.__name__\r
- if inspect.isbuiltin(thing):\r
- return 'built-in function ' + thing.__name__\r
- if inspect.isgetsetdescriptor(thing):\r
- return 'getset descriptor %s.%s.%s' % (\r
- thing.__objclass__.__module__, thing.__objclass__.__name__,\r
- thing.__name__)\r
- if inspect.ismemberdescriptor(thing):\r
- return 'member descriptor %s.%s.%s' % (\r
- thing.__objclass__.__module__, thing.__objclass__.__name__,\r
- thing.__name__)\r
- if inspect.isclass(thing):\r
- return 'class ' + thing.__name__\r
- if inspect.isfunction(thing):\r
- return 'function ' + thing.__name__\r
- if inspect.ismethod(thing):\r
- return 'method ' + thing.__name__\r
- if type(thing) is types.InstanceType:\r
- return 'instance of ' + thing.__class__.__name__\r
- return type(thing).__name__\r
-\r
-def locate(path, forceload=0):\r
- """Locate an object by name or dotted path, importing as necessary."""\r
- parts = [part for part in split(path, '.') if part]\r
- module, n = None, 0\r
- while n < len(parts):\r
- nextmodule = safeimport(join(parts[:n+1], '.'), forceload)\r
- if nextmodule: module, n = nextmodule, n + 1\r
- else: break\r
- if module:\r
- object = module\r
- for part in parts[n:]:\r
- try: object = getattr(object, part)\r
- except AttributeError: return None\r
- return object\r
- else:\r
- if hasattr(__builtin__, path):\r
- return getattr(__builtin__, path)\r
-\r
-# --------------------------------------- interactive interpreter interface\r
-\r
-text = TextDoc()\r
-html = HTMLDoc()\r
-\r
-class _OldStyleClass: pass\r
-_OLD_INSTANCE_TYPE = type(_OldStyleClass())\r
-\r
-def resolve(thing, forceload=0):\r
- """Given an object or a path to an object, get the object and its name."""\r
- if isinstance(thing, str):\r
- object = locate(thing, forceload)\r
- if not object:\r
- raise ImportError, 'no Python documentation found for %r' % thing\r
- return object, thing\r
- else:\r
- return thing, getattr(thing, '__name__', None)\r
-\r
-def render_doc(thing, title='Python Library Documentation: %s', forceload=0):\r
- """Render text documentation, given an object or a path to an object."""\r
- object, name = resolve(thing, forceload)\r
- desc = describe(object)\r
- module = inspect.getmodule(object)\r
- if name and '.' in name:\r
- desc += ' in ' + name[:name.rfind('.')]\r
- elif module and module is not object:\r
- desc += ' in module ' + module.__name__\r
- if type(object) is _OLD_INSTANCE_TYPE:\r
- # If the passed object is an instance of an old-style class,\r
- # document its available methods instead of its value.\r
- object = object.__class__\r
- elif not (inspect.ismodule(object) or\r
- inspect.isclass(object) or\r
- inspect.isroutine(object) or\r
- inspect.isgetsetdescriptor(object) or\r
- inspect.ismemberdescriptor(object) or\r
- isinstance(object, property)):\r
- # If the passed object is a piece of data or an instance,\r
- # document its available methods instead of its value.\r
- object = type(object)\r
- desc += ' object'\r
- return title % desc + '\n\n' + text.document(object, name)\r
-\r
-def doc(thing, title='Python Library Documentation: %s', forceload=0):\r
- """Display text documentation, given an object or a path to an object."""\r
- try:\r
- pager(render_doc(thing, title, forceload))\r
- except (ImportError, ErrorDuringImport), value:\r
- print value\r
-\r
-def writedoc(thing, forceload=0):\r
- """Write HTML documentation to a file in the current directory."""\r
- try:\r
- object, name = resolve(thing, forceload)\r
- page = html.page(describe(object), html.document(object, name))\r
- file = open(name + '.html', 'w')\r
- file.write(page)\r
- file.close()\r
- print 'wrote', name + '.html'\r
- except (ImportError, ErrorDuringImport), value:\r
- print value\r
-\r
-def writedocs(dir, pkgpath='', done=None):\r
- """Write out HTML documentation for all modules in a directory tree."""\r
- if done is None: done = {}\r
- for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):\r
- writedoc(modname)\r
- return\r
-\r
-class Helper:\r
-\r
- # These dictionaries map a topic name to either an alias, or a tuple\r
- # (label, seealso-items). The "label" is the label of the corresponding\r
- # section in the .rst file under Doc/ and an index into the dictionary\r
- # in pydoc_data/topics.py.\r
- #\r
- # CAUTION: if you change one of these dictionaries, be sure to adapt the\r
- # list of needed labels in Doc/tools/sphinxext/pyspecific.py and\r
- # regenerate the pydoc_data/topics.py file by running\r
- # make pydoc-topics\r
- # in Doc/ and copying the output file into the Lib/ directory.\r
-\r
- keywords = {\r
- 'and': 'BOOLEAN',\r
- 'as': 'with',\r
- 'assert': ('assert', ''),\r
- 'break': ('break', 'while for'),\r
- 'class': ('class', 'CLASSES SPECIALMETHODS'),\r
- 'continue': ('continue', 'while for'),\r
- 'def': ('function', ''),\r
- 'del': ('del', 'BASICMETHODS'),\r
- 'elif': 'if',\r
- 'else': ('else', 'while for'),\r
- 'except': 'try',\r
- 'exec': ('exec', ''),\r
- 'finally': 'try',\r
- 'for': ('for', 'break continue while'),\r
- 'from': 'import',\r
- 'global': ('global', 'NAMESPACES'),\r
- 'if': ('if', 'TRUTHVALUE'),\r
- 'import': ('import', 'MODULES'),\r
- 'in': ('in', 'SEQUENCEMETHODS2'),\r
- 'is': 'COMPARISON',\r
- 'lambda': ('lambda', 'FUNCTIONS'),\r
- 'not': 'BOOLEAN',\r
- 'or': 'BOOLEAN',\r
- 'pass': ('pass', ''),\r
- 'print': ('print', ''),\r
- 'raise': ('raise', 'EXCEPTIONS'),\r
- 'return': ('return', 'FUNCTIONS'),\r
- 'try': ('try', 'EXCEPTIONS'),\r
- 'while': ('while', 'break continue if TRUTHVALUE'),\r
- 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),\r
- 'yield': ('yield', ''),\r
- }\r
- # Either add symbols to this dictionary or to the symbols dictionary\r
- # directly: Whichever is easier. They are merged later.\r
- _symbols_inverse = {\r
- 'STRINGS' : ("'", "'''", "r'", "u'", '"""', '"', 'r"', 'u"'),\r
- 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',\r
- '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),\r
- 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),\r
- 'UNARY' : ('-', '~'),\r
- 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',\r
- '^=', '<<=', '>>=', '**=', '//='),\r
- 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),\r
- 'COMPLEX' : ('j', 'J')\r
- }\r
- symbols = {\r
- '%': 'OPERATORS FORMATTING',\r
- '**': 'POWER',\r
- ',': 'TUPLES LISTS FUNCTIONS',\r
- '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',\r
- '...': 'ELLIPSIS',\r
- ':': 'SLICINGS DICTIONARYLITERALS',\r
- '@': 'def class',\r
- '\\': 'STRINGS',\r
- '_': 'PRIVATENAMES',\r
- '__': 'PRIVATENAMES SPECIALMETHODS',\r
- '`': 'BACKQUOTES',\r
- '(': 'TUPLES FUNCTIONS CALLS',\r
- ')': 'TUPLES FUNCTIONS CALLS',\r
- '[': 'LISTS SUBSCRIPTS SLICINGS',\r
- ']': 'LISTS SUBSCRIPTS SLICINGS'\r
- }\r
- for topic, symbols_ in _symbols_inverse.iteritems():\r
- for symbol in symbols_:\r
- topics = symbols.get(symbol, topic)\r
- if topic not in topics:\r
- topics = topics + ' ' + topic\r
- symbols[symbol] = topics\r
-\r
- topics = {\r
- 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '\r
- 'FUNCTIONS CLASSES MODULES FILES inspect'),\r
- 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING '\r
- 'TYPES'),\r
- 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),\r
- 'FORMATTING': ('formatstrings', 'OPERATORS'),\r
- 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '\r
- 'FORMATTING TYPES'),\r
- 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),\r
- 'INTEGER': ('integers', 'int range'),\r
- 'FLOAT': ('floating', 'float math'),\r
- 'COMPLEX': ('imaginary', 'complex cmath'),\r
- 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),\r
- 'MAPPINGS': 'DICTIONARIES',\r
- 'FUNCTIONS': ('typesfunctions', 'def TYPES'),\r
- 'METHODS': ('typesmethods', 'class def CLASSES TYPES'),\r
- 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),\r
- 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),\r
- 'FRAMEOBJECTS': 'TYPES',\r
- 'TRACEBACKS': 'TYPES',\r
- 'NONE': ('bltin-null-object', ''),\r
- 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),\r
- 'FILES': ('bltin-file-objects', ''),\r
- 'SPECIALATTRIBUTES': ('specialattrs', ''),\r
- 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),\r
- 'MODULES': ('typesmodules', 'import'),\r
- 'PACKAGES': 'import',\r
- 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '\r
- 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '\r
- 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '\r
- 'LISTS DICTIONARIES BACKQUOTES'),\r
- 'OPERATORS': 'EXPRESSIONS',\r
- 'PRECEDENCE': 'EXPRESSIONS',\r
- 'OBJECTS': ('objects', 'TYPES'),\r
- 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '\r
- 'CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS '\r
- 'SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),\r
- 'BASICMETHODS': ('customization', 'cmp hash repr str SPECIALMETHODS'),\r
- 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),\r
- 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),\r
- 'SEQUENCEMETHODS1': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS2 '\r
- 'SPECIALMETHODS'),\r
- 'SEQUENCEMETHODS2': ('sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 '\r
- 'SPECIALMETHODS'),\r
- 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),\r
- 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '\r
- 'SPECIALMETHODS'),\r
- 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),\r
- 'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),\r
- 'DYNAMICFEATURES': ('dynamic-features', ''),\r
- 'SCOPING': 'NAMESPACES',\r
- 'FRAMES': 'NAMESPACES',\r
- 'EXCEPTIONS': ('exceptions', 'try except finally raise'),\r
- 'COERCIONS': ('coercion-rules','CONVERSIONS'),\r
- 'CONVERSIONS': ('conversions', 'COERCIONS'),\r
- 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),\r
- 'SPECIALIDENTIFIERS': ('id-classes', ''),\r
- 'PRIVATENAMES': ('atom-identifiers', ''),\r
- 'LITERALS': ('atom-literals', 'STRINGS BACKQUOTES NUMBERS '\r
- 'TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),\r
- 'TUPLES': 'SEQUENCES',\r
- 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),\r
- 'LISTS': ('typesseq-mutable', 'LISTLITERALS'),\r
- 'LISTLITERALS': ('lists', 'LISTS LITERALS'),\r
- 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),\r
- 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),\r
- 'BACKQUOTES': ('string-conversions', 'repr str STRINGS LITERALS'),\r
- 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr '\r
- 'ATTRIBUTEMETHODS'),\r
- 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS1'),\r
- 'SLICINGS': ('slicings', 'SEQUENCEMETHODS2'),\r
- 'CALLS': ('calls', 'EXPRESSIONS'),\r
- 'POWER': ('power', 'EXPRESSIONS'),\r
- 'UNARY': ('unary', 'EXPRESSIONS'),\r
- 'BINARY': ('binary', 'EXPRESSIONS'),\r
- 'SHIFTING': ('shifting', 'EXPRESSIONS'),\r
- 'BITWISE': ('bitwise', 'EXPRESSIONS'),\r
- 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),\r
- 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),\r
- 'ASSERTION': 'assert',\r
- 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),\r
- 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),\r
- 'DELETION': 'del',\r
- 'PRINTING': 'print',\r
- 'RETURNING': 'return',\r
- 'IMPORTING': 'import',\r
- 'CONDITIONAL': 'if',\r
- 'LOOPING': ('compound', 'for while break continue'),\r
- 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),\r
- 'DEBUGGING': ('debugger', 'pdb'),\r
- 'CONTEXTMANAGERS': ('context-managers', 'with'),\r
- }\r
-\r
- def __init__(self, input=None, output=None):\r
- self._input = input\r
- self._output = output\r
-\r
- input = property(lambda self: self._input or sys.stdin)\r
- output = property(lambda self: self._output or sys.stdout)\r
-\r
- def __repr__(self):\r
- if inspect.stack()[1][3] == '?':\r
- self()\r
- return ''\r
- return '<pydoc.Helper instance>'\r
-\r
- _GoInteractive = object()\r
- def __call__(self, request=_GoInteractive):\r
- if request is not self._GoInteractive:\r
- self.help(request)\r
- else:\r
- self.intro()\r
- self.interact()\r
- self.output.write('''\r
-You are now leaving help and returning to the Python interpreter.\r
-If you want to ask for help on a particular object directly from the\r
-interpreter, you can type "help(object)". Executing "help('string')"\r
-has the same effect as typing a particular string at the help> prompt.\r
-''')\r
-\r
- def interact(self):\r
- self.output.write('\n')\r
- while True:\r
- try:\r
- request = self.getline('help> ')\r
- if not request: break\r
- except (KeyboardInterrupt, EOFError):\r
- break\r
- request = strip(replace(request, '"', '', "'", ''))\r
- if lower(request) in ('q', 'quit'): break\r
- self.help(request)\r
-\r
- def getline(self, prompt):\r
- """Read one line, using raw_input when available."""\r
- if self.input is sys.stdin:\r
- return raw_input(prompt)\r
- else:\r
- self.output.write(prompt)\r
- self.output.flush()\r
- return self.input.readline()\r
-\r
- def help(self, request):\r
- if type(request) is type(''):\r
- request = request.strip()\r
- if request == 'help': self.intro()\r
- elif request == 'keywords': self.listkeywords()\r
- elif request == 'symbols': self.listsymbols()\r
- elif request == 'topics': self.listtopics()\r
- elif request == 'modules': self.listmodules()\r
- elif request[:8] == 'modules ':\r
- self.listmodules(split(request)[1])\r
- elif request in self.symbols: self.showsymbol(request)\r
- elif request in self.keywords: self.showtopic(request)\r
- elif request in self.topics: self.showtopic(request)\r
- elif request: doc(request, 'Help on %s:')\r
- elif isinstance(request, Helper): self()\r
- else: doc(request, 'Help on %s:')\r
- self.output.write('\n')\r
-\r
- def intro(self):\r
- self.output.write('''\r
-Welcome to Python %s! This is the online help utility.\r
-\r
-If this is your first time using Python, you should definitely check out\r
-the tutorial on the Internet at http://docs.python.org/tutorial/.\r
-\r
-Enter the name of any module, keyword, or topic to get help on writing\r
-Python programs and using Python modules. To quit this help utility and\r
-return to the interpreter, just type "quit".\r
-\r
-To get a list of available modules, keywords, or topics, type "modules",\r
-"keywords", or "topics". Each module also comes with a one-line summary\r
-of what it does; to list the modules whose summaries contain a given word\r
-such as "spam", type "modules spam".\r
-''' % sys.version[:3])\r
-\r
- def list(self, items, columns=4, width=80):\r
- items = items[:]\r
- items.sort()\r
- colw = width / columns\r
- rows = (len(items) + columns - 1) / columns\r
- for row in range(rows):\r
- for col in range(columns):\r
- i = col * rows + row\r
- if i < len(items):\r
- self.output.write(items[i])\r
- if col < columns - 1:\r
- self.output.write(' ' + ' ' * (colw-1 - len(items[i])))\r
- self.output.write('\n')\r
-\r
- def listkeywords(self):\r
- self.output.write('''\r
-Here is a list of the Python keywords. Enter any keyword to get more help.\r
-\r
-''')\r
- self.list(self.keywords.keys())\r
-\r
- def listsymbols(self):\r
- self.output.write('''\r
-Here is a list of the punctuation symbols which Python assigns special meaning\r
-to. Enter any symbol to get more help.\r
-\r
-''')\r
- self.list(self.symbols.keys())\r
-\r
- def listtopics(self):\r
- self.output.write('''\r
-Here is a list of available topics. Enter any topic name to get more help.\r
-\r
-''')\r
- self.list(self.topics.keys())\r
-\r
- def showtopic(self, topic, more_xrefs=''):\r
- try:\r
- import pydoc_data.topics\r
- except ImportError:\r
- self.output.write('''\r
-Sorry, topic and keyword documentation is not available because the\r
-module "pydoc_data.topics" could not be found.\r
-''')\r
- return\r
- target = self.topics.get(topic, self.keywords.get(topic))\r
- if not target:\r
- self.output.write('no documentation found for %s\n' % repr(topic))\r
- return\r
- if type(target) is type(''):\r
- return self.showtopic(target, more_xrefs)\r
-\r
- label, xrefs = target\r
- try:\r
- doc = pydoc_data.topics.topics[label]\r
- except KeyError:\r
- self.output.write('no documentation found for %s\n' % repr(topic))\r
- return\r
- pager(strip(doc) + '\n')\r
- if more_xrefs:\r
- xrefs = (xrefs or '') + ' ' + more_xrefs\r
- if xrefs:\r
- import StringIO, formatter\r
- buffer = StringIO.StringIO()\r
- formatter.DumbWriter(buffer).send_flowing_data(\r
- 'Related help topics: ' + join(split(xrefs), ', ') + '\n')\r
- self.output.write('\n%s\n' % buffer.getvalue())\r
-\r
- def showsymbol(self, symbol):\r
- target = self.symbols[symbol]\r
- topic, _, xrefs = target.partition(' ')\r
- self.showtopic(topic, xrefs)\r
-\r
- def listmodules(self, key=''):\r
- if key:\r
- self.output.write('''\r
-Here is a list of matching modules. Enter any module name to get more help.\r
-\r
-''')\r
- apropos(key)\r
- else:\r
- self.output.write('''\r
-Please wait a moment while I gather a list of all available modules...\r
-\r
-''')\r
- modules = {}\r
- def callback(path, modname, desc, modules=modules):\r
- if modname and modname[-9:] == '.__init__':\r
- modname = modname[:-9] + ' (package)'\r
- if find(modname, '.') < 0:\r
- modules[modname] = 1\r
- def onerror(modname):\r
- callback(None, modname, None)\r
- ModuleScanner().run(callback, onerror=onerror)\r
- self.list(modules.keys())\r
- self.output.write('''\r
-Enter any module name to get more help. Or, type "modules spam" to search\r
-for modules whose descriptions contain the word "spam".\r
-''')\r
-\r
-help = Helper()\r
-\r
-class Scanner:\r
- """A generic tree iterator."""\r
- def __init__(self, roots, children, descendp):\r
- self.roots = roots[:]\r
- self.state = []\r
- self.children = children\r
- self.descendp = descendp\r
-\r
- def next(self):\r
- if not self.state:\r
- if not self.roots:\r
- return None\r
- root = self.roots.pop(0)\r
- self.state = [(root, self.children(root))]\r
- node, children = self.state[-1]\r
- if not children:\r
- self.state.pop()\r
- return self.next()\r
- child = children.pop(0)\r
- if self.descendp(child):\r
- self.state.append((child, self.children(child)))\r
- return child\r
-\r
-\r
-class ModuleScanner:\r
- """An interruptible scanner that searches module synopses."""\r
-\r
- def run(self, callback, key=None, completer=None, onerror=None):\r
- if key: key = lower(key)\r
- self.quit = False\r
- seen = {}\r
-\r
- for modname in sys.builtin_module_names:\r
- if modname != '__main__':\r
- seen[modname] = 1\r
- if key is None:\r
- callback(None, modname, '')\r
- else:\r
- desc = split(__import__(modname).__doc__ or '', '\n')[0]\r
- if find(lower(modname + ' - ' + desc), key) >= 0:\r
- callback(None, modname, desc)\r
-\r
- for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):\r
- if self.quit:\r
- break\r
- if key is None:\r
- callback(None, modname, '')\r
- else:\r
- loader = importer.find_module(modname)\r
- if hasattr(loader,'get_source'):\r
- import StringIO\r
- desc = source_synopsis(\r
- StringIO.StringIO(loader.get_source(modname))\r
- ) or ''\r
- if hasattr(loader,'get_filename'):\r
- path = loader.get_filename(modname)\r
- else:\r
- path = None\r
- else:\r
- module = loader.load_module(modname)\r
- desc = (module.__doc__ or '').splitlines()[0]\r
- path = getattr(module,'__file__',None)\r
- if find(lower(modname + ' - ' + desc), key) >= 0:\r
- callback(path, modname, desc)\r
-\r
- if completer:\r
- completer()\r
-\r
-def apropos(key):\r
- """Print all the one-line module summaries that contain a substring."""\r
- def callback(path, modname, desc):\r
- if modname[-9:] == '.__init__':\r
- modname = modname[:-9] + ' (package)'\r
- print modname, desc and '- ' + desc\r
- try: import warnings\r
- except ImportError: pass\r
- else: warnings.filterwarnings('ignore') # ignore problems during import\r
- ModuleScanner().run(callback, key)\r
-\r
-# --------------------------------------------------- web browser interface\r
-\r
-def serve(port, callback=None, completer=None):\r
- import BaseHTTPServer, mimetools, select\r
-\r
- # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.\r
- class Message(mimetools.Message):\r
- def __init__(self, fp, seekable=1):\r
- Message = self.__class__\r
- Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)\r
- self.encodingheader = self.getheader('content-transfer-encoding')\r
- self.typeheader = self.getheader('content-type')\r
- self.parsetype()\r
- self.parseplist()\r
-\r
- class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):\r
- def send_document(self, title, contents):\r
- try:\r
- self.send_response(200)\r
- self.send_header('Content-Type', 'text/html')\r
- self.end_headers()\r
- self.wfile.write(html.page(title, contents))\r
- except IOError: pass\r
-\r
- def do_GET(self):\r
- path = self.path\r
- if path[-5:] == '.html': path = path[:-5]\r
- if path[:1] == '/': path = path[1:]\r
- if path and path != '.':\r
- try:\r
- obj = locate(path, forceload=1)\r
- except ErrorDuringImport, value:\r
- self.send_document(path, html.escape(str(value)))\r
- return\r
- if obj:\r
- self.send_document(describe(obj), html.document(obj, path))\r
- else:\r
- self.send_document(path,\r
-'no Python documentation found for %s' % repr(path))\r
- else:\r
- heading = html.heading(\r
-'<big><big><strong>Python: Index of Modules</strong></big></big>',\r
-'#ffffff', '#7799ee')\r
- def bltinlink(name):\r
- return '<a href="%s.html">%s</a>' % (name, name)\r
- names = filter(lambda x: x != '__main__',\r
- sys.builtin_module_names)\r
- contents = html.multicolumn(names, bltinlink)\r
- indices = ['<p>' + html.bigsection(\r
- 'Built-in Modules', '#ffffff', '#ee77aa', contents)]\r
-\r
- seen = {}\r
- for dir in sys.path:\r
- indices.append(html.index(dir, seen))\r
- contents = heading + join(indices) + '''<p align=right>\r
-<font color="#909090" face="helvetica, arial"><strong>\r
-pydoc</strong> by Ka-Ping Yee <ping@lfw.org></font>'''\r
- self.send_document('Index of Modules', contents)\r
-\r
- def log_message(self, *args): pass\r
-\r
- class DocServer(BaseHTTPServer.HTTPServer):\r
- def __init__(self, port, callback):\r
- host = 'localhost'\r
- self.address = (host, port)\r
- self.url = 'http://%s:%d/' % (host, port)\r
- self.callback = callback\r
- self.base.__init__(self, self.address, self.handler)\r
-\r
- def serve_until_quit(self):\r
- import select\r
- self.quit = False\r
- while not self.quit:\r
- rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)\r
- if rd: self.handle_request()\r
-\r
- def server_activate(self):\r
- self.base.server_activate(self)\r
- if self.callback: self.callback(self)\r
-\r
- DocServer.base = BaseHTTPServer.HTTPServer\r
- DocServer.handler = DocHandler\r
- DocHandler.MessageClass = Message\r
- try:\r
- try:\r
- DocServer(port, callback).serve_until_quit()\r
- except (KeyboardInterrupt, select.error):\r
- pass\r
- finally:\r
- if completer: completer()\r
-\r
-# ----------------------------------------------------- graphical interface\r
-\r
-def gui():\r
- """Graphical interface (starts web server and pops up a control window)."""\r
- class GUI:\r
- def __init__(self, window, port=7464):\r
- self.window = window\r
- self.server = None\r
- self.scanner = None\r
-\r
- import Tkinter\r
- self.server_frm = Tkinter.Frame(window)\r
- self.title_lbl = Tkinter.Label(self.server_frm,\r
- text='Starting server...\n ')\r
- self.open_btn = Tkinter.Button(self.server_frm,\r
- text='open browser', command=self.open, state='disabled')\r
- self.quit_btn = Tkinter.Button(self.server_frm,\r
- text='quit serving', command=self.quit, state='disabled')\r
-\r
- self.search_frm = Tkinter.Frame(window)\r
- self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')\r
- self.search_ent = Tkinter.Entry(self.search_frm)\r
- self.search_ent.bind('<Return>', self.search)\r
- self.stop_btn = Tkinter.Button(self.search_frm,\r
- text='stop', pady=0, command=self.stop, state='disabled')\r
- if sys.platform == 'win32':\r
- # Trying to hide and show this button crashes under Windows.\r
- self.stop_btn.pack(side='right')\r
-\r
- self.window.title('pydoc')\r
- self.window.protocol('WM_DELETE_WINDOW', self.quit)\r
- self.title_lbl.pack(side='top', fill='x')\r
- self.open_btn.pack(side='left', fill='x', expand=1)\r
- self.quit_btn.pack(side='right', fill='x', expand=1)\r
- self.server_frm.pack(side='top', fill='x')\r
-\r
- self.search_lbl.pack(side='left')\r
- self.search_ent.pack(side='right', fill='x', expand=1)\r
- self.search_frm.pack(side='top', fill='x')\r
- self.search_ent.focus_set()\r
-\r
- font = ('helvetica', sys.platform == 'win32' and 8 or 10)\r
- self.result_lst = Tkinter.Listbox(window, font=font, height=6)\r
- self.result_lst.bind('<Button-1>', self.select)\r
- self.result_lst.bind('<Double-Button-1>', self.goto)\r
- self.result_scr = Tkinter.Scrollbar(window,\r
- orient='vertical', command=self.result_lst.yview)\r
- self.result_lst.config(yscrollcommand=self.result_scr.set)\r
-\r
- self.result_frm = Tkinter.Frame(window)\r
- self.goto_btn = Tkinter.Button(self.result_frm,\r
- text='go to selected', command=self.goto)\r
- self.hide_btn = Tkinter.Button(self.result_frm,\r
- text='hide results', command=self.hide)\r
- self.goto_btn.pack(side='left', fill='x', expand=1)\r
- self.hide_btn.pack(side='right', fill='x', expand=1)\r
-\r
- self.window.update()\r
- self.minwidth = self.window.winfo_width()\r
- self.minheight = self.window.winfo_height()\r
- self.bigminheight = (self.server_frm.winfo_reqheight() +\r
- self.search_frm.winfo_reqheight() +\r
- self.result_lst.winfo_reqheight() +\r
- self.result_frm.winfo_reqheight())\r
- self.bigwidth, self.bigheight = self.minwidth, self.bigminheight\r
- self.expanded = 0\r
- self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))\r
- self.window.wm_minsize(self.minwidth, self.minheight)\r
- self.window.tk.willdispatch()\r
-\r
- import threading\r
- threading.Thread(\r
- target=serve, args=(port, self.ready, self.quit)).start()\r
-\r
- def ready(self, server):\r
- self.server = server\r
- self.title_lbl.config(\r
- text='Python documentation server at\n' + server.url)\r
- self.open_btn.config(state='normal')\r
- self.quit_btn.config(state='normal')\r
-\r
- def open(self, event=None, url=None):\r
- url = url or self.server.url\r
- try:\r
- import webbrowser\r
- webbrowser.open(url)\r
- except ImportError: # pre-webbrowser.py compatibility\r
- if sys.platform == 'win32':\r
- os.system('start "%s"' % url)\r
- else:\r
- rc = os.system('netscape -remote "openURL(%s)" &' % url)\r
- if rc: os.system('netscape "%s" &' % url)\r
-\r
- def quit(self, event=None):\r
- if self.server:\r
- self.server.quit = 1\r
- self.window.quit()\r
-\r
- def search(self, event=None):\r
- key = self.search_ent.get()\r
- self.stop_btn.pack(side='right')\r
- self.stop_btn.config(state='normal')\r
- self.search_lbl.config(text='Searching for "%s"...' % key)\r
- self.search_ent.forget()\r
- self.search_lbl.pack(side='left')\r
- self.result_lst.delete(0, 'end')\r
- self.goto_btn.config(state='disabled')\r
- self.expand()\r
-\r
- import threading\r
- if self.scanner:\r
- self.scanner.quit = 1\r
- self.scanner = ModuleScanner()\r
- threading.Thread(target=self.scanner.run,\r
- args=(self.update, key, self.done)).start()\r
-\r
- def update(self, path, modname, desc):\r
- if modname[-9:] == '.__init__':\r
- modname = modname[:-9] + ' (package)'\r
- self.result_lst.insert('end',\r
- modname + ' - ' + (desc or '(no description)'))\r
-\r
- def stop(self, event=None):\r
- if self.scanner:\r
- self.scanner.quit = 1\r
- self.scanner = None\r
-\r
- def done(self):\r
- self.scanner = None\r
- self.search_lbl.config(text='Search for')\r
- self.search_lbl.pack(side='left')\r
- self.search_ent.pack(side='right', fill='x', expand=1)\r
- if sys.platform != 'win32': self.stop_btn.forget()\r
- self.stop_btn.config(state='disabled')\r
-\r
- def select(self, event=None):\r
- self.goto_btn.config(state='normal')\r
-\r
- def goto(self, event=None):\r
- selection = self.result_lst.curselection()\r
- if selection:\r
- modname = split(self.result_lst.get(selection[0]))[0]\r
- self.open(url=self.server.url + modname + '.html')\r
-\r
- def collapse(self):\r
- if not self.expanded: return\r
- self.result_frm.forget()\r
- self.result_scr.forget()\r
- self.result_lst.forget()\r
- self.bigwidth = self.window.winfo_width()\r
- self.bigheight = self.window.winfo_height()\r
- self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))\r
- self.window.wm_minsize(self.minwidth, self.minheight)\r
- self.expanded = 0\r
-\r
- def expand(self):\r
- if self.expanded: return\r
- self.result_frm.pack(side='bottom', fill='x')\r
- self.result_scr.pack(side='right', fill='y')\r
- self.result_lst.pack(side='top', fill='both', expand=1)\r
- self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))\r
- self.window.wm_minsize(self.minwidth, self.bigminheight)\r
- self.expanded = 1\r
-\r
- def hide(self, event=None):\r
- self.stop()\r
- self.collapse()\r
-\r
- import Tkinter\r
- try:\r
- root = Tkinter.Tk()\r
- # Tk will crash if pythonw.exe has an XP .manifest\r
- # file and the root has is not destroyed explicitly.\r
- # If the problem is ever fixed in Tk, the explicit\r
- # destroy can go.\r
- try:\r
- gui = GUI(root)\r
- root.mainloop()\r
- finally:\r
- root.destroy()\r
- except KeyboardInterrupt:\r
- pass\r
-\r
-# -------------------------------------------------- command-line interface\r
-\r
-def ispath(x):\r
- return isinstance(x, str) and find(x, os.sep) >= 0\r
-\r
-def cli():\r
- """Command-line interface (looks at sys.argv to decide what to do)."""\r
- import getopt\r
- class BadUsage: pass\r
-\r
- # Scripts don't get the current directory in their path by default\r
- # unless they are run with the '-m' switch\r
- if '' not in sys.path:\r
- scriptdir = os.path.dirname(sys.argv[0])\r
- if scriptdir in sys.path:\r
- sys.path.remove(scriptdir)\r
- sys.path.insert(0, '.')\r
-\r
- try:\r
- opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')\r
- writing = 0\r
-\r
- for opt, val in opts:\r
- if opt == '-g':\r
- gui()\r
- return\r
- if opt == '-k':\r
- apropos(val)\r
- return\r
- if opt == '-p':\r
- try:\r
- port = int(val)\r
- except ValueError:\r
- raise BadUsage\r
- def ready(server):\r
- print 'pydoc server ready at %s' % server.url\r
- def stopped():\r
- print 'pydoc server stopped'\r
- serve(port, ready, stopped)\r
- return\r
- if opt == '-w':\r
- writing = 1\r
-\r
- if not args: raise BadUsage\r
- for arg in args:\r
- if ispath(arg) and not os.path.exists(arg):\r
- print 'file %r does not exist' % arg\r
- break\r
- try:\r
- if ispath(arg) and os.path.isfile(arg):\r
- arg = importfile(arg)\r
- if writing:\r
- if ispath(arg) and os.path.isdir(arg):\r
- writedocs(arg)\r
- else:\r
- writedoc(arg)\r
- else:\r
- help.help(arg)\r
- except ErrorDuringImport, value:\r
- print value\r
-\r
- except (getopt.error, BadUsage):\r
- cmd = os.path.basename(sys.argv[0])\r
- print """pydoc - the Python documentation tool\r
-\r
-%s <name> ...\r
- Show text documentation on something. <name> may be the name of a\r
- Python keyword, topic, function, module, or package, or a dotted\r
- reference to a class or function within a module or module in a\r
- package. If <name> contains a '%s', it is used as the path to a\r
- Python source file to document. If name is 'keywords', 'topics',\r
- or 'modules', a listing of these things is displayed.\r
-\r
-%s -k <keyword>\r
- Search for a keyword in the synopsis lines of all available modules.\r
-\r
-%s -p <port>\r
- Start an HTTP server on the given port on the local machine.\r
-\r
-%s -g\r
- Pop up a graphical interface for finding and serving documentation.\r
-\r
-%s -w <name> ...\r
- Write out the HTML documentation for a module to a file in the current\r
- directory. If <name> contains a '%s', it is treated as a filename; if\r
- it names a directory, documentation is written for all the contents.\r
-""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)\r
-\r
-if __name__ == '__main__': cli()\r