1
0

pydoc.py 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274
  1. #!/usr/bin/env python
  2. # -*- coding: Latin-1 -*-
  3. """Generate Python documentation in HTML or text for interactive use.
  4. In the Python interpreter, do "from pydoc import help" to provide online
  5. help. Calling help(thing) on a Python object documents the object.
  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 -p <port>" to start an HTTP server on a given port on the
  15. local machine to generate documentation web pages.
  16. For platforms without a command line, "pydoc -g" starts the HTTP server
  17. and also pops up a little window for controlling it.
  18. Run "pydoc -w <name>" to write out the HTML documentation for a module
  19. to a file named "<name>.html".
  20. Module docs for core modules are assumed to be in
  21. http://www.python.org/doc/current/lib/
  22. This can be overridden by setting the PYTHONDOCS environment variable
  23. to a different URL or to a local directory containing the Library
  24. Reference Manual pages.
  25. """
  26. __author__ = "Ka-Ping Yee <[email protected]>"
  27. __date__ = "26 February 2001"
  28. __version__ = "$Revision: 43347 $"
  29. __credits__ = """Guido van Rossum, for an excellent programming language.
  30. Tommy Burnette, the original creator of manpy.
  31. Paul Prescod, for all his work on onlinehelp.
  32. Richard Chamberlain, for the first implementation of textdoc.
  33. """
  34. # Known bugs that can't be fixed here:
  35. # - imp.load_module() cannot be prevented from clobbering existing
  36. # loaded modules, so calling synopsis() on a binary module file
  37. # changes the contents of any existing module with the same name.
  38. # - If the __file__ attribute on a module is a relative path and
  39. # the current directory is changed with os.chdir(), an incorrect
  40. # path will be displayed.
  41. import sys, imp, os, re, types, inspect, __builtin__
  42. from repr import Repr
  43. from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
  44. from collections import deque
  45. # --------------------------------------------------------- common routines
  46. def pathdirs():
  47. """Convert sys.path into a list of absolute, existing, unique paths."""
  48. dirs = []
  49. normdirs = []
  50. for dir in sys.path:
  51. dir = os.path.abspath(dir or '.')
  52. normdir = os.path.normcase(dir)
  53. if normdir not in normdirs and os.path.isdir(dir):
  54. dirs.append(dir)
  55. normdirs.append(normdir)
  56. return dirs
  57. def getdoc(object):
  58. """Get the doc string or comments for an object."""
  59. result = inspect.getdoc(object) or inspect.getcomments(object)
  60. return result and re.sub('^ *\n', '', rstrip(result)) or ''
  61. def splitdoc(doc):
  62. """Split a doc string into a synopsis line (if any) and the rest."""
  63. lines = split(strip(doc), '\n')
  64. if len(lines) == 1:
  65. return lines[0], ''
  66. elif len(lines) >= 2 and not rstrip(lines[1]):
  67. return lines[0], join(lines[2:], '\n')
  68. return '', join(lines, '\n')
  69. def classname(object, modname):
  70. """Get a class name and qualify it with a module name if necessary."""
  71. name = object.__name__
  72. if object.__module__ != modname:
  73. name = object.__module__ + '.' + name
  74. return name
  75. def isdata(object):
  76. """Check if an object is of a type that probably means it's data."""
  77. return not (inspect.ismodule(object) or inspect.isclass(object) or
  78. inspect.isroutine(object) or inspect.isframe(object) or
  79. inspect.istraceback(object) or inspect.iscode(object))
  80. def replace(text, *pairs):
  81. """Do a series of global replacements on a string."""
  82. while pairs:
  83. text = join(split(text, pairs[0]), pairs[1])
  84. pairs = pairs[2:]
  85. return text
  86. def cram(text, maxlen):
  87. """Omit part of a string if needed to make it fit in a maximum length."""
  88. if len(text) > maxlen:
  89. pre = max(0, (maxlen-3)//2)
  90. post = max(0, maxlen-3-pre)
  91. return text[:pre] + '...' + text[len(text)-post:]
  92. return text
  93. _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
  94. def stripid(text):
  95. """Remove the hexadecimal id from a Python object representation."""
  96. # The behaviour of %p is implementation-dependent in terms of case.
  97. if _re_stripid.search(repr(Exception)):
  98. return _re_stripid.sub(r'\1', text)
  99. return text
  100. def _is_some_method(obj):
  101. return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)
  102. def allmethods(cl):
  103. methods = {}
  104. for key, value in inspect.getmembers(cl, _is_some_method):
  105. methods[key] = 1
  106. for base in cl.__bases__:
  107. methods.update(allmethods(base)) # all your base are belong to us
  108. for key in methods.keys():
  109. methods[key] = getattr(cl, key)
  110. return methods
  111. def _split_list(s, predicate):
  112. """Split sequence s via predicate, and return pair ([true], [false]).
  113. The return value is a 2-tuple of lists,
  114. ([x for x in s if predicate(x)],
  115. [x for x in s if not predicate(x)])
  116. """
  117. yes = []
  118. no = []
  119. for x in s:
  120. if predicate(x):
  121. yes.append(x)
  122. else:
  123. no.append(x)
  124. return yes, no
  125. def visiblename(name, all=None):
  126. """Decide whether to show documentation on a variable."""
  127. # Certain special names are redundant.
  128. if name in ['__builtins__', '__doc__', '__file__', '__path__',
  129. '__module__', '__name__']: return 0
  130. # Private names are hidden, but special names are displayed.
  131. if name.startswith('__') and name.endswith('__'): return 1
  132. if all is not None:
  133. # only document that which the programmer exported in __all__
  134. return name in all
  135. else:
  136. return not name.startswith('_')
  137. # ----------------------------------------------------- module manipulation
  138. def ispackage(path):
  139. """Guess whether a path refers to a package directory."""
  140. if os.path.isdir(path):
  141. for ext in ['.py', '.pyc', '.pyo']:
  142. if os.path.isfile(os.path.join(path, '__init__' + ext)):
  143. return True
  144. return False
  145. def synopsis(filename, cache={}):
  146. """Get the one-line summary out of a module file."""
  147. mtime = os.stat(filename).st_mtime
  148. lastupdate, result = cache.get(filename, (0, None))
  149. if lastupdate < mtime:
  150. info = inspect.getmoduleinfo(filename)
  151. try:
  152. file = open(filename)
  153. except IOError:
  154. # module can't be opened, so skip it
  155. return None
  156. if info and 'b' in info[2]: # binary modules have to be imported
  157. try: module = imp.load_module('__temp__', file, filename, info[1:])
  158. except: return None
  159. result = split(module.__doc__ or '', '\n')[0]
  160. del sys.modules['__temp__']
  161. else: # text modules can be directly examined
  162. line = file.readline()
  163. while line[:1] == '#' or not strip(line):
  164. line = file.readline()
  165. if not line: break
  166. line = strip(line)
  167. if line[:4] == 'r"""': line = line[1:]
  168. if line[:3] == '"""':
  169. line = line[3:]
  170. if line[-1:] == '\\': line = line[:-1]
  171. while not strip(line):
  172. line = file.readline()
  173. if not line: break
  174. result = strip(split(line, '"""')[0])
  175. else: result = None
  176. file.close()
  177. cache[filename] = (mtime, result)
  178. return result
  179. class ErrorDuringImport(Exception):
  180. """Errors that occurred while trying to import something to document it."""
  181. def __init__(self, filename, (exc, value, tb)):
  182. self.filename = filename
  183. self.exc = exc
  184. self.value = value
  185. self.tb = tb
  186. def __str__(self):
  187. exc = self.exc
  188. if type(exc) is types.ClassType:
  189. exc = exc.__name__
  190. return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
  191. def importfile(path):
  192. """Import a Python source file or compiled file given its path."""
  193. magic = imp.get_magic()
  194. file = open(path, 'r')
  195. if file.read(len(magic)) == magic:
  196. kind = imp.PY_COMPILED
  197. else:
  198. kind = imp.PY_SOURCE
  199. file.close()
  200. filename = os.path.basename(path)
  201. name, ext = os.path.splitext(filename)
  202. file = open(path, 'r')
  203. try:
  204. module = imp.load_module(name, file, path, (ext, 'r', kind))
  205. except:
  206. raise ErrorDuringImport(path, sys.exc_info())
  207. file.close()
  208. return module
  209. def safeimport(path, forceload=0, cache={}):
  210. """Import a module; handle errors; return None if the module isn't found.
  211. If the module *is* found but an exception occurs, it's wrapped in an
  212. ErrorDuringImport exception and reraised. Unlike __import__, if a
  213. package path is specified, the module at the end of the path is returned,
  214. not the package at the beginning. If the optional 'forceload' argument
  215. is 1, we reload the module from disk (unless it's a dynamic extension)."""
  216. try:
  217. # If forceload is 1 and the module has been previously loaded from
  218. # disk, we always have to reload the module. Checking the file's
  219. # mtime isn't good enough (e.g. the module could contain a class
  220. # that inherits from another module that has changed).
  221. if forceload and path in sys.modules:
  222. if path not in sys.builtin_module_names:
  223. # Avoid simply calling reload() because it leaves names in
  224. # the currently loaded module lying around if they're not
  225. # defined in the new source file. Instead, remove the
  226. # module from sys.modules and re-import. Also remove any
  227. # submodules because they won't appear in the newly loaded
  228. # module's namespace if they're already in sys.modules.
  229. subs = [m for m in sys.modules if m.startswith(path + '.')]
  230. for key in [path] + subs:
  231. # Prevent garbage collection.
  232. cache[key] = sys.modules[key]
  233. del sys.modules[key]
  234. module = __import__(path)
  235. except:
  236. # Did the error occur before or after the module was found?
  237. (exc, value, tb) = info = sys.exc_info()
  238. if path in sys.modules:
  239. # An error occurred while executing the imported module.
  240. raise ErrorDuringImport(sys.modules[path].__file__, info)
  241. elif exc is SyntaxError:
  242. # A SyntaxError occurred before we could execute the module.
  243. raise ErrorDuringImport(value.filename, info)
  244. elif exc is ImportError and \
  245. split(lower(str(value)))[:2] == ['no', 'module']:
  246. # The module was not found.
  247. return None
  248. else:
  249. # Some other error occurred during the importing process.
  250. raise ErrorDuringImport(path, sys.exc_info())
  251. for part in split(path, '.')[1:]:
  252. try: module = getattr(module, part)
  253. except AttributeError: return None
  254. return module
  255. # ---------------------------------------------------- formatter base class
  256. class Doc:
  257. def document(self, object, name=None, *args):
  258. """Generate documentation for an object."""
  259. args = (object, name) + args
  260. # 'try' clause is to attempt to handle the possibility that inspect
  261. # identifies something in a way that pydoc itself has issues handling;
  262. # think 'super' and how it is a descriptor (which raises the exception
  263. # by lacking a __name__ attribute) and an instance.
  264. try:
  265. if inspect.ismodule(object): return self.docmodule(*args)
  266. if inspect.isclass(object): return self.docclass(*args)
  267. if inspect.isroutine(object): return self.docroutine(*args)
  268. except AttributeError:
  269. pass
  270. if isinstance(object, property): return self.docproperty(*args)
  271. return self.docother(*args)
  272. def fail(self, object, name=None, *args):
  273. """Raise an exception for unimplemented types."""
  274. message = "don't know how to document object%s of type %s" % (
  275. name and ' ' + repr(name), type(object).__name__)
  276. raise TypeError, message
  277. docmodule = docclass = docroutine = docother = fail
  278. def getdocloc(self, object):
  279. """Return the location of module docs or None"""
  280. try:
  281. file = inspect.getabsfile(object)
  282. except TypeError:
  283. file = '(built-in)'
  284. docloc = os.environ.get("PYTHONDOCS",
  285. "http://www.python.org/doc/current/lib")
  286. basedir = os.path.join(sys.exec_prefix, "lib",
  287. "python"+sys.version[0:3])
  288. if (isinstance(object, type(os)) and
  289. (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
  290. 'marshal', 'posix', 'signal', 'sys',
  291. 'thread', 'zipimport') or
  292. (file.startswith(basedir) and
  293. not file.startswith(os.path.join(basedir, 'site-packages'))))):
  294. htmlfile = "module-%s.html" % object.__name__
  295. if docloc.startswith("http://"):
  296. docloc = "%s/%s" % (docloc.rstrip("/"), htmlfile)
  297. else:
  298. docloc = os.path.join(docloc, htmlfile)
  299. else:
  300. docloc = None
  301. return docloc
  302. # -------------------------------------------- HTML documentation generator
  303. class HTMLRepr(Repr):
  304. """Class for safely making an HTML representation of a Python object."""
  305. def __init__(self):
  306. Repr.__init__(self)
  307. self.maxlist = self.maxtuple = 20
  308. self.maxdict = 10
  309. self.maxstring = self.maxother = 100
  310. def escape(self, text):
  311. return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;')
  312. def repr(self, object):
  313. return Repr.repr(self, object)
  314. def repr1(self, x, level):
  315. if hasattr(type(x), '__name__'):
  316. methodname = 'repr_' + join(split(type(x).__name__), '_')
  317. if hasattr(self, methodname):
  318. return getattr(self, methodname)(x, level)
  319. return self.escape(cram(stripid(repr(x)), self.maxother))
  320. def repr_string(self, x, level):
  321. test = cram(x, self.maxstring)
  322. testrepr = repr(test)
  323. if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  324. # Backslashes are only literal in the string and are never
  325. # needed to make any special characters, so show a raw string.
  326. return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
  327. return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
  328. r'<font color="#c040c0">\1</font>',
  329. self.escape(testrepr))
  330. repr_str = repr_string
  331. def repr_instance(self, x, level):
  332. try:
  333. return self.escape(cram(stripid(repr(x)), self.maxstring))
  334. except:
  335. return self.escape('<%s instance>' % x.__class__.__name__)
  336. repr_unicode = repr_string
  337. class HTMLDoc(Doc):
  338. """Formatter class for HTML documentation."""
  339. # ------------------------------------------- HTML formatting utilities
  340. _repr_instance = HTMLRepr()
  341. repr = _repr_instance.repr
  342. escape = _repr_instance.escape
  343. def page(self, title, contents):
  344. """Format an HTML page."""
  345. return '''
  346. <!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  347. <html><head><title>Python: %s</title>
  348. </head><body bgcolor="#f0f0f8">
  349. %s
  350. </body></html>''' % (title, contents)
  351. def heading(self, title, fgcol, bgcol, extras=''):
  352. """Format a page heading."""
  353. return '''
  354. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
  355. <tr bgcolor="%s">
  356. <td valign=bottom>&nbsp;<br>
  357. <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td
  358. ><td align=right valign=bottom
  359. ><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
  360. ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
  361. def section(self, title, fgcol, bgcol, contents, width=6,
  362. prelude='', marginalia=None, gap='&nbsp;'):
  363. """Format a section with a heading."""
  364. if marginalia is None:
  365. marginalia = '<tt>' + '&nbsp;' * width + '</tt>'
  366. result = '''<p>
  367. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  368. <tr bgcolor="%s">
  369. <td colspan=3 valign=bottom>&nbsp;<br>
  370. <font color="%s" face="helvetica, arial">%s</font></td></tr>
  371. ''' % (bgcol, fgcol, title)
  372. if prelude:
  373. result = result + '''
  374. <tr bgcolor="%s"><td rowspan=2>%s</td>
  375. <td colspan=2>%s</td></tr>
  376. <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
  377. else:
  378. result = result + '''
  379. <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
  380. return result + '\n<td width="100%%">%s</td></tr></table>' % contents
  381. def bigsection(self, title, *args):
  382. """Format a section with a big heading."""
  383. title = '<big><strong>%s</strong></big>' % title
  384. return self.section(title, *args)
  385. def preformat(self, text):
  386. """Format literal preformatted text."""
  387. text = self.escape(expandtabs(text))
  388. return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
  389. ' ', '&nbsp;', '\n', '<br>\n')
  390. def multicolumn(self, list, format, cols=4):
  391. """Format a list of items into a multi-column list."""
  392. result = ''
  393. rows = (len(list)+cols-1)/cols
  394. for col in range(cols):
  395. result = result + '<td width="%d%%" valign=top>' % (100/cols)
  396. for i in range(rows*col, rows*col+rows):
  397. if i < len(list):
  398. result = result + format(list[i]) + '<br>\n'
  399. result = result + '</td>'
  400. return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
  401. def grey(self, text): return '<font color="#909090">%s</font>' % text
  402. def namelink(self, name, *dicts):
  403. """Make a link for an identifier, given name-to-URL mappings."""
  404. for dict in dicts:
  405. if name in dict:
  406. return '<a href="%s">%s</a>' % (dict[name], name)
  407. return name
  408. def classlink(self, object, modname):
  409. """Make a link for a class."""
  410. name, module = object.__name__, sys.modules.get(object.__module__)
  411. if hasattr(module, name) and getattr(module, name) is object:
  412. return '<a href="%s.html#%s">%s</a>' % (
  413. module.__name__, name, classname(object, modname))
  414. return classname(object, modname)
  415. def modulelink(self, object):
  416. """Make a link for a module."""
  417. return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
  418. def modpkglink(self, (name, path, ispackage, shadowed)):
  419. """Make a link for a module or package to display in an index."""
  420. if shadowed:
  421. return self.grey(name)
  422. if path:
  423. url = '%s.%s.html' % (path, name)
  424. else:
  425. url = '%s.html' % name
  426. if ispackage:
  427. text = '<strong>%s</strong>&nbsp;(package)' % name
  428. else:
  429. text = name
  430. return '<a href="%s">%s</a>' % (url, text)
  431. def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
  432. """Mark up some plain text, given a context of symbols to look for.
  433. Each context dictionary maps object names to anchor names."""
  434. escape = escape or self.escape
  435. results = []
  436. here = 0
  437. pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
  438. r'RFC[- ]?(\d+)|'
  439. r'PEP[- ]?(\d+)|'
  440. r'(self\.)?(\w+))')
  441. while True:
  442. match = pattern.search(text, here)
  443. if not match: break
  444. start, end = match.span()
  445. results.append(escape(text[here:start]))
  446. all, scheme, rfc, pep, selfdot, name = match.groups()
  447. if scheme:
  448. url = escape(all).replace('"', '&quot;')
  449. results.append('<a href="%s">%s</a>' % (url, url))
  450. elif rfc:
  451. url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  452. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  453. elif pep:
  454. url = 'http://www.python.org/peps/pep-%04d.html' % int(pep)
  455. results.append('<a href="%s">%s</a>' % (url, escape(all)))
  456. elif text[end:end+1] == '(':
  457. results.append(self.namelink(name, methods, funcs, classes))
  458. elif selfdot:
  459. results.append('self.<strong>%s</strong>' % name)
  460. else:
  461. results.append(self.namelink(name, classes))
  462. here = end
  463. results.append(escape(text[here:]))
  464. return join(results, '')
  465. # ---------------------------------------------- type-specific routines
  466. def formattree(self, tree, modname, parent=None):
  467. """Produce HTML for a class tree as given by inspect.getclasstree()."""
  468. result = ''
  469. for entry in tree:
  470. if type(entry) is type(()):
  471. c, bases = entry
  472. result = result + '<dt><font face="helvetica, arial">'
  473. result = result + self.classlink(c, modname)
  474. if bases and bases != (parent,):
  475. parents = []
  476. for base in bases:
  477. parents.append(self.classlink(base, modname))
  478. result = result + '(' + join(parents, ', ') + ')'
  479. result = result + '\n</font></dt>'
  480. elif type(entry) is type([]):
  481. result = result + '<dd>\n%s</dd>\n' % self.formattree(
  482. entry, modname, c)
  483. return '<dl>\n%s</dl>\n' % result
  484. def docmodule(self, object, name=None, mod=None, *ignored):
  485. """Produce HTML documentation for a module object."""
  486. name = object.__name__ # ignore the passed-in name
  487. try:
  488. all = object.__all__
  489. except AttributeError:
  490. all = None
  491. parts = split(name, '.')
  492. links = []
  493. for i in range(len(parts)-1):
  494. links.append(
  495. '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
  496. (join(parts[:i+1], '.'), parts[i]))
  497. linkedname = join(links + parts[-1:], '.')
  498. head = '<big><big><strong>%s</strong></big></big>' % linkedname
  499. try:
  500. path = inspect.getabsfile(object)
  501. url = path
  502. if sys.platform == 'win32':
  503. import nturl2path
  504. url = nturl2path.pathname2url(path)
  505. filelink = '<a href="file:%s">%s</a>' % (url, path)
  506. except TypeError:
  507. filelink = '(built-in)'
  508. info = []
  509. if hasattr(object, '__version__'):
  510. version = str(object.__version__)
  511. if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  512. version = strip(version[11:-1])
  513. info.append('version %s' % self.escape(version))
  514. if hasattr(object, '__date__'):
  515. info.append(self.escape(str(object.__date__)))
  516. if info:
  517. head = head + ' (%s)' % join(info, ', ')
  518. docloc = self.getdocloc(object)
  519. if docloc is not None:
  520. docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
  521. else:
  522. docloc = ''
  523. result = self.heading(
  524. head, '#ffffff', '#7799ee',
  525. '<a href=".">index</a><br>' + filelink + docloc)
  526. modules = inspect.getmembers(object, inspect.ismodule)
  527. classes, cdict = [], {}
  528. for key, value in inspect.getmembers(object, inspect.isclass):
  529. # if __all__ exists, believe it. Otherwise use old heuristic.
  530. if (all is not None or
  531. (inspect.getmodule(value) or object) is object):
  532. if visiblename(key, all):
  533. classes.append((key, value))
  534. cdict[key] = cdict[value] = '#' + key
  535. for key, value in classes:
  536. for base in value.__bases__:
  537. key, modname = base.__name__, base.__module__
  538. module = sys.modules.get(modname)
  539. if modname != name and module and hasattr(module, key):
  540. if getattr(module, key) is base:
  541. if not key in cdict:
  542. cdict[key] = cdict[base] = modname + '.html#' + key
  543. funcs, fdict = [], {}
  544. for key, value in inspect.getmembers(object, inspect.isroutine):
  545. # if __all__ exists, believe it. Otherwise use old heuristic.
  546. if (all is not None or
  547. inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  548. if visiblename(key, all):
  549. funcs.append((key, value))
  550. fdict[key] = '#-' + key
  551. if inspect.isfunction(value): fdict[value] = fdict[key]
  552. data = []
  553. for key, value in inspect.getmembers(object, isdata):
  554. if visiblename(key, all):
  555. data.append((key, value))
  556. doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
  557. doc = doc and '<tt>%s</tt>' % doc
  558. result = result + '<p>%s</p>\n' % doc
  559. if hasattr(object, '__path__'):
  560. modpkgs = []
  561. modnames = []
  562. for file in os.listdir(object.__path__[0]):
  563. path = os.path.join(object.__path__[0], file)
  564. modname = inspect.getmodulename(file)
  565. if modname != '__init__':
  566. if modname and modname not in modnames:
  567. modpkgs.append((modname, name, 0, 0))
  568. modnames.append(modname)
  569. elif ispackage(path):
  570. modpkgs.append((file, name, 1, 0))
  571. modpkgs.sort()
  572. contents = self.multicolumn(modpkgs, self.modpkglink)
  573. result = result + self.bigsection(
  574. 'Package Contents', '#ffffff', '#aa55cc', contents)
  575. elif modules:
  576. contents = self.multicolumn(
  577. modules, lambda (key, value), s=self: s.modulelink(value))
  578. result = result + self.bigsection(
  579. 'Modules', '#fffff', '#aa55cc', contents)
  580. if classes:
  581. classlist = map(lambda (key, value): value, classes)
  582. contents = [
  583. self.formattree(inspect.getclasstree(classlist, 1), name)]
  584. for key, value in classes:
  585. contents.append(self.document(value, key, name, fdict, cdict))
  586. result = result + self.bigsection(
  587. 'Classes', '#ffffff', '#ee77aa', join(contents))
  588. if funcs:
  589. contents = []
  590. for key, value in funcs:
  591. contents.append(self.document(value, key, name, fdict, cdict))
  592. result = result + self.bigsection(
  593. 'Functions', '#ffffff', '#eeaa77', join(contents))
  594. if data:
  595. contents = []
  596. for key, value in data:
  597. contents.append(self.document(value, key))
  598. result = result + self.bigsection(
  599. 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
  600. if hasattr(object, '__author__'):
  601. contents = self.markup(str(object.__author__), self.preformat)
  602. result = result + self.bigsection(
  603. 'Author', '#ffffff', '#7799ee', contents)
  604. if hasattr(object, '__credits__'):
  605. contents = self.markup(str(object.__credits__), self.preformat)
  606. result = result + self.bigsection(
  607. 'Credits', '#ffffff', '#7799ee', contents)
  608. return result
  609. def docclass(self, object, name=None, mod=None, funcs={}, classes={},
  610. *ignored):
  611. """Produce HTML documentation for a class object."""
  612. realname = object.__name__
  613. name = name or realname
  614. bases = object.__bases__
  615. contents = []
  616. push = contents.append
  617. # Cute little class to pump out a horizontal rule between sections.
  618. class HorizontalRule:
  619. def __init__(self):
  620. self.needone = 0
  621. def maybe(self):
  622. if self.needone:
  623. push('<hr>\n')
  624. self.needone = 1
  625. hr = HorizontalRule()
  626. # List the mro, if non-trivial.
  627. mro = deque(inspect.getmro(object))
  628. if len(mro) > 2:
  629. hr.maybe()
  630. push('<dl><dt>Method resolution order:</dt>\n')
  631. for base in mro:
  632. push('<dd>%s</dd>\n' % self.classlink(base,
  633. object.__module__))
  634. push('</dl>\n')
  635. def spill(msg, attrs, predicate):
  636. ok, attrs = _split_list(attrs, predicate)
  637. if ok:
  638. hr.maybe()
  639. push(msg)
  640. for name, kind, homecls, value in ok:
  641. push(self.document(getattr(object, name), name, mod,
  642. funcs, classes, mdict, object))
  643. push('\n')
  644. return attrs
  645. def spillproperties(msg, attrs, predicate):
  646. ok, attrs = _split_list(attrs, predicate)
  647. if ok:
  648. hr.maybe()
  649. push(msg)
  650. for name, kind, homecls, value in ok:
  651. push(self._docproperty(name, value, mod))
  652. return attrs
  653. def spilldata(msg, attrs, predicate):
  654. ok, attrs = _split_list(attrs, predicate)
  655. if ok:
  656. hr.maybe()
  657. push(msg)
  658. for name, kind, homecls, value in ok:
  659. base = self.docother(getattr(object, name), name, mod)
  660. if callable(value) or inspect.isdatadescriptor(value):
  661. doc = getattr(value, "__doc__", None)
  662. else:
  663. doc = None
  664. if doc is None:
  665. push('<dl><dt>%s</dl>\n' % base)
  666. else:
  667. doc = self.markup(getdoc(value), self.preformat,
  668. funcs, classes, mdict)
  669. doc = '<dd><tt>%s</tt>' % doc
  670. push('<dl><dt>%s%s</dl>\n' % (base, doc))
  671. push('\n')
  672. return attrs
  673. attrs = filter(lambda (name, kind, cls, value): visiblename(name),
  674. inspect.classify_class_attrs(object))
  675. mdict = {}
  676. for key, kind, homecls, value in attrs:
  677. mdict[key] = anchor = '#' + name + '-' + key
  678. value = getattr(object, key)
  679. try:
  680. # The value may not be hashable (e.g., a data attr with
  681. # a dict or list value).
  682. mdict[value] = anchor
  683. except TypeError:
  684. pass
  685. while attrs:
  686. if mro:
  687. thisclass = mro.popleft()
  688. else:
  689. thisclass = attrs[0][2]
  690. attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  691. if thisclass is __builtin__.object:
  692. attrs = inherited
  693. continue
  694. elif thisclass is object:
  695. tag = 'defined here'
  696. else:
  697. tag = 'inherited from %s' % self.classlink(thisclass,
  698. object.__module__)
  699. tag += ':<br>\n'
  700. # Sort attrs by name.
  701. attrs.sort(key=lambda t: t[0])
  702. # Pump out the attrs, segregated by kind.
  703. attrs = spill('Methods %s' % tag, attrs,
  704. lambda t: t[1] == 'method')
  705. attrs = spill('Class methods %s' % tag, attrs,
  706. lambda t: t[1] == 'class method')
  707. attrs = spill('Static methods %s' % tag, attrs,
  708. lambda t: t[1] == 'static method')
  709. attrs = spillproperties('Properties %s' % tag, attrs,
  710. lambda t: t[1] == 'property')
  711. attrs = spilldata('Data and other attributes %s' % tag, attrs,
  712. lambda t: t[1] == 'data')
  713. assert attrs == []
  714. attrs = inherited
  715. contents = ''.join(contents)
  716. if name == realname:
  717. title = '<a name="%s">class <strong>%s</strong></a>' % (
  718. name, realname)
  719. else:
  720. title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
  721. name, name, realname)
  722. if bases:
  723. parents = []
  724. for base in bases:
  725. parents.append(self.classlink(base, object.__module__))
  726. title = title + '(%s)' % join(parents, ', ')
  727. doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
  728. doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc
  729. return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
  730. def formatvalue(self, object):
  731. """Format an argument default value as text."""
  732. return self.grey('=' + self.repr(object))
  733. def docroutine(self, object, name=None, mod=None,
  734. funcs={}, classes={}, methods={}, cl=None):
  735. """Produce HTML documentation for a function or method object."""
  736. realname = object.__name__
  737. name = name or realname
  738. anchor = (cl and cl.__name__ or '') + '-' + name
  739. note = ''
  740. skipdocs = 0
  741. if inspect.ismethod(object):
  742. imclass = object.im_class
  743. if cl:
  744. if imclass is not cl:
  745. note = ' from ' + self.classlink(imclass, mod)
  746. else:
  747. if object.im_self:
  748. note = ' method of %s instance' % self.classlink(
  749. object.im_self.__class__, mod)
  750. else:
  751. note = ' unbound %s method' % self.classlink(imclass,mod)
  752. object = object.im_func
  753. if name == realname:
  754. title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
  755. else:
  756. if (cl and realname in cl.__dict__ and
  757. cl.__dict__[realname] is object):
  758. reallink = '<a href="#%s">%s</a>' % (
  759. cl.__name__ + '-' + realname, realname)
  760. skipdocs = 1
  761. else:
  762. reallink = realname
  763. title = '<a name="%s"><strong>%s</strong></a> = %s' % (
  764. anchor, name, reallink)
  765. if inspect.isfunction(object):
  766. args, varargs, varkw, defaults = inspect.getargspec(object)
  767. argspec = inspect.formatargspec(
  768. args, varargs, varkw, defaults, formatvalue=self.formatvalue)
  769. if realname == '<lambda>':
  770. title = '<strong>%s</strong> <em>lambda</em> ' % name
  771. argspec = argspec[1:-1] # remove parentheses
  772. else:
  773. argspec = '(...)'
  774. decl = title + argspec + (note and self.grey(
  775. '<font face="helvetica, arial">%s</font>' % note))
  776. if skipdocs:
  777. return '<dl><dt>%s</dt></dl>\n' % decl
  778. else:
  779. doc = self.markup(
  780. getdoc(object), self.preformat, funcs, classes, methods)
  781. doc = doc and '<dd><tt>%s</tt></dd>' % doc
  782. return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  783. def _docproperty(self, name, value, mod):
  784. results = []
  785. push = results.append
  786. if name:
  787. push('<dl><dt><strong>%s</strong></dt>\n' % name)
  788. if value.__doc__ is not None:
  789. doc = self.markup(getdoc(value), self.preformat)
  790. push('<dd><tt>%s</tt></dd>\n' % doc)
  791. for attr, tag in [('fget', '<em>get</em>'),
  792. ('fset', '<em>set</em>'),
  793. ('fdel', '<em>delete</em>')]:
  794. func = getattr(value, attr)
  795. if func is not None:
  796. base = self.document(func, tag, mod)
  797. push('<dd>%s</dd>\n' % base)
  798. push('</dl>\n')
  799. return ''.join(results)
  800. def docproperty(self, object, name=None, mod=None, cl=None):
  801. """Produce html documentation for a property."""
  802. return self._docproperty(name, object, mod)
  803. def docother(self, object, name=None, mod=None, *ignored):
  804. """Produce HTML documentation for a data object."""
  805. lhs = name and '<strong>%s</strong> = ' % name or ''
  806. return lhs + self.repr(object)
  807. def index(self, dir, shadowed=None):
  808. """Generate an HTML index for a directory of modules."""
  809. modpkgs = []
  810. if shadowed is None: shadowed = {}
  811. seen = {}
  812. files = os.listdir(dir)
  813. def found(name, ispackage,
  814. modpkgs=modpkgs, shadowed=shadowed, seen=seen):
  815. if name not in seen:
  816. modpkgs.append((name, '', ispackage, name in shadowed))
  817. seen[name] = 1
  818. shadowed[name] = 1
  819. # Package spam/__init__.py takes precedence over module spam.py.
  820. for file in files:
  821. path = os.path.join(dir, file)
  822. if ispackage(path): found(file, 1)
  823. for file in files:
  824. path = os.path.join(dir, file)
  825. if os.path.isfile(path):
  826. modname = inspect.getmodulename(file)
  827. if modname: found(modname, 0)
  828. modpkgs.sort()
  829. contents = self.multicolumn(modpkgs, self.modpkglink)
  830. return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
  831. # -------------------------------------------- text documentation generator
  832. class TextRepr(Repr):
  833. """Class for safely making a text representation of a Python object."""
  834. def __init__(self):
  835. Repr.__init__(self)
  836. self.maxlist = self.maxtuple = 20
  837. self.maxdict = 10
  838. self.maxstring = self.maxother = 100
  839. def repr1(self, x, level):
  840. if hasattr(type(x), '__name__'):
  841. methodname = 'repr_' + join(split(type(x).__name__), '_')
  842. if hasattr(self, methodname):
  843. return getattr(self, methodname)(x, level)
  844. return cram(stripid(repr(x)), self.maxother)
  845. def repr_string(self, x, level):
  846. test = cram(x, self.maxstring)
  847. testrepr = repr(test)
  848. if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  849. # Backslashes are only literal in the string and are never
  850. # needed to make any special characters, so show a raw string.
  851. return 'r' + testrepr[0] + test + testrepr[0]
  852. return testrepr
  853. repr_str = repr_string
  854. def repr_instance(self, x, level):
  855. try:
  856. return cram(stripid(repr(x)), self.maxstring)
  857. except:
  858. return '<%s instance>' % x.__class__.__name__
  859. class TextDoc(Doc):
  860. """Formatter class for text documentation."""
  861. # ------------------------------------------- text formatting utilities
  862. _repr_instance = TextRepr()
  863. repr = _repr_instance.repr
  864. def bold(self, text):
  865. """Format a string in bold by overstriking."""
  866. return join(map(lambda ch: ch + '\b' + ch, text), '')
  867. def indent(self, text, prefix=' '):
  868. """Indent text by prepending a given prefix to each line."""
  869. if not text: return ''
  870. lines = split(text, '\n')
  871. lines = map(lambda line, prefix=prefix: prefix + line, lines)
  872. if lines: lines[-1] = rstrip(lines[-1])
  873. return join(lines, '\n')
  874. def section(self, title, contents):
  875. """Format a section with a given heading."""
  876. return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
  877. # ---------------------------------------------- type-specific routines
  878. def formattree(self, tree, modname, parent=None, prefix=''):
  879. """Render in text a class tree as returned by inspect.getclasstree()."""
  880. result = ''
  881. for entry in tree:
  882. if type(entry) is type(()):
  883. c, bases = entry
  884. result = result + prefix + classname(c, modname)
  885. if bases and bases != (parent,):
  886. parents = map(lambda c, m=modname: classname(c, m), bases)
  887. result = result + '(%s)' % join(parents, ', ')
  888. result = result + '\n'
  889. elif type(entry) is type([]):
  890. result = result + self.formattree(
  891. entry, modname, c, prefix + ' ')
  892. return result
  893. def docmodule(self, object, name=None, mod=None):
  894. """Produce text documentation for a given module object."""
  895. name = object.__name__ # ignore the passed-in name
  896. synop, desc = splitdoc(getdoc(object))
  897. result = self.section('NAME', name + (synop and ' - ' + synop))
  898. try:
  899. all = object.__all__
  900. except AttributeError:
  901. all = None
  902. try:
  903. file = inspect.getabsfile(object)
  904. except TypeError:
  905. file = '(built-in)'
  906. result = result + self.section('FILE', file)
  907. docloc = self.getdocloc(object)
  908. if docloc is not None:
  909. result = result + self.section('MODULE DOCS', docloc)
  910. if desc:
  911. result = result + self.section('DESCRIPTION', desc)
  912. classes = []
  913. for key, value in inspect.getmembers(object, inspect.isclass):
  914. # if __all__ exists, believe it. Otherwise use old heuristic.
  915. if (all is not None
  916. or (inspect.getmodule(value) or object) is object):
  917. if visiblename(key, all):
  918. classes.append((key, value))
  919. funcs = []
  920. for key, value in inspect.getmembers(object, inspect.isroutine):
  921. # if __all__ exists, believe it. Otherwise use old heuristic.
  922. if (all is not None or
  923. inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  924. if visiblename(key, all):
  925. funcs.append((key, value))
  926. data = []
  927. for key, value in inspect.getmembers(object, isdata):
  928. if visiblename(key, all):
  929. data.append((key, value))
  930. if hasattr(object, '__path__'):
  931. modpkgs = []
  932. for file in os.listdir(object.__path__[0]):
  933. path = os.path.join(object.__path__[0], file)
  934. modname = inspect.getmodulename(file)
  935. if modname != '__init__':
  936. if modname and modname not in modpkgs:
  937. modpkgs.append(modname)
  938. elif ispackage(path):
  939. modpkgs.append(file + ' (package)')
  940. modpkgs.sort()
  941. result = result + self.section(
  942. 'PACKAGE CONTENTS', join(modpkgs, '\n'))
  943. if classes:
  944. classlist = map(lambda (key, value): value, classes)
  945. contents = [self.formattree(
  946. inspect.getclasstree(classlist, 1), name)]
  947. for key, value in classes:
  948. contents.append(self.document(value, key, name))
  949. result = result + self.section('CLASSES', join(contents, '\n'))
  950. if funcs:
  951. contents = []
  952. for key, value in funcs:
  953. contents.append(self.document(value, key, name))
  954. result = result + self.section('FUNCTIONS', join(contents, '\n'))
  955. if data:
  956. contents = []
  957. for key, value in data:
  958. contents.append(self.docother(value, key, name, maxlen=70))
  959. result = result + self.section('DATA', join(contents, '\n'))
  960. if hasattr(object, '__version__'):
  961. version = str(object.__version__)
  962. if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  963. version = strip(version[11:-1])
  964. result = result + self.section('VERSION', version)
  965. if hasattr(object, '__date__'):
  966. result = result + self.section('DATE', str(object.__date__))
  967. if hasattr(object, '__author__'):
  968. result = result + self.section('AUTHOR', str(object.__author__))
  969. if hasattr(object, '__credits__'):
  970. result = result + self.section('CREDITS', str(object.__credits__))
  971. return result
  972. def docclass(self, object, name=None, mod=None):
  973. """Produce text documentation for a given class object."""
  974. realname = object.__name__
  975. name = name or realname
  976. bases = object.__bases__
  977. def makename(c, m=object.__module__):
  978. return classname(c, m)
  979. if name == realname:
  980. title = 'class ' + self.bold(realname)
  981. else:
  982. title = self.bold(name) + ' = class ' + realname
  983. if bases:
  984. parents = map(makename, bases)
  985. title = title + '(%s)' % join(parents, ', ')
  986. doc = getdoc(object)
  987. contents = doc and [doc + '\n'] or []
  988. push = contents.append
  989. # List the mro, if non-trivial.
  990. mro = deque(inspect.getmro(object))
  991. if len(mro) > 2:
  992. push("Method resolution order:")
  993. for base in mro:
  994. push(' ' + makename(base))
  995. push('')
  996. # Cute little class to pump out a horizontal rule between sections.
  997. class HorizontalRule:
  998. def __init__(self):
  999. self.needone = 0
  1000. def maybe(self):
  1001. if self.needone:
  1002. push('-' * 70)
  1003. self.needone = 1
  1004. hr = HorizontalRule()
  1005. def spill(msg, attrs, predicate):
  1006. ok, attrs = _split_list(attrs, predicate)
  1007. if ok:
  1008. hr.maybe()
  1009. push(msg)
  1010. for name, kind, homecls, value in ok:
  1011. push(self.document(getattr(object, name),
  1012. name, mod, object))
  1013. return attrs
  1014. def spillproperties(msg, attrs, predicate):
  1015. ok, attrs = _split_list(attrs, predicate)
  1016. if ok:
  1017. hr.maybe()
  1018. push(msg)
  1019. for name, kind, homecls, value in ok:
  1020. push(self._docproperty(name, value, mod))
  1021. return attrs
  1022. def spilldata(msg, attrs, predicate):
  1023. ok, attrs = _split_list(attrs, predicate)
  1024. if ok:
  1025. hr.maybe()
  1026. push(msg)
  1027. for name, kind, homecls, value in ok:
  1028. if callable(value) or inspect.isdatadescriptor(value):
  1029. doc = getdoc(value)
  1030. else:
  1031. doc = None
  1032. push(self.docother(getattr(object, name),
  1033. name, mod, maxlen=70, doc=doc) + '\n')
  1034. return attrs
  1035. attrs = filter(lambda (name, kind, cls, value): visiblename(name),
  1036. inspect.classify_class_attrs(object))
  1037. while attrs:
  1038. if mro:
  1039. thisclass = mro.popleft()
  1040. else:
  1041. thisclass = attrs[0][2]
  1042. attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  1043. if thisclass is __builtin__.object:
  1044. attrs = inherited
  1045. continue
  1046. elif thisclass is object:
  1047. tag = "defined here"
  1048. else:
  1049. tag = "inherited from %s" % classname(thisclass,
  1050. object.__module__)
  1051. filter(lambda t: not t[0].startswith('_'), attrs)
  1052. # Sort attrs by name.
  1053. attrs.sort()
  1054. # Pump out the attrs, segregated by kind.
  1055. attrs = spill("Methods %s:\n" % tag, attrs,
  1056. lambda t: t[1] == 'method')
  1057. attrs = spill("Class methods %s:\n" % tag, attrs,
  1058. lambda t: t[1] == 'class method')
  1059. attrs = spill("Static methods %s:\n" % tag, attrs,
  1060. lambda t: t[1] == 'static method')
  1061. attrs = spillproperties("Properties %s:\n" % tag, attrs,
  1062. lambda t: t[1] == 'property')
  1063. attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
  1064. lambda t: t[1] == 'data')
  1065. assert attrs == []
  1066. attrs = inherited
  1067. contents = '\n'.join(contents)
  1068. if not contents:
  1069. return title + '\n'
  1070. return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n'
  1071. def formatvalue(self, object):
  1072. """Format an argument default value as text."""
  1073. return '=' + self.repr(object)
  1074. def docroutine(self, object, name=None, mod=None, cl=None):
  1075. """Produce text documentation for a function or method object."""
  1076. realname = object.__name__
  1077. name = name or realname
  1078. note = ''
  1079. skipdocs = 0
  1080. if inspect.ismethod(object):
  1081. imclass = object.im_class
  1082. if cl:
  1083. if imclass is not cl:
  1084. note = ' from ' + classname(imclass, mod)
  1085. else:
  1086. if object.im_self:
  1087. note = ' method of %s instance' % classname(
  1088. object.im_self.__class__, mod)
  1089. else:
  1090. note = ' unbound %s method' % classname(imclass,mod)
  1091. object = object.im_func
  1092. if name == realname:
  1093. title = self.bold(realname)
  1094. else:
  1095. if (cl and realname in cl.__dict__ and
  1096. cl.__dict__[realname] is object):
  1097. skipdocs = 1
  1098. title = self.bold(name) + ' = ' + realname
  1099. if inspect.isfunction(object):
  1100. args, varargs, varkw, defaults = inspect.getargspec(object)
  1101. argspec = inspect.formatargspec(
  1102. args, varargs, varkw, defaults, formatvalue=self.formatvalue)
  1103. if realname == '<lambda>':
  1104. title = self.bold(name) + ' lambda '
  1105. argspec = argspec[1:-1] # remove parentheses
  1106. else:
  1107. argspec = '(...)'
  1108. decl = title + argspec + note
  1109. if skipdocs:
  1110. return decl + '\n'
  1111. else:
  1112. doc = getdoc(object) or ''
  1113. return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n')
  1114. def _docproperty(self, name, value, mod):
  1115. results = []
  1116. push = results.append
  1117. if name:
  1118. push(name)
  1119. need_blank_after_doc = 0
  1120. doc = getdoc(value) or ''
  1121. if doc:
  1122. push(self.indent(doc))
  1123. need_blank_after_doc = 1
  1124. for attr, tag in [('fget', '<get>'),
  1125. ('fset', '<set>'),
  1126. ('fdel', '<delete>')]:
  1127. func = getattr(value, attr)
  1128. if func is not None:
  1129. if need_blank_after_doc:
  1130. push('')
  1131. need_blank_after_doc = 0
  1132. base = self.document(func, tag, mod)
  1133. push(self.indent(base))
  1134. return '\n'.join(results)
  1135. def docproperty(self, object, name=None, mod=None, cl=None):
  1136. """Produce text documentation for a property."""
  1137. return self._docproperty(name, object, mod)
  1138. def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
  1139. """Produce text documentation for a data object."""
  1140. repr = self.repr(object)
  1141. if maxlen:
  1142. line = (name and name + ' = ' or '') + repr
  1143. chop = maxlen - len(line)
  1144. if chop < 0: repr = repr[:chop] + '...'
  1145. line = (name and self.bold(name) + ' = ' or '') + repr
  1146. if doc is not None:
  1147. line += '\n' + self.indent(str(doc))
  1148. return line
  1149. # --------------------------------------------------------- user interfaces
  1150. def pager(text):
  1151. """The first time this is called, determine what kind of pager to use."""
  1152. global pager
  1153. pager = getpager()
  1154. pager(text)
  1155. def getpager():
  1156. """Decide what method to use for paging through text."""
  1157. if type(sys.stdout) is not types.FileType:
  1158. return plainpager
  1159. if not sys.stdin.isatty() or not sys.stdout.isatty():
  1160. return plainpager
  1161. if os.environ.get('TERM') in ['dumb', 'emacs']:
  1162. return plainpager
  1163. if 'PAGER' in os.environ:
  1164. if sys.platform == 'win32': # pipes completely broken in Windows
  1165. return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
  1166. elif os.environ.get('TERM') in ['dumb', 'emacs']:
  1167. return lambda text: pipepager(plain(text), os.environ['PAGER'])
  1168. else:
  1169. return lambda text: pipepager(text, os.environ['PAGER'])
  1170. if sys.platform == 'win32' or sys.platform.startswith('os2'):
  1171. return lambda text: tempfilepager(plain(text), 'more <')
  1172. if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
  1173. return lambda text: pipepager(text, 'less')
  1174. import tempfile
  1175. (fd, filename) = tempfile.mkstemp()
  1176. os.close(fd)
  1177. try:
  1178. if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
  1179. return lambda text: pipepager(text, 'more')
  1180. else:
  1181. return ttypager
  1182. finally:
  1183. os.unlink(filename)
  1184. def plain(text):
  1185. """Remove boldface formatting from text."""
  1186. return re.sub('.\b', '', text)
  1187. def pipepager(text, cmd):
  1188. """Page through text by feeding it to another program."""
  1189. pipe = os.popen(cmd, 'w')
  1190. try:
  1191. pipe.write(text)
  1192. pipe.close()
  1193. except IOError:
  1194. pass # Ignore broken pipes caused by quitting the pager program.
  1195. def tempfilepager(text, cmd):
  1196. """Page through text by invoking a program on a temporary file."""
  1197. import tempfile
  1198. filename = tempfile.mktemp()
  1199. file = open(filename, 'w')
  1200. file.write(text)
  1201. file.close()
  1202. try:
  1203. os.system(cmd + ' ' + filename)
  1204. finally:
  1205. os.unlink(filename)
  1206. def ttypager(text):
  1207. """Page through text on a text terminal."""
  1208. lines = split(plain(text), '\n')
  1209. try:
  1210. import tty
  1211. fd = sys.stdin.fileno()
  1212. old = tty.tcgetattr(fd)
  1213. tty.setcbreak(fd)
  1214. getchar = lambda: sys.stdin.read(1)
  1215. except (ImportError, AttributeError):
  1216. tty = None
  1217. getchar = lambda: sys.stdin.readline()[:-1][:1]
  1218. try:
  1219. r = inc = os.environ.get('LINES', 25) - 1
  1220. sys.stdout.write(join(lines[:inc], '\n') + '\n')
  1221. while lines[r:]:
  1222. sys.stdout.write('-- more --')
  1223. sys.stdout.flush()
  1224. c = getchar()
  1225. if c in ['q', 'Q']:
  1226. sys.stdout.write('\r \r')
  1227. break
  1228. elif c in ['\r', '\n']:
  1229. sys.stdout.write('\r \r' + lines[r] + '\n')
  1230. r = r + 1
  1231. continue
  1232. if c in ['b', 'B', '\x1b']:
  1233. r = r - inc - inc
  1234. if r < 0: r = 0
  1235. sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
  1236. r = r + inc
  1237. finally:
  1238. if tty:
  1239. tty.tcsetattr(fd, tty.TCSAFLUSH, old)
  1240. def plainpager(text):
  1241. """Simply print unformatted text. This is the ultimate fallback."""
  1242. sys.stdout.write(plain(text))
  1243. def describe(thing):
  1244. """Produce a short description of the given thing."""
  1245. if inspect.ismodule(thing):
  1246. if thing.__name__ in sys.builtin_module_names:
  1247. return 'built-in module ' + thing.__name__
  1248. if hasattr(thing, '__path__'):
  1249. return 'package ' + thing.__name__
  1250. else:
  1251. return 'module ' + thing.__name__
  1252. if inspect.isbuiltin(thing):
  1253. return 'built-in function ' + thing.__name__
  1254. if inspect.isclass(thing):
  1255. return 'class ' + thing.__name__
  1256. if inspect.isfunction(thing):
  1257. return 'function ' + thing.__name__
  1258. if inspect.ismethod(thing):
  1259. return 'method ' + thing.__name__
  1260. if type(thing) is types.InstanceType:
  1261. return 'instance of ' + thing.__class__.__name__
  1262. return type(thing).__name__
  1263. def locate(path, forceload=0):
  1264. """Locate an object by name or dotted path, importing as necessary."""
  1265. parts = [part for part in split(path, '.') if part]
  1266. module, n = None, 0
  1267. while n < len(parts):
  1268. nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
  1269. if nextmodule: module, n = nextmodule, n + 1
  1270. else: break
  1271. if module:
  1272. object = module
  1273. for part in parts[n:]:
  1274. try: object = getattr(object, part)
  1275. except AttributeError: return None
  1276. return object
  1277. else:
  1278. if hasattr(__builtin__, path):
  1279. return getattr(__builtin__, path)
  1280. # --------------------------------------- interactive interpreter interface
  1281. text = TextDoc()
  1282. html = HTMLDoc()
  1283. def resolve(thing, forceload=0):
  1284. """Given an object or a path to an object, get the object and its name."""
  1285. if isinstance(thing, str):
  1286. object = locate(thing, forceload)
  1287. if not object:
  1288. raise ImportError, 'no Python documentation found for %r' % thing
  1289. return object, thing
  1290. else:
  1291. return thing, getattr(thing, '__name__', None)
  1292. def doc(thing, title='Python Library Documentation: %s', forceload=0):
  1293. """Display text documentation, given an object or a path to an object."""
  1294. try:
  1295. object, name = resolve(thing, forceload)
  1296. desc = describe(object)
  1297. module = inspect.getmodule(object)
  1298. if name and '.' in name:
  1299. desc += ' in ' + name[:name.rfind('.')]
  1300. elif module and module is not object:
  1301. desc += ' in module ' + module.__name__
  1302. if not (inspect.ismodule(object) or
  1303. inspect.isclass(object) or
  1304. inspect.isroutine(object) or
  1305. isinstance(object, property)):
  1306. # If the passed object is a piece of data or an instance,
  1307. # document its available methods instead of its value.
  1308. object = type(object)
  1309. desc += ' object'
  1310. pager(title % desc + '\n\n' + text.document(object, name))
  1311. except (ImportError, ErrorDuringImport), value:
  1312. print value
  1313. def writedoc(thing, forceload=0):
  1314. """Write HTML documentation to a file in the current directory."""
  1315. try:
  1316. object, name = resolve(thing, forceload)
  1317. page = html.page(describe(object), html.document(object, name))
  1318. file = open(name + '.html', 'w')
  1319. file.write(page)
  1320. file.close()
  1321. print 'wrote', name + '.html'
  1322. except (ImportError, ErrorDuringImport), value:
  1323. print value
  1324. def writedocs(dir, pkgpath='', done=None):
  1325. """Write out HTML documentation for all modules in a directory tree."""
  1326. if done is None: done = {}
  1327. for file in os.listdir(dir):
  1328. path = os.path.join(dir, file)
  1329. if ispackage(path):
  1330. writedocs(path, pkgpath + file + '.', done)
  1331. elif os.path.isfile(path):
  1332. modname = inspect.getmodulename(path)
  1333. if modname:
  1334. if modname == '__init__':
  1335. modname = pkgpath[:-1] # remove trailing period
  1336. else:
  1337. modname = pkgpath + modname
  1338. if modname not in done:
  1339. done[modname] = 1
  1340. writedoc(modname)
  1341. class Helper:
  1342. keywords = {
  1343. 'and': 'BOOLEAN',
  1344. 'assert': ('ref/assert', ''),
  1345. 'break': ('ref/break', 'while for'),
  1346. 'class': ('ref/class', 'CLASSES SPECIALMETHODS'),
  1347. 'continue': ('ref/continue', 'while for'),
  1348. 'def': ('ref/function', ''),
  1349. 'del': ('ref/del', 'BASICMETHODS'),
  1350. 'elif': 'if',
  1351. 'else': ('ref/if', 'while for'),
  1352. 'except': 'try',
  1353. 'exec': ('ref/exec', ''),
  1354. 'finally': 'try',
  1355. 'for': ('ref/for', 'break continue while'),
  1356. 'from': 'import',
  1357. 'global': ('ref/global', 'NAMESPACES'),
  1358. 'if': ('ref/if', 'TRUTHVALUE'),
  1359. 'import': ('ref/import', 'MODULES'),
  1360. 'in': ('ref/comparisons', 'SEQUENCEMETHODS2'),
  1361. 'is': 'COMPARISON',
  1362. 'lambda': ('ref/lambdas', 'FUNCTIONS'),
  1363. 'not': 'BOOLEAN',
  1364. 'or': 'BOOLEAN',
  1365. 'pass': ('ref/pass', ''),
  1366. 'print': ('ref/print', ''),
  1367. 'raise': ('ref/raise', 'EXCEPTIONS'),
  1368. 'return': ('ref/return', 'FUNCTIONS'),
  1369. 'try': ('ref/try', 'EXCEPTIONS'),
  1370. 'while': ('ref/while', 'break continue if TRUTHVALUE'),
  1371. 'yield': ('ref/yield', ''),
  1372. }
  1373. topics = {
  1374. 'TYPES': ('ref/types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'),
  1375. 'STRINGS': ('ref/strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'),
  1376. 'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'),
  1377. 'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'),
  1378. 'UNICODE': ('ref/strings', 'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'),
  1379. 'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'),
  1380. 'INTEGER': ('ref/integers', 'int range'),
  1381. 'FLOAT': ('ref/floating', 'float math'),
  1382. 'COMPLEX': ('ref/imaginary', 'complex cmath'),
  1383. 'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
  1384. 'MAPPINGS': 'DICTIONARIES',
  1385. 'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'),
  1386. 'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
  1387. 'CODEOBJECTS': ('lib/bltin-code-objects', 'compile FUNCTIONS TYPES'),
  1388. 'TYPEOBJECTS': ('lib/bltin-type-objects', 'types TYPES'),
  1389. 'FRAMEOBJECTS': 'TYPES',
  1390. 'TRACEBACKS': 'TYPES',
  1391. 'NONE': ('lib/bltin-null-object', ''),
  1392. 'ELLIPSIS': ('lib/bltin-ellipsis-object', 'SLICINGS'),
  1393. 'FILES': ('lib/bltin-file-objects', ''),
  1394. 'SPECIALATTRIBUTES': ('lib/specialattrs', ''),
  1395. 'CLASSES': ('ref/types', 'class SPECIALMETHODS PRIVATENAMES'),
  1396. 'MODULES': ('lib/typesmodules', 'import'),
  1397. 'PACKAGES': 'import',
  1398. 'EXPRESSIONS': ('ref/summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'),
  1399. 'OPERATORS': 'EXPRESSIONS',
  1400. 'PRECEDENCE': 'EXPRESSIONS',
  1401. 'OBJECTS': ('ref/objects', 'TYPES'),
  1402. 'SPECIALMETHODS': ('ref/specialnames', 'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
  1403. 'BASICMETHODS': ('ref/customization', 'cmp hash repr str SPECIALMETHODS'),
  1404. 'ATTRIBUTEMETHODS': ('ref/attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
  1405. 'CALLABLEMETHODS': ('ref/callable-types', 'CALLS SPECIALMETHODS'),
  1406. 'SEQUENCEMETHODS1': ('ref/sequence-types', 'SEQUENCES SEQUENCEMETHODS2 SPECIALMETHODS'),
  1407. 'SEQUENCEMETHODS2': ('ref/sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 SPECIALMETHODS'),
  1408. 'MAPPINGMETHODS': ('ref/sequence-types', 'MAPPINGS SPECIALMETHODS'),
  1409. 'NUMBERMETHODS': ('ref/numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'),
  1410. 'EXECUTION': ('ref/execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
  1411. 'NAMESPACES': ('ref/naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
  1412. 'DYNAMICFEATURES': ('ref/dynamic-features', ''),
  1413. 'SCOPING': 'NAMESPACES',
  1414. 'FRAMES': 'NAMESPACES',
  1415. 'EXCEPTIONS': ('ref/exceptions', 'try except finally raise'),
  1416. 'COERCIONS': ('ref/coercion-rules','CONVERSIONS'),
  1417. 'CONVERSIONS': ('ref/conversions', 'COERCIONS'),
  1418. 'IDENTIFIERS': ('ref/identifiers', 'keywords SPECIALIDENTIFIERS'),
  1419. 'SPECIALIDENTIFIERS': ('ref/id-classes', ''),
  1420. 'PRIVATENAMES': ('ref/atom-identifiers', ''),
  1421. 'LITERALS': ('ref/atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
  1422. 'TUPLES': 'SEQUENCES',
  1423. 'TUPLELITERALS': ('ref/exprlists', 'TUPLES LITERALS'),
  1424. 'LISTS': ('lib/typesseq-mutable', 'LISTLITERALS'),
  1425. 'LISTLITERALS': ('ref/lists', 'LISTS LITERALS'),
  1426. 'DICTIONARIES': ('lib/typesmapping', 'DICTIONARYLITERALS'),
  1427. 'DICTIONARYLITERALS': ('ref/dict', 'DICTIONARIES LITERALS'),
  1428. 'BACKQUOTES': ('ref/string-conversions', 'repr str STRINGS LITERALS'),
  1429. 'ATTRIBUTES': ('ref/attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
  1430. 'SUBSCRIPTS': ('ref/subscriptions', 'SEQUENCEMETHODS1'),
  1431. 'SLICINGS': ('ref/slicings', 'SEQUENCEMETHODS2'),
  1432. 'CALLS': ('ref/calls', 'EXPRESSIONS'),
  1433. 'POWER': ('ref/power', 'EXPRESSIONS'),
  1434. 'UNARY': ('ref/unary', 'EXPRESSIONS'),
  1435. 'BINARY': ('ref/binary', 'EXPRESSIONS'),
  1436. 'SHIFTING': ('ref/shifting', 'EXPRESSIONS'),
  1437. 'BITWISE': ('ref/bitwise', 'EXPRESSIONS'),
  1438. 'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'),
  1439. 'BOOLEAN': ('ref/Booleans', 'EXPRESSIONS TRUTHVALUE'),
  1440. 'ASSERTION': 'assert',
  1441. 'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'),
  1442. 'AUGMENTEDASSIGNMENT': ('ref/augassign', 'NUMBERMETHODS'),
  1443. 'DELETION': 'del',
  1444. 'PRINTING': 'print',
  1445. 'RETURNING': 'return',
  1446. 'IMPORTING': 'import',
  1447. 'CONDITIONAL': 'if',
  1448. 'LOOPING': ('ref/compound', 'for while break continue'),
  1449. 'TRUTHVALUE': ('lib/truth', 'if while and or not BASICMETHODS'),
  1450. 'DEBUGGING': ('lib/module-pdb', 'pdb'),
  1451. }
  1452. def __init__(self, input, output):
  1453. self.input = input
  1454. self.output = output
  1455. self.docdir = None
  1456. execdir = os.path.dirname(sys.executable)
  1457. homedir = os.environ.get('PYTHONHOME')
  1458. for dir in [os.environ.get('PYTHONDOCS'),
  1459. homedir and os.path.join(homedir, 'doc'),
  1460. os.path.join(execdir, 'doc'),
  1461. '/usr/doc/python-docs-' + split(sys.version)[0],
  1462. '/usr/doc/python-' + split(sys.version)[0],
  1463. '/usr/doc/python-docs-' + sys.version[:3],
  1464. '/usr/doc/python-' + sys.version[:3],
  1465. os.path.join(sys.prefix, 'Resources/English.lproj/Documentation')]:
  1466. if dir and os.path.isdir(os.path.join(dir, 'lib')):
  1467. self.docdir = dir
  1468. def __repr__(self):
  1469. if inspect.stack()[1][3] == '?':
  1470. self()
  1471. return ''
  1472. return '<pydoc.Helper instance>'
  1473. def __call__(self, request=None):
  1474. if request is not None:
  1475. self.help(request)
  1476. else:
  1477. self.intro()
  1478. self.interact()
  1479. self.output.write('''
  1480. You are now leaving help and returning to the Python interpreter.
  1481. If you want to ask for help on a particular object directly from the
  1482. interpreter, you can type "help(object)". Executing "help('string')"
  1483. has the same effect as typing a particular string at the help> prompt.
  1484. ''')
  1485. def interact(self):
  1486. self.output.write('\n')
  1487. while True:
  1488. try:
  1489. request = self.getline('help> ')
  1490. if not request: break
  1491. except (KeyboardInterrupt, EOFError):
  1492. break
  1493. request = strip(replace(request, '"', '', "'", ''))
  1494. if lower(request) in ['q', 'quit']: break
  1495. self.help(request)
  1496. def getline(self, prompt):
  1497. """Read one line, using raw_input when available."""
  1498. if self.input is sys.stdin:
  1499. return raw_input(prompt)
  1500. else:
  1501. self.output.write(prompt)
  1502. self.output.flush()
  1503. return self.input.readline()
  1504. def help(self, request):
  1505. if type(request) is type(''):
  1506. if request == 'help': self.intro()
  1507. elif request == 'keywords': self.listkeywords()
  1508. elif request == 'topics': self.listtopics()
  1509. elif request == 'modules': self.listmodules()
  1510. elif request[:8] == 'modules ':
  1511. self.listmodules(split(request)[1])
  1512. elif request in self.keywords: self.showtopic(request)
  1513. elif request in self.topics: self.showtopic(request)
  1514. elif request: doc(request, 'Help on %s:')
  1515. elif isinstance(request, Helper): self()
  1516. else: doc(request, 'Help on %s:')
  1517. self.output.write('\n')
  1518. def intro(self):
  1519. self.output.write('''
  1520. Welcome to Python %s! This is the online help utility.
  1521. If this is your first time using Python, you should definitely check out
  1522. the tutorial on the Internet at http://www.python.org/doc/tut/.
  1523. Enter the name of any module, keyword, or topic to get help on writing
  1524. Python programs and using Python modules. To quit this help utility and
  1525. return to the interpreter, just type "quit".
  1526. To get a list of available modules, keywords, or topics, type "modules",
  1527. "keywords", or "topics". Each module also comes with a one-line summary
  1528. of what it does; to list the modules whose summaries contain a given word
  1529. such as "spam", type "modules spam".
  1530. ''' % sys.version[:3])
  1531. def list(self, items, columns=4, width=80):
  1532. items = items[:]
  1533. items.sort()
  1534. colw = width / columns
  1535. rows = (len(items) + columns - 1) / columns
  1536. for row in range(rows):
  1537. for col in range(columns):
  1538. i = col * rows + row
  1539. if i < len(items):
  1540. self.output.write(items[i])
  1541. if col < columns - 1:
  1542. self.output.write(' ' + ' ' * (colw-1 - len(items[i])))
  1543. self.output.write('\n')
  1544. def listkeywords(self):
  1545. self.output.write('''
  1546. Here is a list of the Python keywords. Enter any keyword to get more help.
  1547. ''')
  1548. self.list(self.keywords.keys())
  1549. def listtopics(self):
  1550. self.output.write('''
  1551. Here is a list of available topics. Enter any topic name to get more help.
  1552. ''')
  1553. self.list(self.topics.keys())
  1554. def showtopic(self, topic):
  1555. if not self.docdir:
  1556. self.output.write('''
  1557. Sorry, topic and keyword documentation is not available because the Python
  1558. HTML documentation files could not be found. If you have installed them,
  1559. please set the environment variable PYTHONDOCS to indicate their location.
  1560. ''')
  1561. return
  1562. target = self.topics.get(topic, self.keywords.get(topic))
  1563. if not target:
  1564. self.output.write('no documentation found for %s\n' % repr(topic))
  1565. return
  1566. if type(target) is type(''):
  1567. return self.showtopic(target)
  1568. filename, xrefs = target
  1569. filename = self.docdir + '/' + filename + '.html'
  1570. try:
  1571. file = open(filename)
  1572. except:
  1573. self.output.write('could not read docs from %s\n' % filename)
  1574. return
  1575. divpat = re.compile('<div[^>]*navigat.*?</div.*?>', re.I | re.S)
  1576. addrpat = re.compile('<address.*?>.*?</address.*?>', re.I | re.S)
  1577. document = re.sub(addrpat, '', re.sub(divpat, '', file.read()))
  1578. file.close()
  1579. import htmllib, formatter, StringIO
  1580. buffer = StringIO.StringIO()
  1581. parser = htmllib.HTMLParser(
  1582. formatter.AbstractFormatter(formatter.DumbWriter(buffer)))
  1583. parser.start_table = parser.do_p
  1584. parser.end_table = lambda parser=parser: parser.do_p({})
  1585. parser.start_tr = parser.do_br
  1586. parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t')
  1587. parser.feed(document)
  1588. buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n ')
  1589. pager(' ' + strip(buffer) + '\n')
  1590. if xrefs:
  1591. buffer = StringIO.StringIO()
  1592. formatter.DumbWriter(buffer).send_flowing_data(
  1593. 'Related help topics: ' + join(split(xrefs), ', ') + '\n')
  1594. self.output.write('\n%s\n' % buffer.getvalue())
  1595. def listmodules(self, key=''):
  1596. if key:
  1597. self.output.write('''
  1598. Here is a list of matching modules. Enter any module name to get more help.
  1599. ''')
  1600. apropos(key)
  1601. else:
  1602. self.output.write('''
  1603. Please wait a moment while I gather a list of all available modules...
  1604. ''')
  1605. modules = {}
  1606. def callback(path, modname, desc, modules=modules):
  1607. if modname and modname[-9:] == '.__init__':
  1608. modname = modname[:-9] + ' (package)'
  1609. if find(modname, '.') < 0:
  1610. modules[modname] = 1
  1611. ModuleScanner().run(callback)
  1612. self.list(modules.keys())
  1613. self.output.write('''
  1614. Enter any module name to get more help. Or, type "modules spam" to search
  1615. for modules whose descriptions contain the word "spam".
  1616. ''')
  1617. help = Helper(sys.stdin, sys.stdout)
  1618. class Scanner:
  1619. """A generic tree iterator."""
  1620. def __init__(self, roots, children, descendp):
  1621. self.roots = roots[:]
  1622. self.state = []
  1623. self.children = children
  1624. self.descendp = descendp
  1625. def next(self):
  1626. if not self.state:
  1627. if not self.roots:
  1628. return None
  1629. root = self.roots.pop(0)
  1630. self.state = [(root, self.children(root))]
  1631. node, children = self.state[-1]
  1632. if not children:
  1633. self.state.pop()
  1634. return self.next()
  1635. child = children.pop(0)
  1636. if self.descendp(child):
  1637. self.state.append((child, self.children(child)))
  1638. return child
  1639. class ModuleScanner(Scanner):
  1640. """An interruptible scanner that searches module synopses."""
  1641. def __init__(self):
  1642. roots = map(lambda dir: (dir, ''), pathdirs())
  1643. Scanner.__init__(self, roots, self.submodules, self.isnewpackage)
  1644. self.inodes = map(lambda (dir, pkg): os.stat(dir).st_ino, roots)
  1645. def submodules(self, (dir, package)):
  1646. children = []
  1647. for file in os.listdir(dir):
  1648. path = os.path.join(dir, file)
  1649. if ispackage(path):
  1650. children.append((path, package + (package and '.') + file))
  1651. else:
  1652. children.append((path, package))
  1653. children.sort() # so that spam.py comes before spam.pyc or spam.pyo
  1654. return children
  1655. def isnewpackage(self, (dir, package)):
  1656. inode = os.path.exists(dir) and os.stat(dir).st_ino
  1657. if not (os.path.islink(dir) and inode in self.inodes):
  1658. self.inodes.append(inode) # detect circular symbolic links
  1659. return ispackage(dir)
  1660. return False
  1661. def run(self, callback, key=None, completer=None):
  1662. if key: key = lower(key)
  1663. self.quit = False
  1664. seen = {}
  1665. for modname in sys.builtin_module_names:
  1666. if modname != '__main__':
  1667. seen[modname] = 1
  1668. if key is None:
  1669. callback(None, modname, '')
  1670. else:
  1671. desc = split(__import__(modname).__doc__ or '', '\n')[0]
  1672. if find(lower(modname + ' - ' + desc), key) >= 0:
  1673. callback(None, modname, desc)
  1674. while not self.quit:
  1675. node = self.next()
  1676. if not node: break
  1677. path, package = node
  1678. modname = inspect.getmodulename(path)
  1679. if os.path.isfile(path) and modname:
  1680. modname = package + (package and '.') + modname
  1681. if not modname in seen:
  1682. seen[modname] = 1 # if we see spam.py, skip spam.pyc
  1683. if key is None:
  1684. callback(path, modname, '')
  1685. else:
  1686. desc = synopsis(path) or ''
  1687. if find(lower(modname + ' - ' + desc), key) >= 0:
  1688. callback(path, modname, desc)
  1689. if completer: completer()
  1690. def apropos(key):
  1691. """Print all the one-line module summaries that contain a substring."""
  1692. def callback(path, modname, desc):
  1693. if modname[-9:] == '.__init__':
  1694. modname = modname[:-9] + ' (package)'
  1695. print modname, desc and '- ' + desc
  1696. try: import warnings
  1697. except ImportError: pass
  1698. else: warnings.filterwarnings('ignore') # ignore problems during import
  1699. ModuleScanner().run(callback, key)
  1700. # --------------------------------------------------- web browser interface
  1701. def serve(port, callback=None, completer=None):
  1702. import BaseHTTPServer, mimetools, select
  1703. # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
  1704. class Message(mimetools.Message):
  1705. def __init__(self, fp, seekable=1):
  1706. Message = self.__class__
  1707. Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
  1708. self.encodingheader = self.getheader('content-transfer-encoding')
  1709. self.typeheader = self.getheader('content-type')
  1710. self.parsetype()
  1711. self.parseplist()
  1712. class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  1713. def send_document(self, title, contents):
  1714. try:
  1715. self.send_response(200)
  1716. self.send_header('Content-Type', 'text/html')
  1717. self.end_headers()
  1718. self.wfile.write(html.page(title, contents))
  1719. except IOError: pass
  1720. def do_GET(self):
  1721. path = self.path
  1722. if path[-5:] == '.html': path = path[:-5]
  1723. if path[:1] == '/': path = path[1:]
  1724. if path and path != '.':
  1725. try:
  1726. obj = locate(path, forceload=1)
  1727. except ErrorDuringImport, value:
  1728. self.send_document(path, html.escape(str(value)))
  1729. return
  1730. if obj:
  1731. self.send_document(describe(obj), html.document(obj, path))
  1732. else:
  1733. self.send_document(path,
  1734. 'no Python documentation found for %s' % repr(path))
  1735. else:
  1736. heading = html.heading(
  1737. '<big><big><strong>Python: Index of Modules</strong></big></big>',
  1738. '#ffffff', '#7799ee')
  1739. def bltinlink(name):
  1740. return '<a href="%s.html">%s</a>' % (name, name)
  1741. names = filter(lambda x: x != '__main__',
  1742. sys.builtin_module_names)
  1743. contents = html.multicolumn(names, bltinlink)
  1744. indices = ['<p>' + html.bigsection(
  1745. 'Built-in Modules', '#ffffff', '#ee77aa', contents)]
  1746. seen = {}
  1747. for dir in pathdirs():
  1748. indices.append(html.index(dir, seen))
  1749. contents = heading + join(indices) + '''<p align=right>
  1750. <font color="#909090" face="helvetica, arial"><strong>
  1751. pydoc</strong> by Ka-Ping Yee &lt;[email protected]&gt;</font>'''
  1752. self.send_document('Index of Modules', contents)
  1753. def log_message(self, *args): pass
  1754. class DocServer(BaseHTTPServer.HTTPServer):
  1755. def __init__(self, port, callback):
  1756. host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
  1757. self.address = ('', port)
  1758. self.url = 'http://%s:%d/' % (host, port)
  1759. self.callback = callback
  1760. self.base.__init__(self, self.address, self.handler)
  1761. def serve_until_quit(self):
  1762. import select
  1763. self.quit = False
  1764. while not self.quit:
  1765. rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
  1766. if rd: self.handle_request()
  1767. def server_activate(self):
  1768. self.base.server_activate(self)
  1769. if self.callback: self.callback(self)
  1770. DocServer.base = BaseHTTPServer.HTTPServer
  1771. DocServer.handler = DocHandler
  1772. DocHandler.MessageClass = Message
  1773. try:
  1774. try:
  1775. DocServer(port, callback).serve_until_quit()
  1776. except (KeyboardInterrupt, select.error):
  1777. pass
  1778. finally:
  1779. if completer: completer()
  1780. # ----------------------------------------------------- graphical interface
  1781. def gui():
  1782. """Graphical interface (starts web server and pops up a control window)."""
  1783. class GUI:
  1784. def __init__(self, window, port=7464):
  1785. self.window = window
  1786. self.server = None
  1787. self.scanner = None
  1788. import Tkinter
  1789. self.server_frm = Tkinter.Frame(window)
  1790. self.title_lbl = Tkinter.Label(self.server_frm,
  1791. text='Starting server...\n ')
  1792. self.open_btn = Tkinter.Button(self.server_frm,
  1793. text='open browser', command=self.open, state='disabled')
  1794. self.quit_btn = Tkinter.Button(self.server_frm,
  1795. text='quit serving', command=self.quit, state='disabled')
  1796. self.search_frm = Tkinter.Frame(window)
  1797. self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
  1798. self.search_ent = Tkinter.Entry(self.search_frm)
  1799. self.search_ent.bind('<Return>', self.search)
  1800. self.stop_btn = Tkinter.Button(self.search_frm,
  1801. text='stop', pady=0, command=self.stop, state='disabled')
  1802. if sys.platform == 'win32':
  1803. # Trying to hide and show this button crashes under Windows.
  1804. self.stop_btn.pack(side='right')
  1805. self.window.title('pydoc')
  1806. self.window.protocol('WM_DELETE_WINDOW', self.quit)
  1807. self.title_lbl.pack(side='top', fill='x')
  1808. self.open_btn.pack(side='left', fill='x', expand=1)
  1809. self.quit_btn.pack(side='right', fill='x', expand=1)
  1810. self.server_frm.pack(side='top', fill='x')
  1811. self.search_lbl.pack(side='left')
  1812. self.search_ent.pack(side='right', fill='x', expand=1)
  1813. self.search_frm.pack(side='top', fill='x')
  1814. self.search_ent.focus_set()
  1815. font = ('helvetica', sys.platform == 'win32' and 8 or 10)
  1816. self.result_lst = Tkinter.Listbox(window, font=font, height=6)
  1817. self.result_lst.bind('<Button-1>', self.select)
  1818. self.result_lst.bind('<Double-Button-1>', self.goto)
  1819. self.result_scr = Tkinter.Scrollbar(window,
  1820. orient='vertical', command=self.result_lst.yview)
  1821. self.result_lst.config(yscrollcommand=self.result_scr.set)
  1822. self.result_frm = Tkinter.Frame(window)
  1823. self.goto_btn = Tkinter.Button(self.result_frm,
  1824. text='go to selected', command=self.goto)
  1825. self.hide_btn = Tkinter.Button(self.result_frm,
  1826. text='hide results', command=self.hide)
  1827. self.goto_btn.pack(side='left', fill='x', expand=1)
  1828. self.hide_btn.pack(side='right', fill='x', expand=1)
  1829. self.window.update()
  1830. self.minwidth = self.window.winfo_width()
  1831. self.minheight = self.window.winfo_height()
  1832. self.bigminheight = (self.server_frm.winfo_reqheight() +
  1833. self.search_frm.winfo_reqheight() +
  1834. self.result_lst.winfo_reqheight() +
  1835. self.result_frm.winfo_reqheight())
  1836. self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
  1837. self.expanded = 0
  1838. self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  1839. self.window.wm_minsize(self.minwidth, self.minheight)
  1840. self.window.tk.willdispatch()
  1841. import threading
  1842. threading.Thread(
  1843. target=serve, args=(port, self.ready, self.quit)).start()
  1844. def ready(self, server):
  1845. self.server = server
  1846. self.title_lbl.config(
  1847. text='Python documentation server at\n' + server.url)
  1848. self.open_btn.config(state='normal')
  1849. self.quit_btn.config(state='normal')
  1850. def open(self, event=None, url=None):
  1851. url = url or self.server.url
  1852. try:
  1853. import webbrowser
  1854. webbrowser.open(url)
  1855. except ImportError: # pre-webbrowser.py compatibility
  1856. if sys.platform == 'win32':
  1857. os.system('start "%s"' % url)
  1858. elif sys.platform == 'mac':
  1859. try: import ic
  1860. except ImportError: pass
  1861. else: ic.launchurl(url)
  1862. else:
  1863. rc = os.system('netscape -remote "openURL(%s)" &' % url)
  1864. if rc: os.system('netscape "%s" &' % url)
  1865. def quit(self, event=None):
  1866. if self.server:
  1867. self.server.quit = 1
  1868. self.window.quit()
  1869. def search(self, event=None):
  1870. key = self.search_ent.get()
  1871. self.stop_btn.pack(side='right')
  1872. self.stop_btn.config(state='normal')
  1873. self.search_lbl.config(text='Searching for "%s"...' % key)
  1874. self.search_ent.forget()
  1875. self.search_lbl.pack(side='left')
  1876. self.result_lst.delete(0, 'end')
  1877. self.goto_btn.config(state='disabled')
  1878. self.expand()
  1879. import threading
  1880. if self.scanner:
  1881. self.scanner.quit = 1
  1882. self.scanner = ModuleScanner()
  1883. threading.Thread(target=self.scanner.run,
  1884. args=(self.update, key, self.done)).start()
  1885. def update(self, path, modname, desc):
  1886. if modname[-9:] == '.__init__':
  1887. modname = modname[:-9] + ' (package)'
  1888. self.result_lst.insert('end',
  1889. modname + ' - ' + (desc or '(no description)'))
  1890. def stop(self, event=None):
  1891. if self.scanner:
  1892. self.scanner.quit = 1
  1893. self.scanner = None
  1894. def done(self):
  1895. self.scanner = None
  1896. self.search_lbl.config(text='Search for')
  1897. self.search_lbl.pack(side='left')
  1898. self.search_ent.pack(side='right', fill='x', expand=1)
  1899. if sys.platform != 'win32': self.stop_btn.forget()
  1900. self.stop_btn.config(state='disabled')
  1901. def select(self, event=None):
  1902. self.goto_btn.config(state='normal')
  1903. def goto(self, event=None):
  1904. selection = self.result_lst.curselection()
  1905. if selection:
  1906. modname = split(self.result_lst.get(selection[0]))[0]
  1907. self.open(url=self.server.url + modname + '.html')
  1908. def collapse(self):
  1909. if not self.expanded: return
  1910. self.result_frm.forget()
  1911. self.result_scr.forget()
  1912. self.result_lst.forget()
  1913. self.bigwidth = self.window.winfo_width()
  1914. self.bigheight = self.window.winfo_height()
  1915. self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  1916. self.window.wm_minsize(self.minwidth, self.minheight)
  1917. self.expanded = 0
  1918. def expand(self):
  1919. if self.expanded: return
  1920. self.result_frm.pack(side='bottom', fill='x')
  1921. self.result_scr.pack(side='right', fill='y')
  1922. self.result_lst.pack(side='top', fill='both', expand=1)
  1923. self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
  1924. self.window.wm_minsize(self.minwidth, self.bigminheight)
  1925. self.expanded = 1
  1926. def hide(self, event=None):
  1927. self.stop()
  1928. self.collapse()
  1929. import Tkinter
  1930. try:
  1931. root = Tkinter.Tk()
  1932. # Tk will crash if pythonw.exe has an XP .manifest
  1933. # file and the root has is not destroyed explicitly.
  1934. # If the problem is ever fixed in Tk, the explicit
  1935. # destroy can go.
  1936. try:
  1937. gui = GUI(root)
  1938. root.mainloop()
  1939. finally:
  1940. root.destroy()
  1941. except KeyboardInterrupt:
  1942. pass
  1943. # -------------------------------------------------- command-line interface
  1944. def ispath(x):
  1945. return isinstance(x, str) and find(x, os.sep) >= 0
  1946. def cli():
  1947. """Command-line interface (looks at sys.argv to decide what to do)."""
  1948. import getopt
  1949. class BadUsage: pass
  1950. # Scripts don't get the current directory in their path by default.
  1951. scriptdir = os.path.dirname(sys.argv[0])
  1952. if scriptdir in sys.path:
  1953. sys.path.remove(scriptdir)
  1954. sys.path.insert(0, '.')
  1955. try:
  1956. opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
  1957. writing = 0
  1958. for opt, val in opts:
  1959. if opt == '-g':
  1960. gui()
  1961. return
  1962. if opt == '-k':
  1963. apropos(val)
  1964. return
  1965. if opt == '-p':
  1966. try:
  1967. port = int(val)
  1968. except ValueError:
  1969. raise BadUsage
  1970. def ready(server):
  1971. print 'pydoc server ready at %s' % server.url
  1972. def stopped():
  1973. print 'pydoc server stopped'
  1974. serve(port, ready, stopped)
  1975. return
  1976. if opt == '-w':
  1977. writing = 1
  1978. if not args: raise BadUsage
  1979. for arg in args:
  1980. if ispath(arg) and not os.path.exists(arg):
  1981. print 'file %r does not exist' % arg
  1982. break
  1983. try:
  1984. if ispath(arg) and os.path.isfile(arg):
  1985. arg = importfile(arg)
  1986. if writing:
  1987. if ispath(arg) and os.path.isdir(arg):
  1988. writedocs(arg)
  1989. else:
  1990. writedoc(arg)
  1991. else:
  1992. help.help(arg)
  1993. except ErrorDuringImport, value:
  1994. print value
  1995. except (getopt.error, BadUsage):
  1996. cmd = os.path.basename(sys.argv[0])
  1997. print """pydoc - the Python documentation tool
  1998. %s <name> ...
  1999. Show text documentation on something. <name> may be the name of a
  2000. Python keyword, topic, function, module, or package, or a dotted
  2001. reference to a class or function within a module or module in a
  2002. package. If <name> contains a '%s', it is used as the path to a
  2003. Python source file to document. If name is 'keywords', 'topics',
  2004. or 'modules', a listing of these things is displayed.
  2005. %s -k <keyword>
  2006. Search for a keyword in the synopsis lines of all available modules.
  2007. %s -p <port>
  2008. Start an HTTP server on the given port on the local machine.
  2009. %s -g
  2010. Pop up a graphical interface for finding and serving documentation.
  2011. %s -w <name> ...
  2012. Write out the HTML documentation for a module to a file in the current
  2013. directory. If <name> contains a '%s', it is treated as a filename; if
  2014. it names a directory, documentation is written for all the contents.
  2015. """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
  2016. if __name__ == '__main__': cli()