blob: 54e6ce8b25bcfcf174036a8bdaa58a82a46bd8fe [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Ka-Ping Yee1d384632001-03-01 00:24:32 +00002"""Generate Python documentation in HTML or text for interactive use.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00003
R David Murray3d050dd2014-04-19 12:59:30 -04004At the Python interactive prompt, calling help(thing) on a Python object
5documents the object, and calling help() starts up an interactive
6help session.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00007
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00008Or, at the shell command line outside of Python:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00009
Ka-Ping Yee37f7b382001-03-23 00:12:53 +000010Run "pydoc <name>" to show documentation on something. <name> may be
11the name of a function, module, package, or a dotted reference to a
12class or function within a module or module in a package. If the
13argument contains a path segment delimiter (e.g. slash on Unix,
14backslash on Windows) it is treated as the path to a Python source file.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000015
Ka-Ping Yee37f7b382001-03-23 00:12:53 +000016Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
17of all available modules.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000018
Feanil Patel6a396c92017-09-14 17:54:09 -040019Run "pydoc -n <hostname>" to start an HTTP server with the given
20hostname (default: localhost) on the local machine.
21
Nick Coghlan7bb30b72010-12-03 09:29:11 +000022Run "pydoc -p <port>" to start an HTTP server on the given port on the
23local machine. Port number 0 can be used to get an arbitrary unused port.
24
25Run "pydoc -b" to start an HTTP server on an arbitrary unused port and
Feanil Patel6a396c92017-09-14 17:54:09 -040026open a Web browser to interactively browse documentation. Combine with
27the -n and -p options to control the hostname and port used.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000028
Ka-Ping Yee37f7b382001-03-23 00:12:53 +000029Run "pydoc -w <name>" to write out the HTML documentation for a module
30to a file named "<name>.html".
Skip Montanaro4997a692003-09-10 16:47:51 +000031
32Module docs for core modules are assumed to be in
33
Martin Panter4f8aaf62016-06-12 04:24:06 +000034 https://docs.python.org/X.Y/library/
Skip Montanaro4997a692003-09-10 16:47:51 +000035
36This can be overridden by setting the PYTHONDOCS environment variable
37to a different URL or to a local directory containing the Library
38Reference Manual pages.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000039"""
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000040__all__ = ['help']
Ka-Ping Yeedd175342001-02-27 14:43:46 +000041__author__ = "Ka-Ping Yee <ping@lfw.org>"
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000042__date__ = "26 February 2001"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043
Martin v. Löwis6fe8f192004-11-14 10:21:04 +000044__credits__ = """Guido van Rossum, for an excellent programming language.
Ka-Ping Yee5e2b1732001-02-27 23:35:09 +000045Tommy Burnette, the original creator of manpy.
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000046Paul Prescod, for all his work on onlinehelp.
47Richard Chamberlain, for the first implementation of textdoc.
Raymond Hettingered2dbe32005-01-01 07:51:01 +000048"""
Ka-Ping Yeedd175342001-02-27 14:43:46 +000049
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000050# Known bugs that can't be fixed here:
Brett Cannonf4ba4ec2013-06-15 14:25:04 -040051# - synopsis() cannot be prevented from clobbering existing
52# loaded modules.
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000053# - If the __file__ attribute on a module is a relative path and
54# the current directory is changed with os.chdir(), an incorrect
55# path will be displayed.
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000056
Nick Coghlan7bb30b72010-12-03 09:29:11 +000057import builtins
Brett Cannond5e6f2e2013-06-11 17:09:36 -040058import importlib._bootstrap
Eric Snow32439d62015-05-02 19:15:18 -060059import importlib._bootstrap_external
Brett Cannoncb66eb02012-05-11 12:58:42 -040060import importlib.machinery
Brett Cannonf4ba4ec2013-06-15 14:25:04 -040061import importlib.util
Nick Coghlan7bb30b72010-12-03 09:29:11 +000062import inspect
Victor Stinnere6c910e2011-06-30 15:55:43 +020063import io
64import os
Nick Coghlan7bb30b72010-12-03 09:29:11 +000065import pkgutil
66import platform
67import re
Victor Stinnere6c910e2011-06-30 15:55:43 +020068import sys
Nick Coghlan7bb30b72010-12-03 09:29:11 +000069import time
Victor Stinnere6c910e2011-06-30 15:55:43 +020070import tokenize
Zachary Wareeb432142014-07-10 11:18:00 -050071import urllib.parse
Nick Coghlan7bb30b72010-12-03 09:29:11 +000072import warnings
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000073from collections import deque
Nick Coghlan7bb30b72010-12-03 09:29:11 +000074from reprlib import Repr
Victor Stinner7fa767e2014-03-20 09:16:38 +010075from traceback import format_exception_only
Nick Coghlan7bb30b72010-12-03 09:29:11 +000076
77
Ka-Ping Yeedd175342001-02-27 14:43:46 +000078# --------------------------------------------------------- common routines
79
Ka-Ping Yeedd175342001-02-27 14:43:46 +000080def pathdirs():
81 """Convert sys.path into a list of absolute, existing, unique paths."""
82 dirs = []
Ka-Ping Yee1d384632001-03-01 00:24:32 +000083 normdirs = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +000084 for dir in sys.path:
85 dir = os.path.abspath(dir or '.')
Ka-Ping Yee1d384632001-03-01 00:24:32 +000086 normdir = os.path.normcase(dir)
87 if normdir not in normdirs and os.path.isdir(dir):
Ka-Ping Yeedd175342001-02-27 14:43:46 +000088 dirs.append(dir)
Ka-Ping Yee1d384632001-03-01 00:24:32 +000089 normdirs.append(normdir)
Ka-Ping Yeedd175342001-02-27 14:43:46 +000090 return dirs
91
92def getdoc(object):
93 """Get the doc string or comments for an object."""
Ka-Ping Yee3bda8792001-03-23 13:17:50 +000094 result = inspect.getdoc(object) or inspect.getcomments(object)
Neal Norwitz9d72bb42007-04-17 08:48:32 +000095 return result and re.sub('^ *\n', '', result.rstrip()) or ''
Ka-Ping Yeedd175342001-02-27 14:43:46 +000096
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +000097def splitdoc(doc):
98 """Split a doc string into a synopsis line (if any) and the rest."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +000099 lines = doc.strip().split('\n')
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000100 if len(lines) == 1:
101 return lines[0], ''
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000102 elif len(lines) >= 2 and not lines[1].rstrip():
103 return lines[0], '\n'.join(lines[2:])
104 return '', '\n'.join(lines)
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000105
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000106def classname(object, modname):
107 """Get a class name and qualify it with a module name if necessary."""
108 name = object.__name__
109 if object.__module__ != modname:
110 name = object.__module__ + '.' + name
111 return name
112
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000113def isdata(object):
Georg Brandl94432422005-07-22 21:52:25 +0000114 """Check if an object is of a type that probably means it's data."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000115 return not (inspect.ismodule(object) or inspect.isclass(object) or
116 inspect.isroutine(object) or inspect.isframe(object) or
117 inspect.istraceback(object) or inspect.iscode(object))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000118
119def replace(text, *pairs):
120 """Do a series of global replacements on a string."""
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000121 while pairs:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000122 text = pairs[1].join(text.split(pairs[0]))
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000123 pairs = pairs[2:]
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000124 return text
125
126def cram(text, maxlen):
127 """Omit part of a string if needed to make it fit in a maximum length."""
128 if len(text) > maxlen:
Raymond Hettingerfca3bb62002-10-21 04:44:11 +0000129 pre = max(0, (maxlen-3)//2)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000130 post = max(0, maxlen-3-pre)
131 return text[:pre] + '...' + text[len(text)-post:]
132 return text
133
Brett Cannon84601f12004-06-19 01:22:48 +0000134_re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000135def stripid(text):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000136 """Remove the hexadecimal id from a Python object representation."""
Brett Cannonc6c1f472004-06-19 01:02:51 +0000137 # The behaviour of %p is implementation-dependent in terms of case.
Ezio Melotti412c95a2010-02-16 23:31:04 +0000138 return _re_stripid.sub(r'\1', text)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000139
Brett Cannonc6c1f472004-06-19 01:02:51 +0000140def _is_some_method(obj):
R David Murrayac0cea52013-03-19 02:47:44 -0400141 return (inspect.isfunction(obj) or
142 inspect.ismethod(obj) or
143 inspect.isbuiltin(obj) or
144 inspect.ismethoddescriptor(obj))
Tim Peters536d2262001-09-20 05:13:38 +0000145
Larry Hastings24a882b2014-02-20 23:34:46 -0800146def _is_bound_method(fn):
147 """
148 Returns True if fn is a bound method, regardless of whether
149 fn was implemented in Python or in C.
150 """
151 if inspect.ismethod(fn):
152 return True
153 if inspect.isbuiltin(fn):
154 self = getattr(fn, '__self__', None)
155 return not (inspect.ismodule(self) or (self is None))
156 return False
157
158
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000159def allmethods(cl):
160 methods = {}
Tim Peters536d2262001-09-20 05:13:38 +0000161 for key, value in inspect.getmembers(cl, _is_some_method):
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000162 methods[key] = 1
163 for base in cl.__bases__:
164 methods.update(allmethods(base)) # all your base are belong to us
165 for key in methods.keys():
166 methods[key] = getattr(cl, key)
167 return methods
168
Tim Petersfa26f7c2001-09-24 08:05:11 +0000169def _split_list(s, predicate):
170 """Split sequence s via predicate, and return pair ([true], [false]).
171
172 The return value is a 2-tuple of lists,
173 ([x for x in s if predicate(x)],
174 [x for x in s if not predicate(x)])
175 """
176
Tim Peters28355492001-09-23 21:29:55 +0000177 yes = []
178 no = []
Tim Petersfa26f7c2001-09-24 08:05:11 +0000179 for x in s:
180 if predicate(x):
181 yes.append(x)
Tim Peters28355492001-09-23 21:29:55 +0000182 else:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000183 no.append(x)
Tim Peters28355492001-09-23 21:29:55 +0000184 return yes, no
185
Raymond Hettinger1103d052011-03-25 14:15:24 -0700186def visiblename(name, all=None, obj=None):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000187 """Decide whether to show documentation on a variable."""
Brett Cannond340b432012-08-06 17:19:22 -0400188 # Certain special names are redundant or internal.
Eric Snowb523f842013-11-22 09:05:39 -0700189 # XXX Remove __initializing__?
Brett Cannond340b432012-08-06 17:19:22 -0400190 if name in {'__author__', '__builtins__', '__cached__', '__credits__',
Eric Snowb523f842013-11-22 09:05:39 -0700191 '__date__', '__doc__', '__file__', '__spec__',
Brett Cannond340b432012-08-06 17:19:22 -0400192 '__loader__', '__module__', '__name__', '__package__',
193 '__path__', '__qualname__', '__slots__', '__version__'}:
Raymond Hettinger68272942011-03-18 02:22:15 -0700194 return 0
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000195 # Private names are hidden, but special names are displayed.
196 if name.startswith('__') and name.endswith('__'): return 1
Raymond Hettinger1103d052011-03-25 14:15:24 -0700197 # Namedtuples have public fields and methods with a single leading underscore
198 if name.startswith('_') and hasattr(obj, '_fields'):
199 return True
Skip Montanaroa5616d22004-06-11 04:46:12 +0000200 if all is not None:
201 # only document that which the programmer exported in __all__
202 return name in all
203 else:
204 return not name.startswith('_')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000205
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000206def classify_class_attrs(object):
207 """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000208 results = []
209 for (name, kind, cls, value) in inspect.classify_class_attrs(object):
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000210 if inspect.isdatadescriptor(value):
211 kind = 'data descriptor'
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000212 results.append((name, kind, cls, value))
213 return results
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000214
Raymond Hettinger95801bb2015-08-18 22:25:16 -0700215def sort_attributes(attrs, object):
216 'Sort the attrs list in-place by _fields and then alphabetically by name'
217 # This allows data descriptors to be ordered according
218 # to a _fields attribute if present.
219 fields = getattr(object, '_fields', [])
220 try:
221 field_order = {name : i-len(fields) for (i, name) in enumerate(fields)}
222 except TypeError:
223 field_order = {}
224 keyfunc = lambda attr: (field_order.get(attr[0], 0), attr[0])
225 attrs.sort(key=keyfunc)
226
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000227# ----------------------------------------------------- module manipulation
228
229def ispackage(path):
230 """Guess whether a path refers to a package directory."""
231 if os.path.isdir(path):
Brett Cannonf299abd2015-04-13 14:21:02 -0400232 for ext in ('.py', '.pyc'):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000233 if os.path.isfile(os.path.join(path, '__init__' + ext)):
Tim Petersbc0e9102002-04-04 22:55:58 +0000234 return True
235 return False
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000236
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000237def source_synopsis(file):
238 line = file.readline()
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000239 while line[:1] == '#' or not line.strip():
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000240 line = file.readline()
241 if not line: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000242 line = line.strip()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000243 if line[:4] == 'r"""': line = line[1:]
244 if line[:3] == '"""':
245 line = line[3:]
246 if line[-1:] == '\\': line = line[:-1]
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000247 while not line.strip():
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000248 line = file.readline()
249 if not line: break
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000250 result = line.split('"""')[0].strip()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000251 else: result = None
252 return result
253
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000254def synopsis(filename, cache={}):
255 """Get the one-line summary out of a module file."""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000256 mtime = os.stat(filename).st_mtime
Charles-François Natali27c4e882011-07-27 19:40:02 +0200257 lastupdate, result = cache.get(filename, (None, None))
258 if lastupdate is None or lastupdate < mtime:
Eric Snowaed5b222014-01-04 20:38:11 -0700259 # Look for binary suffixes first, falling back to source.
260 if filename.endswith(tuple(importlib.machinery.BYTECODE_SUFFIXES)):
261 loader_cls = importlib.machinery.SourcelessFileLoader
262 elif filename.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):
263 loader_cls = importlib.machinery.ExtensionFileLoader
264 else:
265 loader_cls = None
266 # Now handle the choice.
267 if loader_cls is None:
268 # Must be a source file.
269 try:
270 file = tokenize.open(filename)
271 except OSError:
272 # module can't be opened, so skip it
273 return None
274 # text modules can be directly examined
275 with file:
276 result = source_synopsis(file)
277 else:
278 # Must be a binary module, which has to be imported.
279 loader = loader_cls('__temp__', filename)
Eric Snow3a62d142014-01-06 20:42:59 -0700280 # XXX We probably don't need to pass in the loader here.
281 spec = importlib.util.spec_from_file_location('__temp__', filename,
282 loader=loader)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400283 try:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400284 module = importlib._bootstrap._load(spec)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400285 except:
286 return None
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000287 del sys.modules['__temp__']
Benjamin Peterson54237f92015-02-16 19:45:01 -0500288 result = module.__doc__.splitlines()[0] if module.__doc__ else None
Eric Snowaed5b222014-01-04 20:38:11 -0700289 # Cache the result.
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000290 cache[filename] = (mtime, result)
291 return result
292
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000293class ErrorDuringImport(Exception):
294 """Errors that occurred while trying to import something to document it."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000295 def __init__(self, filename, exc_info):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000296 self.filename = filename
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000297 self.exc, self.value, self.tb = exc_info
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000298
299 def __str__(self):
Guido van Rossuma01a8b62007-05-27 09:20:14 +0000300 exc = self.exc.__name__
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000301 return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000302
303def importfile(path):
304 """Import a Python source file or compiled file given its path."""
Brett Cannonf4ba4ec2013-06-15 14:25:04 -0400305 magic = importlib.util.MAGIC_NUMBER
Victor Stinnere975af62011-07-04 02:08:50 +0200306 with open(path, 'rb') as file:
Brett Cannond5e6f2e2013-06-11 17:09:36 -0400307 is_bytecode = magic == file.read(len(magic))
308 filename = os.path.basename(path)
309 name, ext = os.path.splitext(filename)
310 if is_bytecode:
Eric Snow32439d62015-05-02 19:15:18 -0600311 loader = importlib._bootstrap_external.SourcelessFileLoader(name, path)
Brett Cannond5e6f2e2013-06-11 17:09:36 -0400312 else:
Eric Snow32439d62015-05-02 19:15:18 -0600313 loader = importlib._bootstrap_external.SourceFileLoader(name, path)
Eric Snow3a62d142014-01-06 20:42:59 -0700314 # XXX We probably don't need to pass in the loader here.
315 spec = importlib.util.spec_from_file_location(name, path, loader=loader)
Brett Cannond5e6f2e2013-06-11 17:09:36 -0400316 try:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400317 return importlib._bootstrap._load(spec)
Brett Cannond5e6f2e2013-06-11 17:09:36 -0400318 except:
319 raise ErrorDuringImport(path, sys.exc_info())
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000320
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000321def safeimport(path, forceload=0, cache={}):
322 """Import a module; handle errors; return None if the module isn't found.
323
324 If the module *is* found but an exception occurs, it's wrapped in an
325 ErrorDuringImport exception and reraised. Unlike __import__, if a
326 package path is specified, the module at the end of the path is returned,
327 not the package at the beginning. If the optional 'forceload' argument
328 is 1, we reload the module from disk (unless it's a dynamic extension)."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000329 try:
Ka-Ping Yee9a2dcf82005-11-05 05:04:41 +0000330 # If forceload is 1 and the module has been previously loaded from
331 # disk, we always have to reload the module. Checking the file's
332 # mtime isn't good enough (e.g. the module could contain a class
333 # that inherits from another module that has changed).
334 if forceload and path in sys.modules:
335 if path not in sys.builtin_module_names:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000336 # Remove the module from sys.modules and re-import to try
337 # and avoid problems with partially loaded modules.
338 # Also remove any submodules because they won't appear
339 # in the newly loaded module's namespace if they're already
340 # in sys.modules.
Ka-Ping Yee9a2dcf82005-11-05 05:04:41 +0000341 subs = [m for m in sys.modules if m.startswith(path + '.')]
342 for key in [path] + subs:
343 # Prevent garbage collection.
344 cache[key] = sys.modules[key]
345 del sys.modules[key]
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000346 module = __import__(path)
347 except:
348 # Did the error occur before or after the module was found?
349 (exc, value, tb) = info = sys.exc_info()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000350 if path in sys.modules:
Fred Drakedb390c12005-10-28 14:39:47 +0000351 # An error occurred while executing the imported module.
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000352 raise ErrorDuringImport(sys.modules[path].__file__, info)
353 elif exc is SyntaxError:
354 # A SyntaxError occurred before we could execute the module.
355 raise ErrorDuringImport(value.filename, info)
Eric Snow46f97b82016-09-07 16:56:15 -0700356 elif issubclass(exc, ImportError) and value.name == path:
Brett Cannonfd074152012-04-14 14:10:13 -0400357 # No such module in the path.
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000358 return None
359 else:
360 # Some other error occurred during the importing process.
361 raise ErrorDuringImport(path, sys.exc_info())
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000362 for part in path.split('.')[1:]:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000363 try: module = getattr(module, part)
364 except AttributeError: return None
365 return module
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000366
367# ---------------------------------------------------- formatter base class
368
369class Doc:
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000370
371 PYTHONDOCS = os.environ.get("PYTHONDOCS",
R David Murrayead9bfc2016-06-03 19:28:35 -0400372 "https://docs.python.org/%d.%d/library"
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000373 % sys.version_info[:2])
374
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000375 def document(self, object, name=None, *args):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000376 """Generate documentation for an object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000377 args = (object, name) + args
Brett Cannon28a4f0f2003-06-11 23:38:55 +0000378 # 'try' clause is to attempt to handle the possibility that inspect
379 # identifies something in a way that pydoc itself has issues handling;
380 # think 'super' and how it is a descriptor (which raises the exception
381 # by lacking a __name__ attribute) and an instance.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000382 if inspect.isgetsetdescriptor(object): return self.docdata(*args)
383 if inspect.ismemberdescriptor(object): return self.docdata(*args)
Brett Cannon28a4f0f2003-06-11 23:38:55 +0000384 try:
385 if inspect.ismodule(object): return self.docmodule(*args)
386 if inspect.isclass(object): return self.docclass(*args)
387 if inspect.isroutine(object): return self.docroutine(*args)
388 except AttributeError:
389 pass
Johannes Gijsbers8de645a2004-11-07 19:16:05 +0000390 if isinstance(object, property): return self.docproperty(*args)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000391 return self.docother(*args)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000392
393 def fail(self, object, name=None, *args):
394 """Raise an exception for unimplemented types."""
395 message = "don't know how to document object%s of type %s" % (
396 name and ' ' + repr(name), type(object).__name__)
Collin Winterce36ad82007-08-30 01:19:48 +0000397 raise TypeError(message)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000398
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000399 docmodule = docclass = docroutine = docother = docproperty = docdata = fail
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000400
R David Murrayead9bfc2016-06-03 19:28:35 -0400401 def getdocloc(self, object,
402 basedir=os.path.join(sys.base_exec_prefix, "lib",
403 "python%d.%d" % sys.version_info[:2])):
Skip Montanaro4997a692003-09-10 16:47:51 +0000404 """Return the location of module docs or None"""
405
406 try:
407 file = inspect.getabsfile(object)
408 except TypeError:
409 file = '(built-in)'
410
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000411 docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS)
412
Martin Panter4f8aaf62016-06-12 04:24:06 +0000413 basedir = os.path.normcase(basedir)
Skip Montanaro4997a692003-09-10 16:47:51 +0000414 if (isinstance(object, type(os)) and
415 (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
416 'marshal', 'posix', 'signal', 'sys',
Georg Brandl2067bfd2008-05-25 13:05:15 +0000417 '_thread', 'zipimport') or
Skip Montanaro4997a692003-09-10 16:47:51 +0000418 (file.startswith(basedir) and
Brian Curtin49c284c2010-03-31 03:19:28 +0000419 not file.startswith(os.path.join(basedir, 'site-packages')))) and
Brian Curtinedef05b2010-04-01 04:05:25 +0000420 object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
Martin Panter4f8aaf62016-06-12 04:24:06 +0000421 if docloc.startswith(("http://", "https://")):
R David Murrayead9bfc2016-06-03 19:28:35 -0400422 docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__.lower())
Skip Montanaro4997a692003-09-10 16:47:51 +0000423 else:
R David Murrayead9bfc2016-06-03 19:28:35 -0400424 docloc = os.path.join(docloc, object.__name__.lower() + ".html")
Skip Montanaro4997a692003-09-10 16:47:51 +0000425 else:
426 docloc = None
427 return docloc
428
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000429# -------------------------------------------- HTML documentation generator
430
431class HTMLRepr(Repr):
432 """Class for safely making an HTML representation of a Python object."""
433 def __init__(self):
434 Repr.__init__(self)
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000435 self.maxlist = self.maxtuple = 20
436 self.maxdict = 10
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000437 self.maxstring = self.maxother = 100
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000438
439 def escape(self, text):
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000440 return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;')
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000441
442 def repr(self, object):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000443 return Repr.repr(self, object)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000444
445 def repr1(self, x, level):
Skip Montanaro0fe8fce2003-06-27 15:45:41 +0000446 if hasattr(type(x), '__name__'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000447 methodname = 'repr_' + '_'.join(type(x).__name__.split())
Skip Montanaro0fe8fce2003-06-27 15:45:41 +0000448 if hasattr(self, methodname):
449 return getattr(self, methodname)(x, level)
450 return self.escape(cram(stripid(repr(x)), self.maxother))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000451
452 def repr_string(self, x, level):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000453 test = cram(x, self.maxstring)
454 testrepr = repr(test)
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000455 if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000456 # Backslashes are only literal in the string and are never
457 # needed to make any special characters, so show a raw string.
458 return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000459 return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000460 r'<font color="#c040c0">\1</font>',
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000461 self.escape(testrepr))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000462
Skip Montanarodf708782002-03-07 22:58:02 +0000463 repr_str = repr_string
464
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000465 def repr_instance(self, x, level):
466 try:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000467 return self.escape(cram(stripid(repr(x)), self.maxstring))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000468 except:
469 return self.escape('<%s instance>' % x.__class__.__name__)
470
471 repr_unicode = repr_string
472
473class HTMLDoc(Doc):
474 """Formatter class for HTML documentation."""
475
476 # ------------------------------------------- HTML formatting utilities
477
478 _repr_instance = HTMLRepr()
479 repr = _repr_instance.repr
480 escape = _repr_instance.escape
481
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000482 def page(self, title, contents):
483 """Format an HTML page."""
Georg Brandl388faac2009-04-10 08:31:48 +0000484 return '''\
Georg Brandle6066942009-04-10 08:28:28 +0000485<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000486<html><head><title>Python: %s</title>
Georg Brandl388faac2009-04-10 08:31:48 +0000487<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000488</head><body bgcolor="#f0f0f8">
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000489%s
490</body></html>''' % (title, contents)
491
492 def heading(self, title, fgcol, bgcol, extras=''):
493 """Format a page heading."""
494 return '''
Tim Peters59ed4482001-10-31 04:20:26 +0000495<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000496<tr bgcolor="%s">
Tim Peters2306d242001-09-25 03:18:32 +0000497<td valign=bottom>&nbsp;<br>
498<font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000499><td align=right valign=bottom
Ka-Ping Yee987ec902001-03-23 13:35:45 +0000500><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000501 ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
502
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000503 def section(self, title, fgcol, bgcol, contents, width=6,
504 prelude='', marginalia=None, gap='&nbsp;'):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000505 """Format a section with a heading."""
506 if marginalia is None:
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000507 marginalia = '<tt>' + '&nbsp;' * width + '</tt>'
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000508 result = '''<p>
Tim Peters59ed4482001-10-31 04:20:26 +0000509<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000510<tr bgcolor="%s">
Tim Peters2306d242001-09-25 03:18:32 +0000511<td colspan=3 valign=bottom>&nbsp;<br>
512<font color="%s" face="helvetica, arial">%s</font></td></tr>
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000513 ''' % (bgcol, fgcol, title)
514 if prelude:
515 result = result + '''
Ka-Ping Yee987ec902001-03-23 13:35:45 +0000516<tr bgcolor="%s"><td rowspan=2>%s</td>
517<td colspan=2>%s</td></tr>
518<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
519 else:
520 result = result + '''
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000521<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000522
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +0000523 return result + '\n<td width="100%%">%s</td></tr></table>' % contents
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000524
525 def bigsection(self, title, *args):
526 """Format a section with a big heading."""
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000527 title = '<big><strong>%s</strong></big>' % title
Guido van Rossum68468eb2003-02-27 20:14:51 +0000528 return self.section(title, *args)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000529
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000530 def preformat(self, text):
531 """Format literal preformatted text."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000532 text = self.escape(text.expandtabs())
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000533 return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
534 ' ', '&nbsp;', '\n', '<br>\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000535
536 def multicolumn(self, list, format, cols=4):
537 """Format a list of items into a multi-column list."""
538 result = ''
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000539 rows = (len(list)+cols-1)//cols
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000540 for col in range(cols):
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000541 result = result + '<td width="%d%%" valign=top>' % (100//cols)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000542 for i in range(rows*col, rows*col+rows):
543 if i < len(list):
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000544 result = result + format(list[i]) + '<br>\n'
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000545 result = result + '</td>'
Tim Peters59ed4482001-10-31 04:20:26 +0000546 return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000547
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000548 def grey(self, text): return '<font color="#909090">%s</font>' % text
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000549
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000550 def namelink(self, name, *dicts):
551 """Make a link for an identifier, given name-to-URL mappings."""
552 for dict in dicts:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000553 if name in dict:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000554 return '<a href="%s">%s</a>' % (dict[name], name)
555 return name
556
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000557 def classlink(self, object, modname):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000558 """Make a link for a class."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000559 name, module = object.__name__, sys.modules.get(object.__module__)
560 if hasattr(module, name) and getattr(module, name) is object:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000561 return '<a href="%s.html#%s">%s</a>' % (
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000562 module.__name__, name, classname(object, modname))
563 return classname(object, modname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000564
565 def modulelink(self, object):
566 """Make a link for a module."""
567 return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
568
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000569 def modpkglink(self, modpkginfo):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000570 """Make a link for a module or package to display in an index."""
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000571 name, path, ispackage, shadowed = modpkginfo
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000572 if shadowed:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000573 return self.grey(name)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000574 if path:
575 url = '%s.%s.html' % (path, name)
576 else:
577 url = '%s.html' % name
578 if ispackage:
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000579 text = '<strong>%s</strong>&nbsp;(package)' % name
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000580 else:
581 text = name
582 return '<a href="%s">%s</a>' % (url, text)
583
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000584 def filelink(self, url, path):
585 """Make a link to source file."""
586 return '<a href="file:%s">%s</a>' % (url, path)
587
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000588 def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
589 """Mark up some plain text, given a context of symbols to look for.
590 Each context dictionary maps object names to anchor names."""
591 escape = escape or self.escape
592 results = []
593 here = 0
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000594 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
595 r'RFC[- ]?(\d+)|'
Ka-Ping Yeef78a81b2001-03-27 08:13:42 +0000596 r'PEP[- ]?(\d+)|'
Neil Schemenauerd69711c2002-03-24 23:02:07 +0000597 r'(self\.)?(\w+))')
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000598 while True:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000599 match = pattern.search(text, here)
600 if not match: break
601 start, end = match.span()
602 results.append(escape(text[here:start]))
603
Ka-Ping Yeef78a81b2001-03-27 08:13:42 +0000604 all, scheme, rfc, pep, selfdot, name = match.groups()
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000605 if scheme:
Neil Schemenauercddc1a02002-03-24 23:11:21 +0000606 url = escape(all).replace('"', '&quot;')
607 results.append('<a href="%s">%s</a>' % (url, url))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000608 elif rfc:
Ka-Ping Yeef78a81b2001-03-27 08:13:42 +0000609 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
610 results.append('<a href="%s">%s</a>' % (url, escape(all)))
611 elif pep:
Christian Heimes2202f872008-02-06 14:31:34 +0000612 url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000613 results.append('<a href="%s">%s</a>' % (url, escape(all)))
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700614 elif selfdot:
615 # Create a link for methods like 'self.method(...)'
616 # and use <strong> for attributes like 'self.attr'
617 if text[end:end+1] == '(':
618 results.append('self.' + self.namelink(name, methods))
619 else:
620 results.append('self.<strong>%s</strong>' % name)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000621 elif text[end:end+1] == '(':
622 results.append(self.namelink(name, methods, funcs, classes))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000623 else:
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000624 results.append(self.namelink(name, classes))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000625 here = end
626 results.append(escape(text[here:]))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000627 return ''.join(results)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000628
629 # ---------------------------------------------- type-specific routines
630
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000631 def formattree(self, tree, modname, parent=None):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000632 """Produce HTML for a class tree as given by inspect.getclasstree()."""
633 result = ''
634 for entry in tree:
635 if type(entry) is type(()):
636 c, bases = entry
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000637 result = result + '<dt><font face="helvetica, arial">'
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000638 result = result + self.classlink(c, modname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000639 if bases and bases != (parent,):
640 parents = []
641 for base in bases:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000642 parents.append(self.classlink(base, modname))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000643 result = result + '(' + ', '.join(parents) + ')'
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000644 result = result + '\n</font></dt>'
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000645 elif type(entry) is type([]):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000646 result = result + '<dd>\n%s</dd>\n' % self.formattree(
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000647 entry, modname, c)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000648 return '<dl>\n%s</dl>\n' % result
649
Tim Peters8dd7ade2001-10-18 19:56:17 +0000650 def docmodule(self, object, name=None, mod=None, *ignored):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000651 """Produce HTML documentation for a module object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000652 name = object.__name__ # ignore the passed-in name
Skip Montanaroa5616d22004-06-11 04:46:12 +0000653 try:
654 all = object.__all__
655 except AttributeError:
656 all = None
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000657 parts = name.split('.')
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000658 links = []
659 for i in range(len(parts)-1):
660 links.append(
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000661 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000662 ('.'.join(parts[:i+1]), parts[i]))
663 linkedname = '.'.join(links + parts[-1:])
Raymond Hettinger95f285c2009-02-24 23:41:47 +0000664 head = '<big><big><strong>%s</strong></big></big>' % linkedname
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000665 try:
Ka-Ping Yee239432a2001-03-02 02:45:08 +0000666 path = inspect.getabsfile(object)
Zachary Wareeb432142014-07-10 11:18:00 -0500667 url = urllib.parse.quote(path)
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000668 filelink = self.filelink(url, path)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000669 except TypeError:
670 filelink = '(built-in)'
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000671 info = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000672 if hasattr(object, '__version__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000673 version = str(object.__version__)
Ka-Ping Yee40c49912001-02-27 22:46:01 +0000674 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000675 version = version[11:-1].strip()
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000676 info.append('version %s' % self.escape(version))
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000677 if hasattr(object, '__date__'):
678 info.append(self.escape(str(object.__date__)))
679 if info:
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000680 head = head + ' (%s)' % ', '.join(info)
Skip Montanaro4997a692003-09-10 16:47:51 +0000681 docloc = self.getdocloc(object)
682 if docloc is not None:
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000683 docloc = '<br><a href="%(docloc)s">Module Reference</a>' % locals()
Skip Montanaro4997a692003-09-10 16:47:51 +0000684 else:
685 docloc = ''
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000686 result = self.heading(
Skip Montanaro4997a692003-09-10 16:47:51 +0000687 head, '#ffffff', '#7799ee',
688 '<a href=".">index</a><br>' + filelink + docloc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000689
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000690 modules = inspect.getmembers(object, inspect.ismodule)
691
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000692 classes, cdict = [], {}
693 for key, value in inspect.getmembers(object, inspect.isclass):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +0000694 # if __all__ exists, believe it. Otherwise use old heuristic.
695 if (all is not None or
696 (inspect.getmodule(value) or object) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -0700697 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000698 classes.append((key, value))
699 cdict[key] = cdict[value] = '#' + key
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000700 for key, value in classes:
701 for base in value.__bases__:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000702 key, modname = base.__name__, base.__module__
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000703 module = sys.modules.get(modname)
704 if modname != name and module and hasattr(module, key):
705 if getattr(module, key) is base:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000706 if not key in cdict:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000707 cdict[key] = cdict[base] = modname + '.html#' + key
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000708 funcs, fdict = [], {}
709 for key, value in inspect.getmembers(object, inspect.isroutine):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +0000710 # if __all__ exists, believe it. Otherwise use old heuristic.
711 if (all is not None or
712 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -0700713 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000714 funcs.append((key, value))
715 fdict[key] = '#-' + key
716 if inspect.isfunction(value): fdict[value] = fdict[key]
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000717 data = []
718 for key, value in inspect.getmembers(object, isdata):
Raymond Hettinger1103d052011-03-25 14:15:24 -0700719 if visiblename(key, all, object):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000720 data.append((key, value))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000721
722 doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
723 doc = doc and '<tt>%s</tt>' % doc
Tim Peters2306d242001-09-25 03:18:32 +0000724 result = result + '<p>%s</p>\n' % doc
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000725
726 if hasattr(object, '__path__'):
727 modpkgs = []
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000728 for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
729 modpkgs.append((modname, name, ispkg, 0))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000730 modpkgs.sort()
731 contents = self.multicolumn(modpkgs, self.modpkglink)
732 result = result + self.bigsection(
733 'Package Contents', '#ffffff', '#aa55cc', contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000734 elif modules:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000735 contents = self.multicolumn(
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000736 modules, lambda t: self.modulelink(t[1]))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000737 result = result + self.bigsection(
Christian Heimes7131fd92008-02-19 14:21:46 +0000738 'Modules', '#ffffff', '#aa55cc', contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000739
740 if classes:
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000741 classlist = [value for (key, value) in classes]
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000742 contents = [
743 self.formattree(inspect.getclasstree(classlist, 1), name)]
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000744 for key, value in classes:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000745 contents.append(self.document(value, key, name, fdict, cdict))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000746 result = result + self.bigsection(
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000747 'Classes', '#ffffff', '#ee77aa', ' '.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000748 if funcs:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000749 contents = []
750 for key, value in funcs:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000751 contents.append(self.document(value, key, name, fdict, cdict))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000752 result = result + self.bigsection(
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000753 'Functions', '#ffffff', '#eeaa77', ' '.join(contents))
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000754 if data:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000755 contents = []
Ka-Ping Yeedec96e92001-04-13 09:55:49 +0000756 for key, value in data:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000757 contents.append(self.document(value, key))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000758 result = result + self.bigsection(
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000759 'Data', '#ffffff', '#55aa55', '<br>\n'.join(contents))
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000760 if hasattr(object, '__author__'):
761 contents = self.markup(str(object.__author__), self.preformat)
762 result = result + self.bigsection(
763 'Author', '#ffffff', '#7799ee', contents)
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000764 if hasattr(object, '__credits__'):
765 contents = self.markup(str(object.__credits__), self.preformat)
766 result = result + self.bigsection(
767 'Credits', '#ffffff', '#7799ee', contents)
768
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000769 return result
770
Tim Peters8dd7ade2001-10-18 19:56:17 +0000771 def docclass(self, object, name=None, mod=None, funcs={}, classes={},
772 *ignored):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000773 """Produce HTML documentation for a class object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000774 realname = object.__name__
775 name = name or realname
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000776 bases = object.__bases__
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000777
Tim Petersb47879b2001-09-24 04:47:19 +0000778 contents = []
779 push = contents.append
780
Tim Petersfa26f7c2001-09-24 08:05:11 +0000781 # Cute little class to pump out a horizontal rule between sections.
782 class HorizontalRule:
783 def __init__(self):
784 self.needone = 0
785 def maybe(self):
786 if self.needone:
787 push('<hr>\n')
788 self.needone = 1
789 hr = HorizontalRule()
790
Tim Petersc86f6ca2001-09-26 21:31:51 +0000791 # List the mro, if non-trivial.
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000792 mro = deque(inspect.getmro(object))
Tim Petersc86f6ca2001-09-26 21:31:51 +0000793 if len(mro) > 2:
794 hr.maybe()
795 push('<dl><dt>Method resolution order:</dt>\n')
796 for base in mro:
797 push('<dd>%s</dd>\n' % self.classlink(base,
798 object.__module__))
799 push('</dl>\n')
800
Tim Petersb47879b2001-09-24 04:47:19 +0000801 def spill(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +0000802 ok, attrs = _split_list(attrs, predicate)
Tim Petersb47879b2001-09-24 04:47:19 +0000803 if ok:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000804 hr.maybe()
Tim Petersb47879b2001-09-24 04:47:19 +0000805 push(msg)
806 for name, kind, homecls, value in ok:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100807 try:
808 value = getattr(object, name)
809 except Exception:
810 # Some descriptors may meet a failure in their __get__.
811 # (bug #1785)
812 push(self._docdescriptor(name, value, mod))
813 else:
814 push(self.document(value, name, mod,
815 funcs, classes, mdict, object))
Tim Petersb47879b2001-09-24 04:47:19 +0000816 push('\n')
817 return attrs
818
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000819 def spilldescriptors(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +0000820 ok, attrs = _split_list(attrs, predicate)
Tim Petersb47879b2001-09-24 04:47:19 +0000821 if ok:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000822 hr.maybe()
Tim Petersb47879b2001-09-24 04:47:19 +0000823 push(msg)
824 for name, kind, homecls, value in ok:
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000825 push(self._docdescriptor(name, value, mod))
Tim Petersb47879b2001-09-24 04:47:19 +0000826 return attrs
827
Tim Petersfa26f7c2001-09-24 08:05:11 +0000828 def spilldata(msg, attrs, predicate):
829 ok, attrs = _split_list(attrs, predicate)
Tim Petersb47879b2001-09-24 04:47:19 +0000830 if ok:
Tim Petersfa26f7c2001-09-24 08:05:11 +0000831 hr.maybe()
Tim Petersb47879b2001-09-24 04:47:19 +0000832 push(msg)
833 for name, kind, homecls, value in ok:
834 base = self.docother(getattr(object, name), name, mod)
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200835 if callable(value) or inspect.isdatadescriptor(value):
Guido van Rossum5e355b22002-05-21 20:56:15 +0000836 doc = getattr(value, "__doc__", None)
837 else:
838 doc = None
Tim Petersb47879b2001-09-24 04:47:19 +0000839 if doc is None:
840 push('<dl><dt>%s</dl>\n' % base)
841 else:
842 doc = self.markup(getdoc(value), self.preformat,
843 funcs, classes, mdict)
Tim Peters2306d242001-09-25 03:18:32 +0000844 doc = '<dd><tt>%s</tt>' % doc
Tim Petersb47879b2001-09-24 04:47:19 +0000845 push('<dl><dt>%s%s</dl>\n' % (base, doc))
846 push('\n')
847 return attrs
848
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000849 attrs = [(name, kind, cls, value)
850 for name, kind, cls, value in classify_class_attrs(object)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700851 if visiblename(name, obj=object)]
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000852
Tim Petersb47879b2001-09-24 04:47:19 +0000853 mdict = {}
854 for key, kind, homecls, value in attrs:
855 mdict[key] = anchor = '#' + name + '-' + key
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +0100856 try:
857 value = getattr(object, name)
858 except Exception:
859 # Some descriptors may meet a failure in their __get__.
860 # (bug #1785)
861 pass
Tim Petersb47879b2001-09-24 04:47:19 +0000862 try:
863 # The value may not be hashable (e.g., a data attr with
864 # a dict or list value).
865 mdict[value] = anchor
866 except TypeError:
867 pass
868
Tim Petersfa26f7c2001-09-24 08:05:11 +0000869 while attrs:
Tim Peters351e3622001-09-27 03:29:51 +0000870 if mro:
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000871 thisclass = mro.popleft()
Tim Peters351e3622001-09-27 03:29:51 +0000872 else:
873 thisclass = attrs[0][2]
Tim Petersfa26f7c2001-09-24 08:05:11 +0000874 attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
875
Georg Brandl1a3284e2007-12-02 09:40:06 +0000876 if thisclass is builtins.object:
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000877 attrs = inherited
878 continue
879 elif thisclass is object:
880 tag = 'defined here'
Tim Petersb47879b2001-09-24 04:47:19 +0000881 else:
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000882 tag = 'inherited from %s' % self.classlink(thisclass,
883 object.__module__)
Tim Petersb47879b2001-09-24 04:47:19 +0000884 tag += ':<br>\n'
885
Raymond Hettinger95801bb2015-08-18 22:25:16 -0700886 sort_attributes(attrs, object)
Tim Petersb47879b2001-09-24 04:47:19 +0000887
888 # Pump out the attrs, segregated by kind.
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000889 attrs = spill('Methods %s' % tag, attrs,
Tim Petersb47879b2001-09-24 04:47:19 +0000890 lambda t: t[1] == 'method')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000891 attrs = spill('Class methods %s' % tag, attrs,
Tim Petersb47879b2001-09-24 04:47:19 +0000892 lambda t: t[1] == 'class method')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000893 attrs = spill('Static methods %s' % tag, attrs,
Tim Petersb47879b2001-09-24 04:47:19 +0000894 lambda t: t[1] == 'static method')
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000895 attrs = spilldescriptors('Data descriptors %s' % tag, attrs,
896 lambda t: t[1] == 'data descriptor')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000897 attrs = spilldata('Data and other attributes %s' % tag, attrs,
Tim Petersfa26f7c2001-09-24 08:05:11 +0000898 lambda t: t[1] == 'data')
Tim Petersb47879b2001-09-24 04:47:19 +0000899 assert attrs == []
Tim Peters351e3622001-09-27 03:29:51 +0000900 attrs = inherited
Tim Petersb47879b2001-09-24 04:47:19 +0000901
902 contents = ''.join(contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000903
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000904 if name == realname:
905 title = '<a name="%s">class <strong>%s</strong></a>' % (
906 name, realname)
907 else:
908 title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
909 name, name, realname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000910 if bases:
911 parents = []
912 for base in bases:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000913 parents.append(self.classlink(base, object.__module__))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000914 title = title + '(%s)' % ', '.join(parents)
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +0200915
916 decl = ''
917 try:
918 signature = inspect.signature(object)
919 except (ValueError, TypeError):
920 signature = None
921 if signature:
922 argspec = str(signature)
Serhiy Storchaka213f2292017-01-23 14:02:35 +0200923 if argspec and argspec != '()':
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +0200924 decl = name + self.escape(argspec) + '\n\n'
925
926 doc = getdoc(object)
927 if decl:
928 doc = decl + (doc or '')
929 doc = self.markup(doc, self.preformat, funcs, classes, mdict)
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000930 doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc
Tim Petersc86f6ca2001-09-26 21:31:51 +0000931
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +0000932 return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000933
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000934 def formatvalue(self, object):
935 """Format an argument default value as text."""
Tim Peters2306d242001-09-25 03:18:32 +0000936 return self.grey('=' + self.repr(object))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000937
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000938 def docroutine(self, object, name=None, mod=None,
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000939 funcs={}, classes={}, methods={}, cl=None):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000940 """Produce HTML documentation for a function or method object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000941 realname = object.__name__
942 name = name or realname
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000943 anchor = (cl and cl.__name__ or '') + '-' + name
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000944 note = ''
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000945 skipdocs = 0
Larry Hastings24a882b2014-02-20 23:34:46 -0800946 if _is_bound_method(object):
Christian Heimesff737952007-11-27 10:40:20 +0000947 imclass = object.__self__.__class__
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000948 if cl:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +0000949 if imclass is not cl:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000950 note = ' from ' + self.classlink(imclass, mod)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000951 else:
Christian Heimesff737952007-11-27 10:40:20 +0000952 if object.__self__ is not None:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000953 note = ' method of %s instance' % self.classlink(
Christian Heimesff737952007-11-27 10:40:20 +0000954 object.__self__.__class__, mod)
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +0000955 else:
956 note = ' unbound %s method' % self.classlink(imclass,mod)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000957
958 if name == realname:
959 title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
960 else:
Serhiy Storchakaa44d34e2018-11-08 08:48:11 +0200961 if cl and inspect.getattr_static(cl, realname, []) is object:
Ka-Ping Yeee280c062001-03-23 14:05:53 +0000962 reallink = '<a href="#%s">%s</a>' % (
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000963 cl.__name__ + '-' + realname, realname)
964 skipdocs = 1
965 else:
966 reallink = realname
967 title = '<a name="%s"><strong>%s</strong></a> = %s' % (
968 anchor, name, reallink)
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800969 argspec = None
Larry Hastings24a882b2014-02-20 23:34:46 -0800970 if inspect.isroutine(object):
Larry Hastings5c661892014-01-24 06:17:25 -0800971 try:
972 signature = inspect.signature(object)
973 except (ValueError, TypeError):
974 signature = None
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800975 if signature:
976 argspec = str(signature)
977 if realname == '<lambda>':
978 title = '<strong>%s</strong> <em>lambda</em> ' % name
979 # XXX lambda's won't usually have func_annotations['return']
980 # since the syntax doesn't support but it is possible.
981 # So removing parentheses isn't truly safe.
982 argspec = argspec[1:-1] # remove parentheses
983 if not argspec:
Tim Peters4bcfa312001-09-20 06:08:24 +0000984 argspec = '(...)'
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000985
Serhiy Storchaka66dd4aa2014-11-17 23:48:02 +0200986 decl = title + self.escape(argspec) + (note and self.grey(
Tim Peters2306d242001-09-25 03:18:32 +0000987 '<font face="helvetica, arial">%s</font>' % note))
Ka-Ping Yee37f7b382001-03-23 00:12:53 +0000988
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000989 if skipdocs:
Tim Peters2306d242001-09-25 03:18:32 +0000990 return '<dl><dt>%s</dt></dl>\n' % decl
Ka-Ping Yee3bda8792001-03-23 13:17:50 +0000991 else:
992 doc = self.markup(
993 getdoc(object), self.preformat, funcs, classes, methods)
Tim Peters2306d242001-09-25 03:18:32 +0000994 doc = doc and '<dd><tt>%s</tt></dd>' % doc
995 return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000996
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +0000997 def _docdescriptor(self, name, value, mod):
Johannes Gijsbers8de645a2004-11-07 19:16:05 +0000998 results = []
999 push = results.append
1000
1001 if name:
1002 push('<dl><dt><strong>%s</strong></dt>\n' % name)
1003 if value.__doc__ is not None:
Ka-Ping Yeebba6acc2005-02-19 22:58:26 +00001004 doc = self.markup(getdoc(value), self.preformat)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001005 push('<dd><tt>%s</tt></dd>\n' % doc)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001006 push('</dl>\n')
1007
1008 return ''.join(results)
1009
1010 def docproperty(self, object, name=None, mod=None, cl=None):
1011 """Produce html documentation for a property."""
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001012 return self._docdescriptor(name, object, mod)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001013
Tim Peters8dd7ade2001-10-18 19:56:17 +00001014 def docother(self, object, name=None, mod=None, *ignored):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001015 """Produce HTML documentation for a data object."""
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001016 lhs = name and '<strong>%s</strong> = ' % name or ''
1017 return lhs + self.repr(object)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001018
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001019 def docdata(self, object, name=None, mod=None, cl=None):
1020 """Produce html documentation for a data descriptor."""
1021 return self._docdescriptor(name, object, mod)
1022
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001023 def index(self, dir, shadowed=None):
1024 """Generate an HTML index for a directory of modules."""
1025 modpkgs = []
1026 if shadowed is None: shadowed = {}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001027 for importer, name, ispkg in pkgutil.iter_modules([dir]):
Victor Stinner4d652242011-04-12 23:41:50 +02001028 if any((0xD800 <= ord(ch) <= 0xDFFF) for ch in name):
1029 # ignore a module if its name contains a surrogate character
1030 continue
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001031 modpkgs.append((name, '', ispkg, name in shadowed))
1032 shadowed[name] = 1
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001033
1034 modpkgs.sort()
1035 contents = self.multicolumn(modpkgs, self.modpkglink)
1036 return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
1037
1038# -------------------------------------------- text documentation generator
1039
1040class TextRepr(Repr):
1041 """Class for safely making a text representation of a Python object."""
1042 def __init__(self):
1043 Repr.__init__(self)
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001044 self.maxlist = self.maxtuple = 20
1045 self.maxdict = 10
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001046 self.maxstring = self.maxother = 100
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001047
1048 def repr1(self, x, level):
Skip Montanaro0fe8fce2003-06-27 15:45:41 +00001049 if hasattr(type(x), '__name__'):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001050 methodname = 'repr_' + '_'.join(type(x).__name__.split())
Skip Montanaro0fe8fce2003-06-27 15:45:41 +00001051 if hasattr(self, methodname):
1052 return getattr(self, methodname)(x, level)
1053 return cram(stripid(repr(x)), self.maxother)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001054
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +00001055 def repr_string(self, x, level):
1056 test = cram(x, self.maxstring)
1057 testrepr = repr(test)
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001058 if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +00001059 # Backslashes are only literal in the string and are never
1060 # needed to make any special characters, so show a raw string.
1061 return 'r' + testrepr[0] + test + testrepr[0]
1062 return testrepr
1063
Skip Montanarodf708782002-03-07 22:58:02 +00001064 repr_str = repr_string
1065
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001066 def repr_instance(self, x, level):
1067 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001068 return cram(stripid(repr(x)), self.maxstring)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001069 except:
1070 return '<%s instance>' % x.__class__.__name__
1071
1072class TextDoc(Doc):
1073 """Formatter class for text documentation."""
1074
1075 # ------------------------------------------- text formatting utilities
1076
1077 _repr_instance = TextRepr()
1078 repr = _repr_instance.repr
1079
1080 def bold(self, text):
1081 """Format a string in bold by overstriking."""
Georg Brandlcbd2ab12010-12-04 10:39:14 +00001082 return ''.join(ch + '\b' + ch for ch in text)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001083
1084 def indent(self, text, prefix=' '):
1085 """Indent text by prepending a given prefix to each line."""
1086 if not text: return ''
Collin Winter72e110c2007-07-17 00:27:30 +00001087 lines = [prefix + line for line in text.split('\n')]
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001088 if lines: lines[-1] = lines[-1].rstrip()
1089 return '\n'.join(lines)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001090
1091 def section(self, title, contents):
1092 """Format a section with a given heading."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001093 clean_contents = self.indent(contents).rstrip()
1094 return self.bold(title) + '\n' + clean_contents + '\n\n'
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001095
1096 # ---------------------------------------------- type-specific routines
1097
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001098 def formattree(self, tree, modname, parent=None, prefix=''):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001099 """Render in text a class tree as returned by inspect.getclasstree()."""
1100 result = ''
1101 for entry in tree:
1102 if type(entry) is type(()):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001103 c, bases = entry
1104 result = result + prefix + classname(c, modname)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001105 if bases and bases != (parent,):
Georg Brandlcbd2ab12010-12-04 10:39:14 +00001106 parents = (classname(c, modname) for c in bases)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001107 result = result + '(%s)' % ', '.join(parents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001108 result = result + '\n'
1109 elif type(entry) is type([]):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001110 result = result + self.formattree(
1111 entry, modname, c, prefix + ' ')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001112 return result
1113
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001114 def docmodule(self, object, name=None, mod=None):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001115 """Produce text documentation for a given module object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001116 name = object.__name__ # ignore the passed-in name
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001117 synop, desc = splitdoc(getdoc(object))
1118 result = self.section('NAME', name + (synop and ' - ' + synop))
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001119 all = getattr(object, '__all__', None)
Skip Montanaro4997a692003-09-10 16:47:51 +00001120 docloc = self.getdocloc(object)
1121 if docloc is not None:
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001122 result = result + self.section('MODULE REFERENCE', docloc + """
1123
Éric Araujo647ef8c2011-09-11 00:43:20 +02001124The following documentation is automatically generated from the Python
1125source files. It may be incomplete, incorrect or include features that
1126are considered implementation detail and may vary between Python
1127implementations. When in doubt, consult the module reference at the
1128location listed above.
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001129""")
Skip Montanaro4997a692003-09-10 16:47:51 +00001130
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001131 if desc:
1132 result = result + self.section('DESCRIPTION', desc)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001133
1134 classes = []
1135 for key, value in inspect.getmembers(object, inspect.isclass):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +00001136 # if __all__ exists, believe it. Otherwise use old heuristic.
1137 if (all is not None
1138 or (inspect.getmodule(value) or object) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -07001139 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001140 classes.append((key, value))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001141 funcs = []
1142 for key, value in inspect.getmembers(object, inspect.isroutine):
Johannes Gijsbers4c11f602004-08-30 14:13:04 +00001143 # if __all__ exists, believe it. Otherwise use old heuristic.
1144 if (all is not None or
1145 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
Raymond Hettinger1103d052011-03-25 14:15:24 -07001146 if visiblename(key, all, object):
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001147 funcs.append((key, value))
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001148 data = []
1149 for key, value in inspect.getmembers(object, isdata):
Raymond Hettinger1103d052011-03-25 14:15:24 -07001150 if visiblename(key, all, object):
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001151 data.append((key, value))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001152
Christian Heimes1af737c2008-01-23 08:24:23 +00001153 modpkgs = []
1154 modpkgs_names = set()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001155 if hasattr(object, '__path__'):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001156 for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
Christian Heimes1af737c2008-01-23 08:24:23 +00001157 modpkgs_names.add(modname)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001158 if ispkg:
1159 modpkgs.append(modname + ' (package)')
1160 else:
1161 modpkgs.append(modname)
1162
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001163 modpkgs.sort()
1164 result = result + self.section(
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001165 'PACKAGE CONTENTS', '\n'.join(modpkgs))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001166
Christian Heimes1af737c2008-01-23 08:24:23 +00001167 # Detect submodules as sometimes created by C extensions
1168 submodules = []
1169 for key, value in inspect.getmembers(object, inspect.ismodule):
1170 if value.__name__.startswith(name + '.') and key not in modpkgs_names:
1171 submodules.append(key)
1172 if submodules:
1173 submodules.sort()
1174 result = result + self.section(
Amaury Forgeot d'Arc768db922008-04-24 21:00:04 +00001175 'SUBMODULES', '\n'.join(submodules))
Christian Heimes1af737c2008-01-23 08:24:23 +00001176
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001177 if classes:
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001178 classlist = [value for key, value in classes]
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001179 contents = [self.formattree(
1180 inspect.getclasstree(classlist, 1), name)]
1181 for key, value in classes:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001182 contents.append(self.document(value, key, name))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001183 result = result + self.section('CLASSES', '\n'.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001184
1185 if funcs:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001186 contents = []
1187 for key, value in funcs:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001188 contents.append(self.document(value, key, name))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001189 result = result + self.section('FUNCTIONS', '\n'.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001190
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001191 if data:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001192 contents = []
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001193 for key, value in data:
Georg Brandl8b813db2005-10-01 16:32:31 +00001194 contents.append(self.docother(value, key, name, maxlen=70))
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001195 result = result + self.section('DATA', '\n'.join(contents))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001196
1197 if hasattr(object, '__version__'):
1198 version = str(object.__version__)
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001199 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001200 version = version[11:-1].strip()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001201 result = result + self.section('VERSION', version)
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +00001202 if hasattr(object, '__date__'):
1203 result = result + self.section('DATE', str(object.__date__))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001204 if hasattr(object, '__author__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +00001205 result = result + self.section('AUTHOR', str(object.__author__))
1206 if hasattr(object, '__credits__'):
1207 result = result + self.section('CREDITS', str(object.__credits__))
Alexander Belopolskya47bbf52010-11-18 01:52:54 +00001208 try:
1209 file = inspect.getabsfile(object)
1210 except TypeError:
1211 file = '(built-in)'
1212 result = result + self.section('FILE', file)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001213 return result
1214
Georg Brandl9bd45f992010-12-03 09:58:38 +00001215 def docclass(self, object, name=None, mod=None, *ignored):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001216 """Produce text documentation for a given class object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001217 realname = object.__name__
1218 name = name or realname
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001219 bases = object.__bases__
1220
Tim Petersc86f6ca2001-09-26 21:31:51 +00001221 def makename(c, m=object.__module__):
1222 return classname(c, m)
1223
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001224 if name == realname:
1225 title = 'class ' + self.bold(realname)
1226 else:
1227 title = self.bold(name) + ' = class ' + realname
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001228 if bases:
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001229 parents = map(makename, bases)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001230 title = title + '(%s)' % ', '.join(parents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001231
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +02001232 contents = []
Tim Peters28355492001-09-23 21:29:55 +00001233 push = contents.append
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001234
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +02001235 try:
1236 signature = inspect.signature(object)
1237 except (ValueError, TypeError):
1238 signature = None
1239 if signature:
1240 argspec = str(signature)
Serhiy Storchaka213f2292017-01-23 14:02:35 +02001241 if argspec and argspec != '()':
Serhiy Storchakaccb5f3c2017-01-23 12:37:00 +02001242 push(name + argspec + '\n')
1243
1244 doc = getdoc(object)
1245 if doc:
1246 push(doc + '\n')
1247
Tim Petersc86f6ca2001-09-26 21:31:51 +00001248 # List the mro, if non-trivial.
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001249 mro = deque(inspect.getmro(object))
Tim Petersc86f6ca2001-09-26 21:31:51 +00001250 if len(mro) > 2:
1251 push("Method resolution order:")
1252 for base in mro:
1253 push(' ' + makename(base))
1254 push('')
1255
Sanyam Khuranaa323cdc2018-10-21 00:22:02 -07001256 # List the built-in subclasses, if any:
1257 subclasses = sorted(
1258 (str(cls.__name__) for cls in object.__subclasses__()
1259 if not cls.__name__.startswith("_") and cls.__module__ == "builtins"),
1260 key=str.lower
1261 )
1262 no_of_subclasses = len(subclasses)
1263 MAX_SUBCLASSES_TO_DISPLAY = 4
1264 if subclasses:
1265 push("Built-in subclasses:")
1266 for subclassname in subclasses[:MAX_SUBCLASSES_TO_DISPLAY]:
1267 push(' ' + subclassname)
1268 if no_of_subclasses > MAX_SUBCLASSES_TO_DISPLAY:
1269 push(' ... and ' +
1270 str(no_of_subclasses - MAX_SUBCLASSES_TO_DISPLAY) +
1271 ' other subclasses')
1272 push('')
1273
Tim Petersf4aad8e2001-09-24 22:40:47 +00001274 # Cute little class to pump out a horizontal rule between sections.
1275 class HorizontalRule:
1276 def __init__(self):
1277 self.needone = 0
1278 def maybe(self):
1279 if self.needone:
1280 push('-' * 70)
1281 self.needone = 1
1282 hr = HorizontalRule()
1283
Tim Peters28355492001-09-23 21:29:55 +00001284 def spill(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +00001285 ok, attrs = _split_list(attrs, predicate)
Tim Peters28355492001-09-23 21:29:55 +00001286 if ok:
Tim Petersf4aad8e2001-09-24 22:40:47 +00001287 hr.maybe()
Tim Peters28355492001-09-23 21:29:55 +00001288 push(msg)
1289 for name, kind, homecls, value in ok:
Antoine Pitrou86a8a9a2011-12-21 09:57:40 +01001290 try:
1291 value = getattr(object, name)
1292 except Exception:
1293 # Some descriptors may meet a failure in their __get__.
1294 # (bug #1785)
1295 push(self._docdescriptor(name, value, mod))
1296 else:
1297 push(self.document(value,
1298 name, mod, object))
Tim Peters28355492001-09-23 21:29:55 +00001299 return attrs
1300
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001301 def spilldescriptors(msg, attrs, predicate):
Tim Petersfa26f7c2001-09-24 08:05:11 +00001302 ok, attrs = _split_list(attrs, predicate)
Tim Peters28355492001-09-23 21:29:55 +00001303 if ok:
Tim Petersf4aad8e2001-09-24 22:40:47 +00001304 hr.maybe()
Tim Peters28355492001-09-23 21:29:55 +00001305 push(msg)
1306 for name, kind, homecls, value in ok:
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001307 push(self._docdescriptor(name, value, mod))
Tim Peters28355492001-09-23 21:29:55 +00001308 return attrs
Tim Petersb47879b2001-09-24 04:47:19 +00001309
Tim Petersfa26f7c2001-09-24 08:05:11 +00001310 def spilldata(msg, attrs, predicate):
1311 ok, attrs = _split_list(attrs, predicate)
Tim Peters28355492001-09-23 21:29:55 +00001312 if ok:
Tim Petersf4aad8e2001-09-24 22:40:47 +00001313 hr.maybe()
Tim Peters28355492001-09-23 21:29:55 +00001314 push(msg)
1315 for name, kind, homecls, value in ok:
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001316 if callable(value) or inspect.isdatadescriptor(value):
Ka-Ping Yeebba6acc2005-02-19 22:58:26 +00001317 doc = getdoc(value)
Guido van Rossum5e355b22002-05-21 20:56:15 +00001318 else:
1319 doc = None
Serhiy Storchaka056eb022014-02-19 23:05:12 +02001320 try:
1321 obj = getattr(object, name)
1322 except AttributeError:
1323 obj = homecls.__dict__[name]
1324 push(self.docother(obj, name, mod, maxlen=70, doc=doc) +
1325 '\n')
Tim Peters28355492001-09-23 21:29:55 +00001326 return attrs
1327
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001328 attrs = [(name, kind, cls, value)
1329 for name, kind, cls, value in classify_class_attrs(object)
Raymond Hettinger1103d052011-03-25 14:15:24 -07001330 if visiblename(name, obj=object)]
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001331
Tim Petersfa26f7c2001-09-24 08:05:11 +00001332 while attrs:
Tim Peters351e3622001-09-27 03:29:51 +00001333 if mro:
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001334 thisclass = mro.popleft()
Tim Peters351e3622001-09-27 03:29:51 +00001335 else:
1336 thisclass = attrs[0][2]
Tim Petersfa26f7c2001-09-24 08:05:11 +00001337 attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
1338
Georg Brandl1a3284e2007-12-02 09:40:06 +00001339 if thisclass is builtins.object:
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001340 attrs = inherited
1341 continue
1342 elif thisclass is object:
Tim Peters28355492001-09-23 21:29:55 +00001343 tag = "defined here"
1344 else:
Tim Petersfa26f7c2001-09-24 08:05:11 +00001345 tag = "inherited from %s" % classname(thisclass,
1346 object.__module__)
Raymond Hettinger95801bb2015-08-18 22:25:16 -07001347
1348 sort_attributes(attrs, object)
Tim Peters28355492001-09-23 21:29:55 +00001349
1350 # Pump out the attrs, segregated by kind.
Tim Petersf4aad8e2001-09-24 22:40:47 +00001351 attrs = spill("Methods %s:\n" % tag, attrs,
Tim Peters28355492001-09-23 21:29:55 +00001352 lambda t: t[1] == 'method')
Tim Petersf4aad8e2001-09-24 22:40:47 +00001353 attrs = spill("Class methods %s:\n" % tag, attrs,
Tim Peters28355492001-09-23 21:29:55 +00001354 lambda t: t[1] == 'class method')
Tim Petersf4aad8e2001-09-24 22:40:47 +00001355 attrs = spill("Static methods %s:\n" % tag, attrs,
Tim Peters28355492001-09-23 21:29:55 +00001356 lambda t: t[1] == 'static method')
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001357 attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
1358 lambda t: t[1] == 'data descriptor')
Ka-Ping Yeed9e213e2003-03-28 16:35:51 +00001359 attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
1360 lambda t: t[1] == 'data')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001361
Tim Peters28355492001-09-23 21:29:55 +00001362 assert attrs == []
Tim Peters351e3622001-09-27 03:29:51 +00001363 attrs = inherited
Tim Peters28355492001-09-23 21:29:55 +00001364
1365 contents = '\n'.join(contents)
1366 if not contents:
1367 return title + '\n'
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001368 return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n'
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001369
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001370 def formatvalue(self, object):
1371 """Format an argument default value as text."""
1372 return '=' + self.repr(object)
1373
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001374 def docroutine(self, object, name=None, mod=None, cl=None):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001375 """Produce text documentation for a function or method object."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001376 realname = object.__name__
1377 name = name or realname
1378 note = ''
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001379 skipdocs = 0
Larry Hastings24a882b2014-02-20 23:34:46 -08001380 if _is_bound_method(object):
Christian Heimesff737952007-11-27 10:40:20 +00001381 imclass = object.__self__.__class__
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001382 if cl:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001383 if imclass is not cl:
1384 note = ' from ' + classname(imclass, mod)
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001385 else:
Christian Heimesff737952007-11-27 10:40:20 +00001386 if object.__self__ is not None:
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +00001387 note = ' method of %s instance' % classname(
Christian Heimesff737952007-11-27 10:40:20 +00001388 object.__self__.__class__, mod)
Ka-Ping Yeeb7a48302001-04-12 20:39:14 +00001389 else:
1390 note = ' unbound %s method' % classname(imclass,mod)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001391
1392 if name == realname:
1393 title = self.bold(realname)
1394 else:
Serhiy Storchakaa44d34e2018-11-08 08:48:11 +02001395 if cl and inspect.getattr_static(cl, realname, []) is object:
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001396 skipdocs = 1
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001397 title = self.bold(name) + ' = ' + realname
Larry Hastings44e2eaa2013-11-23 15:37:55 -08001398 argspec = None
Larry Hastings5c661892014-01-24 06:17:25 -08001399
1400 if inspect.isroutine(object):
1401 try:
1402 signature = inspect.signature(object)
1403 except (ValueError, TypeError):
1404 signature = None
Larry Hastings44e2eaa2013-11-23 15:37:55 -08001405 if signature:
1406 argspec = str(signature)
1407 if realname == '<lambda>':
1408 title = self.bold(name) + ' lambda '
1409 # XXX lambda's won't usually have func_annotations['return']
1410 # since the syntax doesn't support but it is possible.
1411 # So removing parentheses isn't truly safe.
1412 argspec = argspec[1:-1] # remove parentheses
1413 if not argspec:
Tim Peters4bcfa312001-09-20 06:08:24 +00001414 argspec = '(...)'
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001415 decl = title + argspec + note
1416
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001417 if skipdocs:
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001418 return decl + '\n'
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001419 else:
1420 doc = getdoc(object) or ''
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001421 return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001422
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001423 def _docdescriptor(self, name, value, mod):
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001424 results = []
1425 push = results.append
1426
1427 if name:
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001428 push(self.bold(name))
1429 push('\n')
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001430 doc = getdoc(value) or ''
1431 if doc:
1432 push(self.indent(doc))
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001433 push('\n')
1434 return ''.join(results)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001435
1436 def docproperty(self, object, name=None, mod=None, cl=None):
1437 """Produce text documentation for a property."""
Johannes Gijsbers9ddb3002005-01-08 20:16:43 +00001438 return self._docdescriptor(name, object, mod)
Johannes Gijsbers8de645a2004-11-07 19:16:05 +00001439
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001440 def docdata(self, object, name=None, mod=None, cl=None):
1441 """Produce text documentation for a data descriptor."""
1442 return self._docdescriptor(name, object, mod)
1443
Georg Brandl8b813db2005-10-01 16:32:31 +00001444 def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001445 """Produce text documentation for a data object."""
1446 repr = self.repr(object)
1447 if maxlen:
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001448 line = (name and name + ' = ' or '') + repr
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001449 chop = maxlen - len(line)
1450 if chop < 0: repr = repr[:chop] + '...'
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001451 line = (name and self.bold(name) + ' = ' or '') + repr
Tim Peters28355492001-09-23 21:29:55 +00001452 if doc is not None:
1453 line += '\n' + self.indent(str(doc))
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001454 return line
1455
Georg Brandld80d5f42010-12-03 07:47:22 +00001456class _PlainTextDoc(TextDoc):
1457 """Subclass of TextDoc which overrides string styling"""
1458 def bold(self, text):
1459 return text
1460
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001461# --------------------------------------------------------- user interfaces
1462
1463def pager(text):
1464 """The first time this is called, determine what kind of pager to use."""
1465 global pager
1466 pager = getpager()
1467 pager(text)
1468
1469def getpager():
1470 """Decide what method to use for paging through text."""
Benjamin Peterson159824e2014-06-07 20:14:26 -07001471 if not hasattr(sys.stdin, "isatty"):
1472 return plainpager
Guido van Rossuma01a8b62007-05-27 09:20:14 +00001473 if not hasattr(sys.stdout, "isatty"):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001474 return plainpager
1475 if not sys.stdin.isatty() or not sys.stdout.isatty():
1476 return plainpager
doko@ubuntu.com96575452016-06-14 08:39:31 +02001477 use_pager = os.environ.get('MANPAGER') or os.environ.get('PAGER')
1478 if use_pager:
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001479 if sys.platform == 'win32': # pipes completely broken in Windows
doko@ubuntu.comc8fd1922016-06-14 09:03:52 +02001480 return lambda text: tempfilepager(plain(text), use_pager)
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001481 elif os.environ.get('TERM') in ('dumb', 'emacs'):
doko@ubuntu.comc8fd1922016-06-14 09:03:52 +02001482 return lambda text: pipepager(plain(text), use_pager)
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00001483 else:
doko@ubuntu.comc8fd1922016-06-14 09:03:52 +02001484 return lambda text: pipepager(text, use_pager)
Ka-Ping Yeea487e4e2005-11-05 04:49:18 +00001485 if os.environ.get('TERM') in ('dumb', 'emacs'):
1486 return plainpager
Jesus Cea4791a242012-10-05 03:15:39 +02001487 if sys.platform == 'win32':
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001488 return lambda text: tempfilepager(plain(text), 'more <')
Skip Montanarod404bee2002-09-26 21:44:57 +00001489 if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001490 return lambda text: pipepager(text, 'less')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001491
1492 import tempfile
Guido van Rossum3b0a3292002-08-09 16:38:32 +00001493 (fd, filename) = tempfile.mkstemp()
1494 os.close(fd)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001495 try:
Georg Brandl3dbca812008-07-23 16:10:53 +00001496 if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001497 return lambda text: pipepager(text, 'more')
1498 else:
1499 return ttypager
1500 finally:
1501 os.unlink(filename)
1502
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001503def plain(text):
1504 """Remove boldface formatting from text."""
1505 return re.sub('.\b', '', text)
1506
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001507def pipepager(text, cmd):
1508 """Page through text by feeding it to another program."""
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001509 import subprocess
1510 proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001511 try:
R David Murray1058cda2015-03-29 15:15:40 -04001512 with io.TextIOWrapper(proc.stdin, errors='backslashreplace') as pipe:
R David Murraye7f5e142015-03-30 10:14:47 -04001513 try:
1514 pipe.write(text)
1515 except KeyboardInterrupt:
1516 # We've hereby abandoned whatever text hasn't been written,
1517 # but the pager is still in control of the terminal.
1518 pass
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001519 except OSError:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001520 pass # Ignore broken pipes caused by quitting the pager program.
R David Murray1058cda2015-03-29 15:15:40 -04001521 while True:
1522 try:
1523 proc.wait()
1524 break
1525 except KeyboardInterrupt:
1526 # Ignore ctl-c like the pager itself does. Otherwise the pager is
1527 # left running and the terminal is in raw mode and unusable.
1528 pass
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001529
1530def tempfilepager(text, cmd):
1531 """Page through text by invoking a program on a temporary file."""
1532 import tempfile
Tim Peters550e4e52003-02-07 01:53:46 +00001533 filename = tempfile.mktemp()
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001534 with open(filename, 'w', errors='backslashreplace') as file:
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01001535 file.write(text)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001536 try:
Georg Brandl3dbca812008-07-23 16:10:53 +00001537 os.system(cmd + ' "' + filename + '"')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001538 finally:
1539 os.unlink(filename)
1540
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001541def _escape_stdout(text):
1542 # Escape non-encodable characters to avoid encoding errors later
1543 encoding = getattr(sys.stdout, 'encoding', None) or 'utf-8'
1544 return text.encode(encoding, 'backslashreplace').decode(encoding)
1545
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001546def ttypager(text):
1547 """Page through text on a text terminal."""
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001548 lines = plain(_escape_stdout(text)).split('\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001549 try:
1550 import tty
1551 fd = sys.stdin.fileno()
1552 old = tty.tcgetattr(fd)
1553 tty.setcbreak(fd)
1554 getchar = lambda: sys.stdin.read(1)
Serhiy Storchakaab5e9b92014-11-28 00:09:29 +02001555 except (ImportError, AttributeError, io.UnsupportedOperation):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001556 tty = None
1557 getchar = lambda: sys.stdin.readline()[:-1][:1]
1558
1559 try:
Serhiy Storchakaab5e9b92014-11-28 00:09:29 +02001560 try:
1561 h = int(os.environ.get('LINES', 0))
1562 except ValueError:
1563 h = 0
1564 if h <= 1:
1565 h = 25
1566 r = inc = h - 1
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001567 sys.stdout.write('\n'.join(lines[:inc]) + '\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001568 while lines[r:]:
1569 sys.stdout.write('-- more --')
1570 sys.stdout.flush()
1571 c = getchar()
1572
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001573 if c in ('q', 'Q'):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001574 sys.stdout.write('\r \r')
1575 break
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001576 elif c in ('\r', '\n'):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001577 sys.stdout.write('\r \r' + lines[r] + '\n')
1578 r = r + 1
1579 continue
Raymond Hettingerdbecd932005-02-06 06:57:08 +00001580 if c in ('b', 'B', '\x1b'):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001581 r = r - inc - inc
1582 if r < 0: r = 0
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001583 sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001584 r = r + inc
1585
1586 finally:
1587 if tty:
1588 tty.tcsetattr(fd, tty.TCSAFLUSH, old)
1589
1590def plainpager(text):
1591 """Simply print unformatted text. This is the ultimate fallback."""
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +02001592 sys.stdout.write(plain(_escape_stdout(text)))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001593
1594def describe(thing):
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00001595 """Produce a short description of the given thing."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001596 if inspect.ismodule(thing):
1597 if thing.__name__ in sys.builtin_module_names:
1598 return 'built-in module ' + thing.__name__
1599 if hasattr(thing, '__path__'):
1600 return 'package ' + thing.__name__
1601 else:
1602 return 'module ' + thing.__name__
1603 if inspect.isbuiltin(thing):
1604 return 'built-in function ' + thing.__name__
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001605 if inspect.isgetsetdescriptor(thing):
1606 return 'getset descriptor %s.%s.%s' % (
1607 thing.__objclass__.__module__, thing.__objclass__.__name__,
1608 thing.__name__)
1609 if inspect.ismemberdescriptor(thing):
1610 return 'member descriptor %s.%s.%s' % (
1611 thing.__objclass__.__module__, thing.__objclass__.__name__,
1612 thing.__name__)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001613 if inspect.isclass(thing):
1614 return 'class ' + thing.__name__
1615 if inspect.isfunction(thing):
1616 return 'function ' + thing.__name__
1617 if inspect.ismethod(thing):
1618 return 'method ' + thing.__name__
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001619 return type(thing).__name__
1620
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001621def locate(path, forceload=0):
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001622 """Locate an object by name or dotted path, importing as necessary."""
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001623 parts = [part for part in path.split('.') if part]
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001624 module, n = None, 0
1625 while n < len(parts):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001626 nextmodule = safeimport('.'.join(parts[:n+1]), forceload)
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001627 if nextmodule: module, n = nextmodule, n + 1
1628 else: break
1629 if module:
1630 object = module
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001631 else:
Éric Araujoe64e51b2011-07-29 17:03:55 +02001632 object = builtins
1633 for part in parts[n:]:
1634 try:
1635 object = getattr(object, part)
1636 except AttributeError:
1637 return None
1638 return object
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001639
1640# --------------------------------------- interactive interpreter interface
1641
1642text = TextDoc()
Georg Brandld80d5f42010-12-03 07:47:22 +00001643plaintext = _PlainTextDoc()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001644html = HTMLDoc()
1645
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001646def resolve(thing, forceload=0):
1647 """Given an object or a path to an object, get the object and its name."""
1648 if isinstance(thing, str):
1649 object = locate(thing, forceload)
Serhiy Storchakab6076fb2015-04-21 21:09:48 +03001650 if object is None:
Serhiy Storchaka1c205512015-03-01 00:42:54 +02001651 raise ImportError('''\
1652No Python documentation found for %r.
1653Use help() to get the interactive help utility.
1654Use help(str) for help on the str class.''' % thing)
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001655 return object, thing
1656 else:
R David Murrayc43125a2012-04-23 13:23:57 -04001657 name = getattr(thing, '__name__', None)
1658 return thing, name if isinstance(name, str) else None
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001659
Georg Brandld80d5f42010-12-03 07:47:22 +00001660def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
1661 renderer=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001662 """Render text documentation, given an object or a path to an object."""
Georg Brandld80d5f42010-12-03 07:47:22 +00001663 if renderer is None:
1664 renderer = text
Guido van Rossumd8faa362007-04-27 19:54:29 +00001665 object, name = resolve(thing, forceload)
1666 desc = describe(object)
1667 module = inspect.getmodule(object)
1668 if name and '.' in name:
1669 desc += ' in ' + name[:name.rfind('.')]
1670 elif module and module is not object:
1671 desc += ' in module ' + module.__name__
Amaury Forgeot d'Arc768db922008-04-24 21:00:04 +00001672
1673 if not (inspect.ismodule(object) or
Guido van Rossumd8faa362007-04-27 19:54:29 +00001674 inspect.isclass(object) or
1675 inspect.isroutine(object) or
1676 inspect.isgetsetdescriptor(object) or
1677 inspect.ismemberdescriptor(object) or
1678 isinstance(object, property)):
1679 # If the passed object is a piece of data or an instance,
1680 # document its available methods instead of its value.
1681 object = type(object)
1682 desc += ' object'
Georg Brandld80d5f42010-12-03 07:47:22 +00001683 return title % desc + '\n\n' + renderer.document(object, name)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001684
Georg Brandld80d5f42010-12-03 07:47:22 +00001685def doc(thing, title='Python Library Documentation: %s', forceload=0,
1686 output=None):
Ka-Ping Yee9aa0d902001-04-12 10:50:23 +00001687 """Display text documentation, given an object or a path to an object."""
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001688 try:
Georg Brandld80d5f42010-12-03 07:47:22 +00001689 if output is None:
1690 pager(render_doc(thing, title, forceload))
1691 else:
1692 output.write(render_doc(thing, title, forceload, plaintext))
Guido van Rossumb940e112007-01-10 16:19:56 +00001693 except (ImportError, ErrorDuringImport) as value:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001694 print(value)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001695
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001696def writedoc(thing, forceload=0):
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001697 """Write HTML documentation to a file in the current directory."""
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001698 try:
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00001699 object, name = resolve(thing, forceload)
1700 page = html.page(describe(object), html.document(object, name))
Serhiy Storchaka46ba6c82015-04-04 11:01:02 +03001701 with open(name + '.html', 'w', encoding='utf-8') as file:
1702 file.write(page)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001703 print('wrote', name + '.html')
Guido van Rossumb940e112007-01-10 16:19:56 +00001704 except (ImportError, ErrorDuringImport) as value:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001705 print(value)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001706
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001707def writedocs(dir, pkgpath='', done=None):
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00001708 """Write out HTML documentation for all modules in a directory tree."""
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001709 if done is None: done = {}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001710 for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):
1711 writedoc(modname)
1712 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001713
1714class Helper:
Georg Brandl6b38daa2008-06-01 21:05:17 +00001715
1716 # These dictionaries map a topic name to either an alias, or a tuple
1717 # (label, seealso-items). The "label" is the label of the corresponding
1718 # section in the .rst file under Doc/ and an index into the dictionary
Georg Brandl5617db82009-04-27 16:28:57 +00001719 # in pydoc_data/topics.py.
Georg Brandl6b38daa2008-06-01 21:05:17 +00001720 #
1721 # CAUTION: if you change one of these dictionaries, be sure to adapt the
Jelle Zijlstraac317702017-10-05 20:24:46 -07001722 # list of needed labels in Doc/tools/extensions/pyspecific.py and
Georg Brandl5617db82009-04-27 16:28:57 +00001723 # regenerate the pydoc_data/topics.py file by running
Georg Brandl6b38daa2008-06-01 21:05:17 +00001724 # make pydoc-topics
1725 # in Doc/ and copying the output file into the Lib/ directory.
1726
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001727 keywords = {
Ezio Melottib185a042011-04-28 07:42:55 +03001728 'False': '',
1729 'None': '',
1730 'True': '',
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001731 'and': 'BOOLEAN',
Guido van Rossumd8faa362007-04-27 19:54:29 +00001732 'as': 'with',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001733 'assert': ('assert', ''),
Jelle Zijlstraac317702017-10-05 20:24:46 -07001734 'async': ('async', ''),
1735 'await': ('await', ''),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001736 'break': ('break', 'while for'),
1737 'class': ('class', 'CLASSES SPECIALMETHODS'),
1738 'continue': ('continue', 'while for'),
1739 'def': ('function', ''),
1740 'del': ('del', 'BASICMETHODS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001741 'elif': 'if',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001742 'else': ('else', 'while for'),
Georg Brandl0d855392008-08-30 19:53:05 +00001743 'except': 'try',
1744 'finally': 'try',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001745 'for': ('for', 'break continue while'),
Georg Brandl0d855392008-08-30 19:53:05 +00001746 'from': 'import',
Georg Brandl74abf6f2010-11-20 19:54:36 +00001747 'global': ('global', 'nonlocal NAMESPACES'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001748 'if': ('if', 'TRUTHVALUE'),
1749 'import': ('import', 'MODULES'),
Georg Brandl395ed242009-09-04 08:07:32 +00001750 'in': ('in', 'SEQUENCEMETHODS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001751 'is': 'COMPARISON',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001752 'lambda': ('lambda', 'FUNCTIONS'),
Georg Brandl74abf6f2010-11-20 19:54:36 +00001753 'nonlocal': ('nonlocal', 'global NAMESPACES'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001754 'not': 'BOOLEAN',
1755 'or': 'BOOLEAN',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001756 'pass': ('pass', ''),
1757 'raise': ('raise', 'EXCEPTIONS'),
1758 'return': ('return', 'FUNCTIONS'),
1759 'try': ('try', 'EXCEPTIONS'),
1760 'while': ('while', 'break continue if TRUTHVALUE'),
1761 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
1762 'yield': ('yield', ''),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001763 }
Georg Brandldb7b6b92009-01-01 15:53:14 +00001764 # Either add symbols to this dictionary or to the symbols dictionary
1765 # directly: Whichever is easier. They are merged later.
Andrés Delfinob2043bb2018-05-05 13:07:32 -03001766 _strprefixes = [p + q for p in ('b', 'f', 'r', 'u') for q in ("'", '"')]
Georg Brandldb7b6b92009-01-01 15:53:14 +00001767 _symbols_inverse = {
Andrés Delfinob2043bb2018-05-05 13:07:32 -03001768 'STRINGS' : ("'", "'''", '"', '"""', *_strprefixes),
Georg Brandldb7b6b92009-01-01 15:53:14 +00001769 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',
1770 '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
1771 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),
1772 'UNARY' : ('-', '~'),
1773 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',
1774 '^=', '<<=', '>>=', '**=', '//='),
1775 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),
1776 'COMPLEX' : ('j', 'J')
1777 }
1778 symbols = {
1779 '%': 'OPERATORS FORMATTING',
1780 '**': 'POWER',
1781 ',': 'TUPLES LISTS FUNCTIONS',
1782 '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
1783 '...': 'ELLIPSIS',
1784 ':': 'SLICINGS DICTIONARYLITERALS',
1785 '@': 'def class',
1786 '\\': 'STRINGS',
1787 '_': 'PRIVATENAMES',
1788 '__': 'PRIVATENAMES SPECIALMETHODS',
1789 '`': 'BACKQUOTES',
1790 '(': 'TUPLES FUNCTIONS CALLS',
1791 ')': 'TUPLES FUNCTIONS CALLS',
1792 '[': 'LISTS SUBSCRIPTS SLICINGS',
1793 ']': 'LISTS SUBSCRIPTS SLICINGS'
1794 }
1795 for topic, symbols_ in _symbols_inverse.items():
1796 for symbol in symbols_:
1797 topics = symbols.get(symbol, topic)
1798 if topic not in topics:
1799 topics = topics + ' ' + topic
1800 symbols[symbol] = topics
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001801
1802 topics = {
Georg Brandl6b38daa2008-06-01 21:05:17 +00001803 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
1804 'FUNCTIONS CLASSES MODULES FILES inspect'),
1805 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS '
1806 'FORMATTING TYPES'),
1807 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
1808 'FORMATTING': ('formatstrings', 'OPERATORS'),
1809 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '
1810 'FORMATTING TYPES'),
1811 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
1812 'INTEGER': ('integers', 'int range'),
1813 'FLOAT': ('floating', 'float math'),
1814 'COMPLEX': ('imaginary', 'complex cmath'),
1815 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING range LISTS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001816 'MAPPINGS': 'DICTIONARIES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001817 'FUNCTIONS': ('typesfunctions', 'def TYPES'),
1818 'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
1819 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
1820 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001821 'FRAMEOBJECTS': 'TYPES',
1822 'TRACEBACKS': 'TYPES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001823 'NONE': ('bltin-null-object', ''),
1824 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001825 'SPECIALATTRIBUTES': ('specialattrs', ''),
1826 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
1827 'MODULES': ('typesmodules', 'import'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001828 'PACKAGES': 'import',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001829 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '
1830 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '
1831 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '
1832 'LISTS DICTIONARIES'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001833 'OPERATORS': 'EXPRESSIONS',
1834 'PRECEDENCE': 'EXPRESSIONS',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001835 'OBJECTS': ('objects', 'TYPES'),
1836 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '
Georg Brandl395ed242009-09-04 08:07:32 +00001837 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS '
1838 'NUMBERMETHODS CLASSES'),
Mark Dickinsona56c4672009-01-27 18:17:45 +00001839 'BASICMETHODS': ('customization', 'hash repr str SPECIALMETHODS'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001840 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
1841 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
Georg Brandl395ed242009-09-04 08:07:32 +00001842 'SEQUENCEMETHODS': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS '
Georg Brandl6b38daa2008-06-01 21:05:17 +00001843 'SPECIALMETHODS'),
1844 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
1845 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
1846 'SPECIALMETHODS'),
1847 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
Georg Brandl74abf6f2010-11-20 19:54:36 +00001848 'NAMESPACES': ('naming', 'global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001849 'DYNAMICFEATURES': ('dynamic-features', ''),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001850 'SCOPING': 'NAMESPACES',
1851 'FRAMES': 'NAMESPACES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001852 'EXCEPTIONS': ('exceptions', 'try except finally raise'),
1853 'CONVERSIONS': ('conversions', ''),
1854 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
1855 'SPECIALIDENTIFIERS': ('id-classes', ''),
1856 'PRIVATENAMES': ('atom-identifiers', ''),
1857 'LITERALS': ('atom-literals', 'STRINGS NUMBERS TUPLELITERALS '
1858 'LISTLITERALS DICTIONARYLITERALS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001859 'TUPLES': 'SEQUENCES',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001860 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
1861 'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
1862 'LISTLITERALS': ('lists', 'LISTS LITERALS'),
1863 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
1864 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
1865 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
Georg Brandl395ed242009-09-04 08:07:32 +00001866 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS'),
1867 'SLICINGS': ('slicings', 'SEQUENCEMETHODS'),
Georg Brandl6b38daa2008-06-01 21:05:17 +00001868 'CALLS': ('calls', 'EXPRESSIONS'),
1869 'POWER': ('power', 'EXPRESSIONS'),
1870 'UNARY': ('unary', 'EXPRESSIONS'),
1871 'BINARY': ('binary', 'EXPRESSIONS'),
1872 'SHIFTING': ('shifting', 'EXPRESSIONS'),
1873 'BITWISE': ('bitwise', 'EXPRESSIONS'),
1874 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
1875 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001876 'ASSERTION': 'assert',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001877 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
1878 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001879 'DELETION': 'del',
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001880 'RETURNING': 'return',
1881 'IMPORTING': 'import',
1882 'CONDITIONAL': 'if',
Georg Brandl6b38daa2008-06-01 21:05:17 +00001883 'LOOPING': ('compound', 'for while break continue'),
1884 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
1885 'DEBUGGING': ('debugger', 'pdb'),
1886 'CONTEXTMANAGERS': ('context-managers', 'with'),
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001887 }
1888
Georg Brandl78aa3962010-07-31 21:51:48 +00001889 def __init__(self, input=None, output=None):
1890 self._input = input
1891 self._output = output
1892
Serhiy Storchakabdf6b912017-03-19 08:40:32 +02001893 @property
1894 def input(self):
1895 return self._input or sys.stdin
1896
1897 @property
1898 def output(self):
1899 return self._output or sys.stdout
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001900
Ka-Ping Yee79c009d2001-04-13 10:53:25 +00001901 def __repr__(self):
Ka-Ping Yee9bc576b2001-04-13 13:57:31 +00001902 if inspect.stack()[1][3] == '?':
Ka-Ping Yee79c009d2001-04-13 10:53:25 +00001903 self()
1904 return ''
Serhiy Storchaka465e60e2014-07-25 23:36:00 +03001905 return '<%s.%s instance>' % (self.__class__.__module__,
1906 self.__class__.__qualname__)
Ka-Ping Yee79c009d2001-04-13 10:53:25 +00001907
Alexander Belopolsky2e733c92010-07-04 17:00:20 +00001908 _GoInteractive = object()
1909 def __call__(self, request=_GoInteractive):
1910 if request is not self._GoInteractive:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001911 self.help(request)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001912 else:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001913 self.intro()
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001914 self.interact()
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001915 self.output.write('''
Fred Drakee61967f2001-05-10 18:41:02 +00001916You are now leaving help and returning to the Python interpreter.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001917If you want to ask for help on a particular object directly from the
1918interpreter, you can type "help(object)". Executing "help('string')"
1919has the same effect as typing a particular string at the help> prompt.
1920''')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001921
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001922 def interact(self):
1923 self.output.write('\n')
Guido van Rossum8ca162f2002-04-07 06:36:23 +00001924 while True:
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001925 try:
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001926 request = self.getline('help> ')
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001927 if not request: break
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001928 except (KeyboardInterrupt, EOFError):
1929 break
Andrés Delfinob2043bb2018-05-05 13:07:32 -03001930 request = request.strip()
1931
1932 # Make sure significant trailing quoting marks of literals don't
1933 # get deleted while cleaning input
1934 if (len(request) > 2 and request[0] == request[-1] in ("'", '"')
1935 and request[0] not in request[1:-1]):
1936 request = request[1:-1]
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001937 if request.lower() in ('q', 'quit'): break
Serhiy Storchaka1c205512015-03-01 00:42:54 +02001938 if request == 'help':
1939 self.intro()
1940 else:
1941 self.help(request)
Ka-Ping Yeedec96e92001-04-13 09:55:49 +00001942
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001943 def getline(self, prompt):
Guido van Rossum7c086c02008-01-02 03:52:38 +00001944 """Read one line, using input() when appropriate."""
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001945 if self.input is sys.stdin:
Guido van Rossum7c086c02008-01-02 03:52:38 +00001946 return input(prompt)
Johannes Gijsberse7691d32004-08-17 13:21:53 +00001947 else:
1948 self.output.write(prompt)
1949 self.output.flush()
1950 return self.input.readline()
1951
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001952 def help(self, request):
1953 if type(request) is type(''):
R. David Murray1f1b9d32009-05-27 20:56:59 +00001954 request = request.strip()
Serhiy Storchaka1c205512015-03-01 00:42:54 +02001955 if request == 'keywords': self.listkeywords()
Georg Brandldb7b6b92009-01-01 15:53:14 +00001956 elif request == 'symbols': self.listsymbols()
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001957 elif request == 'topics': self.listtopics()
1958 elif request == 'modules': self.listmodules()
1959 elif request[:8] == 'modules ':
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001960 self.listmodules(request.split()[1])
Georg Brandldb7b6b92009-01-01 15:53:14 +00001961 elif request in self.symbols: self.showsymbol(request)
Ezio Melottib185a042011-04-28 07:42:55 +03001962 elif request in ['True', 'False', 'None']:
1963 # special case these keywords since they are objects too
1964 doc(eval(request), 'Help on %s:')
Raymond Hettinger54f02222002-06-01 14:18:47 +00001965 elif request in self.keywords: self.showtopic(request)
1966 elif request in self.topics: self.showtopic(request)
Georg Brandld80d5f42010-12-03 07:47:22 +00001967 elif request: doc(request, 'Help on %s:', output=self._output)
Serhiy Storchaka1c205512015-03-01 00:42:54 +02001968 else: doc(str, 'Help on %s:', output=self._output)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001969 elif isinstance(request, Helper): self()
Georg Brandld80d5f42010-12-03 07:47:22 +00001970 else: doc(request, 'Help on %s:', output=self._output)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001971 self.output.write('\n')
1972
1973 def intro(self):
1974 self.output.write('''
Serhiy Storchaka885bdc42016-02-11 13:10:36 +02001975Welcome to Python {0}'s help utility!
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001976
1977If this is your first time using Python, you should definitely check out
oldke5681b92017-12-28 22:37:46 +08001978the tutorial on the Internet at https://docs.python.org/{0}/tutorial/.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001979
1980Enter the name of any module, keyword, or topic to get help on writing
1981Python programs and using Python modules. To quit this help utility and
1982return to the interpreter, just type "quit".
1983
Terry Jan Reedy34200572013-02-11 02:23:13 -05001984To get a list of available modules, keywords, symbols, or topics, type
1985"modules", "keywords", "symbols", or "topics". Each module also comes
1986with a one-line summary of what it does; to list the modules whose name
1987or summary contain a given string such as "spam", type "modules spam".
Serhiy Storchaka885bdc42016-02-11 13:10:36 +02001988'''.format('%d.%d' % sys.version_info[:2]))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001989
1990 def list(self, items, columns=4, width=80):
Guido van Rossum486364b2007-06-30 05:01:58 +00001991 items = list(sorted(items))
1992 colw = width // columns
1993 rows = (len(items) + columns - 1) // columns
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00001994 for row in range(rows):
1995 for col in range(columns):
1996 i = col * rows + row
1997 if i < len(items):
1998 self.output.write(items[i])
1999 if col < columns - 1:
Guido van Rossum486364b2007-06-30 05:01:58 +00002000 self.output.write(' ' + ' ' * (colw - 1 - len(items[i])))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002001 self.output.write('\n')
2002
2003 def listkeywords(self):
2004 self.output.write('''
2005Here is a list of the Python keywords. Enter any keyword to get more help.
2006
2007''')
2008 self.list(self.keywords.keys())
2009
Georg Brandldb7b6b92009-01-01 15:53:14 +00002010 def listsymbols(self):
2011 self.output.write('''
2012Here is a list of the punctuation symbols which Python assigns special meaning
2013to. Enter any symbol to get more help.
2014
2015''')
2016 self.list(self.symbols.keys())
2017
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002018 def listtopics(self):
2019 self.output.write('''
2020Here is a list of available topics. Enter any topic name to get more help.
2021
2022''')
2023 self.list(self.topics.keys())
2024
Georg Brandldb7b6b92009-01-01 15:53:14 +00002025 def showtopic(self, topic, more_xrefs=''):
Georg Brandl6b38daa2008-06-01 21:05:17 +00002026 try:
Georg Brandl5617db82009-04-27 16:28:57 +00002027 import pydoc_data.topics
Brett Cannoncd171c82013-07-04 17:43:24 -04002028 except ImportError:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002029 self.output.write('''
Georg Brandl6b38daa2008-06-01 21:05:17 +00002030Sorry, topic and keyword documentation is not available because the
Georg Brandl5617db82009-04-27 16:28:57 +00002031module "pydoc_data.topics" could not be found.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002032''')
2033 return
2034 target = self.topics.get(topic, self.keywords.get(topic))
2035 if not target:
2036 self.output.write('no documentation found for %s\n' % repr(topic))
2037 return
2038 if type(target) is type(''):
Georg Brandldb7b6b92009-01-01 15:53:14 +00002039 return self.showtopic(target, more_xrefs)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002040
Georg Brandl6b38daa2008-06-01 21:05:17 +00002041 label, xrefs = target
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002042 try:
Georg Brandl5617db82009-04-27 16:28:57 +00002043 doc = pydoc_data.topics.topics[label]
Georg Brandl6b38daa2008-06-01 21:05:17 +00002044 except KeyError:
2045 self.output.write('no documentation found for %s\n' % repr(topic))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002046 return
Berker Peksagd04f46c2018-07-23 08:37:47 +03002047 doc = doc.strip() + '\n'
Georg Brandldb7b6b92009-01-01 15:53:14 +00002048 if more_xrefs:
2049 xrefs = (xrefs or '') + ' ' + more_xrefs
Ka-Ping Yeeda793892001-04-13 11:02:51 +00002050 if xrefs:
Brett Cannon1448ecf2013-10-04 11:38:59 -04002051 import textwrap
2052 text = 'Related help topics: ' + ', '.join(xrefs.split()) + '\n'
2053 wrapped_text = textwrap.wrap(text, 72)
Berker Peksagd04f46c2018-07-23 08:37:47 +03002054 doc += '\n%s\n' % '\n'.join(wrapped_text)
2055 pager(doc)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002056
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002057 def _gettopic(self, topic, more_xrefs=''):
2058 """Return unbuffered tuple of (topic, xrefs).
2059
Georg Brandld2f38572011-01-30 08:37:19 +00002060 If an error occurs here, the exception is caught and displayed by
2061 the url handler.
2062
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002063 This function duplicates the showtopic method but returns its
2064 result directly so it can be formatted for display in an html page.
2065 """
2066 try:
2067 import pydoc_data.topics
Brett Cannoncd171c82013-07-04 17:43:24 -04002068 except ImportError:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002069 return('''
2070Sorry, topic and keyword documentation is not available because the
2071module "pydoc_data.topics" could not be found.
2072''' , '')
2073 target = self.topics.get(topic, self.keywords.get(topic))
2074 if not target:
Georg Brandld2f38572011-01-30 08:37:19 +00002075 raise ValueError('could not find topic')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002076 if isinstance(target, str):
2077 return self._gettopic(target, more_xrefs)
2078 label, xrefs = target
Georg Brandld2f38572011-01-30 08:37:19 +00002079 doc = pydoc_data.topics.topics[label]
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002080 if more_xrefs:
2081 xrefs = (xrefs or '') + ' ' + more_xrefs
2082 return doc, xrefs
2083
Georg Brandldb7b6b92009-01-01 15:53:14 +00002084 def showsymbol(self, symbol):
2085 target = self.symbols[symbol]
2086 topic, _, xrefs = target.partition(' ')
2087 self.showtopic(topic, xrefs)
2088
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002089 def listmodules(self, key=''):
2090 if key:
2091 self.output.write('''
Terry Jan Reedy34200572013-02-11 02:23:13 -05002092Here is a list of modules whose name or summary contains '{}'.
2093If there are any, enter a module name to get more help.
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002094
Terry Jan Reedy34200572013-02-11 02:23:13 -05002095'''.format(key))
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002096 apropos(key)
2097 else:
2098 self.output.write('''
2099Please wait a moment while I gather a list of all available modules...
2100
2101''')
2102 modules = {}
2103 def callback(path, modname, desc, modules=modules):
2104 if modname and modname[-9:] == '.__init__':
2105 modname = modname[:-9] + ' (package)'
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002106 if modname.find('.') < 0:
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002107 modules[modname] = 1
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002108 def onerror(modname):
2109 callback(None, modname, None)
2110 ModuleScanner().run(callback, onerror=onerror)
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002111 self.list(modules.keys())
2112 self.output.write('''
2113Enter any module name to get more help. Or, type "modules spam" to search
Terry Jan Reedy34200572013-02-11 02:23:13 -05002114for modules whose name or summary contain the string "spam".
Ka-Ping Yee35cf0a32001-04-12 19:53:52 +00002115''')
2116
Georg Brandl78aa3962010-07-31 21:51:48 +00002117help = Helper()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002118
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002119class ModuleScanner:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002120 """An interruptible scanner that searches module synopses."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002121
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002122 def run(self, callback, key=None, completer=None, onerror=None):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002123 if key: key = key.lower()
Guido van Rossum8ca162f2002-04-07 06:36:23 +00002124 self.quit = False
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002125 seen = {}
2126
2127 for modname in sys.builtin_module_names:
Ka-Ping Yee239432a2001-03-02 02:45:08 +00002128 if modname != '__main__':
2129 seen[modname] = 1
Ka-Ping Yee66246962001-04-12 11:59:50 +00002130 if key is None:
2131 callback(None, modname, '')
2132 else:
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002133 name = __import__(modname).__doc__ or ''
2134 desc = name.split('\n')[0]
2135 name = modname + ' - ' + desc
2136 if name.lower().find(key) >= 0:
Ka-Ping Yee66246962001-04-12 11:59:50 +00002137 callback(None, modname, desc)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002138
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002139 for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002140 if self.quit:
2141 break
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002142
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002143 if key is None:
2144 callback(None, modname, '')
2145 else:
Georg Brandl126c8792009-04-05 15:05:48 +00002146 try:
Eric Snow3a62d142014-01-06 20:42:59 -07002147 spec = pkgutil._get_spec(importer, modname)
Georg Brandl126c8792009-04-05 15:05:48 +00002148 except SyntaxError:
2149 # raised by tests for bad coding cookies or BOM
2150 continue
Eric Snow3a62d142014-01-06 20:42:59 -07002151 loader = spec.loader
Georg Brandl126c8792009-04-05 15:05:48 +00002152 if hasattr(loader, 'get_source'):
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002153 try:
2154 source = loader.get_source(modname)
Nick Coghlan2824cb52012-07-15 22:12:14 +10002155 except Exception:
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002156 if onerror:
2157 onerror(modname)
2158 continue
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002159 desc = source_synopsis(io.StringIO(source)) or ''
Georg Brandl126c8792009-04-05 15:05:48 +00002160 if hasattr(loader, 'get_filename'):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002161 path = loader.get_filename(modname)
Ka-Ping Yee66246962001-04-12 11:59:50 +00002162 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002163 path = None
2164 else:
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002165 try:
Brett Cannon2a17bde2014-05-30 14:55:29 -04002166 module = importlib._bootstrap._load(spec)
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002167 except ImportError:
2168 if onerror:
2169 onerror(modname)
2170 continue
Benjamin Peterson54237f92015-02-16 19:45:01 -05002171 desc = module.__doc__.splitlines()[0] if module.__doc__ else ''
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002172 path = getattr(module,'__file__',None)
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002173 name = modname + ' - ' + desc
2174 if name.lower().find(key) >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002175 callback(path, modname, desc)
2176
2177 if completer:
2178 completer()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002179
2180def apropos(key):
2181 """Print all the one-line module summaries that contain a substring."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002182 def callback(path, modname, desc):
2183 if modname[-9:] == '.__init__':
2184 modname = modname[:-9] + ' (package)'
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002185 print(modname, desc and '- ' + desc)
Amaury Forgeot d'Arc9196dc62008-06-19 20:54:32 +00002186 def onerror(modname):
2187 pass
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002188 with warnings.catch_warnings():
2189 warnings.filterwarnings('ignore') # ignore problems during import
2190 ModuleScanner().run(callback, key, onerror=onerror)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002191
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002192# --------------------------------------- enhanced Web browser interface
2193
Feanil Patel6a396c92017-09-14 17:54:09 -04002194def _start_server(urlhandler, hostname, port):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002195 """Start an HTTP server thread on a specific port.
2196
2197 Start an HTML/text server thread, so HTML or text documents can be
2198 browsed dynamically and interactively with a Web browser. Example use:
2199
2200 >>> import time
2201 >>> import pydoc
2202
2203 Define a URL handler. To determine what the client is asking
2204 for, check the URL and content_type.
2205
2206 Then get or generate some text or HTML code and return it.
2207
2208 >>> def my_url_handler(url, content_type):
2209 ... text = 'the URL sent was: (%s, %s)' % (url, content_type)
2210 ... return text
2211
2212 Start server thread on port 0.
2213 If you use port 0, the server will pick a random port number.
2214 You can then use serverthread.port to get the port number.
2215
2216 >>> port = 0
2217 >>> serverthread = pydoc._start_server(my_url_handler, port)
2218
2219 Check that the server is really started. If it is, open browser
2220 and get first page. Use serverthread.url as the starting page.
2221
2222 >>> if serverthread.serving:
2223 ... import webbrowser
2224
2225 The next two lines are commented out so a browser doesn't open if
2226 doctest is run on this module.
2227
2228 #... webbrowser.open(serverthread.url)
2229 #True
2230
2231 Let the server do its thing. We just need to monitor its status.
2232 Use time.sleep so the loop doesn't hog the CPU.
2233
2234 >>> starttime = time.time()
2235 >>> timeout = 1 #seconds
2236
2237 This is a short timeout for testing purposes.
2238
2239 >>> while serverthread.serving:
2240 ... time.sleep(.01)
2241 ... if serverthread.serving and time.time() - starttime > timeout:
2242 ... serverthread.stop()
2243 ... break
2244
2245 Print any errors that may have occurred.
2246
2247 >>> print(serverthread.error)
2248 None
2249 """
2250 import http.server
2251 import email.message
2252 import select
2253 import threading
2254
2255 class DocHandler(http.server.BaseHTTPRequestHandler):
2256
2257 def do_GET(self):
2258 """Process a request from an HTML browser.
2259
2260 The URL received is in self.path.
2261 Get an HTML page from self.urlhandler and send it.
2262 """
2263 if self.path.endswith('.css'):
2264 content_type = 'text/css'
2265 else:
2266 content_type = 'text/html'
2267 self.send_response(200)
Georg Brandld2f38572011-01-30 08:37:19 +00002268 self.send_header('Content-Type', '%s; charset=UTF-8' % content_type)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002269 self.end_headers()
2270 self.wfile.write(self.urlhandler(
2271 self.path, content_type).encode('utf-8'))
2272
2273 def log_message(self, *args):
2274 # Don't log messages.
2275 pass
2276
2277 class DocServer(http.server.HTTPServer):
2278
Feanil Patel6a396c92017-09-14 17:54:09 -04002279 def __init__(self, host, port, callback):
2280 self.host = host
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +08002281 self.address = (self.host, port)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002282 self.callback = callback
2283 self.base.__init__(self, self.address, self.handler)
2284 self.quit = False
2285
2286 def serve_until_quit(self):
2287 while not self.quit:
2288 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
2289 if rd:
2290 self.handle_request()
Victor Stinnera3abd1d2011-01-03 16:12:39 +00002291 self.server_close()
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002292
2293 def server_activate(self):
2294 self.base.server_activate(self)
2295 if self.callback:
2296 self.callback(self)
2297
2298 class ServerThread(threading.Thread):
2299
Feanil Patel6a396c92017-09-14 17:54:09 -04002300 def __init__(self, urlhandler, host, port):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002301 self.urlhandler = urlhandler
Feanil Patel6a396c92017-09-14 17:54:09 -04002302 self.host = host
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002303 self.port = int(port)
2304 threading.Thread.__init__(self)
2305 self.serving = False
2306 self.error = None
2307
2308 def run(self):
2309 """Start the server."""
2310 try:
2311 DocServer.base = http.server.HTTPServer
2312 DocServer.handler = DocHandler
2313 DocHandler.MessageClass = email.message.Message
2314 DocHandler.urlhandler = staticmethod(self.urlhandler)
Feanil Patel6a396c92017-09-14 17:54:09 -04002315 docsvr = DocServer(self.host, self.port, self.ready)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002316 self.docserver = docsvr
2317 docsvr.serve_until_quit()
2318 except Exception as e:
2319 self.error = e
2320
2321 def ready(self, server):
2322 self.serving = True
2323 self.host = server.host
2324 self.port = server.server_port
2325 self.url = 'http://%s:%d/' % (self.host, self.port)
2326
2327 def stop(self):
2328 """Stop the server and this thread nicely"""
2329 self.docserver.quit = True
Victor Stinner4cab2cd2017-08-21 23:24:40 +02002330 self.join()
2331 # explicitly break a reference cycle: DocServer.callback
2332 # has indirectly a reference to ServerThread.
2333 self.docserver = None
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002334 self.serving = False
2335 self.url = None
2336
Feanil Patel6a396c92017-09-14 17:54:09 -04002337 thread = ServerThread(urlhandler, hostname, port)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002338 thread.start()
2339 # Wait until thread.serving is True to make sure we are
2340 # really up before returning.
2341 while not thread.error and not thread.serving:
2342 time.sleep(.01)
2343 return thread
2344
2345
2346def _url_handler(url, content_type="text/html"):
2347 """The pydoc url handler for use with the pydoc server.
2348
2349 If the content_type is 'text/css', the _pydoc.css style
2350 sheet is read and returned if it exits.
2351
2352 If the content_type is 'text/html', then the result of
2353 get_html_page(url) is returned.
2354 """
2355 class _HTMLDoc(HTMLDoc):
2356
2357 def page(self, title, contents):
2358 """Format an HTML page."""
2359 css_path = "pydoc_data/_pydoc.css"
2360 css_link = (
2361 '<link rel="stylesheet" type="text/css" href="%s">' %
2362 css_path)
2363 return '''\
2364<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Georg Brandld2f38572011-01-30 08:37:19 +00002365<html><head><title>Pydoc: %s</title>
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002366<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Georg Brandld2f38572011-01-30 08:37:19 +00002367%s</head><body bgcolor="#f0f0f8">%s<div style="clear:both;padding-top:.5em;">%s</div>
2368</body></html>''' % (title, css_link, html_navbar(), contents)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002369
2370 def filelink(self, url, path):
2371 return '<a href="getfile?key=%s">%s</a>' % (url, path)
2372
2373
2374 html = _HTMLDoc()
2375
2376 def html_navbar():
Georg Brandld2f38572011-01-30 08:37:19 +00002377 version = html.escape("%s [%s, %s]" % (platform.python_version(),
2378 platform.python_build()[0],
2379 platform.python_compiler()))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002380 return """
2381 <div style='float:left'>
Georg Brandld2f38572011-01-30 08:37:19 +00002382 Python %s<br>%s
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002383 </div>
2384 <div style='float:right'>
2385 <div style='text-align:center'>
2386 <a href="index.html">Module Index</a>
2387 : <a href="topics.html">Topics</a>
2388 : <a href="keywords.html">Keywords</a>
2389 </div>
2390 <div>
Georg Brandld2f38572011-01-30 08:37:19 +00002391 <form action="get" style='display:inline;'>
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002392 <input type=text name=key size=15>
2393 <input type=submit value="Get">
Georg Brandld2f38572011-01-30 08:37:19 +00002394 </form>&nbsp;
2395 <form action="search" style='display:inline;'>
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002396 <input type=text name=key size=15>
2397 <input type=submit value="Search">
2398 </form>
2399 </div>
2400 </div>
Georg Brandld2f38572011-01-30 08:37:19 +00002401 """ % (version, html.escape(platform.platform(terse=True)))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002402
2403 def html_index():
2404 """Module Index page."""
2405
2406 def bltinlink(name):
2407 return '<a href="%s.html">%s</a>' % (name, name)
2408
2409 heading = html.heading(
2410 '<big><big><strong>Index of Modules</strong></big></big>',
2411 '#ffffff', '#7799ee')
2412 names = [name for name in sys.builtin_module_names
2413 if name != '__main__']
2414 contents = html.multicolumn(names, bltinlink)
2415 contents = [heading, '<p>' + html.bigsection(
2416 'Built-in Modules', '#ffffff', '#ee77aa', contents)]
2417
2418 seen = {}
2419 for dir in sys.path:
2420 contents.append(html.index(dir, seen))
2421
2422 contents.append(
2423 '<p align=right><font color="#909090" face="helvetica,'
2424 'arial"><strong>pydoc</strong> by Ka-Ping Yee'
2425 '&lt;ping@lfw.org&gt;</font>')
Nick Coghlanecace282010-12-03 16:08:46 +00002426 return 'Index of Modules', ''.join(contents)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002427
2428 def html_search(key):
2429 """Search results page."""
2430 # scan for modules
2431 search_result = []
2432
2433 def callback(path, modname, desc):
2434 if modname[-9:] == '.__init__':
2435 modname = modname[:-9] + ' (package)'
2436 search_result.append((modname, desc and '- ' + desc))
2437
2438 with warnings.catch_warnings():
2439 warnings.filterwarnings('ignore') # ignore problems during import
Martin Panter9ad0aae2015-11-06 00:27:14 +00002440 def onerror(modname):
2441 pass
2442 ModuleScanner().run(callback, key, onerror=onerror)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002443
2444 # format page
2445 def bltinlink(name):
2446 return '<a href="%s.html">%s</a>' % (name, name)
2447
2448 results = []
2449 heading = html.heading(
2450 '<big><big><strong>Search Results</strong></big></big>',
2451 '#ffffff', '#7799ee')
2452 for name, desc in search_result:
2453 results.append(bltinlink(name) + desc)
2454 contents = heading + html.bigsection(
2455 'key = %s' % key, '#ffffff', '#ee77aa', '<br>'.join(results))
Nick Coghlanecace282010-12-03 16:08:46 +00002456 return 'Search Results', contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002457
2458 def html_getfile(path):
2459 """Get and display a source file listing safely."""
Zachary Wareeb432142014-07-10 11:18:00 -05002460 path = urllib.parse.unquote(path)
Victor Stinner91e08772011-07-05 14:30:41 +02002461 with tokenize.open(path) as fp:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002462 lines = html.escape(fp.read())
2463 body = '<pre>%s</pre>' % lines
2464 heading = html.heading(
2465 '<big><big><strong>File Listing</strong></big></big>',
2466 '#ffffff', '#7799ee')
2467 contents = heading + html.bigsection(
2468 'File: %s' % path, '#ffffff', '#ee77aa', body)
Nick Coghlanecace282010-12-03 16:08:46 +00002469 return 'getfile %s' % path, contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002470
2471 def html_topics():
2472 """Index of topic texts available."""
2473
2474 def bltinlink(name):
Georg Brandld2f38572011-01-30 08:37:19 +00002475 return '<a href="topic?key=%s">%s</a>' % (name, name)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002476
2477 heading = html.heading(
2478 '<big><big><strong>INDEX</strong></big></big>',
2479 '#ffffff', '#7799ee')
2480 names = sorted(Helper.topics.keys())
2481
2482 contents = html.multicolumn(names, bltinlink)
2483 contents = heading + html.bigsection(
2484 'Topics', '#ffffff', '#ee77aa', contents)
Nick Coghlanecace282010-12-03 16:08:46 +00002485 return 'Topics', contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002486
2487 def html_keywords():
2488 """Index of keywords."""
2489 heading = html.heading(
2490 '<big><big><strong>INDEX</strong></big></big>',
2491 '#ffffff', '#7799ee')
2492 names = sorted(Helper.keywords.keys())
2493
2494 def bltinlink(name):
Georg Brandld2f38572011-01-30 08:37:19 +00002495 return '<a href="topic?key=%s">%s</a>' % (name, name)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002496
2497 contents = html.multicolumn(names, bltinlink)
2498 contents = heading + html.bigsection(
2499 'Keywords', '#ffffff', '#ee77aa', contents)
Nick Coghlanecace282010-12-03 16:08:46 +00002500 return 'Keywords', contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002501
2502 def html_topicpage(topic):
2503 """Topic or keyword help page."""
2504 buf = io.StringIO()
2505 htmlhelp = Helper(buf, buf)
2506 contents, xrefs = htmlhelp._gettopic(topic)
2507 if topic in htmlhelp.keywords:
2508 title = 'KEYWORD'
2509 else:
2510 title = 'TOPIC'
2511 heading = html.heading(
2512 '<big><big><strong>%s</strong></big></big>' % title,
2513 '#ffffff', '#7799ee')
Georg Brandld2f38572011-01-30 08:37:19 +00002514 contents = '<pre>%s</pre>' % html.markup(contents)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002515 contents = html.bigsection(topic , '#ffffff','#ee77aa', contents)
Georg Brandld2f38572011-01-30 08:37:19 +00002516 if xrefs:
2517 xrefs = sorted(xrefs.split())
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002518
Georg Brandld2f38572011-01-30 08:37:19 +00002519 def bltinlink(name):
2520 return '<a href="topic?key=%s">%s</a>' % (name, name)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002521
Georg Brandld2f38572011-01-30 08:37:19 +00002522 xrefs = html.multicolumn(xrefs, bltinlink)
2523 xrefs = html.section('Related help topics: ',
2524 '#ffffff', '#ee77aa', xrefs)
Nick Coghlanecace282010-12-03 16:08:46 +00002525 return ('%s %s' % (title, topic),
2526 ''.join((heading, contents, xrefs)))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002527
Georg Brandld2f38572011-01-30 08:37:19 +00002528 def html_getobj(url):
2529 obj = locate(url, forceload=1)
2530 if obj is None and url != 'None':
2531 raise ValueError('could not find object')
2532 title = describe(obj)
2533 content = html.document(obj, url)
2534 return title, content
2535
2536 def html_error(url, exc):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002537 heading = html.heading(
2538 '<big><big><strong>Error</strong></big></big>',
Georg Brandld2f38572011-01-30 08:37:19 +00002539 '#ffffff', '#7799ee')
2540 contents = '<br>'.join(html.escape(line) for line in
2541 format_exception_only(type(exc), exc))
2542 contents = heading + html.bigsection(url, '#ffffff', '#bb0000',
2543 contents)
2544 return "Error - %s" % url, contents
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002545
2546 def get_html_page(url):
2547 """Generate an HTML page for url."""
Georg Brandld2f38572011-01-30 08:37:19 +00002548 complete_url = url
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002549 if url.endswith('.html'):
2550 url = url[:-5]
Georg Brandld2f38572011-01-30 08:37:19 +00002551 try:
2552 if url in ("", "index"):
2553 title, content = html_index()
2554 elif url == "topics":
2555 title, content = html_topics()
2556 elif url == "keywords":
2557 title, content = html_keywords()
2558 elif '=' in url:
2559 op, _, url = url.partition('=')
2560 if op == "search?key":
2561 title, content = html_search(url)
2562 elif op == "getfile?key":
2563 title, content = html_getfile(url)
2564 elif op == "topic?key":
2565 # try topics first, then objects.
2566 try:
2567 title, content = html_topicpage(url)
2568 except ValueError:
2569 title, content = html_getobj(url)
2570 elif op == "get?key":
2571 # try objects first, then topics.
2572 if url in ("", "index"):
2573 title, content = html_index()
2574 else:
2575 try:
2576 title, content = html_getobj(url)
2577 except ValueError:
2578 title, content = html_topicpage(url)
2579 else:
2580 raise ValueError('bad pydoc url')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002581 else:
Georg Brandld2f38572011-01-30 08:37:19 +00002582 title, content = html_getobj(url)
2583 except Exception as exc:
2584 # Catch any errors and display them in an error page.
2585 title, content = html_error(complete_url, exc)
2586 return html.page(title, content)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002587
2588 if url.startswith('/'):
2589 url = url[1:]
2590 if content_type == 'text/css':
2591 path_here = os.path.dirname(os.path.realpath(__file__))
Georg Brandld2f38572011-01-30 08:37:19 +00002592 css_path = os.path.join(path_here, url)
2593 with open(css_path) as fp:
2594 return ''.join(fp.readlines())
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002595 elif content_type == 'text/html':
2596 return get_html_page(url)
Georg Brandld2f38572011-01-30 08:37:19 +00002597 # Errors outside the url handler are caught by the server.
2598 raise TypeError('unknown content type %r for url %s' % (content_type, url))
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002599
2600
Feanil Patel6a396c92017-09-14 17:54:09 -04002601def browse(port=0, *, open_browser=True, hostname='localhost'):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002602 """Start the enhanced pydoc Web server and open a Web browser.
2603
2604 Use port '0' to start the server on an arbitrary port.
2605 Set open_browser to False to suppress opening a browser.
2606 """
2607 import webbrowser
Feanil Patel6a396c92017-09-14 17:54:09 -04002608 serverthread = _start_server(_url_handler, hostname, port)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002609 if serverthread.error:
2610 print(serverthread.error)
2611 return
2612 if serverthread.serving:
2613 server_help_msg = 'Server commands: [b]rowser, [q]uit'
2614 if open_browser:
2615 webbrowser.open(serverthread.url)
2616 try:
2617 print('Server ready at', serverthread.url)
2618 print(server_help_msg)
2619 while serverthread.serving:
2620 cmd = input('server> ')
2621 cmd = cmd.lower()
2622 if cmd == 'q':
2623 break
2624 elif cmd == 'b':
2625 webbrowser.open(serverthread.url)
2626 else:
2627 print(server_help_msg)
2628 except (KeyboardInterrupt, EOFError):
2629 print()
2630 finally:
2631 if serverthread.serving:
2632 serverthread.stop()
2633 print('Server stopped')
2634
2635
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002636# -------------------------------------------------- command-line interface
2637
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002638def ispath(x):
Neal Norwitz9d72bb42007-04-17 08:48:32 +00002639 return isinstance(x, str) and x.find(os.sep) >= 0
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002640
Nick Coghlan82a94812018-04-15 21:52:57 +10002641def _get_revised_path(given_path, argv0):
2642 """Ensures current directory is on returned path, and argv0 directory is not
2643
2644 Exception: argv0 dir is left alone if it's also pydoc's directory.
2645
2646 Returns a new path entry list, or None if no adjustment is needed.
2647 """
2648 # Scripts may get the current directory in their path by default if they're
2649 # run with the -m switch, or directly from the current directory.
2650 # The interactive prompt also allows imports from the current directory.
2651
2652 # Accordingly, if the current directory is already present, don't make
2653 # any changes to the given_path
2654 if '' in given_path or os.curdir in given_path or os.getcwd() in given_path:
2655 return None
2656
2657 # Otherwise, add the current directory to the given path, and remove the
2658 # script directory (as long as the latter isn't also pydoc's directory.
2659 stdlib_dir = os.path.dirname(__file__)
2660 script_dir = os.path.dirname(argv0)
2661 revised_path = given_path.copy()
2662 if script_dir in given_path and not os.path.samefile(script_dir, stdlib_dir):
2663 revised_path.remove(script_dir)
2664 revised_path.insert(0, os.getcwd())
2665 return revised_path
2666
2667
2668# Note: the tests only cover _get_revised_path, not _adjust_cli_path itself
2669def _adjust_cli_sys_path():
Nick Coghlan1a5c4bd2018-04-15 23:32:05 +10002670 """Ensures current directory is on sys.path, and __main__ directory is not.
Nick Coghlan82a94812018-04-15 21:52:57 +10002671
2672 Exception: __main__ dir is left alone if it's also pydoc's directory.
2673 """
2674 revised_path = _get_revised_path(sys.path, sys.argv[0])
2675 if revised_path is not None:
2676 sys.path[:] = revised_path
2677
2678
Ka-Ping Yee1d384632001-03-01 00:24:32 +00002679def cli():
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002680 """Command-line interface (looks at sys.argv to decide what to do)."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002681 import getopt
Guido van Rossum756aa932007-04-07 03:04:01 +00002682 class BadUsage(Exception): pass
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002683
Nick Coghlan82a94812018-04-15 21:52:57 +10002684 _adjust_cli_sys_path()
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002685
Ka-Ping Yee3bda8792001-03-23 13:17:50 +00002686 try:
Feanil Patel6a396c92017-09-14 17:54:09 -04002687 opts, args = getopt.getopt(sys.argv[1:], 'bk:n:p:w')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002688 writing = False
2689 start_server = False
2690 open_browser = False
Feanil Patel6a396c92017-09-14 17:54:09 -04002691 port = 0
2692 hostname = 'localhost'
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002693 for opt, val in opts:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002694 if opt == '-b':
2695 start_server = True
2696 open_browser = True
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002697 if opt == '-k':
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002698 apropos(val)
2699 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002700 if opt == '-p':
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002701 start_server = True
2702 port = val
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002703 if opt == '-w':
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002704 writing = True
Feanil Patel6a396c92017-09-14 17:54:09 -04002705 if opt == '-n':
2706 start_server = True
2707 hostname = val
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002708
Benjamin Petersonb29614e2012-10-09 11:16:03 -04002709 if start_server:
Feanil Patel6a396c92017-09-14 17:54:09 -04002710 browse(port, hostname=hostname, open_browser=open_browser)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002711 return
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002712
2713 if not args: raise BadUsage
2714 for arg in args:
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00002715 if ispath(arg) and not os.path.exists(arg):
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002716 print('file %r does not exist' % arg)
Ka-Ping Yee45daeb02002-08-11 15:11:33 +00002717 break
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002718 try:
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002719 if ispath(arg) and os.path.isfile(arg):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002720 arg = importfile(arg)
Ka-Ping Yee37f7b382001-03-23 00:12:53 +00002721 if writing:
2722 if ispath(arg) and os.path.isdir(arg):
2723 writedocs(arg)
2724 else:
2725 writedoc(arg)
2726 else:
Martin v. Löwisb8c084e2003-06-14 09:03:46 +00002727 help.help(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +00002728 except ErrorDuringImport as value:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002729 print(value)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002730
2731 except (getopt.error, BadUsage):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002732 cmd = os.path.splitext(os.path.basename(sys.argv[0]))[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002733 print("""pydoc - the Python documentation tool
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002734
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002735{cmd} <name> ...
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002736 Show text documentation on something. <name> may be the name of a
Martin v. Löwisb8c084e2003-06-14 09:03:46 +00002737 Python keyword, topic, function, module, or package, or a dotted
2738 reference to a class or function within a module or module in a
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002739 package. If <name> contains a '{sep}', it is used as the path to a
Martin v. Löwisb8c084e2003-06-14 09:03:46 +00002740 Python source file to document. If name is 'keywords', 'topics',
2741 or 'modules', a listing of these things is displayed.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002742
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002743{cmd} -k <keyword>
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002744 Search for a keyword in the synopsis lines of all available modules.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002745
Feanil Patel6a396c92017-09-14 17:54:09 -04002746{cmd} -n <hostname>
2747 Start an HTTP server with the given hostname (default: localhost).
2748
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002749{cmd} -p <port>
2750 Start an HTTP server on the given port on the local machine. Port
2751 number 0 can be used to get an arbitrary unused port.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002752
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002753{cmd} -b
2754 Start an HTTP server on an arbitrary unused port and open a Web browser
Feanil Patel6a396c92017-09-14 17:54:09 -04002755 to interactively browse documentation. This option can be used in
2756 combination with -n and/or -p.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00002757
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002758{cmd} -w <name> ...
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00002759 Write out the HTML documentation for a module to a file in the current
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002760 directory. If <name> contains a '{sep}', it is treated as a filename; if
Ka-Ping Yee5a804ed2001-04-10 11:46:02 +00002761 it names a directory, documentation is written for all the contents.
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002762""".format(cmd=cmd, sep=os.sep))
Ka-Ping Yee1d384632001-03-01 00:24:32 +00002763
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002764if __name__ == '__main__':
2765 cli()