pydoc.py 104 KB

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