PageRenderTime 37ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/analyzefile/lib/python2.6/pydoc.py

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