pydoc.py 107 KB

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