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