logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

pydoc.py (109534B)


  1. #!/usr/bin/env python3
  2. """Generate Python documentation in HTML or text for interactive use.
  3. At the Python interactive prompt, calling help(thing) on a Python object
  4. documents the object, and calling help() starts up an interactive
  5. help session.
  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 -n <hostname>" to start an HTTP server with the given
  15. hostname (default: localhost) on the local machine.
  16. Run "pydoc -p <port>" to start an HTTP server on the given port on the
  17. local machine. Port number 0 can be used to get an arbitrary unused port.
  18. Run "pydoc -b" to start an HTTP server on an arbitrary unused port and
  19. open a web browser to interactively browse documentation. Combine with
  20. the -n and -p options to control the hostname and port used.
  21. Run "pydoc -w <name>" to write out the HTML documentation for a module
  22. to a file named "<name>.html".
  23. Module docs for core modules are assumed to be in
  24. https://docs.python.org/X.Y/library/
  25. This can be overridden by setting the PYTHONDOCS environment variable
  26. to a different URL or to a local directory containing the Library
  27. Reference Manual pages.
  28. """
  29. __all__ = ['help']
  30. __author__ = "Ka-Ping Yee <ping@lfw.org>"
  31. __date__ = "26 February 2001"
  32. __credits__ = """Guido van Rossum, for an excellent programming language.
  33. Tommy Burnette, the original creator of manpy.
  34. Paul Prescod, for all his work on onlinehelp.
  35. Richard Chamberlain, for the first implementation of textdoc.
  36. """
  37. # Known bugs that can't be fixed here:
  38. # - synopsis() cannot be prevented from clobbering existing
  39. # loaded modules.
  40. # - If the __file__ attribute on a module is a relative path and
  41. # the current directory is changed with os.chdir(), an incorrect
  42. # path will be displayed.
  43. import builtins
  44. import importlib._bootstrap
  45. import importlib._bootstrap_external
  46. import importlib.machinery
  47. import importlib.util
  48. import inspect
  49. import io
  50. import os
  51. import pkgutil
  52. import platform
  53. import re
  54. import sys
  55. import sysconfig
  56. import time
  57. import tokenize
  58. import urllib.parse
  59. import warnings
  60. from collections import deque
  61. from reprlib import Repr
  62. from traceback import format_exception_only
  63. # --------------------------------------------------------- common routines
  64. def pathdirs():
  65. """Convert sys.path into a list of absolute, existing, unique paths."""
  66. dirs = []
  67. normdirs = []
  68. for dir in sys.path:
  69. dir = os.path.abspath(dir or '.')
  70. normdir = os.path.normcase(dir)
  71. if normdir not in normdirs and os.path.isdir(dir):
  72. dirs.append(dir)
  73. normdirs.append(normdir)
  74. return dirs
  75. def _findclass(func):
  76. cls = sys.modules.get(func.__module__)
  77. if cls is None:
  78. return None
  79. for name in func.__qualname__.split('.')[:-1]:
  80. cls = getattr(cls, name)
  81. if not inspect.isclass(cls):
  82. return None
  83. return cls
  84. def _finddoc(obj):
  85. if inspect.ismethod(obj):
  86. name = obj.__func__.__name__
  87. self = obj.__self__
  88. if (inspect.isclass(self) and
  89. getattr(getattr(self, name, None), '__func__') is obj.__func__):
  90. # classmethod
  91. cls = self
  92. else:
  93. cls = self.__class__
  94. elif inspect.isfunction(obj):
  95. name = obj.__name__
  96. cls = _findclass(obj)
  97. if cls is None or getattr(cls, name) is not obj:
  98. return None
  99. elif inspect.isbuiltin(obj):
  100. name = obj.__name__
  101. self = obj.__self__
  102. if (inspect.isclass(self) and
  103. self.__qualname__ + '.' + name == obj.__qualname__):
  104. # classmethod
  105. cls = self
  106. else:
  107. cls = self.__class__
  108. # Should be tested before isdatadescriptor().
  109. elif isinstance(obj, property):
  110. func = obj.fget
  111. name = func.__name__
  112. cls = _findclass(func)
  113. if cls is None or getattr(cls, name) is not obj:
  114. return None
  115. elif inspect.ismethoddescriptor(obj) or inspect.isdatadescriptor(obj):
  116. name = obj.__name__
  117. cls = obj.__objclass__
  118. if getattr(cls, name) is not obj:
  119. return None
  120. if inspect.ismemberdescriptor(obj):
  121. slots = getattr(cls, '__slots__', None)
  122. if isinstance(slots, dict) and name in slots:
  123. return slots[name]
  124. else:
  125. return None
  126. for base in cls.__mro__:
  127. try:
  128. doc = _getowndoc(getattr(base, name))
  129. except AttributeError:
  130. continue
  131. if doc is not None:
  132. return doc
  133. return None
  134. def _getowndoc(obj):
  135. """Get the documentation string for an object if it is not
  136. inherited from its class."""
  137. try:
  138. doc = object.__getattribute__(obj, '__doc__')
  139. if doc is None:
  140. return None
  141. if obj is not type:
  142. typedoc = type(obj).__doc__
  143. if isinstance(typedoc, str) and typedoc == doc:
  144. return None
  145. return doc
  146. except AttributeError:
  147. return None
  148. def _getdoc(object):
  149. """Get the documentation string for an object.
  150. All tabs are expanded to spaces. To clean up docstrings that are
  151. indented to line up with blocks of code, any whitespace than can be
  152. uniformly removed from the second line onwards is removed."""
  153. doc = _getowndoc(object)
  154. if doc is None:
  155. try:
  156. doc = _finddoc(object)
  157. except (AttributeError, TypeError):
  158. return None
  159. if not isinstance(doc, str):
  160. return None
  161. return inspect.cleandoc(doc)
  162. def getdoc(object):
  163. """Get the doc string or comments for an object."""
  164. result = _getdoc(object) or inspect.getcomments(object)
  165. return result and re.sub('^ *\n', '', result.rstrip()) or ''
  166. def splitdoc(doc):
  167. """Split a doc string into a synopsis line (if any) and the rest."""
  168. lines = doc.strip().split('\n')
  169. if len(lines) == 1:
  170. return lines[0], ''
  171. elif len(lines) >= 2 and not lines[1].rstrip():
  172. return lines[0], '\n'.join(lines[2:])
  173. return '', '\n'.join(lines)
  174. def classname(object, modname):
  175. """Get a class name and qualify it with a module name if necessary."""
  176. name = object.__name__
  177. if object.__module__ != modname:
  178. name = object.__module__ + '.' + name
  179. return name
  180. def isdata(object):
  181. """Check if an object is of a type that probably means it's data."""
  182. return not (inspect.ismodule(object) or inspect.isclass(object) or
  183. inspect.isroutine(object) or inspect.isframe(object) or
  184. inspect.istraceback(object) or inspect.iscode(object))
  185. def replace(text, *pairs):
  186. """Do a series of global replacements on a string."""
  187. while pairs:
  188. text = pairs[1].join(text.split(pairs[0]))
  189. pairs = pairs[2:]
  190. return text
  191. def cram(text, maxlen):
  192. """Omit part of a string if needed to make it fit in a maximum length."""
  193. if len(text) > maxlen:
  194. pre = max(0, (maxlen-3)//2)
  195. post = max(0, maxlen-3-pre)
  196. return text[:pre] + '...' + text[len(text)-post:]
  197. return text
  198. _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
  199. def stripid(text):
  200. """Remove the hexadecimal id from a Python object representation."""
  201. # The behaviour of %p is implementation-dependent in terms of case.
  202. return _re_stripid.sub(r'\1', text)
  203. def _is_bound_method(fn):
  204. """
  205. Returns True if fn is a bound method, regardless of whether
  206. fn was implemented in Python or in C.
  207. """
  208. if inspect.ismethod(fn):
  209. return True
  210. if inspect.isbuiltin(fn):
  211. self = getattr(fn, '__self__', None)
  212. return not (inspect.ismodule(self) or (self is None))
  213. return False
  214. def allmethods(cl):
  215. methods = {}
  216. for key, value in inspect.getmembers(cl, inspect.isroutine):
  217. methods[key] = 1
  218. for base in cl.__bases__:
  219. methods.update(allmethods(base)) # all your base are belong to us
  220. for key in methods.keys():
  221. methods[key] = getattr(cl, key)
  222. return methods
  223. def _split_list(s, predicate):
  224. """Split sequence s via predicate, and return pair ([true], [false]).
  225. The return value is a 2-tuple of lists,
  226. ([x for x in s if predicate(x)],
  227. [x for x in s if not predicate(x)])
  228. """
  229. yes = []
  230. no = []
  231. for x in s:
  232. if predicate(x):
  233. yes.append(x)
  234. else:
  235. no.append(x)
  236. return yes, no
  237. def visiblename(name, all=None, obj=None):
  238. """Decide whether to show documentation on a variable."""
  239. # Certain special names are redundant or internal.
  240. # XXX Remove __initializing__?
  241. if name in {'__author__', '__builtins__', '__cached__', '__credits__',
  242. '__date__', '__doc__', '__file__', '__spec__',
  243. '__loader__', '__module__', '__name__', '__package__',
  244. '__path__', '__qualname__', '__slots__', '__version__'}:
  245. return 0
  246. # Private names are hidden, but special names are displayed.
  247. if name.startswith('__') and name.endswith('__'): return 1
  248. # Namedtuples have public fields and methods with a single leading underscore
  249. if name.startswith('_') and hasattr(obj, '_fields'):
  250. return True
  251. if all is not None:
  252. # only document that which the programmer exported in __all__
  253. return name in all
  254. else:
  255. return not name.startswith('_')
  256. def classify_class_attrs(object):
  257. """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
  258. results = []
  259. for (name, kind, cls, value) in inspect.classify_class_attrs(object):
  260. if inspect.isdatadescriptor(value):
  261. kind = 'data descriptor'
  262. if isinstance(value, property) and value.fset is None:
  263. kind = 'readonly property'
  264. results.append((name, kind, cls, value))
  265. return results
  266. def sort_attributes(attrs, object):
  267. 'Sort the attrs list in-place by _fields and then alphabetically by name'
  268. # This allows data descriptors to be ordered according
  269. # to a _fields attribute if present.
  270. fields = getattr(object, '_fields', [])
  271. try:
  272. field_order = {name : i-len(fields) for (i, name) in enumerate(fields)}
  273. except TypeError:
  274. field_order = {}
  275. keyfunc = lambda attr: (field_order.get(attr[0], 0), attr[0])
  276. attrs.sort(key=keyfunc)
  277. # ----------------------------------------------------- module manipulation
  278. def ispackage(path):
  279. """Guess whether a path refers to a package directory."""
  280. if os.path.isdir(path):
  281. for ext in ('.py', '.pyc'):
  282. if os.path.isfile(os.path.join(path, '__init__' + ext)):
  283. return True
  284. return False
  285. def source_synopsis(file):
  286. line = file.readline()
  287. while line[:1] == '#' or not line.strip():
  288. line = file.readline()
  289. if not line: break
  290. line = line.strip()
  291. if line[:4] == 'r"""': line = line[1:]
  292. if line[:3] == '"""':
  293. line = line[3:]
  294. if line[-1:] == '\\': line = line[:-1]
  295. while not line.strip():
  296. line = file.readline()
  297. if not line: break
  298. result = line.split('"""')[0].strip()
  299. else: result = None
  300. return result
  301. def synopsis(filename, cache={}):
  302. """Get the one-line summary out of a module file."""
  303. mtime = os.stat(filename).st_mtime
  304. lastupdate, result = cache.get(filename, (None, None))
  305. if lastupdate is None or lastupdate < mtime:
  306. # Look for binary suffixes first, falling back to source.
  307. if filename.endswith(tuple(importlib.machinery.BYTECODE_SUFFIXES)):
  308. loader_cls = importlib.machinery.SourcelessFileLoader
  309. elif filename.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):
  310. loader_cls = importlib.machinery.ExtensionFileLoader
  311. else:
  312. loader_cls = None
  313. # Now handle the choice.
  314. if loader_cls is None:
  315. # Must be a source file.
  316. try:
  317. file = tokenize.open(filename)
  318. except OSError:
  319. # module can't be opened, so skip it
  320. return None
  321. # text modules can be directly examined
  322. with file:
  323. result = source_synopsis(file)
  324. else:
  325. # Must be a binary module, which has to be imported.
  326. loader = loader_cls('__temp__', filename)
  327. # XXX We probably don't need to pass in the loader here.
  328. spec = importlib.util.spec_from_file_location('__temp__', filename,
  329. loader=loader)
  330. try:
  331. module = importlib._bootstrap._load(spec)
  332. except:
  333. return None
  334. del sys.modules['__temp__']
  335. result = module.__doc__.splitlines()[0] if module.__doc__ else None
  336. # Cache the result.
  337. cache[filename] = (mtime, result)
  338. return result
  339. class ErrorDuringImport(Exception):
  340. """Errors that occurred while trying to import something to document it."""
  341. def __init__(self, filename, exc_info):
  342. self.filename = filename
  343. self.exc, self.value, self.tb = exc_info
  344. def __str__(self):
  345. exc = self.exc.__name__
  346. return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
  347. def importfile(path):
  348. """Import a Python source file or compiled file given its path."""
  349. magic = importlib.util.MAGIC_NUMBER
  350. with open(path, 'rb') as file:
  351. is_bytecode = magic == file.read(len(magic))
  352. filename = os.path.basename(path)
  353. name, ext = os.path.splitext(filename)
  354. if is_bytecode:
  355. loader = importlib._bootstrap_external.SourcelessFileLoader(name, path)
  356. else:
  357. loader = importlib._bootstrap_external.SourceFileLoader(name, path)
  358. # XXX We probably don't need to pass in the loader here.
  359. spec = importlib.util.spec_from_file_location(name, path, loader=loader)
  360. try:
  361. return importlib._bootstrap._load(spec)
  362. except:
  363. raise ErrorDuringImport(path, sys.exc_info())
  364. def safeimport(path, forceload=0, cache={}):
  365. """Import a module; handle errors; return None if the module isn't found.
  366. If the module *is* found but an exception occurs, it's wrapped in an
  367. ErrorDuringImport exception and reraised. Unlike __import__, if a
  368. package path is specified, the module at the end of the path is returned,
  369. not the package at the beginning. If the optional 'forceload' argument
  370. is 1, we reload the module from disk (unless it's a dynamic extension)."""
  371. try:
  372. # If forceload is 1 and the module has been previously loaded from
  373. # disk, we always have to reload the module. Checking the file's
  374. # mtime isn't good enough (e.g. the module could contain a class
  375. # that inherits from another module that has changed).
  376. if forceload and path in sys.modules:
  377. if path not in sys.builtin_module_names:
  378. # Remove the module from sys.modules and re-import to try
  379. # and avoid problems with partially loaded modules.
  380. # Also remove any submodules because they won't appear
  381. # in the newly loaded module's namespace if they're already
  382. # in sys.modules.
  383. subs = [m for m in sys.modules if m.startswith(path + '.')]
  384. for key in [path] + subs:
  385. # Prevent garbage collection.
  386. cache[key] = sys.modules[key]
  387. del sys.modules[key]
  388. module = __import__(path)
  389. except:
  390. # Did the error occur before or after the module was found?
  391. (exc, value, tb) = info = sys.exc_info()
  392. if path in sys.modules:
  393. # An error occurred while executing the imported module.
  394. raise ErrorDuringImport(sys.modules[path].__file__, info)
  395. elif exc is SyntaxError:
  396. # A SyntaxError occurred before we could execute the module.
  397. raise ErrorDuringImport(value.filename, info)
  398. elif issubclass(exc, ImportError) and value.name == path:
  399. # No such module in the path.
  400. return None
  401. else:
  402. # Some other error occurred during the importing process.
  403. raise ErrorDuringImport(path, sys.exc_info())
  404. for part in path.split('.')[1:]:
  405. try: module = getattr(module, part)
  406. except AttributeError: return None
  407. return module
  408. # ---------------------------------------------------- formatter base class
  409. class Doc:
  410. PYTHONDOCS = os.environ.get("PYTHONDOCS",
  411. "https://docs.python.org/%d.%d/library"
  412. % sys.version_info[:2])
  413. def document(self, object, name=None, *args):
  414. """Generate documentation for an object."""
  415. args = (object, name) + args
  416. # 'try' clause is to attempt to handle the possibility that inspect
  417. # identifies something in a way that pydoc itself has issues handling;
  418. # think 'super' and how it is a descriptor (which raises the exception
  419. # by lacking a __name__ attribute) and an instance.
  420. try:
  421. if inspect.ismodule(object): return self.docmodule(*args)
  422. if inspect.isclass(object): return self.docclass(*args)
  423. if inspect.isroutine(object): return self.docroutine(*args)
  424. except AttributeError:
  425. pass
  426. if inspect.isdatadescriptor(object): return self.docdata(*args)
  427. return self.docother(*args)
  428. def fail(self, object, name=None, *args):
  429. """Raise an exception for unimplemented types."""
  430. message = "don't know how to document object%s of type %s" % (
  431. name and ' ' + repr(name), type(object).__name__)
  432. raise TypeError(message)
  433. docmodule = docclass = docroutine = docother = docproperty = docdata = fail
  434. def getdocloc(self, object, basedir=sysconfig.get_path('stdlib')):
  435. """Return the location of module docs or None"""
  436. try:
  437. file = inspect.getabsfile(object)
  438. except TypeError:
  439. file = '(built-in)'
  440. docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS)
  441. basedir = os.path.normcase(basedir)
  442. if (isinstance(object, type(os)) and
  443. (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
  444. 'marshal', 'posix', 'signal', 'sys',
  445. '_thread', 'zipimport') or
  446. (file.startswith(basedir) and
  447. not file.startswith(os.path.join(basedir, 'site-packages')))) and
  448. object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
  449. if docloc.startswith(("http://", "https://")):
  450. docloc = "{}/{}.html".format(docloc.rstrip("/"), object.__name__.lower())
  451. else:
  452. docloc = os.path.join(docloc, object.__name__.lower() + ".html")
  453. else:
  454. docloc = None
  455. return docloc
  456. # -------------------------------------------- HTML documentation generator
  457. class HTMLRepr(Repr):
  458. """Class for safely making an HTML representation of a Python object."""
  459. def __init__(self):
  460. Repr.__init__(self)
  461. self.maxlist = self.maxtuple = 20
  462. self.maxdict = 10
  463. self.maxstring = self.maxother = 100
  464. def escape(self, text):
  465. return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;')
  466. def repr(self, object):
  467. return Repr.repr(self, object)
  468. def repr1(self, x, level):
  469. if hasattr(type(x), '__name__'):
  470. methodname = 'repr_' + '_'.join(type(x).__name__.split())
  471. if hasattr(self, methodname):
  472. return getattr(self, methodname)(x, level)
  473. return self.escape(cram(stripid(repr(x)), self.maxother))
  474. def repr_string(self, x, level):
  475. test = cram(x, self.maxstring)
  476. testrepr = repr(test)
  477. if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  478. # Backslashes are only literal in the string and are never
  479. # needed to make any special characters, so show a raw string.
  480. return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
  481. return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
  482. r'<font color="#c040c0">\1</font>',
  483. self.escape(testrepr))
  484. repr_str = repr_string
  485. def repr_instance(self, x, level):
  486. try:
  487. return self.escape(cram(stripid(repr(x)), self.maxstring))
  488. except:
  489. return self.escape('<%s instance>' % x.__class__.__name__)
  490. repr_unicode = repr_string
  491. class HTMLDoc(Doc):
  492. """Formatter class for HTML documentation."""
  493. # ------------------------------------------- HTML formatting utilities
  494. _repr_instance = HTMLRepr()
  495. repr = _repr_instance.repr
  496. escape = _repr_instance.escape
  497. def page(self, title, contents):
  498. """Format an HTML page."""
  499. return '''\
  500. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  501. <html><head><title>Python: %s</title>
  502. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  503. </head><body bgcolor="#f0f0f8">
  504. %s
  505. </body></html>''' % (title, contents)
  506. def heading(self, title, fgcol, bgcol, extras=''):
  507. """Format a page heading."""
  508. return '''
  509. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
  510. <tr bgcolor="%s">
  511. <td valign=bottom>&nbsp;<br>
  512. <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td
  513. ><td align=right valign=bottom
  514. ><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
  515. ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
  516. def section(self, title, fgcol, bgcol, contents, width=6,
  517. prelude='', marginalia=None, gap='&nbsp;'):
  518. """Format a section with a heading."""
  519. if marginalia is None:
  520. marginalia = '<tt>' + '&nbsp;' * width + '</tt>'
  521. result = '''<p>
  522. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  523. <tr bgcolor="%s">
  524. <td colspan=3 valign=bottom>&nbsp;<br>
  525. <font color="%s" face="helvetica, arial">%s</font></td></tr>
  526. ''' % (bgcol, fgcol, title)
  527. if prelude:
  528. result = result + '''
  529. <tr bgcolor="%s"><td rowspan=2>%s</td>
  530. <td colspan=2>%s</td></tr>
  531. <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
  532. else:
  533. result = result + '''
  534. <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
  535. return result + '\n<td width="100%%">%s</td></tr></table>' % contents
  536. def bigsection(self, title, *args):
  537. """Format a section with a big heading."""
  538. title = '<big><strong>%s</strong></big>' % title
  539. return self.section(title, *args)
  540. def preformat(self, text):
  541. """Format literal preformatted text."""
  542. text = self.escape(text.expandtabs())
  543. return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
  544. ' ', '&nbsp;', '\n', '<br>\n')
  545. def multicolumn(self, list, format, cols=4):
  546. """Format a list of items into a multi-column list."""
  547. result = ''
  548. rows = (len(list)+cols-1)//cols
  549. for col in range(cols):
  550. result = result + '<td width="%d%%" valign=top>' % (100//cols)
  551. for i in range(rows*col, rows*col+rows):
  552. if i < len(list):
  553. result = result + format(list[i]) + '<br>\n'
  554. result = result + '</td>'
  555. return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
  556. def grey(self, text): return '<font color="#909090">%s</font>' % text
  557. def namelink(self, name, *dicts):
  558. """Make a link for an identifier, given name-to-URL mappings."""
  559. for dict in dicts:
  560. if name in dict:
  561. return '<a href="%s">%s</a>' % (dict[name], name)
  562. return name
  563. def classlink(self, object, modname):
  564. """Make a link for a class."""
  565. name, module = object.__name__, sys.modules.get(object.__module__)
  566. if hasattr(module, name) and getattr(module, name) is object:
  567. return '<a href="%s.html#%s">%s</a>' % (
  568. module.__name__, name, classname(object, modname))
  569. return classname(object, modname)
  570. def modulelink(self, object):
  571. """Make a link for a module."""
  572. return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
  573. def modpkglink(self, modpkginfo):
  574. """Make a link for a module or package to display in an index."""
  575. name, path, ispackage, shadowed = modpkginfo
  576. if shadowed:
  577. return self.grey(name)
  578. if path:
  579. url = '%s.%s.html' % (path, name)
  580. else:
  581. url = '%s.html' % name
  582. if ispackage:
  583. text = '<strong>%s</strong>&nbsp;(package)' % name
  584. else:
  585. text = name
  586. return '<a href="%s">%s</a>' % (url, text)
  587. def filelink(self, url, path):
  588. """Make a link to source file."""
  589. return '<a href="file:%s">%s</a>' % (url, path)
  590. def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
  591. """Mark up some plain text, given a context of symbols to look for.
  592. Each context dictionary maps object names to anchor names."""
  593. escape = escape or self.escape
  594. results = []
  595. here = 0
  596. pattern = re.compile(r'\b((http|https|ftp)://\S+[\w/]|'
  597. r'RFC[- ]?(\d+)|'
  598. r'PEP[- ]?(\d+)|'
  599. r'(self\.)?(\w+))')
  600. while True:
  601. match = pattern.search(text, here)
  602. if not match: break
  603. start, end = match.span()
  604. results.append(escape(text[here:start]))
  605. all, scheme, rfc, pep, selfdot, name = match.groups()
  606. if scheme:
  607. url = escape(all).replace('"', '&quot;')
  608. results.append('<a href="%s">%s</a>' % (url, url))
  609. elif rfc:
  610. url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  611. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  612. elif pep:
  613. url = 'https://www.python.org/dev/peps/pep-%04d/' % int(pep)
  614. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  615. elif selfdot:
  616. # Create a link for methods like 'self.method(...)'
  617. # and use <strong> for attributes like 'self.attr'
  618. if text[end:end+1] == '(':
  619. results.append('self.' + self.namelink(name, methods))
  620. else:
  621. results.append('self.<strong>%s</strong>' % name)
  622. elif text[end:end+1] == '(':
  623. results.append(self.namelink(name, methods, funcs, classes))
  624. else:
  625. results.append(self.namelink(name, classes))
  626. here = end
  627. results.append(escape(text[here:]))
  628. return ''.join(results)
  629. # ---------------------------------------------- type-specific routines
  630. def formattree(self, tree, modname, parent=None):
  631. """Produce HTML for a class tree as given by inspect.getclasstree()."""
  632. result = ''
  633. for entry in tree:
  634. if type(entry) is type(()):
  635. c, bases = entry
  636. result = result + '<dt><font face="helvetica, arial">'
  637. result = result + self.classlink(c, modname)
  638. if bases and bases != (parent,):
  639. parents = []
  640. for base in bases:
  641. parents.append(self.classlink(base, modname))
  642. result = result + '(' + ', '.join(parents) + ')'
  643. result = result + '\n</font></dt>'
  644. elif type(entry) is type([]):
  645. result = result + '<dd>\n%s</dd>\n' % self.formattree(
  646. entry, modname, c)
  647. return '<dl>\n%s</dl>\n' % result
  648. def docmodule(self, object, name=None, mod=None, *ignored):
  649. """Produce HTML documentation for a module object."""
  650. name = object.__name__ # ignore the passed-in name
  651. try:
  652. all = object.__all__
  653. except AttributeError:
  654. all = None
  655. parts = name.split('.')
  656. links = []
  657. for i in range(len(parts)-1):
  658. links.append(
  659. '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
  660. ('.'.join(parts[:i+1]), parts[i]))
  661. linkedname = '.'.join(links + parts[-1:])
  662. head = '<big><big><strong>%s</strong></big></big>' % linkedname
  663. try:
  664. path = inspect.getabsfile(object)
  665. url = urllib.parse.quote(path)
  666. filelink = self.filelink(url, path)
  667. except TypeError:
  668. filelink = '(built-in)'
  669. info = []
  670. if hasattr(object, '__version__'):
  671. version = str(object.__version__)
  672. if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  673. version = version[11:-1].strip()
  674. info.append('version %s' % self.escape(version))
  675. if hasattr(object, '__date__'):
  676. info.append(self.escape(str(object.__date__)))
  677. if info:
  678. head = head + ' (%s)' % ', '.join(info)
  679. docloc = self.getdocloc(object)
  680. if docloc is not None:
  681. docloc = '<br><a href="%(docloc)s">Module Reference</a>' % locals()
  682. else:
  683. docloc = ''
  684. result = self.heading(
  685. head, '#ffffff', '#7799ee',
  686. '<a href=".">index</a><br>' + filelink + docloc)
  687. modules = inspect.getmembers(object, inspect.ismodule)
  688. classes, cdict = [], {}
  689. for key, value in inspect.getmembers(object, inspect.isclass):
  690. # if __all__ exists, believe it. Otherwise use old heuristic.
  691. if (all is not None or
  692. (inspect.getmodule(value) or object) is object):
  693. if visiblename(key, all, object):
  694. classes.append((key, value))
  695. cdict[key] = cdict[value] = '#' + key
  696. for key, value in classes:
  697. for base in value.__bases__:
  698. key, modname = base.__name__, base.__module__
  699. module = sys.modules.get(modname)
  700. if modname != name and module and hasattr(module, key):
  701. if getattr(module, key) is base:
  702. if not key in cdict:
  703. cdict[key] = cdict[base] = modname + '.html#' + key
  704. funcs, fdict = [], {}
  705. for key, value in inspect.getmembers(object, inspect.isroutine):
  706. # if __all__ exists, believe it. Otherwise use old heuristic.
  707. if (all is not None or
  708. inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  709. if visiblename(key, all, object):
  710. funcs.append((key, value))
  711. fdict[key] = '#-' + key
  712. if inspect.isfunction(value): fdict[value] = fdict[key]
  713. data = []
  714. for key, value in inspect.getmembers(object, isdata):
  715. if visiblename(key, all, object):
  716. data.append((key, value))
  717. doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
  718. doc = doc and '<tt>%s</tt>' % doc
  719. result = result + '<p>%s</p>\n' % doc
  720. if hasattr(object, '__path__'):
  721. modpkgs = []
  722. for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  723. modpkgs.append((modname, name, ispkg, 0))
  724. modpkgs.sort()
  725. contents = self.multicolumn(modpkgs, self.modpkglink)
  726. result = result + self.bigsection(
  727. 'Package Contents', '#ffffff', '#aa55cc', contents)
  728. elif modules:
  729. contents = self.multicolumn(
  730. modules, lambda t: self.modulelink(t[1]))
  731. result = result + self.bigsection(
  732. 'Modules', '#ffffff', '#aa55cc', contents)
  733. if classes:
  734. classlist = [value for (key, value) in classes]
  735. contents = [
  736. self.formattree(inspect.getclasstree(classlist, 1), name)]
  737. for key, value in classes:
  738. contents.append(self.document(value, key, name, fdict, cdict))
  739. result = result + self.bigsection(
  740. 'Classes', '#ffffff', '#ee77aa', ' '.join(contents))
  741. if funcs:
  742. contents = []
  743. for key, value in funcs:
  744. contents.append(self.document(value, key, name, fdict, cdict))
  745. result = result + self.bigsection(
  746. 'Functions', '#ffffff', '#eeaa77', ' '.join(contents))
  747. if data:
  748. contents = []
  749. for key, value in data:
  750. contents.append(self.document(value, key))
  751. result = result + self.bigsection(
  752. 'Data', '#ffffff', '#55aa55', '<br>\n'.join(contents))
  753. if hasattr(object, '__author__'):
  754. contents = self.markup(str(object.__author__), self.preformat)
  755. result = result + self.bigsection(
  756. 'Author', '#ffffff', '#7799ee', contents)
  757. if hasattr(object, '__credits__'):
  758. contents = self.markup(str(object.__credits__), self.preformat)
  759. result = result + self.bigsection(
  760. 'Credits', '#ffffff', '#7799ee', contents)
  761. return result
  762. def docclass(self, object, name=None, mod=None, funcs={}, classes={},
  763. *ignored):
  764. """Produce HTML documentation for a class object."""
  765. realname = object.__name__
  766. name = name or realname
  767. bases = object.__bases__
  768. contents = []
  769. push = contents.append
  770. # Cute little class to pump out a horizontal rule between sections.
  771. class HorizontalRule:
  772. def __init__(self):
  773. self.needone = 0
  774. def maybe(self):
  775. if self.needone:
  776. push('<hr>\n')
  777. self.needone = 1
  778. hr = HorizontalRule()
  779. # List the mro, if non-trivial.
  780. mro = deque(inspect.getmro(object))
  781. if len(mro) > 2:
  782. hr.maybe()
  783. push('<dl><dt>Method resolution order:</dt>\n')
  784. for base in mro:
  785. push('<dd>%s</dd>\n' % self.classlink(base,
  786. object.__module__))
  787. push('</dl>\n')
  788. def spill(msg, attrs, predicate):
  789. ok, attrs = _split_list(attrs, predicate)
  790. if ok:
  791. hr.maybe()
  792. push(msg)
  793. for name, kind, homecls, value in ok:
  794. try:
  795. value = getattr(object, name)
  796. except Exception:
  797. # Some descriptors may meet a failure in their __get__.
  798. # (bug #1785)
  799. push(self.docdata(value, name, mod))
  800. else:
  801. push(self.document(value, name, mod,
  802. funcs, classes, mdict, object))
  803. push('\n')
  804. return attrs
  805. def spilldescriptors(msg, attrs, predicate):
  806. ok, attrs = _split_list(attrs, predicate)
  807. if ok:
  808. hr.maybe()
  809. push(msg)
  810. for name, kind, homecls, value in ok:
  811. push(self.docdata(value, name, mod))
  812. return attrs
  813. def spilldata(msg, attrs, predicate):
  814. ok, attrs = _split_list(attrs, predicate)
  815. if ok:
  816. hr.maybe()
  817. push(msg)
  818. for name, kind, homecls, value in ok:
  819. base = self.docother(getattr(object, name), name, mod)
  820. doc = getdoc(value)
  821. if not doc:
  822. push('<dl><dt>%s</dl>\n' % base)
  823. else:
  824. doc = self.markup(getdoc(value), self.preformat,
  825. funcs, classes, mdict)
  826. doc = '<dd><tt>%s</tt>' % doc
  827. push('<dl><dt>%s%s</dl>\n' % (base, doc))
  828. push('\n')
  829. return attrs
  830. attrs = [(name, kind, cls, value)
  831. for name, kind, cls, value in classify_class_attrs(object)
  832. if visiblename(name, obj=object)]
  833. mdict = {}
  834. for key, kind, homecls, value in attrs:
  835. mdict[key] = anchor = '#' + name + '-' + key
  836. try:
  837. value = getattr(object, name)
  838. except Exception:
  839. # Some descriptors may meet a failure in their __get__.
  840. # (bug #1785)
  841. pass
  842. try:
  843. # The value may not be hashable (e.g., a data attr with
  844. # a dict or list value).
  845. mdict[value] = anchor
  846. except TypeError:
  847. pass
  848. while attrs:
  849. if mro:
  850. thisclass = mro.popleft()
  851. else:
  852. thisclass = attrs[0][2]
  853. attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  854. if object is not builtins.object and thisclass is builtins.object:
  855. attrs = inherited
  856. continue
  857. elif thisclass is object:
  858. tag = 'defined here'
  859. else:
  860. tag = 'inherited from %s' % self.classlink(thisclass,
  861. object.__module__)
  862. tag += ':<br>\n'
  863. sort_attributes(attrs, object)
  864. # Pump out the attrs, segregated by kind.
  865. attrs = spill('Methods %s' % tag, attrs,
  866. lambda t: t[1] == 'method')
  867. attrs = spill('Class methods %s' % tag, attrs,
  868. lambda t: t[1] == 'class method')
  869. attrs = spill('Static methods %s' % tag, attrs,
  870. lambda t: t[1] == 'static method')
  871. attrs = spilldescriptors("Readonly properties %s" % tag, attrs,
  872. lambda t: t[1] == 'readonly property')
  873. attrs = spilldescriptors('Data descriptors %s' % tag, attrs,
  874. lambda t: t[1] == 'data descriptor')
  875. attrs = spilldata('Data and other attributes %s' % tag, attrs,
  876. lambda t: t[1] == 'data')
  877. assert attrs == []
  878. attrs = inherited
  879. contents = ''.join(contents)
  880. if name == realname:
  881. title = '<a name="%s">class <strong>%s</strong></a>' % (
  882. name, realname)
  883. else:
  884. title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
  885. name, name, realname)
  886. if bases:
  887. parents = []
  888. for base in bases:
  889. parents.append(self.classlink(base, object.__module__))
  890. title = title + '(%s)' % ', '.join(parents)
  891. decl = ''
  892. try:
  893. signature = inspect.signature(object)
  894. except (ValueError, TypeError):
  895. signature = None
  896. if signature:
  897. argspec = str(signature)
  898. if argspec and argspec != '()':
  899. decl = name + self.escape(argspec) + '\n\n'
  900. doc = getdoc(object)
  901. if decl:
  902. doc = decl + (doc or '')
  903. doc = self.markup(doc, self.preformat, funcs, classes, mdict)
  904. doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc
  905. return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
  906. def formatvalue(self, object):
  907. """Format an argument default value as text."""
  908. return self.grey('=' + self.repr(object))
  909. def docroutine(self, object, name=None, mod=None,
  910. funcs={}, classes={}, methods={}, cl=None):
  911. """Produce HTML documentation for a function or method object."""
  912. realname = object.__name__
  913. name = name or realname
  914. anchor = (cl and cl.__name__ or '') + '-' + name
  915. note = ''
  916. skipdocs = 0
  917. if _is_bound_method(object):
  918. imclass = object.__self__.__class__
  919. if cl:
  920. if imclass is not cl:
  921. note = ' from ' + self.classlink(imclass, mod)
  922. else:
  923. if object.__self__ is not None:
  924. note = ' method of %s instance' % self.classlink(
  925. object.__self__.__class__, mod)
  926. else:
  927. note = ' unbound %s method' % self.classlink(imclass,mod)
  928. if (inspect.iscoroutinefunction(object) or
  929. inspect.isasyncgenfunction(object)):
  930. asyncqualifier = 'async '
  931. else:
  932. asyncqualifier = ''
  933. if name == realname:
  934. title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
  935. else:
  936. if cl and inspect.getattr_static(cl, realname, []) is object:
  937. reallink = '<a href="#%s">%s</a>' % (
  938. cl.__name__ + '-' + realname, realname)
  939. skipdocs = 1
  940. else:
  941. reallink = realname
  942. title = '<a name="%s"><strong>%s</strong></a> = %s' % (
  943. anchor, name, reallink)
  944. argspec = None
  945. if inspect.isroutine(object):
  946. try:
  947. signature = inspect.signature(object)
  948. except (ValueError, TypeError):
  949. signature = None
  950. if signature:
  951. argspec = str(signature)
  952. if realname == '<lambda>':
  953. title = '<strong>%s</strong> <em>lambda</em> ' % name
  954. # XXX lambda's won't usually have func_annotations['return']
  955. # since the syntax doesn't support but it is possible.
  956. # So removing parentheses isn't truly safe.
  957. argspec = argspec[1:-1] # remove parentheses
  958. if not argspec:
  959. argspec = '(...)'
  960. decl = asyncqualifier + title + self.escape(argspec) + (note and
  961. self.grey('<font face="helvetica, arial">%s</font>' % note))
  962. if skipdocs:
  963. return '<dl><dt>%s</dt></dl>\n' % decl
  964. else:
  965. doc = self.markup(
  966. getdoc(object), self.preformat, funcs, classes, methods)
  967. doc = doc and '<dd><tt>%s</tt></dd>' % doc
  968. return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  969. def docdata(self, object, name=None, mod=None, cl=None):
  970. """Produce html documentation for a data descriptor."""
  971. results = []
  972. push = results.append
  973. if name:
  974. push('<dl><dt><strong>%s</strong></dt>\n' % name)
  975. doc = self.markup(getdoc(object), self.preformat)
  976. if doc:
  977. push('<dd><tt>%s</tt></dd>\n' % doc)
  978. push('</dl>\n')
  979. return ''.join(results)
  980. docproperty = docdata
  981. def docother(self, object, name=None, mod=None, *ignored):
  982. """Produce HTML documentation for a data object."""
  983. lhs = name and '<strong>%s</strong> = ' % name or ''
  984. return lhs + self.repr(object)
  985. def index(self, dir, shadowed=None):
  986. """Generate an HTML index for a directory of modules."""
  987. modpkgs = []
  988. if shadowed is None: shadowed = {}
  989. for importer, name, ispkg in pkgutil.iter_modules([dir]):
  990. if any((0xD800 <= ord(ch) <= 0xDFFF) for ch in name):
  991. # ignore a module if its name contains a surrogate character
  992. continue
  993. modpkgs.append((name, '', ispkg, name in shadowed))
  994. shadowed[name] = 1
  995. modpkgs.sort()
  996. contents = self.multicolumn(modpkgs, self.modpkglink)
  997. return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
  998. # -------------------------------------------- text documentation generator
  999. class TextRepr(Repr):
  1000. """Class for safely making a text representation of a Python object."""
  1001. def __init__(self):
  1002. Repr.__init__(self)
  1003. self.maxlist = self.maxtuple = 20
  1004. self.maxdict = 10
  1005. self.maxstring = self.maxother = 100
  1006. def repr1(self, x, level):
  1007. if hasattr(type(x), '__name__'):
  1008. methodname = 'repr_' + '_'.join(type(x).__name__.split())
  1009. if hasattr(self, methodname):
  1010. return getattr(self, methodname)(x, level)
  1011. return cram(stripid(repr(x)), self.maxother)
  1012. def repr_string(self, x, level):
  1013. test = cram(x, self.maxstring)
  1014. testrepr = repr(test)
  1015. if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  1016. # Backslashes are only literal in the string and are never
  1017. # needed to make any special characters, so show a raw string.
  1018. return 'r' + testrepr[0] + test + testrepr[0]
  1019. return testrepr
  1020. repr_str = repr_string
  1021. def repr_instance(self, x, level):
  1022. try:
  1023. return cram(stripid(repr(x)), self.maxstring)
  1024. except:
  1025. return '<%s instance>' % x.__class__.__name__
  1026. class TextDoc(Doc):
  1027. """Formatter class for text documentation."""
  1028. # ------------------------------------------- text formatting utilities
  1029. _repr_instance = TextRepr()
  1030. repr = _repr_instance.repr
  1031. def bold(self, text):
  1032. """Format a string in bold by overstriking."""
  1033. return ''.join(ch + '\b' + ch for ch in text)
  1034. def indent(self, text, prefix=' '):
  1035. """Indent text by prepending a given prefix to each line."""
  1036. if not text: return ''
  1037. lines = [prefix + line for line in text.split('\n')]
  1038. if lines: lines[-1] = lines[-1].rstrip()
  1039. return '\n'.join(lines)
  1040. def section(self, title, contents):
  1041. """Format a section with a given heading."""
  1042. clean_contents = self.indent(contents).rstrip()
  1043. return self.bold(title) + '\n' + clean_contents + '\n\n'
  1044. # ---------------------------------------------- type-specific routines
  1045. def formattree(self, tree, modname, parent=None, prefix=''):
  1046. """Render in text a class tree as returned by inspect.getclasstree()."""
  1047. result = ''
  1048. for entry in tree:
  1049. if type(entry) is type(()):
  1050. c, bases = entry
  1051. result = result + prefix + classname(c, modname)
  1052. if bases and bases != (parent,):
  1053. parents = (classname(c, modname) for c in bases)
  1054. result = result + '(%s)' % ', '.join(parents)
  1055. result = result + '\n'
  1056. elif type(entry) is type([]):
  1057. result = result + self.formattree(
  1058. entry, modname, c, prefix + ' ')
  1059. return result
  1060. def docmodule(self, object, name=None, mod=None):
  1061. """Produce text documentation for a given module object."""
  1062. name = object.__name__ # ignore the passed-in name
  1063. synop, desc = splitdoc(getdoc(object))
  1064. result = self.section('NAME', name + (synop and ' - ' + synop))
  1065. all = getattr(object, '__all__', None)
  1066. docloc = self.getdocloc(object)
  1067. if docloc is not None:
  1068. result = result + self.section('MODULE REFERENCE', docloc + """
  1069. The following documentation is automatically generated from the Python
  1070. source files. It may be incomplete, incorrect or include features that
  1071. are considered implementation detail and may vary between Python
  1072. implementations. When in doubt, consult the module reference at the
  1073. location listed above.
  1074. """)
  1075. if desc:
  1076. result = result + self.section('DESCRIPTION', desc)
  1077. classes = []
  1078. for key, value in inspect.getmembers(object, inspect.isclass):
  1079. # if __all__ exists, believe it. Otherwise use old heuristic.
  1080. if (all is not None
  1081. or (inspect.getmodule(value) or object) is object):
  1082. if visiblename(key, all, object):
  1083. classes.append((key, value))
  1084. funcs = []
  1085. for key, value in inspect.getmembers(object, inspect.isroutine):
  1086. # if __all__ exists, believe it. Otherwise use old heuristic.
  1087. if (all is not None or
  1088. inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  1089. if visiblename(key, all, object):
  1090. funcs.append((key, value))
  1091. data = []
  1092. for key, value in inspect.getmembers(object, isdata):
  1093. if visiblename(key, all, object):
  1094. data.append((key, value))
  1095. modpkgs = []
  1096. modpkgs_names = set()
  1097. if hasattr(object, '__path__'):
  1098. for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  1099. modpkgs_names.add(modname)
  1100. if ispkg:
  1101. modpkgs.append(modname + ' (package)')
  1102. else:
  1103. modpkgs.append(modname)
  1104. modpkgs.sort()
  1105. result = result + self.section(
  1106. 'PACKAGE CONTENTS', '\n'.join(modpkgs))
  1107. # Detect submodules as sometimes created by C extensions
  1108. submodules = []
  1109. for key, value in inspect.getmembers(object, inspect.ismodule):
  1110. if value.__name__.startswith(name + '.') and key not in modpkgs_names:
  1111. submodules.append(key)
  1112. if submodules:
  1113. submodules.sort()
  1114. result = result + self.section(
  1115. 'SUBMODULES', '\n'.join(submodules))
  1116. if classes:
  1117. classlist = [value for key, value in classes]
  1118. contents = [self.formattree(
  1119. inspect.getclasstree(classlist, 1), name)]
  1120. for key, value in classes:
  1121. contents.append(self.document(value, key, name))
  1122. result = result + self.section('CLASSES', '\n'.join(contents))
  1123. if funcs:
  1124. contents = []
  1125. for key, value in funcs:
  1126. contents.append(self.document(value, key, name))
  1127. result = result + self.section('FUNCTIONS', '\n'.join(contents))
  1128. if data:
  1129. contents = []
  1130. for key, value in data:
  1131. contents.append(self.docother(value, key, name, maxlen=70))
  1132. result = result + self.section('DATA', '\n'.join(contents))
  1133. if hasattr(object, '__version__'):
  1134. version = str(object.__version__)
  1135. if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  1136. version = version[11:-1].strip()
  1137. result = result + self.section('VERSION', version)
  1138. if hasattr(object, '__date__'):
  1139. result = result + self.section('DATE', str(object.__date__))
  1140. if hasattr(object, '__author__'):
  1141. result = result + self.section('AUTHOR', str(object.__author__))
  1142. if hasattr(object, '__credits__'):
  1143. result = result + self.section('CREDITS', str(object.__credits__))
  1144. try:
  1145. file = inspect.getabsfile(object)
  1146. except TypeError:
  1147. file = '(built-in)'
  1148. result = result + self.section('FILE', file)
  1149. return result
  1150. def docclass(self, object, name=None, mod=None, *ignored):
  1151. """Produce text documentation for a given class object."""
  1152. realname = object.__name__
  1153. name = name or realname
  1154. bases = object.__bases__
  1155. def makename(c, m=object.__module__):
  1156. return classname(c, m)
  1157. if name == realname:
  1158. title = 'class ' + self.bold(realname)
  1159. else:
  1160. title = self.bold(name) + ' = class ' + realname
  1161. if bases:
  1162. parents = map(makename, bases)
  1163. title = title + '(%s)' % ', '.join(parents)
  1164. contents = []
  1165. push = contents.append
  1166. try:
  1167. signature = inspect.signature(object)
  1168. except (ValueError, TypeError):
  1169. signature = None
  1170. if signature:
  1171. argspec = str(signature)
  1172. if argspec and argspec != '()':
  1173. push(name + argspec + '\n')
  1174. doc = getdoc(object)
  1175. if doc:
  1176. push(doc + '\n')
  1177. # List the mro, if non-trivial.
  1178. mro = deque(inspect.getmro(object))
  1179. if len(mro) > 2:
  1180. push("Method resolution order:")
  1181. for base in mro:
  1182. push(' ' + makename(base))
  1183. push('')
  1184. # List the built-in subclasses, if any:
  1185. subclasses = sorted(
  1186. (str(cls.__name__) for cls in type.__subclasses__(object)
  1187. if not cls.__name__.startswith("_") and cls.__module__ == "builtins"),
  1188. key=str.lower
  1189. )
  1190. no_of_subclasses = len(subclasses)
  1191. MAX_SUBCLASSES_TO_DISPLAY = 4
  1192. if subclasses:
  1193. push("Built-in subclasses:")
  1194. for subclassname in subclasses[:MAX_SUBCLASSES_TO_DISPLAY]:
  1195. push(' ' + subclassname)
  1196. if no_of_subclasses > MAX_SUBCLASSES_TO_DISPLAY:
  1197. push(' ... and ' +
  1198. str(no_of_subclasses - MAX_SUBCLASSES_TO_DISPLAY) +
  1199. ' other subclasses')
  1200. push('')
  1201. # Cute little class to pump out a horizontal rule between sections.
  1202. class HorizontalRule:
  1203. def __init__(self):
  1204. self.needone = 0
  1205. def maybe(self):
  1206. if self.needone:
  1207. push('-' * 70)
  1208. self.needone = 1
  1209. hr = HorizontalRule()
  1210. def spill(msg, attrs, predicate):
  1211. ok, attrs = _split_list(attrs, predicate)
  1212. if ok:
  1213. hr.maybe()
  1214. push(msg)
  1215. for name, kind, homecls, value in ok:
  1216. try:
  1217. value = getattr(object, name)
  1218. except Exception:
  1219. # Some descriptors may meet a failure in their __get__.
  1220. # (bug #1785)
  1221. push(self.docdata(value, name, mod))
  1222. else:
  1223. push(self.document(value,
  1224. name, mod, object))
  1225. return attrs
  1226. def spilldescriptors(msg, attrs, predicate):
  1227. ok, attrs = _split_list(attrs, predicate)
  1228. if ok:
  1229. hr.maybe()
  1230. push(msg)
  1231. for name, kind, homecls, value in ok:
  1232. push(self.docdata(value, name, mod))
  1233. return attrs
  1234. def spilldata(msg, attrs, predicate):
  1235. ok, attrs = _split_list(attrs, predicate)
  1236. if ok:
  1237. hr.maybe()
  1238. push(msg)
  1239. for name, kind, homecls, value in ok:
  1240. doc = getdoc(value)
  1241. try:
  1242. obj = getattr(object, name)
  1243. except AttributeError:
  1244. obj = homecls.__dict__[name]
  1245. push(self.docother(obj, name, mod, maxlen=70, doc=doc) +
  1246. '\n')
  1247. return attrs
  1248. attrs = [(name, kind, cls, value)
  1249. for name, kind, cls, value in classify_class_attrs(object)
  1250. if visiblename(name, obj=object)]
  1251. while attrs:
  1252. if mro:
  1253. thisclass = mro.popleft()
  1254. else:
  1255. thisclass = attrs[0][2]
  1256. attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  1257. if object is not builtins.object and thisclass is builtins.object:
  1258. attrs = inherited
  1259. continue
  1260. elif thisclass is object:
  1261. tag = "defined here"
  1262. else:
  1263. tag = "inherited from %s" % classname(thisclass,
  1264. object.__module__)
  1265. sort_attributes(attrs, object)
  1266. # Pump out the attrs, segregated by kind.
  1267. attrs = spill("Methods %s:\n" % tag, attrs,
  1268. lambda t: t[1] == 'method')
  1269. attrs = spill("Class methods %s:\n" % tag, attrs,
  1270. lambda t: t[1] == 'class method')
  1271. attrs = spill("Static methods %s:\n" % tag, attrs,
  1272. lambda t: t[1] == 'static method')
  1273. attrs = spilldescriptors("Readonly properties %s:\n" % tag, attrs,
  1274. lambda t: t[1] == 'readonly property')
  1275. attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
  1276. lambda t: t[1] == 'data descriptor')
  1277. attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
  1278. lambda t: t[1] == 'data')
  1279. assert attrs == []
  1280. attrs = inherited
  1281. contents = '\n'.join(contents)
  1282. if not contents:
  1283. return title + '\n'
  1284. return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n'
  1285. def formatvalue(self, object):
  1286. """Format an argument default value as text."""
  1287. return '=' + self.repr(object)
  1288. def docroutine(self, object, name=None, mod=None, cl=None):
  1289. """Produce text documentation for a function or method object."""
  1290. realname = object.__name__
  1291. name = name or realname
  1292. note = ''
  1293. skipdocs = 0
  1294. if _is_bound_method(object):
  1295. imclass = object.__self__.__class__
  1296. if cl:
  1297. if imclass is not cl:
  1298. note = ' from ' + classname(imclass, mod)
  1299. else:
  1300. if object.__self__ is not None:
  1301. note = ' method of %s instance' % classname(
  1302. object.__self__.__class__, mod)
  1303. else:
  1304. note = ' unbound %s method' % classname(imclass,mod)
  1305. if (inspect.iscoroutinefunction(object) or
  1306. inspect.isasyncgenfunction(object)):
  1307. asyncqualifier = 'async '
  1308. else:
  1309. asyncqualifier = ''
  1310. if name == realname:
  1311. title = self.bold(realname)
  1312. else:
  1313. if cl and inspect.getattr_static(cl, realname, []) is object:
  1314. skipdocs = 1
  1315. title = self.bold(name) + ' = ' + realname
  1316. argspec = None
  1317. if inspect.isroutine(object):
  1318. try:
  1319. signature = inspect.signature(object)
  1320. except (ValueError, TypeError):
  1321. signature = None
  1322. if signature:
  1323. argspec = str(signature)
  1324. if realname == '<lambda>':
  1325. title = self.bold(name) + ' lambda '
  1326. # XXX lambda's won't usually have func_annotations['return']
  1327. # since the syntax doesn't support but it is possible.
  1328. # So removing parentheses isn't truly safe.
  1329. argspec = argspec[1:-1] # remove parentheses
  1330. if not argspec:
  1331. argspec = '(...)'
  1332. decl = asyncqualifier + title + argspec + note
  1333. if skipdocs:
  1334. return decl + '\n'
  1335. else:
  1336. doc = getdoc(object) or ''
  1337. return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
  1338. def docdata(self, object, name=None, mod=None, cl=None):
  1339. """Produce text documentation for a data descriptor."""
  1340. results = []
  1341. push = results.append
  1342. if name:
  1343. push(self.bold(name))
  1344. push('\n')
  1345. doc = getdoc(object) or ''
  1346. if doc:
  1347. push(self.indent(doc))
  1348. push('\n')
  1349. return ''.join(results)
  1350. docproperty = docdata
  1351. def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
  1352. """Produce text documentation for a data object."""
  1353. repr = self.repr(object)
  1354. if maxlen:
  1355. line = (name and name + ' = ' or '') + repr
  1356. chop = maxlen - len(line)
  1357. if chop < 0: repr = repr[:chop] + '...'
  1358. line = (name and self.bold(name) + ' = ' or '') + repr
  1359. if not doc:
  1360. doc = getdoc(object)
  1361. if doc:
  1362. line += '\n' + self.indent(str(doc)) + '\n'
  1363. return line
  1364. class _PlainTextDoc(TextDoc):
  1365. """Subclass of TextDoc which overrides string styling"""
  1366. def bold(self, text):
  1367. return text
  1368. # --------------------------------------------------------- user interfaces
  1369. def pager(text):
  1370. """The first time this is called, determine what kind of pager to use."""
  1371. global pager
  1372. pager = getpager()
  1373. pager(text)
  1374. def getpager():
  1375. """Decide what method to use for paging through text."""
  1376. if not hasattr(sys.stdin, "isatty"):
  1377. return plainpager
  1378. if not hasattr(sys.stdout, "isatty"):
  1379. return plainpager
  1380. if not sys.stdin.isatty() or not sys.stdout.isatty():
  1381. return plainpager
  1382. use_pager = os.environ.get('MANPAGER') or os.environ.get('PAGER')
  1383. if use_pager:
  1384. if sys.platform == 'win32': # pipes completely broken in Windows
  1385. return lambda text: tempfilepager(plain(text), use_pager)
  1386. elif os.environ.get('TERM') in ('dumb', 'emacs'):
  1387. return lambda text: pipepager(plain(text), use_pager)
  1388. else:
  1389. return lambda text: pipepager(text, use_pager)
  1390. if os.environ.get('TERM') in ('dumb', 'emacs'):
  1391. return plainpager
  1392. if sys.platform == 'win32':
  1393. return lambda text: tempfilepager(plain(text), 'more <')
  1394. if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
  1395. return lambda text: pipepager(text, 'less')
  1396. import tempfile
  1397. (fd, filename) = tempfile.mkstemp()
  1398. os.close(fd)
  1399. try:
  1400. if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
  1401. return lambda text: pipepager(text, 'more')
  1402. else:
  1403. return ttypager
  1404. finally:
  1405. os.unlink(filename)
  1406. def plain(text):
  1407. """Remove boldface formatting from text."""
  1408. return re.sub('.\b', '', text)
  1409. def pipepager(text, cmd):
  1410. """Page through text by feeding it to another program."""
  1411. import subprocess
  1412. proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
  1413. errors='backslashreplace')
  1414. try:
  1415. with proc.stdin as pipe:
  1416. try:
  1417. pipe.write(text)
  1418. except KeyboardInterrupt:
  1419. # We've hereby abandoned whatever text hasn't been written,
  1420. # but the pager is still in control of the terminal.
  1421. pass
  1422. except OSError:
  1423. pass # Ignore broken pipes caused by quitting the pager program.
  1424. while True:
  1425. try:
  1426. proc.wait()
  1427. break
  1428. except KeyboardInterrupt:
  1429. # Ignore ctl-c like the pager itself does. Otherwise the pager is
  1430. # left running and the terminal is in raw mode and unusable.
  1431. pass
  1432. def tempfilepager(text, cmd):
  1433. """Page through text by invoking a program on a temporary file."""
  1434. import tempfile
  1435. with tempfile.TemporaryDirectory() as tempdir:
  1436. filename = os.path.join(tempdir, 'pydoc.out')
  1437. with open(filename, 'w', errors='backslashreplace',
  1438. encoding=os.device_encoding(0) if
  1439. sys.platform == 'win32' else None
  1440. ) as file:
  1441. file.write(text)
  1442. os.system(cmd + ' "' + filename + '"')
  1443. def _escape_stdout(text):
  1444. # Escape non-encodable characters to avoid encoding errors later
  1445. encoding = getattr(sys.stdout, 'encoding', None) or 'utf-8'
  1446. return text.encode(encoding, 'backslashreplace').decode(encoding)
  1447. def ttypager(text):
  1448. """Page through text on a text terminal."""
  1449. lines = plain(_escape_stdout(text)).split('\n')
  1450. try:
  1451. import tty
  1452. fd = sys.stdin.fileno()
  1453. old = tty.tcgetattr(fd)
  1454. tty.setcbreak(fd)
  1455. getchar = lambda: sys.stdin.read(1)
  1456. except (ImportError, AttributeError, io.UnsupportedOperation):
  1457. tty = None
  1458. getchar = lambda: sys.stdin.readline()[:-1][:1]
  1459. try:
  1460. try:
  1461. h = int(os.environ.get('LINES', 0))
  1462. except ValueError:
  1463. h = 0
  1464. if h <= 1:
  1465. h = 25
  1466. r = inc = h - 1
  1467. sys.stdout.write('\n'.join(lines[:inc]) + '\n')
  1468. while lines[r:]:
  1469. sys.stdout.write('-- more --')
  1470. sys.stdout.flush()
  1471. c = getchar()
  1472. if c in ('q', 'Q'):
  1473. sys.stdout.write('\r \r')
  1474. break
  1475. elif c in ('\r', '\n'):
  1476. sys.stdout.write('\r \r' + lines[r] + '\n')
  1477. r = r + 1
  1478. continue
  1479. if c in ('b', 'B', '\x1b'):
  1480. r = r - inc - inc
  1481. if r < 0: r = 0
  1482. sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
  1483. r = r + inc
  1484. finally:
  1485. if tty:
  1486. tty.tcsetattr(fd, tty.TCSAFLUSH, old)
  1487. def plainpager(text):
  1488. """Simply print unformatted text. This is the ultimate fallback."""
  1489. sys.stdout.write(plain(_escape_stdout(text)))
  1490. def describe(thing):
  1491. """Produce a short description of the given thing."""
  1492. if inspect.ismodule(thing):
  1493. if thing.__name__ in sys.builtin_module_names:
  1494. return 'built-in module ' + thing.__name__
  1495. if hasattr(thing, '__path__'):
  1496. return 'package ' + thing.__name__
  1497. else:
  1498. return 'module ' + thing.__name__
  1499. if inspect.isbuiltin(thing):
  1500. return 'built-in function ' + thing.__name__
  1501. if inspect.isgetsetdescriptor(thing):
  1502. return 'getset descriptor %s.%s.%s' % (
  1503. thing.__objclass__.__module__, thing.__objclass__.__name__,
  1504. thing.__name__)
  1505. if inspect.ismemberdescriptor(thing):
  1506. return 'member descriptor %s.%s.%s' % (
  1507. thing.__objclass__.__module__, thing.__objclass__.__name__,
  1508. thing.__name__)
  1509. if inspect.isclass(thing):
  1510. return 'class ' + thing.__name__
  1511. if inspect.isfunction(thing):
  1512. return 'function ' + thing.__name__
  1513. if inspect.ismethod(thing):
  1514. return 'method ' + thing.__name__
  1515. return type(thing).__name__
  1516. def locate(path, forceload=0):
  1517. """Locate an object by name or dotted path, importing as necessary."""
  1518. parts = [part for part in path.split('.') if part]
  1519. module, n = None, 0
  1520. while n < len(parts):
  1521. nextmodule = safeimport('.'.join(parts[:n+1]), forceload)
  1522. if nextmodule: module, n = nextmodule, n + 1
  1523. else: break
  1524. if module:
  1525. object = module
  1526. else:
  1527. object = builtins
  1528. for part in parts[n:]:
  1529. try:
  1530. object = getattr(object, part)
  1531. except AttributeError:
  1532. return None
  1533. return object
  1534. # --------------------------------------- interactive interpreter interface
  1535. text = TextDoc()
  1536. plaintext = _PlainTextDoc()
  1537. html = HTMLDoc()
  1538. def resolve(thing, forceload=0):
  1539. """Given an object or a path to an object, get the object and its name."""
  1540. if isinstance(thing, str):
  1541. object = locate(thing, forceload)
  1542. if object is None:
  1543. raise ImportError('''\
  1544. No Python documentation found for %r.
  1545. Use help() to get the interactive help utility.
  1546. Use help(str) for help on the str class.''' % thing)
  1547. return object, thing
  1548. else:
  1549. name = getattr(thing, '__name__', None)
  1550. return thing, name if isinstance(name, str) else None
  1551. def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
  1552. renderer=None):
  1553. """Render text documentation, given an object or a path to an object."""
  1554. if renderer is None:
  1555. renderer = text
  1556. object, name = resolve(thing, forceload)
  1557. desc = describe(object)
  1558. module = inspect.getmodule(object)
  1559. if name and '.' in name:
  1560. desc += ' in ' + name[:name.rfind('.')]
  1561. elif module and module is not object:
  1562. desc += ' in module ' + module.__name__
  1563. if not (inspect.ismodule(object) or
  1564. inspect.isclass(object) or
  1565. inspect.isroutine(object) or
  1566. inspect.isdatadescriptor(object) or
  1567. _getdoc(object)):
  1568. # If the passed object is a piece of data or an instance,
  1569. # document its available methods instead of its value.
  1570. if hasattr(object, '__origin__'):
  1571. object = object.__origin__
  1572. else:
  1573. object = type(object)
  1574. desc += ' object'
  1575. return title % desc + '\n\n' + renderer.document(object, name)
  1576. def doc(thing, title='Python Library Documentation: %s', forceload=0,
  1577. output=None):
  1578. """Display text documentation, given an object or a path to an object."""
  1579. try:
  1580. if output is None:
  1581. pager(render_doc(thing, title, forceload))
  1582. else:
  1583. output.write(render_doc(thing, title, forceload, plaintext))
  1584. except (ImportError, ErrorDuringImport) as value:
  1585. print(value)
  1586. def writedoc(thing, forceload=0):
  1587. """Write HTML documentation to a file in the current directory."""
  1588. try:
  1589. object, name = resolve(thing, forceload)
  1590. page = html.page(describe(object), html.document(object, name))
  1591. with open(name + '.html', 'w', encoding='utf-8') as file:
  1592. file.write(page)
  1593. print('wrote', name + '.html')
  1594. except (ImportError, ErrorDuringImport) as value:
  1595. print(value)
  1596. def writedocs(dir, pkgpath='', done=None):
  1597. """Write out HTML documentation for all modules in a directory tree."""
  1598. if done is None: done = {}
  1599. for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):
  1600. writedoc(modname)
  1601. return
  1602. class Helper:
  1603. # These dictionaries map a topic name to either an alias, or a tuple
  1604. # (label, seealso-items). The "label" is the label of the corresponding
  1605. # section in the .rst file under Doc/ and an index into the dictionary
  1606. # in pydoc_data/topics.py.
  1607. #
  1608. # CAUTION: if you change one of these dictionaries, be sure to adapt the
  1609. # list of needed labels in Doc/tools/extensions/pyspecific.py and
  1610. # regenerate the pydoc_data/topics.py file by running
  1611. # make pydoc-topics
  1612. # in Doc/ and copying the output file into the Lib/ directory.
  1613. keywords = {
  1614. 'False': '',
  1615. 'None': '',
  1616. 'True': '',
  1617. 'and': 'BOOLEAN',
  1618. 'as': 'with',
  1619. 'assert': ('assert', ''),
  1620. 'async': ('async', ''),
  1621. 'await': ('await', ''),
  1622. 'break': ('break', 'while for'),
  1623. 'class': ('class', 'CLASSES SPECIALMETHODS'),
  1624. 'continue': ('continue', 'while for'),
  1625. 'def': ('function', ''),
  1626. 'del': ('del', 'BASICMETHODS'),
  1627. 'elif': 'if',
  1628. 'else': ('else', 'while for'),
  1629. 'except': 'try',
  1630. 'finally': 'try',
  1631. 'for': ('for', 'break continue while'),
  1632. 'from': 'import',
  1633. 'global': ('global', 'nonlocal NAMESPACES'),
  1634. 'if': ('if', 'TRUTHVALUE'),
  1635. 'import': ('import', 'MODULES'),
  1636. 'in': ('in', 'SEQUENCEMETHODS'),
  1637. 'is': 'COMPARISON',
  1638. 'lambda': ('lambda', 'FUNCTIONS'),
  1639. 'nonlocal': ('nonlocal', 'global NAMESPACES'),
  1640. 'not': 'BOOLEAN',
  1641. 'or': 'BOOLEAN',
  1642. 'pass': ('pass', ''),
  1643. 'raise': ('raise', 'EXCEPTIONS'),
  1644. 'return': ('return', 'FUNCTIONS'),
  1645. 'try': ('try', 'EXCEPTIONS'),
  1646. 'while': ('while', 'break continue if TRUTHVALUE'),
  1647. 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
  1648. 'yield': ('yield', ''),
  1649. }
  1650. # Either add symbols to this dictionary or to the symbols dictionary
  1651. # directly: Whichever is easier. They are merged later.
  1652. _strprefixes = [p + q for p in ('b', 'f', 'r', 'u') for q in ("'", '"')]
  1653. _symbols_inverse = {
  1654. 'STRINGS' : ("'", "'''", '"', '"""', *_strprefixes),
  1655. 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',
  1656. '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
  1657. 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),
  1658. 'UNARY' : ('-', '~'),
  1659. 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',
  1660. '^=', '<<=', '>>=', '**=', '//='),
  1661. 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),
  1662. 'COMPLEX' : ('j', 'J')
  1663. }
  1664. symbols = {
  1665. '%': 'OPERATORS FORMATTING',
  1666. '**': 'POWER',
  1667. ',': 'TUPLES LISTS FUNCTIONS',
  1668. '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
  1669. '...': 'ELLIPSIS',
  1670. ':': 'SLICINGS DICTIONARYLITERALS',
  1671. '@': 'def class',
  1672. '\\': 'STRINGS',
  1673. '_': 'PRIVATENAMES',
  1674. '__': 'PRIVATENAMES SPECIALMETHODS',
  1675. '`': 'BACKQUOTES',
  1676. '(': 'TUPLES FUNCTIONS CALLS',
  1677. ')': 'TUPLES FUNCTIONS CALLS',
  1678. '[': 'LISTS SUBSCRIPTS SLICINGS',
  1679. ']': 'LISTS SUBSCRIPTS SLICINGS'
  1680. }
  1681. for topic, symbols_ in _symbols_inverse.items():
  1682. for symbol in symbols_:
  1683. topics = symbols.get(symbol, topic)
  1684. if topic not in topics:
  1685. topics = topics + ' ' + topic
  1686. symbols[symbol] = topics
  1687. topics = {
  1688. 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
  1689. 'FUNCTIONS CLASSES MODULES FILES inspect'),
  1690. 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS '
  1691. 'FORMATTING TYPES'),
  1692. 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
  1693. 'FORMATTING': ('formatstrings', 'OPERATORS'),
  1694. 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '
  1695. 'FORMATTING TYPES'),
  1696. 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
  1697. 'INTEGER': ('integers', 'int range'),
  1698. 'FLOAT': ('floating', 'float math'),
  1699. 'COMPLEX': ('imaginary', 'complex cmath'),
  1700. 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING range LISTS'),
  1701. 'MAPPINGS': 'DICTIONARIES',
  1702. 'FUNCTIONS': ('typesfunctions', 'def TYPES'),
  1703. 'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
  1704. 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
  1705. 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
  1706. 'FRAMEOBJECTS': 'TYPES',
  1707. 'TRACEBACKS': 'TYPES',
  1708. 'NONE': ('bltin-null-object', ''),
  1709. 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
  1710. 'SPECIALATTRIBUTES': ('specialattrs', ''),
  1711. 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
  1712. 'MODULES': ('typesmodules', 'import'),
  1713. 'PACKAGES': 'import',
  1714. 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '
  1715. 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '
  1716. 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '
  1717. 'LISTS DICTIONARIES'),
  1718. 'OPERATORS': 'EXPRESSIONS',
  1719. 'PRECEDENCE': 'EXPRESSIONS',
  1720. 'OBJECTS': ('objects', 'TYPES'),
  1721. 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '
  1722. 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS '
  1723. 'NUMBERMETHODS CLASSES'),
  1724. 'BASICMETHODS': ('customization', 'hash repr str SPECIALMETHODS'),
  1725. 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
  1726. 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
  1727. 'SEQUENCEMETHODS': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS '
  1728. 'SPECIALMETHODS'),
  1729. 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
  1730. 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
  1731. 'SPECIALMETHODS'),
  1732. 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
  1733. 'NAMESPACES': ('naming', 'global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'),
  1734. 'DYNAMICFEATURES': ('dynamic-features', ''),
  1735. 'SCOPING': 'NAMESPACES',
  1736. 'FRAMES': 'NAMESPACES',
  1737. 'EXCEPTIONS': ('exceptions', 'try except finally raise'),
  1738. 'CONVERSIONS': ('conversions', ''),
  1739. 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
  1740. 'SPECIALIDENTIFIERS': ('id-classes', ''),
  1741. 'PRIVATENAMES': ('atom-identifiers', ''),
  1742. 'LITERALS': ('atom-literals', 'STRINGS NUMBERS TUPLELITERALS '
  1743. 'LISTLITERALS DICTIONARYLITERALS'),
  1744. 'TUPLES': 'SEQUENCES',
  1745. 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
  1746. 'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
  1747. 'LISTLITERALS': ('lists', 'LISTS LITERALS'),
  1748. 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
  1749. 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
  1750. 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
  1751. 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS'),
  1752. 'SLICINGS': ('slicings', 'SEQUENCEMETHODS'),
  1753. 'CALLS': ('calls', 'EXPRESSIONS'),
  1754. 'POWER': ('power', 'EXPRESSIONS'),
  1755. 'UNARY': ('unary', 'EXPRESSIONS'),
  1756. 'BINARY': ('binary', 'EXPRESSIONS'),
  1757. 'SHIFTING': ('shifting', 'EXPRESSIONS'),
  1758. 'BITWISE': ('bitwise', 'EXPRESSIONS'),
  1759. 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
  1760. 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
  1761. 'ASSERTION': 'assert',
  1762. 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
  1763. 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
  1764. 'DELETION': 'del',
  1765. 'RETURNING': 'return',
  1766. 'IMPORTING': 'import',
  1767. 'CONDITIONAL': 'if',
  1768. 'LOOPING': ('compound', 'for while break continue'),
  1769. 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
  1770. 'DEBUGGING': ('debugger', 'pdb'),
  1771. 'CONTEXTMANAGERS': ('context-managers', 'with'),
  1772. }
  1773. def __init__(self, input=None, output=None):
  1774. self._input = input
  1775. self._output = output
  1776. @property
  1777. def input(self):
  1778. return self._input or sys.stdin
  1779. @property
  1780. def output(self):
  1781. return self._output or sys.stdout
  1782. def __repr__(self):
  1783. if inspect.stack()[1][3] == '?':
  1784. self()
  1785. return ''
  1786. return '<%s.%s instance>' % (self.__class__.__module__,
  1787. self.__class__.__qualname__)
  1788. _GoInteractive = object()
  1789. def __call__(self, request=_GoInteractive):
  1790. if request is not self._GoInteractive:
  1791. self.help(request)
  1792. else:
  1793. self.intro()
  1794. self.interact()
  1795. self.output.write('''
  1796. You are now leaving help and returning to the Python interpreter.
  1797. If you want to ask for help on a particular object directly from the
  1798. interpreter, you can type "help(object)". Executing "help('string')"
  1799. has the same effect as typing a particular string at the help> prompt.
  1800. ''')
  1801. def interact(self):
  1802. self.output.write('\n')
  1803. while True:
  1804. try:
  1805. request = self.getline('help> ')
  1806. if not request: break
  1807. except (KeyboardInterrupt, EOFError):
  1808. break
  1809. request = request.strip()
  1810. # Make sure significant trailing quoting marks of literals don't
  1811. # get deleted while cleaning input
  1812. if (len(request) > 2 and request[0] == request[-1] in ("'", '"')
  1813. and request[0] not in request[1:-1]):
  1814. request = request[1:-1]
  1815. if request.lower() in ('q', 'quit'): break
  1816. if request == 'help':
  1817. self.intro()
  1818. else:
  1819. self.help(request)
  1820. def getline(self, prompt):
  1821. """Read one line, using input() when appropriate."""
  1822. if self.input is sys.stdin:
  1823. return input(prompt)
  1824. else:
  1825. self.output.write(prompt)
  1826. self.output.flush()
  1827. return self.input.readline()
  1828. def help(self, request):
  1829. if type(request) is type(''):
  1830. request = request.strip()
  1831. if request == 'keywords': self.listkeywords()
  1832. elif request == 'symbols': self.listsymbols()
  1833. elif request == 'topics': self.listtopics()
  1834. elif request == 'modules': self.listmodules()
  1835. elif request[:8] == 'modules ':
  1836. self.listmodules(request.split()[1])
  1837. elif request in self.symbols: self.showsymbol(request)
  1838. elif request in ['True', 'False', 'None']:
  1839. # special case these keywords since they are objects too
  1840. doc(eval(request), 'Help on %s:')
  1841. elif request in self.keywords: self.showtopic(request)
  1842. elif request in self.topics: self.showtopic(request)
  1843. elif request: doc(request, 'Help on %s:', output=self._output)
  1844. else: doc(str, 'Help on %s:', output=self._output)
  1845. elif isinstance(request, Helper): self()
  1846. else: doc(request, 'Help on %s:', output=self._output)
  1847. self.output.write('\n')
  1848. def intro(self):
  1849. self.output.write('''
  1850. Welcome to Python {0}'s help utility!
  1851. If this is your first time using Python, you should definitely check out
  1852. the tutorial on the internet at https://docs.python.org/{0}/tutorial/.
  1853. Enter the name of any module, keyword, or topic to get help on writing
  1854. Python programs and using Python modules. To quit this help utility and
  1855. return to the interpreter, just type "quit".
  1856. To get a list of available modules, keywords, symbols, or topics, type
  1857. "modules", "keywords", "symbols", or "topics". Each module also comes
  1858. with a one-line summary of what it does; to list the modules whose name
  1859. or summary contain a given string such as "spam", type "modules spam".
  1860. '''.format('%d.%d' % sys.version_info[:2]))
  1861. def list(self, items, columns=4, width=80):
  1862. items = list(sorted(items))
  1863. colw = width // columns
  1864. rows = (len(items) + columns - 1) // columns
  1865. for row in range(rows):
  1866. for col in range(columns):
  1867. i = col * rows + row
  1868. if i < len(items):
  1869. self.output.write(items[i])
  1870. if col < columns - 1:
  1871. self.output.write(' ' + ' ' * (colw - 1 - len(items[i])))
  1872. self.output.write('\n')
  1873. def listkeywords(self):
  1874. self.output.write('''
  1875. Here is a list of the Python keywords. Enter any keyword to get more help.
  1876. ''')
  1877. self.list(self.keywords.keys())
  1878. def listsymbols(self):
  1879. self.output.write('''
  1880. Here is a list of the punctuation symbols which Python assigns special meaning
  1881. to. Enter any symbol to get more help.
  1882. ''')
  1883. self.list(self.symbols.keys())
  1884. def listtopics(self):
  1885. self.output.write('''
  1886. Here is a list of available topics. Enter any topic name to get more help.
  1887. ''')
  1888. self.list(self.topics.keys())
  1889. def showtopic(self, topic, more_xrefs=''):
  1890. try:
  1891. import pydoc_data.topics
  1892. except ImportError:
  1893. self.output.write('''
  1894. Sorry, topic and keyword documentation is not available because the
  1895. module "pydoc_data.topics" could not be found.
  1896. ''')
  1897. return
  1898. target = self.topics.get(topic, self.keywords.get(topic))
  1899. if not target:
  1900. self.output.write('no documentation found for %s\n' % repr(topic))
  1901. return
  1902. if type(target) is type(''):
  1903. return self.showtopic(target, more_xrefs)
  1904. label, xrefs = target
  1905. try:
  1906. doc = pydoc_data.topics.topics[label]
  1907. except KeyError:
  1908. self.output.write('no documentation found for %s\n' % repr(topic))
  1909. return
  1910. doc = doc.strip() + '\n'
  1911. if more_xrefs:
  1912. xrefs = (xrefs or '') + ' ' + more_xrefs
  1913. if xrefs:
  1914. import textwrap
  1915. text = 'Related help topics: ' + ', '.join(xrefs.split()) + '\n'
  1916. wrapped_text = textwrap.wrap(text, 72)
  1917. doc += '\n%s\n' % '\n'.join(wrapped_text)
  1918. pager(doc)
  1919. def _gettopic(self, topic, more_xrefs=''):
  1920. """Return unbuffered tuple of (topic, xrefs).
  1921. If an error occurs here, the exception is caught and displayed by
  1922. the url handler.
  1923. This function duplicates the showtopic method but returns its
  1924. result directly so it can be formatted for display in an html page.
  1925. """
  1926. try:
  1927. import pydoc_data.topics
  1928. except ImportError:
  1929. return('''
  1930. Sorry, topic and keyword documentation is not available because the
  1931. module "pydoc_data.topics" could not be found.
  1932. ''' , '')
  1933. target = self.topics.get(topic, self.keywords.get(topic))
  1934. if not target:
  1935. raise ValueError('could not find topic')
  1936. if isinstance(target, str):
  1937. return self._gettopic(target, more_xrefs)
  1938. label, xrefs = target
  1939. doc = pydoc_data.topics.topics[label]
  1940. if more_xrefs:
  1941. xrefs = (xrefs or '') + ' ' + more_xrefs
  1942. return doc, xrefs
  1943. def showsymbol(self, symbol):
  1944. target = self.symbols[symbol]
  1945. topic, _, xrefs = target.partition(' ')
  1946. self.showtopic(topic, xrefs)
  1947. def listmodules(self, key=''):
  1948. if key:
  1949. self.output.write('''
  1950. Here is a list of modules whose name or summary contains '{}'.
  1951. If there are any, enter a module name to get more help.
  1952. '''.format(key))
  1953. apropos(key)
  1954. else:
  1955. self.output.write('''
  1956. Please wait a moment while I gather a list of all available modules...
  1957. ''')
  1958. modules = {}
  1959. def callback(path, modname, desc, modules=modules):
  1960. if modname and modname[-9:] == '.__init__':
  1961. modname = modname[:-9] + ' (package)'
  1962. if modname.find('.') < 0:
  1963. modules[modname] = 1
  1964. def onerror(modname):
  1965. callback(None, modname, None)
  1966. ModuleScanner().run(callback, onerror=onerror)
  1967. self.list(modules.keys())
  1968. self.output.write('''
  1969. Enter any module name to get more help. Or, type "modules spam" to search
  1970. for modules whose name or summary contain the string "spam".
  1971. ''')
  1972. help = Helper()
  1973. class ModuleScanner:
  1974. """An interruptible scanner that searches module synopses."""
  1975. def run(self, callback, key=None, completer=None, onerror=None):
  1976. if key: key = key.lower()
  1977. self.quit = False
  1978. seen = {}
  1979. for modname in sys.builtin_module_names:
  1980. if modname != '__main__':
  1981. seen[modname] = 1
  1982. if key is None:
  1983. callback(None, modname, '')
  1984. else:
  1985. name = __import__(modname).__doc__ or ''
  1986. desc = name.split('\n')[0]
  1987. name = modname + ' - ' + desc
  1988. if name.lower().find(key) >= 0:
  1989. callback(None, modname, desc)
  1990. for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
  1991. if self.quit:
  1992. break
  1993. if key is None:
  1994. callback(None, modname, '')
  1995. else:
  1996. try:
  1997. spec = pkgutil._get_spec(importer, modname)
  1998. except SyntaxError:
  1999. # raised by tests for bad coding cookies or BOM
  2000. continue
  2001. loader = spec.loader
  2002. if hasattr(loader, 'get_source'):
  2003. try:
  2004. source = loader.get_source(modname)
  2005. except Exception:
  2006. if onerror:
  2007. onerror(modname)
  2008. continue
  2009. desc = source_synopsis(io.StringIO(source)) or ''
  2010. if hasattr(loader, 'get_filename'):
  2011. path = loader.get_filename(modname)
  2012. else:
  2013. path = None
  2014. else:
  2015. try:
  2016. module = importlib._bootstrap._load(spec)
  2017. except ImportError:
  2018. if onerror:
  2019. onerror(modname)
  2020. continue
  2021. desc = module.__doc__.splitlines()[0] if module.__doc__ else ''
  2022. path = getattr(module,'__file__',None)
  2023. name = modname + ' - ' + desc
  2024. if name.lower().find(key) >= 0:
  2025. callback(path, modname, desc)
  2026. if completer:
  2027. completer()
  2028. def apropos(key):
  2029. """Print all the one-line module summaries that contain a substring."""
  2030. def callback(path, modname, desc):
  2031. if modname[-9:] == '.__init__':
  2032. modname = modname[:-9] + ' (package)'
  2033. print(modname, desc and '- ' + desc)
  2034. def onerror(modname):
  2035. pass
  2036. with warnings.catch_warnings():
  2037. warnings.filterwarnings('ignore') # ignore problems during import
  2038. ModuleScanner().run(callback, key, onerror=onerror)
  2039. # --------------------------------------- enhanced web browser interface
  2040. def _start_server(urlhandler, hostname, port):
  2041. """Start an HTTP server thread on a specific port.
  2042. Start an HTML/text server thread, so HTML or text documents can be
  2043. browsed dynamically and interactively with a web browser. Example use:
  2044. >>> import time
  2045. >>> import pydoc
  2046. Define a URL handler. To determine what the client is asking
  2047. for, check the URL and content_type.
  2048. Then get or generate some text or HTML code and return it.
  2049. >>> def my_url_handler(url, content_type):
  2050. ... text = 'the URL sent was: (%s, %s)' % (url, content_type)
  2051. ... return text
  2052. Start server thread on port 0.
  2053. If you use port 0, the server will pick a random port number.
  2054. You can then use serverthread.port to get the port number.
  2055. >>> port = 0
  2056. >>> serverthread = pydoc._start_server(my_url_handler, port)
  2057. Check that the server is really started. If it is, open browser
  2058. and get first page. Use serverthread.url as the starting page.
  2059. >>> if serverthread.serving:
  2060. ... import webbrowser
  2061. The next two lines are commented out so a browser doesn't open if
  2062. doctest is run on this module.
  2063. #... webbrowser.open(serverthread.url)
  2064. #True
  2065. Let the server do its thing. We just need to monitor its status.
  2066. Use time.sleep so the loop doesn't hog the CPU.
  2067. >>> starttime = time.monotonic()
  2068. >>> timeout = 1 #seconds
  2069. This is a short timeout for testing purposes.
  2070. >>> while serverthread.serving:
  2071. ... time.sleep(.01)
  2072. ... if serverthread.serving and time.monotonic() - starttime > timeout:
  2073. ... serverthread.stop()
  2074. ... break
  2075. Print any errors that may have occurred.
  2076. >>> print(serverthread.error)
  2077. None
  2078. """
  2079. import http.server
  2080. import email.message
  2081. import select
  2082. import threading
  2083. class DocHandler(http.server.BaseHTTPRequestHandler):
  2084. def do_GET(self):
  2085. """Process a request from an HTML browser.
  2086. The URL received is in self.path.
  2087. Get an HTML page from self.urlhandler and send it.
  2088. """
  2089. if self.path.endswith('.css'):
  2090. content_type = 'text/css'
  2091. else:
  2092. content_type = 'text/html'
  2093. self.send_response(200)
  2094. self.send_header('Content-Type', '%s; charset=UTF-8' % content_type)
  2095. self.end_headers()
  2096. self.wfile.write(self.urlhandler(
  2097. self.path, content_type).encode('utf-8'))
  2098. def log_message(self, *args):
  2099. # Don't log messages.
  2100. pass
  2101. class DocServer(http.server.HTTPServer):
  2102. def __init__(self, host, port, callback):
  2103. self.host = host
  2104. self.address = (self.host, port)
  2105. self.callback = callback
  2106. self.base.__init__(self, self.address, self.handler)
  2107. self.quit = False
  2108. def serve_until_quit(self):
  2109. while not self.quit:
  2110. rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
  2111. if rd:
  2112. self.handle_request()
  2113. self.server_close()
  2114. def server_activate(self):
  2115. self.base.server_activate(self)
  2116. if self.callback:
  2117. self.callback(self)
  2118. class ServerThread(threading.Thread):
  2119. def __init__(self, urlhandler, host, port):
  2120. self.urlhandler = urlhandler
  2121. self.host = host
  2122. self.port = int(port)
  2123. threading.Thread.__init__(self)
  2124. self.serving = False
  2125. self.error = None
  2126. def run(self):
  2127. """Start the server."""
  2128. try:
  2129. DocServer.base = http.server.HTTPServer
  2130. DocServer.handler = DocHandler
  2131. DocHandler.MessageClass = email.message.Message
  2132. DocHandler.urlhandler = staticmethod(self.urlhandler)
  2133. docsvr = DocServer(self.host, self.port, self.ready)
  2134. self.docserver = docsvr
  2135. docsvr.serve_until_quit()
  2136. except Exception as e:
  2137. self.error = e
  2138. def ready(self, server):
  2139. self.serving = True
  2140. self.host = server.host
  2141. self.port = server.server_port
  2142. self.url = 'http://%s:%d/' % (self.host, self.port)
  2143. def stop(self):
  2144. """Stop the server and this thread nicely"""
  2145. self.docserver.quit = True
  2146. self.join()
  2147. # explicitly break a reference cycle: DocServer.callback
  2148. # has indirectly a reference to ServerThread.
  2149. self.docserver = None
  2150. self.serving = False
  2151. self.url = None
  2152. thread = ServerThread(urlhandler, hostname, port)
  2153. thread.start()
  2154. # Wait until thread.serving is True to make sure we are
  2155. # really up before returning.
  2156. while not thread.error and not thread.serving:
  2157. time.sleep(.01)
  2158. return thread
  2159. def _url_handler(url, content_type="text/html"):
  2160. """The pydoc url handler for use with the pydoc server.
  2161. If the content_type is 'text/css', the _pydoc.css style
  2162. sheet is read and returned if it exits.
  2163. If the content_type is 'text/html', then the result of
  2164. get_html_page(url) is returned.
  2165. """
  2166. class _HTMLDoc(HTMLDoc):
  2167. def page(self, title, contents):
  2168. """Format an HTML page."""
  2169. css_path = "pydoc_data/_pydoc.css"
  2170. css_link = (
  2171. '<link rel="stylesheet" type="text/css" href="%s">' %
  2172. css_path)
  2173. return '''\
  2174. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2175. <html><head><title>Pydoc: %s</title>
  2176. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  2177. %s</head><body bgcolor="#f0f0f8">%s<div style="clear:both;padding-top:.5em;">%s</div>
  2178. </body></html>''' % (title, css_link, html_navbar(), contents)
  2179. html = _HTMLDoc()
  2180. def html_navbar():
  2181. version = html.escape("%s [%s, %s]" % (platform.python_version(),
  2182. platform.python_build()[0],
  2183. platform.python_compiler()))
  2184. return """
  2185. <div style='float:left'>
  2186. Python %s<br>%s
  2187. </div>
  2188. <div style='float:right'>
  2189. <div style='text-align:center'>
  2190. <a href="index.html">Module Index</a>
  2191. : <a href="topics.html">Topics</a>
  2192. : <a href="keywords.html">Keywords</a>
  2193. </div>
  2194. <div>
  2195. <form action="get" style='display:inline;'>
  2196. <input type=text name=key size=15>
  2197. <input type=submit value="Get">
  2198. </form>&nbsp;
  2199. <form action="search" style='display:inline;'>
  2200. <input type=text name=key size=15>
  2201. <input type=submit value="Search">
  2202. </form>
  2203. </div>
  2204. </div>
  2205. """ % (version, html.escape(platform.platform(terse=True)))
  2206. def html_index():
  2207. """Module Index page."""
  2208. def bltinlink(name):
  2209. return '<a href="%s.html">%s</a>' % (name, name)
  2210. heading = html.heading(
  2211. '<big><big><strong>Index of Modules</strong></big></big>',
  2212. '#ffffff', '#7799ee')
  2213. names = [name for name in sys.builtin_module_names
  2214. if name != '__main__']
  2215. contents = html.multicolumn(names, bltinlink)
  2216. contents = [heading, '<p>' + html.bigsection(
  2217. 'Built-in Modules', '#ffffff', '#ee77aa', contents)]
  2218. seen = {}
  2219. for dir in sys.path:
  2220. contents.append(html.index(dir, seen))
  2221. contents.append(
  2222. '<p align=right><font color="#909090" face="helvetica,'
  2223. 'arial"><strong>pydoc</strong> by Ka-Ping Yee'
  2224. '&lt;ping@lfw.org&gt;</font>')
  2225. return 'Index of Modules', ''.join(contents)
  2226. def html_search(key):
  2227. """Search results page."""
  2228. # scan for modules
  2229. search_result = []
  2230. def callback(path, modname, desc):
  2231. if modname[-9:] == '.__init__':
  2232. modname = modname[:-9] + ' (package)'
  2233. search_result.append((modname, desc and '- ' + desc))
  2234. with warnings.catch_warnings():
  2235. warnings.filterwarnings('ignore') # ignore problems during import
  2236. def onerror(modname):
  2237. pass
  2238. ModuleScanner().run(callback, key, onerror=onerror)
  2239. # format page
  2240. def bltinlink(name):
  2241. return '<a href="%s.html">%s</a>' % (name, name)
  2242. results = []
  2243. heading = html.heading(
  2244. '<big><big><strong>Search Results</strong></big></big>',
  2245. '#ffffff', '#7799ee')
  2246. for name, desc in search_result:
  2247. results.append(bltinlink(name) + desc)
  2248. contents = heading + html.bigsection(
  2249. 'key = %s' % key, '#ffffff', '#ee77aa', '<br>'.join(results))
  2250. return 'Search Results', contents
  2251. def html_topics():
  2252. """Index of topic texts available."""
  2253. def bltinlink(name):
  2254. return '<a href="topic?key=%s">%s</a>' % (name, name)
  2255. heading = html.heading(
  2256. '<big><big><strong>INDEX</strong></big></big>',
  2257. '#ffffff', '#7799ee')
  2258. names = sorted(Helper.topics.keys())
  2259. contents = html.multicolumn(names, bltinlink)
  2260. contents = heading + html.bigsection(
  2261. 'Topics', '#ffffff', '#ee77aa', contents)
  2262. return 'Topics', contents
  2263. def html_keywords():
  2264. """Index of keywords."""
  2265. heading = html.heading(
  2266. '<big><big><strong>INDEX</strong></big></big>',
  2267. '#ffffff', '#7799ee')
  2268. names = sorted(Helper.keywords.keys())
  2269. def bltinlink(name):
  2270. return '<a href="topic?key=%s">%s</a>' % (name, name)
  2271. contents = html.multicolumn(names, bltinlink)
  2272. contents = heading + html.bigsection(
  2273. 'Keywords', '#ffffff', '#ee77aa', contents)
  2274. return 'Keywords', contents
  2275. def html_topicpage(topic):
  2276. """Topic or keyword help page."""
  2277. buf = io.StringIO()
  2278. htmlhelp = Helper(buf, buf)
  2279. contents, xrefs = htmlhelp._gettopic(topic)
  2280. if topic in htmlhelp.keywords:
  2281. title = 'KEYWORD'
  2282. else:
  2283. title = 'TOPIC'
  2284. heading = html.heading(
  2285. '<big><big><strong>%s</strong></big></big>' % title,
  2286. '#ffffff', '#7799ee')
  2287. contents = '<pre>%s</pre>' % html.markup(contents)
  2288. contents = html.bigsection(topic , '#ffffff','#ee77aa', contents)
  2289. if xrefs:
  2290. xrefs = sorted(xrefs.split())
  2291. def bltinlink(name):
  2292. return '<a href="topic?key=%s">%s</a>' % (name, name)
  2293. xrefs = html.multicolumn(xrefs, bltinlink)
  2294. xrefs = html.section('Related help topics: ',
  2295. '#ffffff', '#ee77aa', xrefs)
  2296. return ('%s %s' % (title, topic),
  2297. ''.join((heading, contents, xrefs)))
  2298. def html_getobj(url):
  2299. obj = locate(url, forceload=1)
  2300. if obj is None and url != 'None':
  2301. raise ValueError('could not find object')
  2302. title = describe(obj)
  2303. content = html.document(obj, url)
  2304. return title, content
  2305. def html_error(url, exc):
  2306. heading = html.heading(
  2307. '<big><big><strong>Error</strong></big></big>',
  2308. '#ffffff', '#7799ee')
  2309. contents = '<br>'.join(html.escape(line) for line in
  2310. format_exception_only(type(exc), exc))
  2311. contents = heading + html.bigsection(url, '#ffffff', '#bb0000',
  2312. contents)
  2313. return "Error - %s" % url, contents
  2314. def get_html_page(url):
  2315. """Generate an HTML page for url."""
  2316. complete_url = url
  2317. if url.endswith('.html'):
  2318. url = url[:-5]
  2319. try:
  2320. if url in ("", "index"):
  2321. title, content = html_index()
  2322. elif url == "topics":
  2323. title, content = html_topics()
  2324. elif url == "keywords":
  2325. title, content = html_keywords()
  2326. elif '=' in url:
  2327. op, _, url = url.partition('=')
  2328. if op == "search?key":
  2329. title, content = html_search(url)
  2330. elif op == "topic?key":
  2331. # try topics first, then objects.
  2332. try:
  2333. title, content = html_topicpage(url)
  2334. except ValueError:
  2335. title, content = html_getobj(url)
  2336. elif op == "get?key":
  2337. # try objects first, then topics.
  2338. if url in ("", "index"):
  2339. title, content = html_index()
  2340. else:
  2341. try:
  2342. title, content = html_getobj(url)
  2343. except ValueError:
  2344. title, content = html_topicpage(url)
  2345. else:
  2346. raise ValueError('bad pydoc url')
  2347. else:
  2348. title, content = html_getobj(url)
  2349. except Exception as exc:
  2350. # Catch any errors and display them in an error page.
  2351. title, content = html_error(complete_url, exc)
  2352. return html.page(title, content)
  2353. if url.startswith('/'):
  2354. url = url[1:]
  2355. if content_type == 'text/css':
  2356. path_here = os.path.dirname(os.path.realpath(__file__))
  2357. css_path = os.path.join(path_here, url)
  2358. with open(css_path) as fp:
  2359. return ''.join(fp.readlines())
  2360. elif content_type == 'text/html':
  2361. return get_html_page(url)
  2362. # Errors outside the url handler are caught by the server.
  2363. raise TypeError('unknown content type %r for url %s' % (content_type, url))
  2364. def browse(port=0, *, open_browser=True, hostname='localhost'):
  2365. """Start the enhanced pydoc web server and open a web browser.
  2366. Use port '0' to start the server on an arbitrary port.
  2367. Set open_browser to False to suppress opening a browser.
  2368. """
  2369. import webbrowser
  2370. serverthread = _start_server(_url_handler, hostname, port)
  2371. if serverthread.error:
  2372. print(serverthread.error)
  2373. return
  2374. if serverthread.serving:
  2375. server_help_msg = 'Server commands: [b]rowser, [q]uit'
  2376. if open_browser:
  2377. webbrowser.open(serverthread.url)
  2378. try:
  2379. print('Server ready at', serverthread.url)
  2380. print(server_help_msg)
  2381. while serverthread.serving:
  2382. cmd = input('server> ')
  2383. cmd = cmd.lower()
  2384. if cmd == 'q':
  2385. break
  2386. elif cmd == 'b':
  2387. webbrowser.open(serverthread.url)
  2388. else:
  2389. print(server_help_msg)
  2390. except (KeyboardInterrupt, EOFError):
  2391. print()
  2392. finally:
  2393. if serverthread.serving:
  2394. serverthread.stop()
  2395. print('Server stopped')
  2396. # -------------------------------------------------- command-line interface
  2397. def ispath(x):
  2398. return isinstance(x, str) and x.find(os.sep) >= 0
  2399. def _get_revised_path(given_path, argv0):
  2400. """Ensures current directory is on returned path, and argv0 directory is not
  2401. Exception: argv0 dir is left alone if it's also pydoc's directory.
  2402. Returns a new path entry list, or None if no adjustment is needed.
  2403. """
  2404. # Scripts may get the current directory in their path by default if they're
  2405. # run with the -m switch, or directly from the current directory.
  2406. # The interactive prompt also allows imports from the current directory.
  2407. # Accordingly, if the current directory is already present, don't make
  2408. # any changes to the given_path
  2409. if '' in given_path or os.curdir in given_path or os.getcwd() in given_path:
  2410. return None
  2411. # Otherwise, add the current directory to the given path, and remove the
  2412. # script directory (as long as the latter isn't also pydoc's directory.
  2413. stdlib_dir = os.path.dirname(__file__)
  2414. script_dir = os.path.dirname(argv0)
  2415. revised_path = given_path.copy()
  2416. if script_dir in given_path and not os.path.samefile(script_dir, stdlib_dir):
  2417. revised_path.remove(script_dir)
  2418. revised_path.insert(0, os.getcwd())
  2419. return revised_path
  2420. # Note: the tests only cover _get_revised_path, not _adjust_cli_path itself
  2421. def _adjust_cli_sys_path():
  2422. """Ensures current directory is on sys.path, and __main__ directory is not.
  2423. Exception: __main__ dir is left alone if it's also pydoc's directory.
  2424. """
  2425. revised_path = _get_revised_path(sys.path, sys.argv[0])
  2426. if revised_path is not None:
  2427. sys.path[:] = revised_path
  2428. def cli():
  2429. """Command-line interface (looks at sys.argv to decide what to do)."""
  2430. import getopt
  2431. class BadUsage(Exception): pass
  2432. _adjust_cli_sys_path()
  2433. try:
  2434. opts, args = getopt.getopt(sys.argv[1:], 'bk:n:p:w')
  2435. writing = False
  2436. start_server = False
  2437. open_browser = False
  2438. port = 0
  2439. hostname = 'localhost'
  2440. for opt, val in opts:
  2441. if opt == '-b':
  2442. start_server = True
  2443. open_browser = True
  2444. if opt == '-k':
  2445. apropos(val)
  2446. return
  2447. if opt == '-p':
  2448. start_server = True
  2449. port = val
  2450. if opt == '-w':
  2451. writing = True
  2452. if opt == '-n':
  2453. start_server = True
  2454. hostname = val
  2455. if start_server:
  2456. browse(port, hostname=hostname, open_browser=open_browser)
  2457. return
  2458. if not args: raise BadUsage
  2459. for arg in args:
  2460. if ispath(arg) and not os.path.exists(arg):
  2461. print('file %r does not exist' % arg)
  2462. break
  2463. try:
  2464. if ispath(arg) and os.path.isfile(arg):
  2465. arg = importfile(arg)
  2466. if writing:
  2467. if ispath(arg) and os.path.isdir(arg):
  2468. writedocs(arg)
  2469. else:
  2470. writedoc(arg)
  2471. else:
  2472. help.help(arg)
  2473. except ErrorDuringImport as value:
  2474. print(value)
  2475. except (getopt.error, BadUsage):
  2476. cmd = os.path.splitext(os.path.basename(sys.argv[0]))[0]
  2477. print("""pydoc - the Python documentation tool
  2478. {cmd} <name> ...
  2479. Show text documentation on something. <name> may be the name of a
  2480. Python keyword, topic, function, module, or package, or a dotted
  2481. reference to a class or function within a module or module in a
  2482. package. If <name> contains a '{sep}', it is used as the path to a
  2483. Python source file to document. If name is 'keywords', 'topics',
  2484. or 'modules', a listing of these things is displayed.
  2485. {cmd} -k <keyword>
  2486. Search for a keyword in the synopsis lines of all available modules.
  2487. {cmd} -n <hostname>
  2488. Start an HTTP server with the given hostname (default: localhost).
  2489. {cmd} -p <port>
  2490. Start an HTTP server on the given port on the local machine. Port
  2491. number 0 can be used to get an arbitrary unused port.
  2492. {cmd} -b
  2493. Start an HTTP server on an arbitrary unused port and open a web browser
  2494. to interactively browse documentation. This option can be used in
  2495. combination with -n and/or -p.
  2496. {cmd} -w <name> ...
  2497. Write out the HTML documentation for a module to a file in the current
  2498. directory. If <name> contains a '{sep}', it is treated as a filename; if
  2499. it names a directory, documentation is written for all the contents.
  2500. """.format(cmd=cmd, sep=os.sep))
  2501. if __name__ == '__main__':
  2502. cli()