PageRenderTime 63ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/pydoc.py

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