pydoc.py 105 KB

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