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