pydoc.py 111 KB

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