pydoc.py 110 KB

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