PageRenderTime 64ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/pydoc.py

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