PageRenderTime 69ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/pydoc.py

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