PageRenderTime 32ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/pydoc.py

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