PageRenderTime 65ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/plugins/PythonScript/lib/pydoc.py

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