home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / pydoc.py < prev    next >
Encoding:
Python Source  |  2007-04-12  |  89.1 KB  |  2,279 lines

  1. #! /usr/bin/python2.4
  2. # -*- coding: Latin-1 -*-
  3. """Generate Python documentation in HTML or text for interactive use.
  4.  
  5. In the Python interpreter, do "from pydoc import help" to provide online
  6. help.  Calling help(thing) on a Python object documents the object.
  7.  
  8. Or, at the shell command line outside of Python:
  9.  
  10. Run "pydoc <name>" to show documentation on something.  <name> may be
  11. the name of a function, module, package, or a dotted reference to a
  12. class or function within a module or module in a package.  If the
  13. argument contains a path segment delimiter (e.g. slash on Unix,
  14. backslash on Windows) it is treated as the path to a Python source file.
  15.  
  16. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
  17. of all available modules.
  18.  
  19. Run "pydoc -p <port>" to start an HTTP server on a given port on the
  20. local machine to generate documentation web pages.
  21.  
  22. For platforms without a command line, "pydoc -g" starts the HTTP server
  23. and also pops up a little window for controlling it.
  24.  
  25. Run "pydoc -w <name>" to write out the HTML documentation for a module
  26. to a file named "<name>.html".
  27.  
  28. Module docs for core modules are assumed to be in
  29.  
  30.     http://www.python.org/doc/current/lib/
  31.  
  32. This can be overridden by setting the PYTHONDOCS environment variable
  33. to a different URL or to a local directory containing the Library
  34. Reference Manual pages.
  35. """
  36.  
  37. __author__ = "Ka-Ping Yee <ping@lfw.org>"
  38. __date__ = "26 February 2001"
  39. __version__ = "$Revision: 43347 $"
  40. __credits__ = """Guido van Rossum, for an excellent programming language.
  41. Tommy Burnette, the original creator of manpy.
  42. Paul Prescod, for all his work on onlinehelp.
  43. Richard Chamberlain, for the first implementation of textdoc.
  44. """
  45.  
  46. # Known bugs that can't be fixed here:
  47. #   - imp.load_module() cannot be prevented from clobbering existing
  48. #     loaded modules, so calling synopsis() on a binary module file
  49. #     changes the contents of any existing module with the same name.
  50. #   - If the __file__ attribute on a module is a relative path and
  51. #     the current directory is changed with os.chdir(), an incorrect
  52. #     path will be displayed.
  53.  
  54. import sys, imp, os, re, types, inspect, __builtin__
  55. from repr import Repr
  56. from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
  57. from collections import deque
  58.  
  59. # --------------------------------------------------------- common routines
  60.  
  61. def pathdirs():
  62.     """Convert sys.path into a list of absolute, existing, unique paths."""
  63.     dirs = []
  64.     normdirs = []
  65.     for dir in sys.path:
  66.         dir = os.path.abspath(dir or '.')
  67.         normdir = os.path.normcase(dir)
  68.         if normdir not in normdirs and os.path.isdir(dir):
  69.             dirs.append(dir)
  70.             normdirs.append(normdir)
  71.     return dirs
  72.  
  73. def getdoc(object):
  74.     """Get the doc string or comments for an object."""
  75.     result = inspect.getdoc(object) or inspect.getcomments(object)
  76.     return result and re.sub('^ *\n', '', rstrip(result)) or ''
  77.  
  78. def splitdoc(doc):
  79.     """Split a doc string into a synopsis line (if any) and the rest."""
  80.     lines = split(strip(doc), '\n')
  81.     if len(lines) == 1:
  82.         return lines[0], ''
  83.     elif len(lines) >= 2 and not rstrip(lines[1]):
  84.         return lines[0], join(lines[2:], '\n')
  85.     return '', join(lines, '\n')
  86.  
  87. def classname(object, modname):
  88.     """Get a class name and qualify it with a module name if necessary."""
  89.     name = object.__name__
  90.     if object.__module__ != modname:
  91.         name = object.__module__ + '.' + name
  92.     return name
  93.  
  94. def isdata(object):
  95.     """Check if an object is of a type that probably means it's data."""
  96.     return not (inspect.ismodule(object) or inspect.isclass(object) or
  97.                 inspect.isroutine(object) or inspect.isframe(object) or
  98.                 inspect.istraceback(object) or inspect.iscode(object))
  99.  
  100. def replace(text, *pairs):
  101.     """Do a series of global replacements on a string."""
  102.     while pairs:
  103.         text = join(split(text, pairs[0]), pairs[1])
  104.         pairs = pairs[2:]
  105.     return text
  106.  
  107. def cram(text, maxlen):
  108.     """Omit part of a string if needed to make it fit in a maximum length."""
  109.     if len(text) > maxlen:
  110.         pre = max(0, (maxlen-3)//2)
  111.         post = max(0, maxlen-3-pre)
  112.         return text[:pre] + '...' + text[len(text)-post:]
  113.     return text
  114.  
  115. _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
  116. def stripid(text):
  117.     """Remove the hexadecimal id from a Python object representation."""
  118.     # The behaviour of %p is implementation-dependent in terms of case.
  119.     if _re_stripid.search(repr(Exception)):
  120.         return _re_stripid.sub(r'\1', text)
  121.     return text
  122.  
  123. def _is_some_method(obj):
  124.     return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)
  125.  
  126. def allmethods(cl):
  127.     methods = {}
  128.     for key, value in inspect.getmembers(cl, _is_some_method):
  129.         methods[key] = 1
  130.     for base in cl.__bases__:
  131.         methods.update(allmethods(base)) # all your base are belong to us
  132.     for key in methods.keys():
  133.         methods[key] = getattr(cl, key)
  134.     return methods
  135.  
  136. def _split_list(s, predicate):
  137.     """Split sequence s via predicate, and return pair ([true], [false]).
  138.  
  139.     The return value is a 2-tuple of lists,
  140.         ([x for x in s if predicate(x)],
  141.          [x for x in s if not predicate(x)])
  142.     """
  143.  
  144.     yes = []
  145.     no = []
  146.     for x in s:
  147.         if predicate(x):
  148.             yes.append(x)
  149.         else:
  150.             no.append(x)
  151.     return yes, no
  152.  
  153. def visiblename(name, all=None):
  154.     """Decide whether to show documentation on a variable."""
  155.     # Certain special names are redundant.
  156.     if name in ['__builtins__', '__doc__', '__file__', '__path__',
  157.                 '__module__', '__name__']: return 0
  158.     # Private names are hidden, but special names are displayed.
  159.     if name.startswith('__') and name.endswith('__'): return 1
  160.     if all is not None:
  161.         # only document that which the programmer exported in __all__
  162.         return name in all
  163.     else:
  164.         return not name.startswith('_')
  165.  
  166. # ----------------------------------------------------- module manipulation
  167.  
  168. def ispackage(path):
  169.     """Guess whether a path refers to a package directory."""
  170.     if os.path.isdir(path):
  171.         for ext in ['.py', '.pyc', '.pyo']:
  172.             if os.path.isfile(os.path.join(path, '__init__' + ext)):
  173.                 return True
  174.     return False
  175.  
  176. def synopsis(filename, cache={}):
  177.     """Get the one-line summary out of a module file."""
  178.     mtime = os.stat(filename).st_mtime
  179.     lastupdate, result = cache.get(filename, (0, None))
  180.     if lastupdate < mtime:
  181.         info = inspect.getmoduleinfo(filename)
  182.         try:
  183.             file = open(filename)
  184.         except IOError:
  185.             # module can't be opened, so skip it
  186.             return None
  187.         if info and 'b' in info[2]: # binary modules have to be imported
  188.             try: module = imp.load_module('__temp__', file, filename, info[1:])
  189.             except: return None
  190.             result = split(module.__doc__ or '', '\n')[0]
  191.             del sys.modules['__temp__']
  192.         else: # text modules can be directly examined
  193.             line = file.readline()
  194.             while line[:1] == '#' or not strip(line):
  195.                 line = file.readline()
  196.                 if not line: break
  197.             line = strip(line)
  198.             if line[:4] == 'r"""': line = line[1:]
  199.             if line[:3] == '"""':
  200.                 line = line[3:]
  201.                 if line[-1:] == '\\': line = line[:-1]
  202.                 while not strip(line):
  203.                     line = file.readline()
  204.                     if not line: break
  205.                 result = strip(split(line, '"""')[0])
  206.             else: result = None
  207.         file.close()
  208.         cache[filename] = (mtime, result)
  209.     return result
  210.  
  211. class ErrorDuringImport(Exception):
  212.     """Errors that occurred while trying to import something to document it."""
  213.     def __init__(self, filename, (exc, value, tb)):
  214.         self.filename = filename
  215.         self.exc = exc
  216.         self.value = value
  217.         self.tb = tb
  218.  
  219.     def __str__(self):
  220.         exc = self.exc
  221.         if type(exc) is types.ClassType:
  222.             exc = exc.__name__
  223.         return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
  224.  
  225. def importfile(path):
  226.     """Import a Python source file or compiled file given its path."""
  227.     magic = imp.get_magic()
  228.     file = open(path, 'r')
  229.     if file.read(len(magic)) == magic:
  230.         kind = imp.PY_COMPILED
  231.     else:
  232.         kind = imp.PY_SOURCE
  233.     file.close()
  234.     filename = os.path.basename(path)
  235.     name, ext = os.path.splitext(filename)
  236.     file = open(path, 'r')
  237.     try:
  238.         module = imp.load_module(name, file, path, (ext, 'r', kind))
  239.     except:
  240.         raise ErrorDuringImport(path, sys.exc_info())
  241.     file.close()
  242.     return module
  243.  
  244. def safeimport(path, forceload=0, cache={}):
  245.     """Import a module; handle errors; return None if the module isn't found.
  246.  
  247.     If the module *is* found but an exception occurs, it's wrapped in an
  248.     ErrorDuringImport exception and reraised.  Unlike __import__, if a
  249.     package path is specified, the module at the end of the path is returned,
  250.     not the package at the beginning.  If the optional 'forceload' argument
  251.     is 1, we reload the module from disk (unless it's a dynamic extension)."""
  252.     try:
  253.         # If forceload is 1 and the module has been previously loaded from
  254.         # disk, we always have to reload the module.  Checking the file's
  255.         # mtime isn't good enough (e.g. the module could contain a class
  256.         # that inherits from another module that has changed).
  257.         if forceload and path in sys.modules:
  258.             if path not in sys.builtin_module_names:
  259.                 # Avoid simply calling reload() because it leaves names in
  260.                 # the currently loaded module lying around if they're not
  261.                 # defined in the new source file.  Instead, remove the
  262.                 # module from sys.modules and re-import.  Also remove any
  263.                 # submodules because they won't appear in the newly loaded
  264.                 # module's namespace if they're already in sys.modules.
  265.                 subs = [m for m in sys.modules if m.startswith(path + '.')]
  266.                 for key in [path] + subs:
  267.                     # Prevent garbage collection.
  268.                     cache[key] = sys.modules[key]
  269.                     del sys.modules[key]
  270.         module = __import__(path)
  271.     except:
  272.         # Did the error occur before or after the module was found?
  273.         (exc, value, tb) = info = sys.exc_info()
  274.         if path in sys.modules:
  275.             # An error occurred while executing the imported module.
  276.             raise ErrorDuringImport(sys.modules[path].__file__, info)
  277.         elif exc is SyntaxError:
  278.             # A SyntaxError occurred before we could execute the module.
  279.             raise ErrorDuringImport(value.filename, info)
  280.         elif exc is ImportError and \
  281.              split(lower(str(value)))[:2] == ['no', 'module']:
  282.             # The module was not found.
  283.             return None
  284.         else:
  285.             # Some other error occurred during the importing process.
  286.             raise ErrorDuringImport(path, sys.exc_info())
  287.     for part in split(path, '.')[1:]:
  288.         try: module = getattr(module, part)
  289.         except AttributeError: return None
  290.     return module
  291.  
  292. # ---------------------------------------------------- formatter base class
  293.  
  294. class Doc:
  295.     def document(self, object, name=None, *args):
  296.         """Generate documentation for an object."""
  297.         args = (object, name) + args
  298.         # 'try' clause is to attempt to handle the possibility that inspect
  299.         # identifies something in a way that pydoc itself has issues handling;
  300.         # think 'super' and how it is a descriptor (which raises the exception
  301.         # by lacking a __name__ attribute) and an instance.
  302.         try:
  303.             if inspect.ismodule(object): return self.docmodule(*args)
  304.             if inspect.isclass(object): return self.docclass(*args)
  305.             if inspect.isroutine(object): return self.docroutine(*args)
  306.         except AttributeError:
  307.             pass
  308.         if isinstance(object, property): return self.docproperty(*args)
  309.         return self.docother(*args)
  310.  
  311.     def fail(self, object, name=None, *args):
  312.         """Raise an exception for unimplemented types."""
  313.         message = "don't know how to document object%s of type %s" % (
  314.             name and ' ' + repr(name), type(object).__name__)
  315.         raise TypeError, message
  316.  
  317.     docmodule = docclass = docroutine = docother = fail
  318.  
  319.     def getdocloc(self, object):
  320.         """Return the location of module docs or None"""
  321.  
  322.         try:
  323.             file = inspect.getabsfile(object)
  324.         except TypeError:
  325.             file = '(built-in)'
  326.  
  327.         docloc = os.environ.get("PYTHONDOCS",
  328.                                 "http://www.python.org/doc/current/lib")
  329.         basedir = os.path.join(sys.exec_prefix, "lib",
  330.                                "python"+sys.version[0:3])
  331.         if (isinstance(object, type(os)) and
  332.             (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
  333.                                  'marshal', 'posix', 'signal', 'sys',
  334.                                  'thread', 'zipimport') or
  335.              (file.startswith(basedir) and
  336.               not file.startswith(os.path.join(basedir, 'site-packages'))))):
  337.             htmlfile = "module-%s.html" % object.__name__
  338.             if docloc.startswith("http://"):
  339.                 docloc = "%s/%s" % (docloc.rstrip("/"), htmlfile)
  340.             else:
  341.                 docloc = os.path.join(docloc, htmlfile)
  342.         else:
  343.             docloc = None
  344.         return docloc
  345.  
  346. # -------------------------------------------- HTML documentation generator
  347.  
  348. class HTMLRepr(Repr):
  349.     """Class for safely making an HTML representation of a Python object."""
  350.     def __init__(self):
  351.         Repr.__init__(self)
  352.         self.maxlist = self.maxtuple = 20
  353.         self.maxdict = 10
  354.         self.maxstring = self.maxother = 100
  355.  
  356.     def escape(self, text):
  357.         return replace(text, '&', '&', '<', '<', '>', '>')
  358.  
  359.     def repr(self, object):
  360.         return Repr.repr(self, object)
  361.  
  362.     def repr1(self, x, level):
  363.         if hasattr(type(x), '__name__'):
  364.             methodname = 'repr_' + join(split(type(x).__name__), '_')
  365.             if hasattr(self, methodname):
  366.                 return getattr(self, methodname)(x, level)
  367.         return self.escape(cram(stripid(repr(x)), self.maxother))
  368.  
  369.     def repr_string(self, x, level):
  370.         test = cram(x, self.maxstring)
  371.         testrepr = repr(test)
  372.         if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  373.             # Backslashes are only literal in the string and are never
  374.             # needed to make any special characters, so show a raw string.
  375.             return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
  376.         return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
  377.                       r'<font color="#c040c0">\1</font>',
  378.                       self.escape(testrepr))
  379.  
  380.     repr_str = repr_string
  381.  
  382.     def repr_instance(self, x, level):
  383.         try:
  384.             return self.escape(cram(stripid(repr(x)), self.maxstring))
  385.         except:
  386.             return self.escape('<%s instance>' % x.__class__.__name__)
  387.  
  388.     repr_unicode = repr_string
  389.  
  390. class HTMLDoc(Doc):
  391.     """Formatter class for HTML documentation."""
  392.  
  393.     # ------------------------------------------- HTML formatting utilities
  394.  
  395.     _repr_instance = HTMLRepr()
  396.     repr = _repr_instance.repr
  397.     escape = _repr_instance.escape
  398.  
  399.     def page(self, title, contents):
  400.         """Format an HTML page."""
  401.         return '''
  402. <!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  403. <html><head><title>Python: %s</title>
  404. </head><body bgcolor="#f0f0f8">
  405. %s
  406. </body></html>''' % (title, contents)
  407.  
  408.     def heading(self, title, fgcol, bgcol, extras=''):
  409.         """Format a page heading."""
  410.         return '''
  411. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
  412. <tr bgcolor="%s">
  413. <td valign=bottom> <br>
  414. <font color="%s" face="helvetica, arial"> <br>%s</font></td
  415. ><td align=right valign=bottom
  416. ><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
  417.     ''' % (bgcol, fgcol, title, fgcol, extras or ' ')
  418.  
  419.     def section(self, title, fgcol, bgcol, contents, width=6,
  420.                 prelude='', marginalia=None, gap=' '):
  421.         """Format a section with a heading."""
  422.         if marginalia is None:
  423.             marginalia = '<tt>' + ' ' * width + '</tt>'
  424.         result = '''<p>
  425. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  426. <tr bgcolor="%s">
  427. <td colspan=3 valign=bottom> <br>
  428. <font color="%s" face="helvetica, arial">%s</font></td></tr>
  429.     ''' % (bgcol, fgcol, title)
  430.         if prelude:
  431.             result = result + '''
  432. <tr bgcolor="%s"><td rowspan=2>%s</td>
  433. <td colspan=2>%s</td></tr>
  434. <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
  435.         else:
  436.             result = result + '''
  437. <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
  438.  
  439.         return result + '\n<td width="100%%">%s</td></tr></table>' % contents
  440.  
  441.     def bigsection(self, title, *args):
  442.         """Format a section with a big heading."""
  443.         title = '<big><strong>%s</strong></big>' % title
  444.         return self.section(title, *args)
  445.  
  446.     def preformat(self, text):
  447.         """Format literal preformatted text."""
  448.         text = self.escape(expandtabs(text))
  449.         return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
  450.                              ' ', ' ', '\n', '<br>\n')
  451.  
  452.     def multicolumn(self, list, format, cols=4):
  453.         """Format a list of items into a multi-column list."""
  454.         result = ''
  455.         rows = (len(list)+cols-1)/cols
  456.         for col in range(cols):
  457.             result = result + '<td width="%d%%" valign=top>' % (100/cols)
  458.             for i in range(rows*col, rows*col+rows):
  459.                 if i < len(list):
  460.                     result = result + format(list[i]) + '<br>\n'
  461.             result = result + '</td>'
  462.         return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
  463.  
  464.     def grey(self, text): return '<font color="#909090">%s</font>' % text
  465.  
  466.     def namelink(self, name, *dicts):
  467.         """Make a link for an identifier, given name-to-URL mappings."""
  468.         for dict in dicts:
  469.             if name in dict:
  470.                 return '<a href="%s">%s</a>' % (dict[name], name)
  471.         return name
  472.  
  473.     def classlink(self, object, modname):
  474.         """Make a link for a class."""
  475.         name, module = object.__name__, sys.modules.get(object.__module__)
  476.         if hasattr(module, name) and getattr(module, name) is object:
  477.             return '<a href="%s.html#%s">%s</a>' % (
  478.                 module.__name__, name, classname(object, modname))
  479.         return classname(object, modname)
  480.  
  481.     def modulelink(self, object):
  482.         """Make a link for a module."""
  483.         return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
  484.  
  485.     def modpkglink(self, (name, path, ispackage, shadowed)):
  486.         """Make a link for a module or package to display in an index."""
  487.         if shadowed:
  488.             return self.grey(name)
  489.         if path:
  490.             url = '%s.%s.html' % (path, name)
  491.         else:
  492.             url = '%s.html' % name
  493.         if ispackage:
  494.             text = '<strong>%s</strong> (package)' % name
  495.         else:
  496.             text = name
  497.         return '<a href="%s">%s</a>' % (url, text)
  498.  
  499.     def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
  500.         """Mark up some plain text, given a context of symbols to look for.
  501.         Each context dictionary maps object names to anchor names."""
  502.         escape = escape or self.escape
  503.         results = []
  504.         here = 0
  505.         pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
  506.                                 r'RFC[- ]?(\d+)|'
  507.                                 r'PEP[- ]?(\d+)|'
  508.                                 r'(self\.)?(\w+))')
  509.         while True:
  510.             match = pattern.search(text, here)
  511.             if not match: break
  512.             start, end = match.span()
  513.             results.append(escape(text[here:start]))
  514.  
  515.             all, scheme, rfc, pep, selfdot, name = match.groups()
  516.             if scheme:
  517.                 url = escape(all).replace('"', '"')
  518.                 results.append('<a href="%s">%s</a>' % (url, url))
  519.             elif rfc:
  520.                 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  521.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  522.             elif pep:
  523.                 url = 'http://www.python.org/peps/pep-%04d.html' % int(pep)
  524.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  525.             elif text[end:end+1] == '(':
  526.                 results.append(self.namelink(name, methods, funcs, classes))
  527.             elif selfdot:
  528.                 results.append('self.<strong>%s</strong>' % name)
  529.             else:
  530.                 results.append(self.namelink(name, classes))
  531.             here = end
  532.         results.append(escape(text[here:]))
  533.         return join(results, '')
  534.  
  535.     # ---------------------------------------------- type-specific routines
  536.  
  537.     def formattree(self, tree, modname, parent=None):
  538.         """Produce HTML for a class tree as given by inspect.getclasstree()."""
  539.         result = ''
  540.         for entry in tree:
  541.             if type(entry) is type(()):
  542.                 c, bases = entry
  543.                 result = result + '<dt><font face="helvetica, arial">'
  544.                 result = result + self.classlink(c, modname)
  545.                 if bases and bases != (parent,):
  546.                     parents = []
  547.                     for base in bases:
  548.                         parents.append(self.classlink(base, modname))
  549.                     result = result + '(' + join(parents, ', ') + ')'
  550.                 result = result + '\n</font></dt>'
  551.             elif type(entry) is type([]):
  552.                 result = result + '<dd>\n%s</dd>\n' % self.formattree(
  553.                     entry, modname, c)
  554.         return '<dl>\n%s</dl>\n' % result
  555.  
  556.     def docmodule(self, object, name=None, mod=None, *ignored):
  557.         """Produce HTML documentation for a module object."""
  558.         name = object.__name__ # ignore the passed-in name
  559.         try:
  560.             all = object.__all__
  561.         except AttributeError:
  562.             all = None
  563.         parts = split(name, '.')
  564.         links = []
  565.         for i in range(len(parts)-1):
  566.             links.append(
  567.                 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
  568.                 (join(parts[:i+1], '.'), parts[i]))
  569.         linkedname = join(links + parts[-1:], '.')
  570.         head = '<big><big><strong>%s</strong></big></big>' % linkedname
  571.         try:
  572.             path = inspect.getabsfile(object)
  573.             url = path
  574.             if sys.platform == 'win32':
  575.                 import nturl2path
  576.                 url = nturl2path.pathname2url(path)
  577.             filelink = '<a href="file:%s">%s</a>' % (url, path)
  578.         except TypeError:
  579.             filelink = '(built-in)'
  580.         info = []
  581.         if hasattr(object, '__version__'):
  582.             version = str(object.__version__)
  583.             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  584.                 version = strip(version[11:-1])
  585.             info.append('version %s' % self.escape(version))
  586.         if hasattr(object, '__date__'):
  587.             info.append(self.escape(str(object.__date__)))
  588.         if info:
  589.             head = head + ' (%s)' % join(info, ', ')
  590.         docloc = self.getdocloc(object)
  591.         if docloc is not None:
  592.             docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
  593.         else:
  594.             docloc = ''
  595.         result = self.heading(
  596.             head, '#ffffff', '#7799ee',
  597.             '<a href=".">index</a><br>' + filelink + docloc)
  598.  
  599.         modules = inspect.getmembers(object, inspect.ismodule)
  600.  
  601.         classes, cdict = [], {}
  602.         for key, value in inspect.getmembers(object, inspect.isclass):
  603.             # if __all__ exists, believe it.  Otherwise use old heuristic.
  604.             if (all is not None or
  605.                 (inspect.getmodule(value) or object) is object):
  606.                 if visiblename(key, all):
  607.                     classes.append((key, value))
  608.                     cdict[key] = cdict[value] = '#' + key
  609.         for key, value in classes:
  610.             for base in value.__bases__:
  611.                 key, modname = base.__name__, base.__module__
  612.                 module = sys.modules.get(modname)
  613.                 if modname != name and module and hasattr(module, key):
  614.                     if getattr(module, key) is base:
  615.                         if not key in cdict:
  616.                             cdict[key] = cdict[base] = modname + '.html#' + key
  617.         funcs, fdict = [], {}
  618.         for key, value in inspect.getmembers(object, inspect.isroutine):
  619.             # if __all__ exists, believe it.  Otherwise use old heuristic.
  620.             if (all is not None or
  621.                 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  622.                 if visiblename(key, all):
  623.                     funcs.append((key, value))
  624.                     fdict[key] = '#-' + key
  625.                     if inspect.isfunction(value): fdict[value] = fdict[key]
  626.         data = []
  627.         for key, value in inspect.getmembers(object, isdata):
  628.             if visiblename(key, all):
  629.                 data.append((key, value))
  630.  
  631.         doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
  632.         doc = doc and '<tt>%s</tt>' % doc
  633.         result = result + '<p>%s</p>\n' % doc
  634.  
  635.         if hasattr(object, '__path__'):
  636.             modpkgs = []
  637.             modnames = []
  638.             for file in os.listdir(object.__path__[0]):
  639.                 path = os.path.join(object.__path__[0], file)
  640.                 modname = inspect.getmodulename(file)
  641.                 if modname != '__init__':
  642.                     if modname and modname not in modnames:
  643.                         modpkgs.append((modname, name, 0, 0))
  644.                         modnames.append(modname)
  645.                     elif ispackage(path):
  646.                         modpkgs.append((file, name, 1, 0))
  647.             modpkgs.sort()
  648.             contents = self.multicolumn(modpkgs, self.modpkglink)
  649.             result = result + self.bigsection(
  650.                 'Package Contents', '#ffffff', '#aa55cc', contents)
  651.         elif modules:
  652.             contents = self.multicolumn(
  653.                 modules, lambda (key, value), s=self: s.modulelink(value))
  654.             result = result + self.bigsection(
  655.                 'Modules', '#fffff', '#aa55cc', contents)
  656.  
  657.         if classes:
  658.             classlist = map(lambda (key, value): value, classes)
  659.             contents = [
  660.                 self.formattree(inspect.getclasstree(classlist, 1), name)]
  661.             for key, value in classes:
  662.                 contents.append(self.document(value, key, name, fdict, cdict))
  663.             result = result + self.bigsection(
  664.                 'Classes', '#ffffff', '#ee77aa', join(contents))
  665.         if funcs:
  666.             contents = []
  667.             for key, value in funcs:
  668.                 contents.append(self.document(value, key, name, fdict, cdict))
  669.             result = result + self.bigsection(
  670.                 'Functions', '#ffffff', '#eeaa77', join(contents))
  671.         if data:
  672.             contents = []
  673.             for key, value in data:
  674.                 contents.append(self.document(value, key))
  675.             result = result + self.bigsection(
  676.                 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
  677.         if hasattr(object, '__author__'):
  678.             contents = self.markup(str(object.__author__), self.preformat)
  679.             result = result + self.bigsection(
  680.                 'Author', '#ffffff', '#7799ee', contents)
  681.         if hasattr(object, '__credits__'):
  682.             contents = self.markup(str(object.__credits__), self.preformat)
  683.             result = result + self.bigsection(
  684.                 'Credits', '#ffffff', '#7799ee', contents)
  685.  
  686.         return result
  687.  
  688.     def docclass(self, object, name=None, mod=None, funcs={}, classes={},
  689.                  *ignored):
  690.         """Produce HTML documentation for a class object."""
  691.         realname = object.__name__
  692.         name = name or realname
  693.         bases = object.__bases__
  694.  
  695.         contents = []
  696.         push = contents.append
  697.  
  698.         # Cute little class to pump out a horizontal rule between sections.
  699.         class HorizontalRule:
  700.             def __init__(self):
  701.                 self.needone = 0
  702.             def maybe(self):
  703.                 if self.needone:
  704.                     push('<hr>\n')
  705.                 self.needone = 1
  706.         hr = HorizontalRule()
  707.  
  708.         # List the mro, if non-trivial.
  709.         mro = deque(inspect.getmro(object))
  710.         if len(mro) > 2:
  711.             hr.maybe()
  712.             push('<dl><dt>Method resolution order:</dt>\n')
  713.             for base in mro:
  714.                 push('<dd>%s</dd>\n' % self.classlink(base,
  715.                                                       object.__module__))
  716.             push('</dl>\n')
  717.  
  718.         def spill(msg, attrs, predicate):
  719.             ok, attrs = _split_list(attrs, predicate)
  720.             if ok:
  721.                 hr.maybe()
  722.                 push(msg)
  723.                 for name, kind, homecls, value in ok:
  724.                     push(self.document(getattr(object, name), name, mod,
  725.                                        funcs, classes, mdict, object))
  726.                     push('\n')
  727.             return attrs
  728.  
  729.         def spillproperties(msg, attrs, predicate):
  730.             ok, attrs = _split_list(attrs, predicate)
  731.             if ok:
  732.                 hr.maybe()
  733.                 push(msg)
  734.                 for name, kind, homecls, value in ok:
  735.                     push(self._docproperty(name, value, mod))
  736.             return attrs
  737.  
  738.         def spilldata(msg, attrs, predicate):
  739.             ok, attrs = _split_list(attrs, predicate)
  740.             if ok:
  741.                 hr.maybe()
  742.                 push(msg)
  743.                 for name, kind, homecls, value in ok:
  744.                     base = self.docother(getattr(object, name), name, mod)
  745.                     if callable(value) or inspect.isdatadescriptor(value):
  746.                         doc = getattr(value, "__doc__", None)
  747.                     else:
  748.                         doc = None
  749.                     if doc is None:
  750.                         push('<dl><dt>%s</dl>\n' % base)
  751.                     else:
  752.                         doc = self.markup(getdoc(value), self.preformat,
  753.                                           funcs, classes, mdict)
  754.                         doc = '<dd><tt>%s</tt>' % doc
  755.                         push('<dl><dt>%s%s</dl>\n' % (base, doc))
  756.                     push('\n')
  757.             return attrs
  758.  
  759.         attrs = filter(lambda (name, kind, cls, value): visiblename(name),
  760.                        inspect.classify_class_attrs(object))
  761.         mdict = {}
  762.         for key, kind, homecls, value in attrs:
  763.             mdict[key] = anchor = '#' + name + '-' + key
  764.             value = getattr(object, key)
  765.             try:
  766.                 # The value may not be hashable (e.g., a data attr with
  767.                 # a dict or list value).
  768.                 mdict[value] = anchor
  769.             except TypeError:
  770.                 pass
  771.  
  772.         while attrs:
  773.             if mro:
  774.                 thisclass = mro.popleft()
  775.             else:
  776.                 thisclass = attrs[0][2]
  777.             attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  778.  
  779.             if thisclass is __builtin__.object:
  780.                 attrs = inherited
  781.                 continue
  782.             elif thisclass is object:
  783.                 tag = 'defined here'
  784.             else:
  785.                 tag = 'inherited from %s' % self.classlink(thisclass,
  786.                                                            object.__module__)
  787.             tag += ':<br>\n'
  788.  
  789.             # Sort attrs by name.
  790.             attrs.sort(key=lambda t: t[0])
  791.  
  792.             # Pump out the attrs, segregated by kind.
  793.             attrs = spill('Methods %s' % tag, attrs,
  794.                           lambda t: t[1] == 'method')
  795.             attrs = spill('Class methods %s' % tag, attrs,
  796.                           lambda t: t[1] == 'class method')
  797.             attrs = spill('Static methods %s' % tag, attrs,
  798.                           lambda t: t[1] == 'static method')
  799.             attrs = spillproperties('Properties %s' % tag, attrs,
  800.                                     lambda t: t[1] == 'property')
  801.             attrs = spilldata('Data and other attributes %s' % tag, attrs,
  802.                               lambda t: t[1] == 'data')
  803.             assert attrs == []
  804.             attrs = inherited
  805.  
  806.         contents = ''.join(contents)
  807.  
  808.         if name == realname:
  809.             title = '<a name="%s">class <strong>%s</strong></a>' % (
  810.                 name, realname)
  811.         else:
  812.             title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
  813.                 name, name, realname)
  814.         if bases:
  815.             parents = []
  816.             for base in bases:
  817.                 parents.append(self.classlink(base, object.__module__))
  818.             title = title + '(%s)' % join(parents, ', ')
  819.         doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
  820.         doc = doc and '<tt>%s<br> </tt>' % doc
  821.  
  822.         return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
  823.  
  824.     def formatvalue(self, object):
  825.         """Format an argument default value as text."""
  826.         return self.grey('=' + self.repr(object))
  827.  
  828.     def docroutine(self, object, name=None, mod=None,
  829.                    funcs={}, classes={}, methods={}, cl=None):
  830.         """Produce HTML documentation for a function or method object."""
  831.         realname = object.__name__
  832.         name = name or realname
  833.         anchor = (cl and cl.__name__ or '') + '-' + name
  834.         note = ''
  835.         skipdocs = 0
  836.         if inspect.ismethod(object):
  837.             imclass = object.im_class
  838.             if cl:
  839.                 if imclass is not cl:
  840.                     note = ' from ' + self.classlink(imclass, mod)
  841.             else:
  842.                 if object.im_self:
  843.                     note = ' method of %s instance' % self.classlink(
  844.                         object.im_self.__class__, mod)
  845.                 else:
  846.                     note = ' unbound %s method' % self.classlink(imclass,mod)
  847.             object = object.im_func
  848.  
  849.         if name == realname:
  850.             title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
  851.         else:
  852.             if (cl and realname in cl.__dict__ and
  853.                 cl.__dict__[realname] is object):
  854.                 reallink = '<a href="#%s">%s</a>' % (
  855.                     cl.__name__ + '-' + realname, realname)
  856.                 skipdocs = 1
  857.             else:
  858.                 reallink = realname
  859.             title = '<a name="%s"><strong>%s</strong></a> = %s' % (
  860.                 anchor, name, reallink)
  861.         if inspect.isfunction(object):
  862.             args, varargs, varkw, defaults = inspect.getargspec(object)
  863.             argspec = inspect.formatargspec(
  864.                 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
  865.             if realname == '<lambda>':
  866.                 title = '<strong>%s</strong> <em>lambda</em> ' % name
  867.                 argspec = argspec[1:-1] # remove parentheses
  868.         else:
  869.             argspec = '(...)'
  870.  
  871.         decl = title + argspec + (note and self.grey(
  872.                '<font face="helvetica, arial">%s</font>' % note))
  873.  
  874.         if skipdocs:
  875.             return '<dl><dt>%s</dt></dl>\n' % decl
  876.         else:
  877.             doc = self.markup(
  878.                 getdoc(object), self.preformat, funcs, classes, methods)
  879.             doc = doc and '<dd><tt>%s</tt></dd>' % doc
  880.             return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  881.  
  882.     def _docproperty(self, name, value, mod):
  883.         results = []
  884.         push = results.append
  885.  
  886.         if name:
  887.             push('<dl><dt><strong>%s</strong></dt>\n' % name)
  888.         if value.__doc__ is not None:
  889.             doc = self.markup(getdoc(value), self.preformat)
  890.             push('<dd><tt>%s</tt></dd>\n' % doc)
  891.         for attr, tag in [('fget', '<em>get</em>'),
  892.                           ('fset', '<em>set</em>'),
  893.                           ('fdel', '<em>delete</em>')]:
  894.             func = getattr(value, attr)
  895.             if func is not None:
  896.                 base = self.document(func, tag, mod)
  897.                 push('<dd>%s</dd>\n' % base)
  898.         push('</dl>\n')
  899.  
  900.         return ''.join(results)
  901.  
  902.     def docproperty(self, object, name=None, mod=None, cl=None):
  903.         """Produce html documentation for a property."""
  904.         return self._docproperty(name, object, mod)
  905.  
  906.     def docother(self, object, name=None, mod=None, *ignored):
  907.         """Produce HTML documentation for a data object."""
  908.         lhs = name and '<strong>%s</strong> = ' % name or ''
  909.         return lhs + self.repr(object)
  910.  
  911.     def index(self, dir, shadowed=None):
  912.         """Generate an HTML index for a directory of modules."""
  913.         modpkgs = []
  914.         if shadowed is None: shadowed = {}
  915.         seen = {}
  916.         files = os.listdir(dir)
  917.  
  918.         def found(name, ispackage,
  919.                   modpkgs=modpkgs, shadowed=shadowed, seen=seen):
  920.             if name not in seen:
  921.                 modpkgs.append((name, '', ispackage, name in shadowed))
  922.                 seen[name] = 1
  923.                 shadowed[name] = 1
  924.  
  925.         # Package spam/__init__.py takes precedence over module spam.py.
  926.         for file in files:
  927.             path = os.path.join(dir, file)
  928.             if ispackage(path): found(file, 1)
  929.         for file in files:
  930.             path = os.path.join(dir, file)
  931.             if os.path.isfile(path):
  932.                 modname = inspect.getmodulename(file)
  933.                 if modname: found(modname, 0)
  934.  
  935.         modpkgs.sort()
  936.         contents = self.multicolumn(modpkgs, self.modpkglink)
  937.         return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
  938.  
  939. # -------------------------------------------- text documentation generator
  940.  
  941. class TextRepr(Repr):
  942.     """Class for safely making a text representation of a Python object."""
  943.     def __init__(self):
  944.         Repr.__init__(self)
  945.         self.maxlist = self.maxtuple = 20
  946.         self.maxdict = 10
  947.         self.maxstring = self.maxother = 100
  948.  
  949.     def repr1(self, x, level):
  950.         if hasattr(type(x), '__name__'):
  951.             methodname = 'repr_' + join(split(type(x).__name__), '_')
  952.             if hasattr(self, methodname):
  953.                 return getattr(self, methodname)(x, level)
  954.         return cram(stripid(repr(x)), self.maxother)
  955.  
  956.     def repr_string(self, x, level):
  957.         test = cram(x, self.maxstring)
  958.         testrepr = repr(test)
  959.         if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  960.             # Backslashes are only literal in the string and are never
  961.             # needed to make any special characters, so show a raw string.
  962.             return 'r' + testrepr[0] + test + testrepr[0]
  963.         return testrepr
  964.  
  965.     repr_str = repr_string
  966.  
  967.     def repr_instance(self, x, level):
  968.         try:
  969.             return cram(stripid(repr(x)), self.maxstring)
  970.         except:
  971.             return '<%s instance>' % x.__class__.__name__
  972.  
  973. class TextDoc(Doc):
  974.     """Formatter class for text documentation."""
  975.  
  976.     # ------------------------------------------- text formatting utilities
  977.  
  978.     _repr_instance = TextRepr()
  979.     repr = _repr_instance.repr
  980.  
  981.     def bold(self, text):
  982.         """Format a string in bold by overstriking."""
  983.         return join(map(lambda ch: ch + '\b' + ch, text), '')
  984.  
  985.     def indent(self, text, prefix='    '):
  986.         """Indent text by prepending a given prefix to each line."""
  987.         if not text: return ''
  988.         lines = split(text, '\n')
  989.         lines = map(lambda line, prefix=prefix: prefix + line, lines)
  990.         if lines: lines[-1] = rstrip(lines[-1])
  991.         return join(lines, '\n')
  992.  
  993.     def section(self, title, contents):
  994.         """Format a section with a given heading."""
  995.         return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
  996.  
  997.     # ---------------------------------------------- type-specific routines
  998.  
  999.     def formattree(self, tree, modname, parent=None, prefix=''):
  1000.         """Render in text a class tree as returned by inspect.getclasstree()."""
  1001.         result = ''
  1002.         for entry in tree:
  1003.             if type(entry) is type(()):
  1004.                 c, bases = entry
  1005.                 result = result + prefix + classname(c, modname)
  1006.                 if bases and bases != (parent,):
  1007.                     parents = map(lambda c, m=modname: classname(c, m), bases)
  1008.                     result = result + '(%s)' % join(parents, ', ')
  1009.                 result = result + '\n'
  1010.             elif type(entry) is type([]):
  1011.                 result = result + self.formattree(
  1012.                     entry, modname, c, prefix + '    ')
  1013.         return result
  1014.  
  1015.     def docmodule(self, object, name=None, mod=None):
  1016.         """Produce text documentation for a given module object."""
  1017.         name = object.__name__ # ignore the passed-in name
  1018.         synop, desc = splitdoc(getdoc(object))
  1019.         result = self.section('NAME', name + (synop and ' - ' + synop))
  1020.  
  1021.         try:
  1022.             all = object.__all__
  1023.         except AttributeError:
  1024.             all = None
  1025.  
  1026.         try:
  1027.             file = inspect.getabsfile(object)
  1028.         except TypeError:
  1029.             file = '(built-in)'
  1030.         result = result + self.section('FILE', file)
  1031.  
  1032.         docloc = self.getdocloc(object)
  1033.         if docloc is not None:
  1034.             result = result + self.section('MODULE DOCS', docloc)
  1035.  
  1036.         if desc:
  1037.             result = result + self.section('DESCRIPTION', desc)
  1038.  
  1039.         classes = []
  1040.         for key, value in inspect.getmembers(object, inspect.isclass):
  1041.             # if __all__ exists, believe it.  Otherwise use old heuristic.
  1042.             if (all is not None
  1043.                 or (inspect.getmodule(value) or object) is object):
  1044.                 if visiblename(key, all):
  1045.                     classes.append((key, value))
  1046.         funcs = []
  1047.         for key, value in inspect.getmembers(object, inspect.isroutine):
  1048.             # if __all__ exists, believe it.  Otherwise use old heuristic.
  1049.             if (all is not None or
  1050.                 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  1051.                 if visiblename(key, all):
  1052.                     funcs.append((key, value))
  1053.         data = []
  1054.         for key, value in inspect.getmembers(object, isdata):
  1055.             if visiblename(key, all):
  1056.                 data.append((key, value))
  1057.  
  1058.         if hasattr(object, '__path__'):
  1059.             modpkgs = []
  1060.             for file in os.listdir(object.__path__[0]):
  1061.                 path = os.path.join(object.__path__[0], file)
  1062.                 modname = inspect.getmodulename(file)
  1063.                 if modname != '__init__':
  1064.                     if modname and modname not in modpkgs:
  1065.                         modpkgs.append(modname)
  1066.                     elif ispackage(path):
  1067.                         modpkgs.append(file + ' (package)')
  1068.             modpkgs.sort()
  1069.             result = result + self.section(
  1070.                 'PACKAGE CONTENTS', join(modpkgs, '\n'))
  1071.  
  1072.         if classes:
  1073.             classlist = map(lambda (key, value): value, classes)
  1074.             contents = [self.formattree(
  1075.                 inspect.getclasstree(classlist, 1), name)]
  1076.             for key, value in classes:
  1077.                 contents.append(self.document(value, key, name))
  1078.             result = result + self.section('CLASSES', join(contents, '\n'))
  1079.  
  1080.         if funcs:
  1081.             contents = []
  1082.             for key, value in funcs:
  1083.                 contents.append(self.document(value, key, name))
  1084.             result = result + self.section('FUNCTIONS', join(contents, '\n'))
  1085.  
  1086.         if data:
  1087.             contents = []
  1088.             for key, value in data:
  1089.                 contents.append(self.docother(value, key, name, maxlen=70))
  1090.             result = result + self.section('DATA', join(contents, '\n'))
  1091.  
  1092.         if hasattr(object, '__version__'):
  1093.             version = str(object.__version__)
  1094.             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  1095.                 version = strip(version[11:-1])
  1096.             result = result + self.section('VERSION', version)
  1097.         if hasattr(object, '__date__'):
  1098.             result = result + self.section('DATE', str(object.__date__))
  1099.         if hasattr(object, '__author__'):
  1100.             result = result + self.section('AUTHOR', str(object.__author__))
  1101.         if hasattr(object, '__credits__'):
  1102.             result = result + self.section('CREDITS', str(object.__credits__))
  1103.         return result
  1104.  
  1105.     def docclass(self, object, name=None, mod=None):
  1106.         """Produce text documentation for a given class object."""
  1107.         realname = object.__name__
  1108.         name = name or realname
  1109.         bases = object.__bases__
  1110.  
  1111.         def makename(c, m=object.__module__):
  1112.             return classname(c, m)
  1113.  
  1114.         if name == realname:
  1115.             title = 'class ' + self.bold(realname)
  1116.         else:
  1117.             title = self.bold(name) + ' = class ' + realname
  1118.         if bases:
  1119.             parents = map(makename, bases)
  1120.             title = title + '(%s)' % join(parents, ', ')
  1121.  
  1122.         doc = getdoc(object)
  1123.         contents = doc and [doc + '\n'] or []
  1124.         push = contents.append
  1125.  
  1126.         # List the mro, if non-trivial.
  1127.         mro = deque(inspect.getmro(object))
  1128.         if len(mro) > 2:
  1129.             push("Method resolution order:")
  1130.             for base in mro:
  1131.                 push('    ' + makename(base))
  1132.             push('')
  1133.  
  1134.         # Cute little class to pump out a horizontal rule between sections.
  1135.         class HorizontalRule:
  1136.             def __init__(self):
  1137.                 self.needone = 0
  1138.             def maybe(self):
  1139.                 if self.needone:
  1140.                     push('-' * 70)
  1141.                 self.needone = 1
  1142.         hr = HorizontalRule()
  1143.  
  1144.         def spill(msg, attrs, predicate):
  1145.             ok, attrs = _split_list(attrs, predicate)
  1146.             if ok:
  1147.                 hr.maybe()
  1148.                 push(msg)
  1149.                 for name, kind, homecls, value in ok:
  1150.                     push(self.document(getattr(object, name),
  1151.                                        name, mod, object))
  1152.             return attrs
  1153.  
  1154.         def spillproperties(msg, attrs, predicate):
  1155.             ok, attrs = _split_list(attrs, predicate)
  1156.             if ok:
  1157.                 hr.maybe()
  1158.                 push(msg)
  1159.                 for name, kind, homecls, value in ok:
  1160.                     push(self._docproperty(name, value, mod))
  1161.             return attrs
  1162.  
  1163.         def spilldata(msg, attrs, predicate):
  1164.             ok, attrs = _split_list(attrs, predicate)
  1165.             if ok:
  1166.                 hr.maybe()
  1167.                 push(msg)
  1168.                 for name, kind, homecls, value in ok:
  1169.                     if callable(value) or inspect.isdatadescriptor(value):
  1170.                         doc = getdoc(value)
  1171.                     else:
  1172.                         doc = None
  1173.                     push(self.docother(getattr(object, name),
  1174.                                        name, mod, maxlen=70, doc=doc) + '\n')
  1175.             return attrs
  1176.  
  1177.         attrs = filter(lambda (name, kind, cls, value): visiblename(name),
  1178.                        inspect.classify_class_attrs(object))
  1179.         while attrs:
  1180.             if mro:
  1181.                 thisclass = mro.popleft()
  1182.             else:
  1183.                 thisclass = attrs[0][2]
  1184.             attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  1185.  
  1186.             if thisclass is __builtin__.object:
  1187.                 attrs = inherited
  1188.                 continue
  1189.             elif thisclass is object:
  1190.                 tag = "defined here"
  1191.             else:
  1192.                 tag = "inherited from %s" % classname(thisclass,
  1193.                                                       object.__module__)
  1194.             filter(lambda t: not t[0].startswith('_'), attrs)
  1195.  
  1196.             # Sort attrs by name.
  1197.             attrs.sort()
  1198.  
  1199.             # Pump out the attrs, segregated by kind.
  1200.             attrs = spill("Methods %s:\n" % tag, attrs,
  1201.                           lambda t: t[1] == 'method')
  1202.             attrs = spill("Class methods %s:\n" % tag, attrs,
  1203.                           lambda t: t[1] == 'class method')
  1204.             attrs = spill("Static methods %s:\n" % tag, attrs,
  1205.                           lambda t: t[1] == 'static method')
  1206.             attrs = spillproperties("Properties %s:\n" % tag, attrs,
  1207.                                     lambda t: t[1] == 'property')
  1208.             attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
  1209.                               lambda t: t[1] == 'data')
  1210.             assert attrs == []
  1211.             attrs = inherited
  1212.  
  1213.         contents = '\n'.join(contents)
  1214.         if not contents:
  1215.             return title + '\n'
  1216.         return title + '\n' + self.indent(rstrip(contents), ' |  ') + '\n'
  1217.  
  1218.     def formatvalue(self, object):
  1219.         """Format an argument default value as text."""
  1220.         return '=' + self.repr(object)
  1221.  
  1222.     def docroutine(self, object, name=None, mod=None, cl=None):
  1223.         """Produce text documentation for a function or method object."""
  1224.         realname = object.__name__
  1225.         name = name or realname
  1226.         note = ''
  1227.         skipdocs = 0
  1228.         if inspect.ismethod(object):
  1229.             imclass = object.im_class
  1230.             if cl:
  1231.                 if imclass is not cl:
  1232.                     note = ' from ' + classname(imclass, mod)
  1233.             else:
  1234.                 if object.im_self:
  1235.                     note = ' method of %s instance' % classname(
  1236.                         object.im_self.__class__, mod)
  1237.                 else:
  1238.                     note = ' unbound %s method' % classname(imclass,mod)
  1239.             object = object.im_func
  1240.  
  1241.         if name == realname:
  1242.             title = self.bold(realname)
  1243.         else:
  1244.             if (cl and realname in cl.__dict__ and
  1245.                 cl.__dict__[realname] is object):
  1246.                 skipdocs = 1
  1247.             title = self.bold(name) + ' = ' + realname
  1248.         if inspect.isfunction(object):
  1249.             args, varargs, varkw, defaults = inspect.getargspec(object)
  1250.             argspec = inspect.formatargspec(
  1251.                 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
  1252.             if realname == '<lambda>':
  1253.                 title = self.bold(name) + ' lambda '
  1254.                 argspec = argspec[1:-1] # remove parentheses
  1255.         else:
  1256.             argspec = '(...)'
  1257.         decl = title + argspec + note
  1258.  
  1259.         if skipdocs:
  1260.             return decl + '\n'
  1261.         else:
  1262.             doc = getdoc(object) or ''
  1263.             return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n')
  1264.  
  1265.     def _docproperty(self, name, value, mod):
  1266.         results = []
  1267.         push = results.append
  1268.  
  1269.         if name:
  1270.             push(name)
  1271.         need_blank_after_doc = 0
  1272.         doc = getdoc(value) or ''
  1273.         if doc:
  1274.             push(self.indent(doc))
  1275.             need_blank_after_doc = 1
  1276.         for attr, tag in [('fget', '<get>'),
  1277.                           ('fset', '<set>'),
  1278.                           ('fdel', '<delete>')]:
  1279.             func = getattr(value, attr)
  1280.             if func is not None:
  1281.                 if need_blank_after_doc:
  1282.                     push('')
  1283.                     need_blank_after_doc = 0
  1284.                 base = self.document(func, tag, mod)
  1285.                 push(self.indent(base))
  1286.  
  1287.         return '\n'.join(results)
  1288.  
  1289.     def docproperty(self, object, name=None, mod=None, cl=None):
  1290.         """Produce text documentation for a property."""
  1291.         return self._docproperty(name, object, mod)
  1292.  
  1293.     def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
  1294.         """Produce text documentation for a data object."""
  1295.         repr = self.repr(object)
  1296.         if maxlen:
  1297.             line = (name and name + ' = ' or '') + repr
  1298.             chop = maxlen - len(line)
  1299.             if chop < 0: repr = repr[:chop] + '...'
  1300.         line = (name and self.bold(name) + ' = ' or '') + repr
  1301.         if doc is not None:
  1302.             line += '\n' + self.indent(str(doc))
  1303.         return line
  1304.  
  1305. # --------------------------------------------------------- user interfaces
  1306.  
  1307. def pager(text):
  1308.     """The first time this is called, determine what kind of pager to use."""
  1309.     global pager
  1310.     pager = getpager()
  1311.     pager(text)
  1312.  
  1313. def getpager():
  1314.     """Decide what method to use for paging through text."""
  1315.     if type(sys.stdout) is not types.FileType:
  1316.         return plainpager
  1317.     if not sys.stdin.isatty() or not sys.stdout.isatty():
  1318.         return plainpager
  1319.     if os.environ.get('TERM') in ['dumb', 'emacs']:
  1320.         return plainpager
  1321.     if 'PAGER' in os.environ:
  1322.         if sys.platform == 'win32': # pipes completely broken in Windows
  1323.             return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
  1324.         elif os.environ.get('TERM') in ['dumb', 'emacs']:
  1325.             return lambda text: pipepager(plain(text), os.environ['PAGER'])
  1326.         else:
  1327.             return lambda text: pipepager(text, os.environ['PAGER'])
  1328.     if sys.platform == 'win32' or sys.platform.startswith('os2'):
  1329.         return lambda text: tempfilepager(plain(text), 'more <')
  1330.     if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
  1331.         return lambda text: pipepager(text, 'less')
  1332.  
  1333.     import tempfile
  1334.     (fd, filename) = tempfile.mkstemp()
  1335.     os.close(fd)
  1336.     try:
  1337.         if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
  1338.             return lambda text: pipepager(text, 'more')
  1339.         else:
  1340.             return ttypager
  1341.     finally:
  1342.         os.unlink(filename)
  1343.  
  1344. def plain(text):
  1345.     """Remove boldface formatting from text."""
  1346.     return re.sub('.\b', '', text)
  1347.  
  1348. def pipepager(text, cmd):
  1349.     """Page through text by feeding it to another program."""
  1350.     pipe = os.popen(cmd, 'w')
  1351.     try:
  1352.         pipe.write(text)
  1353.         pipe.close()
  1354.     except IOError:
  1355.         pass # Ignore broken pipes caused by quitting the pager program.
  1356.  
  1357. def tempfilepager(text, cmd):
  1358.     """Page through text by invoking a program on a temporary file."""
  1359.     import tempfile
  1360.     filename = tempfile.mktemp()
  1361.     file = open(filename, 'w')
  1362.     file.write(text)
  1363.     file.close()
  1364.     try:
  1365.         os.system(cmd + ' ' + filename)
  1366.     finally:
  1367.         os.unlink(filename)
  1368.  
  1369. def ttypager(text):
  1370.     """Page through text on a text terminal."""
  1371.     lines = split(plain(text), '\n')
  1372.     try:
  1373.         import tty
  1374.         fd = sys.stdin.fileno()
  1375.         old = tty.tcgetattr(fd)
  1376.         tty.setcbreak(fd)
  1377.         getchar = lambda: sys.stdin.read(1)
  1378.     except (ImportError, AttributeError):
  1379.         tty = None
  1380.         getchar = lambda: sys.stdin.readline()[:-1][:1]
  1381.  
  1382.     try:
  1383.         r = inc = os.environ.get('LINES', 25) - 1
  1384.         sys.stdout.write(join(lines[:inc], '\n') + '\n')
  1385.         while lines[r:]:
  1386.             sys.stdout.write('-- more --')
  1387.             sys.stdout.flush()
  1388.             c = getchar()
  1389.  
  1390.             if c in ['q', 'Q']:
  1391.                 sys.stdout.write('\r          \r')
  1392.                 break
  1393.             elif c in ['\r', '\n']:
  1394.                 sys.stdout.write('\r          \r' + lines[r] + '\n')
  1395.                 r = r + 1
  1396.                 continue
  1397.             if c in ['b', 'B', '\x1b']:
  1398.                 r = r - inc - inc
  1399.                 if r < 0: r = 0
  1400.             sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
  1401.             r = r + inc
  1402.  
  1403.     finally:
  1404.         if tty:
  1405.             tty.tcsetattr(fd, tty.TCSAFLUSH, old)
  1406.  
  1407. def plainpager(text):
  1408.     """Simply print unformatted text.  This is the ultimate fallback."""
  1409.     sys.stdout.write(plain(text))
  1410.  
  1411. def describe(thing):
  1412.     """Produce a short description of the given thing."""
  1413.     if inspect.ismodule(thing):
  1414.         if thing.__name__ in sys.builtin_module_names:
  1415.             return 'built-in module ' + thing.__name__
  1416.         if hasattr(thing, '__path__'):
  1417.             return 'package ' + thing.__name__
  1418.         else:
  1419.             return 'module ' + thing.__name__
  1420.     if inspect.isbuiltin(thing):
  1421.         return 'built-in function ' + thing.__name__
  1422.     if inspect.isclass(thing):
  1423.         return 'class ' + thing.__name__
  1424.     if inspect.isfunction(thing):
  1425.         return 'function ' + thing.__name__
  1426.     if inspect.ismethod(thing):
  1427.         return 'method ' + thing.__name__
  1428.     if type(thing) is types.InstanceType:
  1429.         return 'instance of ' + thing.__class__.__name__
  1430.     return type(thing).__name__
  1431.  
  1432. def locate(path, forceload=0):
  1433.     """Locate an object by name or dotted path, importing as necessary."""
  1434.     parts = [part for part in split(path, '.') if part]
  1435.     module, n = None, 0
  1436.     while n < len(parts):
  1437.         nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
  1438.         if nextmodule: module, n = nextmodule, n + 1
  1439.         else: break
  1440.     if module:
  1441.         object = module
  1442.         for part in parts[n:]:
  1443.             try: object = getattr(object, part)
  1444.             except AttributeError: return None
  1445.         return object
  1446.     else:
  1447.         if hasattr(__builtin__, path):
  1448.             return getattr(__builtin__, path)
  1449.  
  1450. # --------------------------------------- interactive interpreter interface
  1451.  
  1452. text = TextDoc()
  1453. html = HTMLDoc()
  1454.  
  1455. def resolve(thing, forceload=0):
  1456.     """Given an object or a path to an object, get the object and its name."""
  1457.     if isinstance(thing, str):
  1458.         object = locate(thing, forceload)
  1459.         if not object:
  1460.             raise ImportError, 'no Python documentation found for %r' % thing
  1461.         return object, thing
  1462.     else:
  1463.         return thing, getattr(thing, '__name__', None)
  1464.  
  1465. def doc(thing, title='Python Library Documentation: %s', forceload=0):
  1466.     """Display text documentation, given an object or a path to an object."""
  1467.     try:
  1468.         object, name = resolve(thing, forceload)
  1469.         desc = describe(object)
  1470.         module = inspect.getmodule(object)
  1471.         if name and '.' in name:
  1472.             desc += ' in ' + name[:name.rfind('.')]
  1473.         elif module and module is not object:
  1474.             desc += ' in module ' + module.__name__
  1475.         if not (inspect.ismodule(object) or
  1476.                 inspect.isclass(object) or
  1477.                 inspect.isroutine(object) or
  1478.                 isinstance(object, property)):
  1479.             # If the passed object is a piece of data or an instance,
  1480.             # document its available methods instead of its value.
  1481.             object = type(object)
  1482.             desc += ' object'
  1483.         pager(title % desc + '\n\n' + text.document(object, name))
  1484.     except (ImportError, ErrorDuringImport), value:
  1485.         print value
  1486.  
  1487. def writedoc(thing, forceload=0):
  1488.     """Write HTML documentation to a file in the current directory."""
  1489.     try:
  1490.         object, name = resolve(thing, forceload)
  1491.         page = html.page(describe(object), html.document(object, name))
  1492.         file = open(name + '.html', 'w')
  1493.         file.write(page)
  1494.         file.close()
  1495.         print 'wrote', name + '.html'
  1496.     except (ImportError, ErrorDuringImport), value:
  1497.         print value
  1498.  
  1499. def writedocs(dir, pkgpath='', done=None):
  1500.     """Write out HTML documentation for all modules in a directory tree."""
  1501.     if done is None: done = {}
  1502.     for file in os.listdir(dir):
  1503.         path = os.path.join(dir, file)
  1504.         if ispackage(path):
  1505.             writedocs(path, pkgpath + file + '.', done)
  1506.         elif os.path.isfile(path):
  1507.             modname = inspect.getmodulename(path)
  1508.             if modname:
  1509.                 if modname == '__init__':
  1510.                     modname = pkgpath[:-1] # remove trailing period
  1511.                 else:
  1512.                     modname = pkgpath + modname
  1513.                 if modname not in done:
  1514.                     done[modname] = 1
  1515.                     writedoc(modname)
  1516.  
  1517. class Helper:
  1518.     keywords = {
  1519.         'and': 'BOOLEAN',
  1520.         'assert': ('ref/assert', ''),
  1521.         'break': ('ref/break', 'while for'),
  1522.         'class': ('ref/class', 'CLASSES SPECIALMETHODS'),
  1523.         'continue': ('ref/continue', 'while for'),
  1524.         'def': ('ref/function', ''),
  1525.         'del': ('ref/del', 'BASICMETHODS'),
  1526.         'elif': 'if',
  1527.         'else': ('ref/if', 'while for'),
  1528.         'except': 'try',
  1529.         'exec': ('ref/exec', ''),
  1530.         'finally': 'try',
  1531.         'for': ('ref/for', 'break continue while'),
  1532.         'from': 'import',
  1533.         'global': ('ref/global', 'NAMESPACES'),
  1534.         'if': ('ref/if', 'TRUTHVALUE'),
  1535.         'import': ('ref/import', 'MODULES'),
  1536.         'in': ('ref/comparisons', 'SEQUENCEMETHODS2'),
  1537.         'is': 'COMPARISON',
  1538.         'lambda': ('ref/lambdas', 'FUNCTIONS'),
  1539.         'not': 'BOOLEAN',
  1540.         'or': 'BOOLEAN',
  1541.         'pass': ('ref/pass', ''),
  1542.         'print': ('ref/print', ''),
  1543.         'raise': ('ref/raise', 'EXCEPTIONS'),
  1544.         'return': ('ref/return', 'FUNCTIONS'),
  1545.         'try': ('ref/try', 'EXCEPTIONS'),
  1546.         'while': ('ref/while', 'break continue if TRUTHVALUE'),
  1547.         'yield': ('ref/yield', ''),
  1548.     }
  1549.  
  1550.     topics = {
  1551.         'TYPES': ('ref/types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'),
  1552.         'STRINGS': ('ref/strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'),
  1553.         'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'),
  1554.         'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'),
  1555.         'UNICODE': ('ref/strings', 'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'),
  1556.         'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'),
  1557.         'INTEGER': ('ref/integers', 'int range'),
  1558.         'FLOAT': ('ref/floating', 'float math'),
  1559.         'COMPLEX': ('ref/imaginary', 'complex cmath'),
  1560.         'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
  1561.         'MAPPINGS': 'DICTIONARIES',
  1562.         'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'),
  1563.         'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
  1564.         'CODEOBJECTS': ('lib/bltin-code-objects', 'compile FUNCTIONS TYPES'),
  1565.         'TYPEOBJECTS': ('lib/bltin-type-objects', 'types TYPES'),
  1566.         'FRAMEOBJECTS': 'TYPES',
  1567.         'TRACEBACKS': 'TYPES',
  1568.         'NONE': ('lib/bltin-null-object', ''),
  1569.         'ELLIPSIS': ('lib/bltin-ellipsis-object', 'SLICINGS'),
  1570.         'FILES': ('lib/bltin-file-objects', ''),
  1571.         'SPECIALATTRIBUTES': ('lib/specialattrs', ''),
  1572.         'CLASSES': ('ref/types', 'class SPECIALMETHODS PRIVATENAMES'),
  1573.         'MODULES': ('lib/typesmodules', 'import'),
  1574.         'PACKAGES': 'import',
  1575.         'EXPRESSIONS': ('ref/summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'),
  1576.         'OPERATORS': 'EXPRESSIONS',
  1577.         'PRECEDENCE': 'EXPRESSIONS',
  1578.         'OBJECTS': ('ref/objects', 'TYPES'),
  1579.         'SPECIALMETHODS': ('ref/specialnames', 'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
  1580.         'BASICMETHODS': ('ref/customization', 'cmp hash repr str SPECIALMETHODS'),
  1581.         'ATTRIBUTEMETHODS': ('ref/attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
  1582.         'CALLABLEMETHODS': ('ref/callable-types', 'CALLS SPECIALMETHODS'),
  1583.         'SEQUENCEMETHODS1': ('ref/sequence-types', 'SEQUENCES SEQUENCEMETHODS2 SPECIALMETHODS'),
  1584.         'SEQUENCEMETHODS2': ('ref/sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 SPECIALMETHODS'),
  1585.         'MAPPINGMETHODS': ('ref/sequence-types', 'MAPPINGS SPECIALMETHODS'),
  1586.         'NUMBERMETHODS': ('ref/numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'),
  1587.         'EXECUTION': ('ref/execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
  1588.         'NAMESPACES': ('ref/naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
  1589.         'DYNAMICFEATURES': ('ref/dynamic-features', ''),
  1590.         'SCOPING': 'NAMESPACES',
  1591.         'FRAMES': 'NAMESPACES',
  1592.         'EXCEPTIONS': ('ref/exceptions', 'try except finally raise'),
  1593.         'COERCIONS': ('ref/coercion-rules','CONVERSIONS'),
  1594.         'CONVERSIONS': ('ref/conversions', 'COERCIONS'),
  1595.         'IDENTIFIERS': ('ref/identifiers', 'keywords SPECIALIDENTIFIERS'),
  1596.         'SPECIALIDENTIFIERS': ('ref/id-classes', ''),
  1597.         'PRIVATENAMES': ('ref/atom-identifiers', ''),
  1598.         'LITERALS': ('ref/atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
  1599.         'TUPLES': 'SEQUENCES',
  1600.         'TUPLELITERALS': ('ref/exprlists', 'TUPLES LITERALS'),
  1601.         'LISTS': ('lib/typesseq-mutable', 'LISTLITERALS'),
  1602.         'LISTLITERALS': ('ref/lists', 'LISTS LITERALS'),
  1603.         'DICTIONARIES': ('lib/typesmapping', 'DICTIONARYLITERALS'),
  1604.         'DICTIONARYLITERALS': ('ref/dict', 'DICTIONARIES LITERALS'),
  1605.         'BACKQUOTES': ('ref/string-conversions', 'repr str STRINGS LITERALS'),
  1606.         'ATTRIBUTES': ('ref/attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
  1607.         'SUBSCRIPTS': ('ref/subscriptions', 'SEQUENCEMETHODS1'),
  1608.         'SLICINGS': ('ref/slicings', 'SEQUENCEMETHODS2'),
  1609.         'CALLS': ('ref/calls', 'EXPRESSIONS'),
  1610.         'POWER': ('ref/power', 'EXPRESSIONS'),
  1611.         'UNARY': ('ref/unary', 'EXPRESSIONS'),
  1612.         'BINARY': ('ref/binary', 'EXPRESSIONS'),
  1613.         'SHIFTING': ('ref/shifting', 'EXPRESSIONS'),
  1614.         'BITWISE': ('ref/bitwise', 'EXPRESSIONS'),
  1615.         'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'),
  1616.         'BOOLEAN': ('ref/Booleans', 'EXPRESSIONS TRUTHVALUE'),
  1617.         'ASSERTION': 'assert',
  1618.         'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'),
  1619.         'AUGMENTEDASSIGNMENT': ('ref/augassign', 'NUMBERMETHODS'),
  1620.         'DELETION': 'del',
  1621.         'PRINTING': 'print',
  1622.         'RETURNING': 'return',
  1623.         'IMPORTING': 'import',
  1624.         'CONDITIONAL': 'if',
  1625.         'LOOPING': ('ref/compound', 'for while break continue'),
  1626.         'TRUTHVALUE': ('lib/truth', 'if while and or not BASICMETHODS'),
  1627.         'DEBUGGING': ('lib/module-pdb', 'pdb'),
  1628.     }
  1629.  
  1630.     def __init__(self, input, output):
  1631.         self.input = input
  1632.         self.output = output
  1633.         self.docdir = None
  1634.         execdir = os.path.dirname(sys.executable)
  1635.         homedir = os.environ.get('PYTHONHOME')
  1636.         for dir in [os.environ.get('PYTHONDOCS'),
  1637.                     homedir and os.path.join(homedir, 'doc'),
  1638.                     os.path.join(execdir, 'doc'),
  1639.                     '/usr/share/doc/python' + sys.version[:3] + '-doc/html',
  1640.                     '/usr/doc/python-docs-' + split(sys.version)[0],
  1641.                     '/usr/doc/python-' + split(sys.version)[0],
  1642.                     '/usr/doc/python-docs-' + sys.version[:3],
  1643.                     '/usr/doc/python-' + sys.version[:3],
  1644.                     os.path.join(sys.prefix, 'Resources/English.lproj/Documentation')]:
  1645.             if dir and os.path.isdir(os.path.join(dir, 'lib')):
  1646.                 self.docdir = dir
  1647.  
  1648.     def __repr__(self):
  1649.         if inspect.stack()[1][3] == '?':
  1650.             self()
  1651.             return ''
  1652.         return '<pydoc.Helper instance>'
  1653.  
  1654.     def __call__(self, request=None):
  1655.         if request is not None:
  1656.             self.help(request)
  1657.         else:
  1658.             self.intro()
  1659.             self.interact()
  1660.             self.output.write('''
  1661. You are now leaving help and returning to the Python interpreter.
  1662. If you want to ask for help on a particular object directly from the
  1663. interpreter, you can type "help(object)".  Executing "help('string')"
  1664. has the same effect as typing a particular string at the help> prompt.
  1665. ''')
  1666.  
  1667.     def interact(self):
  1668.         self.output.write('\n')
  1669.         while True:
  1670.             try:
  1671.                 request = self.getline('help> ')
  1672.                 if not request: break
  1673.             except (KeyboardInterrupt, EOFError):
  1674.                 break
  1675.             request = strip(replace(request, '"', '', "'", ''))
  1676.             if lower(request) in ['q', 'quit']: break
  1677.             self.help(request)
  1678.  
  1679.     def getline(self, prompt):
  1680.         """Read one line, using raw_input when available."""
  1681.         if self.input is sys.stdin:
  1682.             return raw_input(prompt)
  1683.         else:
  1684.             self.output.write(prompt)
  1685.             self.output.flush()
  1686.             return self.input.readline()
  1687.  
  1688.     def help(self, request):
  1689.         if type(request) is type(''):
  1690.             if request == 'help': self.intro()
  1691.             elif request == 'keywords': self.listkeywords()
  1692.             elif request == 'topics': self.listtopics()
  1693.             elif request == 'modules': self.listmodules()
  1694.             elif request[:8] == 'modules ':
  1695.                 self.listmodules(split(request)[1])
  1696.             elif request in self.keywords: self.showtopic(request)
  1697.             elif request in self.topics: self.showtopic(request)
  1698.             elif request: doc(request, 'Help on %s:')
  1699.         elif isinstance(request, Helper): self()
  1700.         else: doc(request, 'Help on %s:')
  1701.         self.output.write('\n')
  1702.  
  1703.     def intro(self):
  1704.         self.output.write('''
  1705. Welcome to Python %s!  This is the online help utility.
  1706.  
  1707. If this is your first time using Python, you should definitely check out
  1708. the tutorial on the Internet at http://www.python.org/doc/tut/.
  1709.  
  1710. Enter the name of any module, keyword, or topic to get help on writing
  1711. Python programs and using Python modules.  To quit this help utility and
  1712. return to the interpreter, just type "quit".
  1713.  
  1714. To get a list of available modules, keywords, or topics, type "modules",
  1715. "keywords", or "topics".  Each module also comes with a one-line summary
  1716. of what it does; to list the modules whose summaries contain a given word
  1717. such as "spam", type "modules spam".
  1718. ''' % sys.version[:3])
  1719.  
  1720.     def list(self, items, columns=4, width=80):
  1721.         items = items[:]
  1722.         items.sort()
  1723.         colw = width / columns
  1724.         rows = (len(items) + columns - 1) / columns
  1725.         for row in range(rows):
  1726.             for col in range(columns):
  1727.                 i = col * rows + row
  1728.                 if i < len(items):
  1729.                     self.output.write(items[i])
  1730.                     if col < columns - 1:
  1731.                         self.output.write(' ' + ' ' * (colw-1 - len(items[i])))
  1732.             self.output.write('\n')
  1733.  
  1734.     def listkeywords(self):
  1735.         self.output.write('''
  1736. Here is a list of the Python keywords.  Enter any keyword to get more help.
  1737.  
  1738. ''')
  1739.         self.list(self.keywords.keys())
  1740.  
  1741.     def listtopics(self):
  1742.         self.output.write('''
  1743. Here is a list of available topics.  Enter any topic name to get more help.
  1744.  
  1745. ''')
  1746.         self.list(self.topics.keys())
  1747.  
  1748.     def showtopic(self, topic):
  1749.         if not self.docdir:
  1750.             self.output.write('''
  1751. Sorry, topic and keyword documentation is not available because the Python
  1752. HTML documentation files could not be found.  If you have installed them,
  1753. please set the environment variable PYTHONDOCS to indicate their location.
  1754.  
  1755. On Debian GNU/{Linux,Hurd} systems you have to install the corresponding
  1756. pythonX.Y-doc package, i.e. python2.3-doc.
  1757. ''')
  1758.             return
  1759.         target = self.topics.get(topic, self.keywords.get(topic))
  1760.         if not target:
  1761.             self.output.write('no documentation found for %s\n' % repr(topic))
  1762.             return
  1763.         if type(target) is type(''):
  1764.             return self.showtopic(target)
  1765.  
  1766.         filename, xrefs = target
  1767.         filename = self.docdir + '/' + filename + '.html'
  1768.         try:
  1769.             file = open(filename)
  1770.         except:
  1771.             self.output.write('could not read docs from %s\n' % filename)
  1772.             return
  1773.  
  1774.         divpat = re.compile('<div[^>]*navigat.*?</div.*?>', re.I | re.S)
  1775.         addrpat = re.compile('<address.*?>.*?</address.*?>', re.I | re.S)
  1776.         document = re.sub(addrpat, '', re.sub(divpat, '', file.read()))
  1777.         file.close()
  1778.  
  1779.         import htmllib, formatter, StringIO
  1780.         buffer = StringIO.StringIO()
  1781.         parser = htmllib.HTMLParser(
  1782.             formatter.AbstractFormatter(formatter.DumbWriter(buffer)))
  1783.         parser.start_table = parser.do_p
  1784.         parser.end_table = lambda parser=parser: parser.do_p({})
  1785.         parser.start_tr = parser.do_br
  1786.         parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t')
  1787.         parser.feed(document)
  1788.         buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n  ')
  1789.         pager('  ' + strip(buffer) + '\n')
  1790.         if xrefs:
  1791.             buffer = StringIO.StringIO()
  1792.             formatter.DumbWriter(buffer).send_flowing_data(
  1793.                 'Related help topics: ' + join(split(xrefs), ', ') + '\n')
  1794.             self.output.write('\n%s\n' % buffer.getvalue())
  1795.  
  1796.     def listmodules(self, key=''):
  1797.         if key:
  1798.             self.output.write('''
  1799. Here is a list of matching modules.  Enter any module name to get more help.
  1800.  
  1801. ''')
  1802.             apropos(key)
  1803.         else:
  1804.             self.output.write('''
  1805. Please wait a moment while I gather a list of all available modules...
  1806.  
  1807. ''')
  1808.             modules = {}
  1809.             def callback(path, modname, desc, modules=modules):
  1810.                 if modname and modname[-9:] == '.__init__':
  1811.                     modname = modname[:-9] + ' (package)'
  1812.                 if find(modname, '.') < 0:
  1813.                     modules[modname] = 1
  1814.             ModuleScanner().run(callback)
  1815.             self.list(modules.keys())
  1816.             self.output.write('''
  1817. Enter any module name to get more help.  Or, type "modules spam" to search
  1818. for modules whose descriptions contain the word "spam".
  1819. ''')
  1820.  
  1821. help = Helper(sys.stdin, sys.stdout)
  1822.  
  1823. class Scanner:
  1824.     """A generic tree iterator."""
  1825.     def __init__(self, roots, children, descendp):
  1826.         self.roots = roots[:]
  1827.         self.state = []
  1828.         self.children = children
  1829.         self.descendp = descendp
  1830.  
  1831.     def next(self):
  1832.         if not self.state:
  1833.             if not self.roots:
  1834.                 return None
  1835.             root = self.roots.pop(0)
  1836.             self.state = [(root, self.children(root))]
  1837.         node, children = self.state[-1]
  1838.         if not children:
  1839.             self.state.pop()
  1840.             return self.next()
  1841.         child = children.pop(0)
  1842.         if self.descendp(child):
  1843.             self.state.append((child, self.children(child)))
  1844.         return child
  1845.  
  1846. class ModuleScanner(Scanner):
  1847.     """An interruptible scanner that searches module synopses."""
  1848.     def __init__(self):
  1849.         roots = map(lambda dir: (dir, ''), pathdirs())
  1850.         Scanner.__init__(self, roots, self.submodules, self.isnewpackage)
  1851.         self.inodes = map(lambda (dir, pkg): os.stat(dir).st_ino, roots)
  1852.  
  1853.     def submodules(self, (dir, package)):
  1854.         children = []
  1855.         for file in os.listdir(dir):
  1856.             path = os.path.join(dir, file)
  1857.             if ispackage(path):
  1858.                 children.append((path, package + (package and '.') + file))
  1859.             else:
  1860.                 children.append((path, package))
  1861.         children.sort() # so that spam.py comes before spam.pyc or spam.pyo
  1862.         return children
  1863.  
  1864.     def isnewpackage(self, (dir, package)):
  1865.         inode = os.path.exists(dir) and os.stat(dir).st_ino
  1866.         if not (os.path.islink(dir) and inode in self.inodes):
  1867.             self.inodes.append(inode) # detect circular symbolic links
  1868.             return ispackage(dir)
  1869.         return False
  1870.  
  1871.     def run(self, callback, key=None, completer=None):
  1872.         if key: key = lower(key)
  1873.         self.quit = False
  1874.         seen = {}
  1875.  
  1876.         for modname in sys.builtin_module_names:
  1877.             if modname != '__main__':
  1878.                 seen[modname] = 1
  1879.                 if key is None:
  1880.                     callback(None, modname, '')
  1881.                 else:
  1882.                     desc = split(__import__(modname).__doc__ or '', '\n')[0]
  1883.                     if find(lower(modname + ' - ' + desc), key) >= 0:
  1884.                         callback(None, modname, desc)
  1885.  
  1886.         while not self.quit:
  1887.             node = self.next()
  1888.             if not node: break
  1889.             path, package = node
  1890.             modname = inspect.getmodulename(path)
  1891.             if os.path.isfile(path) and modname:
  1892.                 modname = package + (package and '.') + modname
  1893.                 if not modname in seen:
  1894.                     seen[modname] = 1 # if we see spam.py, skip spam.pyc
  1895.                     if key is None:
  1896.                         callback(path, modname, '')
  1897.                     else:
  1898.                         desc = synopsis(path) or ''
  1899.                         if find(lower(modname + ' - ' + desc), key) >= 0:
  1900.                             callback(path, modname, desc)
  1901.         if completer: completer()
  1902.  
  1903. def apropos(key):
  1904.     """Print all the one-line module summaries that contain a substring."""
  1905.     def callback(path, modname, desc):
  1906.         if modname[-9:] == '.__init__':
  1907.             modname = modname[:-9] + ' (package)'
  1908.         print modname, desc and '- ' + desc
  1909.     try: import warnings
  1910.     except ImportError: pass
  1911.     else: warnings.filterwarnings('ignore') # ignore problems during import
  1912.     ModuleScanner().run(callback, key)
  1913.  
  1914. # --------------------------------------------------- web browser interface
  1915.  
  1916. def serve(port, callback=None, completer=None):
  1917.     import BaseHTTPServer, mimetools, select
  1918.  
  1919.     # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
  1920.     class Message(mimetools.Message):
  1921.         def __init__(self, fp, seekable=1):
  1922.             Message = self.__class__
  1923.             Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
  1924.             self.encodingheader = self.getheader('content-transfer-encoding')
  1925.             self.typeheader = self.getheader('content-type')
  1926.             self.parsetype()
  1927.             self.parseplist()
  1928.  
  1929.     class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  1930.         def send_document(self, title, contents):
  1931.             try:
  1932.                 self.send_response(200)
  1933.                 self.send_header('Content-Type', 'text/html')
  1934.                 self.end_headers()
  1935.                 self.wfile.write(html.page(title, contents))
  1936.             except IOError: pass
  1937.  
  1938.         def do_GET(self):
  1939.             path = self.path
  1940.             if path[-5:] == '.html': path = path[:-5]
  1941.             if path[:1] == '/': path = path[1:]
  1942.             if path and path != '.':
  1943.                 try:
  1944.                     obj = locate(path, forceload=1)
  1945.                 except ErrorDuringImport, value:
  1946.                     self.send_document(path, html.escape(str(value)))
  1947.                     return
  1948.                 if obj:
  1949.                     self.send_document(describe(obj), html.document(obj, path))
  1950.                 else:
  1951.                     self.send_document(path,
  1952. 'no Python documentation found for %s' % repr(path))
  1953.             else:
  1954.                 heading = html.heading(
  1955. '<big><big><strong>Python: Index of Modules</strong></big></big>',
  1956. '#ffffff', '#7799ee')
  1957.                 def bltinlink(name):
  1958.                     return '<a href="%s.html">%s</a>' % (name, name)
  1959.                 names = filter(lambda x: x != '__main__',
  1960.                                sys.builtin_module_names)
  1961.                 contents = html.multicolumn(names, bltinlink)
  1962.                 indices = ['<p>' + html.bigsection(
  1963.                     'Built-in Modules', '#ffffff', '#ee77aa', contents)]
  1964.  
  1965.                 seen = {}
  1966.                 for dir in pathdirs():
  1967.                     indices.append(html.index(dir, seen))
  1968.                 contents = heading + join(indices) + '''<p align=right>
  1969. <font color="#909090" face="helvetica, arial"><strong>
  1970. pydoc</strong> by Ka-Ping Yee <ping@lfw.org></font>'''
  1971.                 self.send_document('Index of Modules', contents)
  1972.  
  1973.         def log_message(self, *args): pass
  1974.  
  1975.     class DocServer(BaseHTTPServer.HTTPServer):
  1976.         def __init__(self, port, callback):
  1977.             host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
  1978.             self.address = ('', port)
  1979.             self.url = 'http://%s:%d/' % (host, port)
  1980.             self.callback = callback
  1981.             self.base.__init__(self, self.address, self.handler)
  1982.  
  1983.         def serve_until_quit(self):
  1984.             import select
  1985.             self.quit = False
  1986.             while not self.quit:
  1987.                 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
  1988.                 if rd: self.handle_request()
  1989.  
  1990.         def server_activate(self):
  1991.             self.base.server_activate(self)
  1992.             if self.callback: self.callback(self)
  1993.  
  1994.     DocServer.base = BaseHTTPServer.HTTPServer
  1995.     DocServer.handler = DocHandler
  1996.     DocHandler.MessageClass = Message
  1997.     try:
  1998.         try:
  1999.             DocServer(port, callback).serve_until_quit()
  2000.         except (KeyboardInterrupt, select.error):
  2001.             pass
  2002.     finally:
  2003.         if completer: completer()
  2004.  
  2005. # ----------------------------------------------------- graphical interface
  2006.  
  2007. def gui():
  2008.     """Graphical interface (starts web server and pops up a control window)."""
  2009.     class GUI:
  2010.         def __init__(self, window, port=7464):
  2011.             self.window = window
  2012.             self.server = None
  2013.             self.scanner = None
  2014.  
  2015.             import Tkinter
  2016.             self.server_frm = Tkinter.Frame(window)
  2017.             self.title_lbl = Tkinter.Label(self.server_frm,
  2018.                 text='Starting server...\n ')
  2019.             self.open_btn = Tkinter.Button(self.server_frm,
  2020.                 text='open browser', command=self.open, state='disabled')
  2021.             self.quit_btn = Tkinter.Button(self.server_frm,
  2022.                 text='quit serving', command=self.quit, state='disabled')
  2023.  
  2024.             self.search_frm = Tkinter.Frame(window)
  2025.             self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
  2026.             self.search_ent = Tkinter.Entry(self.search_frm)
  2027.             self.search_ent.bind('<Return>', self.search)
  2028.             self.stop_btn = Tkinter.Button(self.search_frm,
  2029.                 text='stop', pady=0, command=self.stop, state='disabled')
  2030.             if sys.platform == 'win32':
  2031.                 # Trying to hide and show this button crashes under Windows.
  2032.                 self.stop_btn.pack(side='right')
  2033.  
  2034.             self.window.title('pydoc')
  2035.             self.window.protocol('WM_DELETE_WINDOW', self.quit)
  2036.             self.title_lbl.pack(side='top', fill='x')
  2037.             self.open_btn.pack(side='left', fill='x', expand=1)
  2038.             self.quit_btn.pack(side='right', fill='x', expand=1)
  2039.             self.server_frm.pack(side='top', fill='x')
  2040.  
  2041.             self.search_lbl.pack(side='left')
  2042.             self.search_ent.pack(side='right', fill='x', expand=1)
  2043.             self.search_frm.pack(side='top', fill='x')
  2044.             self.search_ent.focus_set()
  2045.  
  2046.             font = ('helvetica', sys.platform == 'win32' and 8 or 10)
  2047.             self.result_lst = Tkinter.Listbox(window, font=font, height=6)
  2048.             self.result_lst.bind('<Button-1>', self.select)
  2049.             self.result_lst.bind('<Double-Button-1>', self.goto)
  2050.             self.result_scr = Tkinter.Scrollbar(window,
  2051.                 orient='vertical', command=self.result_lst.yview)
  2052.             self.result_lst.config(yscrollcommand=self.result_scr.set)
  2053.  
  2054.             self.result_frm = Tkinter.Frame(window)
  2055.             self.goto_btn = Tkinter.Button(self.result_frm,
  2056.                 text='go to selected', command=self.goto)
  2057.             self.hide_btn = Tkinter.Button(self.result_frm,
  2058.                 text='hide results', command=self.hide)
  2059.             self.goto_btn.pack(side='left', fill='x', expand=1)
  2060.             self.hide_btn.pack(side='right', fill='x', expand=1)
  2061.  
  2062.             self.window.update()
  2063.             self.minwidth = self.window.winfo_width()
  2064.             self.minheight = self.window.winfo_height()
  2065.             self.bigminheight = (self.server_frm.winfo_reqheight() +
  2066.                                  self.search_frm.winfo_reqheight() +
  2067.                                  self.result_lst.winfo_reqheight() +
  2068.                                  self.result_frm.winfo_reqheight())
  2069.             self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
  2070.             self.expanded = 0
  2071.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  2072.             self.window.wm_minsize(self.minwidth, self.minheight)
  2073.             self.window.tk.willdispatch()
  2074.  
  2075.             import threading
  2076.             threading.Thread(
  2077.                 target=serve, args=(port, self.ready, self.quit)).start()
  2078.  
  2079.         def ready(self, server):
  2080.             self.server = server
  2081.             self.title_lbl.config(
  2082.                 text='Python documentation server at\n' + server.url)
  2083.             self.open_btn.config(state='normal')
  2084.             self.quit_btn.config(state='normal')
  2085.  
  2086.         def open(self, event=None, url=None):
  2087.             url = url or self.server.url
  2088.             try:
  2089.                 import webbrowser
  2090.                 webbrowser.open(url)
  2091.             except ImportError: # pre-webbrowser.py compatibility
  2092.                 if sys.platform == 'win32':
  2093.                     os.system('start "%s"' % url)
  2094.                 elif sys.platform == 'mac':
  2095.                     try: import ic
  2096.                     except ImportError: pass
  2097.                     else: ic.launchurl(url)
  2098.                 else:
  2099.                     rc = os.system('netscape -remote "openURL(%s)" &' % url)
  2100.                     if rc: os.system('netscape "%s" &' % url)
  2101.  
  2102.         def quit(self, event=None):
  2103.             if self.server:
  2104.                 self.server.quit = 1
  2105.             self.window.quit()
  2106.  
  2107.         def search(self, event=None):
  2108.             key = self.search_ent.get()
  2109.             self.stop_btn.pack(side='right')
  2110.             self.stop_btn.config(state='normal')
  2111.             self.search_lbl.config(text='Searching for "%s"...' % key)
  2112.             self.search_ent.forget()
  2113.             self.search_lbl.pack(side='left')
  2114.             self.result_lst.delete(0, 'end')
  2115.             self.goto_btn.config(state='disabled')
  2116.             self.expand()
  2117.  
  2118.             import threading
  2119.             if self.scanner:
  2120.                 self.scanner.quit = 1
  2121.             self.scanner = ModuleScanner()
  2122.             threading.Thread(target=self.scanner.run,
  2123.                              args=(self.update, key, self.done)).start()
  2124.  
  2125.         def update(self, path, modname, desc):
  2126.             if modname[-9:] == '.__init__':
  2127.                 modname = modname[:-9] + ' (package)'
  2128.             self.result_lst.insert('end',
  2129.                 modname + ' - ' + (desc or '(no description)'))
  2130.  
  2131.         def stop(self, event=None):
  2132.             if self.scanner:
  2133.                 self.scanner.quit = 1
  2134.                 self.scanner = None
  2135.  
  2136.         def done(self):
  2137.             self.scanner = None
  2138.             self.search_lbl.config(text='Search for')
  2139.             self.search_lbl.pack(side='left')
  2140.             self.search_ent.pack(side='right', fill='x', expand=1)
  2141.             if sys.platform != 'win32': self.stop_btn.forget()
  2142.             self.stop_btn.config(state='disabled')
  2143.  
  2144.         def select(self, event=None):
  2145.             self.goto_btn.config(state='normal')
  2146.  
  2147.         def goto(self, event=None):
  2148.             selection = self.result_lst.curselection()
  2149.             if selection:
  2150.                 modname = split(self.result_lst.get(selection[0]))[0]
  2151.                 self.open(url=self.server.url + modname + '.html')
  2152.  
  2153.         def collapse(self):
  2154.             if not self.expanded: return
  2155.             self.result_frm.forget()
  2156.             self.result_scr.forget()
  2157.             self.result_lst.forget()
  2158.             self.bigwidth = self.window.winfo_width()
  2159.             self.bigheight = self.window.winfo_height()
  2160.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  2161.             self.window.wm_minsize(self.minwidth, self.minheight)
  2162.             self.expanded = 0
  2163.  
  2164.         def expand(self):
  2165.             if self.expanded: return
  2166.             self.result_frm.pack(side='bottom', fill='x')
  2167.             self.result_scr.pack(side='right', fill='y')
  2168.             self.result_lst.pack(side='top', fill='both', expand=1)
  2169.             self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
  2170.             self.window.wm_minsize(self.minwidth, self.bigminheight)
  2171.             self.expanded = 1
  2172.  
  2173.         def hide(self, event=None):
  2174.             self.stop()
  2175.             self.collapse()
  2176.  
  2177.     import Tkinter
  2178.     try:
  2179.         root = Tkinter.Tk()
  2180.         # Tk will crash if pythonw.exe has an XP .manifest
  2181.         # file and the root has is not destroyed explicitly.
  2182.         # If the problem is ever fixed in Tk, the explicit
  2183.         # destroy can go.
  2184.         try:
  2185.             gui = GUI(root)
  2186.             root.mainloop()
  2187.         finally:
  2188.             root.destroy()
  2189.     except KeyboardInterrupt:
  2190.         pass
  2191.  
  2192. # -------------------------------------------------- command-line interface
  2193.  
  2194. def ispath(x):
  2195.     return isinstance(x, str) and find(x, os.sep) >= 0
  2196.  
  2197. def cli():
  2198.     """Command-line interface (looks at sys.argv to decide what to do)."""
  2199.     import getopt
  2200.     class BadUsage: pass
  2201.  
  2202.     # Scripts don't get the current directory in their path by default.
  2203.     scriptdir = os.path.dirname(sys.argv[0])
  2204.     if scriptdir in sys.path:
  2205.         sys.path.remove(scriptdir)
  2206.     sys.path.insert(0, '.')
  2207.  
  2208.     try:
  2209.         opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
  2210.         writing = 0
  2211.  
  2212.         for opt, val in opts:
  2213.             if opt == '-g':
  2214.                 gui()
  2215.                 return
  2216.             if opt == '-k':
  2217.                 apropos(val)
  2218.                 return
  2219.             if opt == '-p':
  2220.                 try:
  2221.                     port = int(val)
  2222.                 except ValueError:
  2223.                     raise BadUsage
  2224.                 def ready(server):
  2225.                     print 'pydoc server ready at %s' % server.url
  2226.                 def stopped():
  2227.                     print 'pydoc server stopped'
  2228.                 serve(port, ready, stopped)
  2229.                 return
  2230.             if opt == '-w':
  2231.                 writing = 1
  2232.  
  2233.         if not args: raise BadUsage
  2234.         for arg in args:
  2235.             if ispath(arg) and not os.path.exists(arg):
  2236.                 print 'file %r does not exist' % arg
  2237.                 break
  2238.             try:
  2239.                 if ispath(arg) and os.path.isfile(arg):
  2240.                     arg = importfile(arg)
  2241.                 if writing:
  2242.                     if ispath(arg) and os.path.isdir(arg):
  2243.                         writedocs(arg)
  2244.                     else:
  2245.                         writedoc(arg)
  2246.                 else:
  2247.                     help.help(arg)
  2248.             except ErrorDuringImport, value:
  2249.                 print value
  2250.  
  2251.     except (getopt.error, BadUsage):
  2252.         cmd = os.path.basename(sys.argv[0])
  2253.         print """pydoc - the Python documentation tool
  2254.  
  2255. %s <name> ...
  2256.     Show text documentation on something.  <name> may be the name of a
  2257.     Python keyword, topic, function, module, or package, or a dotted
  2258.     reference to a class or function within a module or module in a
  2259.     package.  If <name> contains a '%s', it is used as the path to a
  2260.     Python source file to document. If name is 'keywords', 'topics',
  2261.     or 'modules', a listing of these things is displayed.
  2262.  
  2263. %s -k <keyword>
  2264.     Search for a keyword in the synopsis lines of all available modules.
  2265.  
  2266. %s -p <port>
  2267.     Start an HTTP server on the given port on the local machine.
  2268.  
  2269. %s -g
  2270.     Pop up a graphical interface for finding and serving documentation.
  2271.  
  2272. %s -w <name> ...
  2273.     Write out the HTML documentation for a module to a file in the current
  2274.     directory.  If <name> contains a '%s', it is treated as a filename; if
  2275.     it names a directory, documentation is written for all the contents.
  2276. """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
  2277.  
  2278. if __name__ == '__main__': cli()
  2279.