pydoc.py 106 KB

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