pydoc.py 107 KB

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