PageRenderTime 59ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/setuptools/pydoc.py

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