blob: bbacf4606c85719c9d33f944a31175f32e43ebe7 [file] [log] [blame]
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001#!/usr/bin/env python
Ka-Ping Yee1d384632001-03-01 00:24:32 +00002"""Generate Python documentation in HTML or text for interactive use.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00003
4At the shell command line outside of Python, run "pydoc <name>" to show
5documentation on something. <name> may be the name of a Python function,
6module, package, or a dotted reference to a class or function within a
7module or module in a package. Alternatively, the argument can be the
8path to a Python source file.
9
10Or, at the shell prompt, run "pydoc -k <keyword>" to search for a keyword
11in the one-line descriptions of modules.
12
13Or, at the shell prompt, run "pydoc -p <port>" to start an HTTP server
14on a given port on the local machine to generate documentation web pages.
15
16Or, at the shell prompt, run "pydoc -w <name>" to write out the HTML
17documentation for a module to a file named "<name>.html".
18
19In the Python interpreter, do "from pydoc import help" to provide online
20help. Calling help(thing) on a Python object documents the object."""
21
22__author__ = "Ka-Ping Yee <ping@lfw.org>"
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000023__date__ = "26 February 2001"
Ka-Ping Yee09d7d9a2001-02-27 22:43:48 +000024__version__ = "$Revision$"
Ka-Ping Yee5e2b1732001-02-27 23:35:09 +000025__credits__ = """Guido van Rossum, for an excellent programming language.
26Tommy Burnette, the original creator of manpy.
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000027Paul Prescod, for all his work on onlinehelp.
28Richard Chamberlain, for the first implementation of textdoc.
29
Ka-Ping Yee5e2b1732001-02-27 23:35:09 +000030Mynd you, møøse bites Kan be pretty nasti..."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +000031
32import sys, imp, os, stat, re, types, inspect
33from repr import Repr
34from string import expandtabs, find, join, lower, split, strip, rstrip
35
36# --------------------------------------------------------- common routines
37
38def synopsis(filename, cache={}):
39 """Get the one-line summary out of a module file."""
40 mtime = os.stat(filename)[stat.ST_MTIME]
41 lastupdate, result = cache.get(filename, (0, None))
42 if lastupdate < mtime:
43 file = open(filename)
44 line = file.readline()
45 while line[:1] == '#' or strip(line) == '':
46 line = file.readline()
47 if not line: break
48 if line[-2:] == '\\\n':
49 line = line[:-2] + file.readline()
50 line = strip(line)
51 if line[:3] == '"""':
52 line = line[3:]
53 while strip(line) == '':
54 line = file.readline()
55 if not line: break
56 result = split(line, '"""')[0]
57 else: result = None
58 file.close()
59 cache[filename] = (mtime, result)
60 return result
61
62def index(dir):
63 """Return a list of (module-name, synopsis) pairs for a directory tree."""
64 results = []
65 for entry in os.listdir(dir):
66 path = os.path.join(dir, entry)
67 if ispackage(path):
68 results.extend(map(
69 lambda (m, s), pkg=entry: (pkg + '.' + m, s), index(path)))
70 elif os.path.isfile(path) and entry[-3:] == '.py':
71 results.append((entry[:-3], synopsis(path)))
72 return results
73
74def pathdirs():
75 """Convert sys.path into a list of absolute, existing, unique paths."""
76 dirs = []
Ka-Ping Yee1d384632001-03-01 00:24:32 +000077 normdirs = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +000078 for dir in sys.path:
79 dir = os.path.abspath(dir or '.')
Ka-Ping Yee1d384632001-03-01 00:24:32 +000080 normdir = os.path.normcase(dir)
81 if normdir not in normdirs and os.path.isdir(dir):
Ka-Ping Yeedd175342001-02-27 14:43:46 +000082 dirs.append(dir)
Ka-Ping Yee1d384632001-03-01 00:24:32 +000083 normdirs.append(normdir)
Ka-Ping Yeedd175342001-02-27 14:43:46 +000084 return dirs
85
86def getdoc(object):
87 """Get the doc string or comments for an object."""
88 result = inspect.getdoc(object)
89 if not result:
90 try: result = inspect.getcomments(object)
91 except: pass
92 return result and rstrip(result) or ''
93
94def classname(object, modname):
95 """Get a class name and qualify it with a module name if necessary."""
96 name = object.__name__
97 if object.__module__ != modname:
98 name = object.__module__ + '.' + name
99 return name
100
101def isconstant(object):
102 """Check if an object is of a type that probably means it's a constant."""
103 return type(object) in [
104 types.FloatType, types.IntType, types.ListType, types.LongType,
105 types.StringType, types.TupleType, types.TypeType,
106 hasattr(types, 'UnicodeType') and types.UnicodeType or 0]
107
108def replace(text, *pairs):
109 """Do a series of global replacements on a string."""
110 for old, new in pairs:
111 text = join(split(text, old), new)
112 return text
113
114def cram(text, maxlen):
115 """Omit part of a string if needed to make it fit in a maximum length."""
116 if len(text) > maxlen:
117 pre = max(0, (maxlen-3)/2)
118 post = max(0, maxlen-3-pre)
119 return text[:pre] + '...' + text[len(text)-post:]
120 return text
121
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000122def stripid(text):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000123 """Remove the hexadecimal id from a Python object representation."""
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000124 # The behaviour of %p is implementation-dependent, so we need an example.
125 for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']:
126 if re.search(pattern, repr(Exception)):
127 return re.sub(pattern, '>', text)
128 return text
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000129
130def modulename(path):
131 """Return the Python module name for a given path, or None."""
132 filename = os.path.basename(path)
133 if lower(filename[-3:]) == '.py':
134 return filename[:-3]
135 elif lower(filename[-4:]) == '.pyc':
136 return filename[:-4]
137 elif lower(filename[-11:]) == 'module.so':
138 return filename[:-11]
139 elif lower(filename[-13:]) == 'module.so.1':
140 return filename[:-13]
141
142class DocImportError(Exception):
143 """Class for errors while trying to import something to document it."""
144 def __init__(self, filename, etype, evalue):
145 self.filename = filename
146 self.etype = etype
147 self.evalue = evalue
148 if type(etype) is types.ClassType:
149 etype = etype.__name__
150 self.args = '%s: %s' % (etype, evalue)
151
152def importfile(path):
153 """Import a Python source file or compiled file given its path."""
154 magic = imp.get_magic()
155 file = open(path, 'r')
156 if file.read(len(magic)) == magic:
157 kind = imp.PY_COMPILED
158 else:
159 kind = imp.PY_SOURCE
160 file.close()
161 filename = os.path.basename(path)
162 name, ext = os.path.splitext(filename)
163 file = open(path, 'r')
164 try:
165 module = imp.load_module(name, file, path, (ext, 'r', kind))
166 except:
167 raise DocImportError(path, sys.exc_type, sys.exc_value)
168 file.close()
169 return module
170
171def ispackage(path):
172 """Guess whether a path refers to a package directory."""
173 if os.path.isdir(path):
174 init = os.path.join(path, '__init__.py')
175 initc = os.path.join(path, '__init__.pyc')
176 if os.path.isfile(init) or os.path.isfile(initc):
177 return 1
178
179# ---------------------------------------------------- formatter base class
180
181class Doc:
182 def document(self, object, *args):
183 """Generate documentation for an object."""
184 args = (object,) + args
185 if inspect.ismodule(object): return apply(self.docmodule, args)
186 if inspect.isclass(object): return apply(self.docclass, args)
187 if inspect.ismethod(object): return apply(self.docmethod, args)
188 if inspect.isbuiltin(object): return apply(self.docbuiltin, args)
189 if inspect.isfunction(object): return apply(self.docfunction, args)
190 raise TypeError, "don't know how to document objects of type " + \
191 type(object).__name__
192
193# -------------------------------------------- HTML documentation generator
194
195class HTMLRepr(Repr):
196 """Class for safely making an HTML representation of a Python object."""
197 def __init__(self):
198 Repr.__init__(self)
199 self.maxlist = self.maxtuple = self.maxdict = 10
200 self.maxstring = self.maxother = 50
201
202 def escape(self, text):
203 return replace(text, ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'))
204
205 def repr(self, object):
206 result = Repr.repr(self, object)
207 return result
208
209 def repr1(self, x, level):
210 methodname = 'repr_' + join(split(type(x).__name__), '_')
211 if hasattr(self, methodname):
212 return getattr(self, methodname)(x, level)
213 else:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000214 return self.escape(cram(stripid(repr(x)), self.maxother))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000215
216 def repr_string(self, x, level):
217 text = self.escape(cram(x, self.maxstring))
218 return re.sub(r'((\\[\\abfnrtv]|\\x..|\\u....)+)',
219 r'<font color="#c040c0">\1</font>', repr(text))
220
221 def repr_instance(self, x, level):
222 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000223 return cram(stripid(repr(x)), self.maxstring)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000224 except:
225 return self.escape('<%s instance>' % x.__class__.__name__)
226
227 repr_unicode = repr_string
228
229class HTMLDoc(Doc):
230 """Formatter class for HTML documentation."""
231
232 # ------------------------------------------- HTML formatting utilities
233
234 _repr_instance = HTMLRepr()
235 repr = _repr_instance.repr
236 escape = _repr_instance.escape
237
238 def preformat(self, text):
239 """Format literal preformatted text."""
240 text = self.escape(expandtabs(text))
241 return replace(text, ('\n\n', '\n \n'), ('\n\n', '\n \n'),
242 (' ', '&nbsp;'), ('\n', '<br>\n'))
243
244 def multicolumn(self, list, format, cols=4):
245 """Format a list of items into a multi-column list."""
246 result = ''
247 rows = (len(list)+cols-1)/cols
248
249 for col in range(cols):
250 result = result + '<td width="%d%%" valign=top>' % (100/cols)
251 for i in range(rows*col, rows*col+rows):
252 if i < len(list):
253 result = result + format(list[i]) + '<br>'
254 result = result + '</td>'
255 return '<table width="100%%"><tr>%s</tr></table>' % result
256
257 def heading(self, title, fgcol, bgcol, extras=''):
258 """Format a page heading."""
259 return """
260<p><table width="100%%" cellspacing=0 cellpadding=0 border=0>
261<tr bgcolor="%s"><td colspan=3 valign=bottom><small><small><br></small></small
262><font color="%s" face="helvetica, arial">&nbsp;%s</font></td
263><td align=right valign=bottom
264><font color="%s" face="helvetica, arial">&nbsp;%s</font></td></tr></table>
265 """ % (bgcol, fgcol, title, fgcol, extras)
266
267 def section(self, title, fgcol, bgcol, contents, width=20,
268 prelude='', marginalia=None, gap='&nbsp;&nbsp;&nbsp;'):
269 """Format a section with a heading."""
270 if marginalia is None:
271 marginalia = '&nbsp;' * width
272 result = """
273<p><table width="100%%" cellspacing=0 cellpadding=0 border=0>
274<tr bgcolor="%s"><td colspan=3 valign=bottom><small><small><br></small></small
275><font color="%s" face="helvetica, arial">&nbsp;%s</font></td></tr>
276 """ % (bgcol, fgcol, title)
277 if prelude:
278 result = result + """
279<tr><td bgcolor="%s">%s</td>
280<td bgcolor="%s" colspan=2>%s</td></tr>
281 """ % (bgcol, marginalia, bgcol, prelude)
282 result = result + """
283<tr><td bgcolor="%s">%s</td><td>%s</td>
284 """ % (bgcol, marginalia, gap)
285
286 result = result + '<td width="100%%">%s</td></tr></table>' % contents
287 return result
288
289 def bigsection(self, title, *args):
290 """Format a section with a big heading."""
291 title = '<big><strong>%s</strong></big>' % title
292 return apply(self.section, (title,) + args)
293
294 def footer(self):
295 return """
296<table width="100%"><tr><td align=right>
297<font face="helvetica, arial"><small><small>generated with
298<strong>htmldoc</strong> by Ka-Ping Yee</a></small></small></font>
299</td></tr></table>
300 """
301
302 def namelink(self, name, *dicts):
303 """Make a link for an identifier, given name-to-URL mappings."""
304 for dict in dicts:
305 if dict.has_key(name):
306 return '<a href="%s">%s</a>' % (dict[name], name)
307 return name
308
309 def classlink(self, object, modname, *dicts):
310 """Make a link for a class."""
311 name = object.__name__
312 if object.__module__ != modname:
313 name = object.__module__ + '.' + name
314 for dict in dicts:
315 if dict.has_key(object):
316 return '<a href="%s">%s</a>' % (dict[object], name)
317 return name
318
319 def modulelink(self, object):
320 """Make a link for a module."""
321 return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
322
323 def modpkglink(self, (name, path, ispackage, shadowed)):
324 """Make a link for a module or package to display in an index."""
325 if shadowed:
326 return '<font color="#909090">%s</font>' % name
327 if path:
328 url = '%s.%s.html' % (path, name)
329 else:
330 url = '%s.html' % name
331 if ispackage:
332 text = '<strong>%s</strong>&nbsp;(package)' % name
333 else:
334 text = name
335 return '<a href="%s">%s</a>' % (url, text)
336
337 def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
338 """Mark up some plain text, given a context of symbols to look for.
339 Each context dictionary maps object names to anchor names."""
340 escape = escape or self.escape
341 results = []
342 here = 0
343 pattern = re.compile(r'\b(((http|ftp)://\S+[\w/])|'
344 r'(RFC[- ]?(\d+))|'
345 r'(self\.)?(\w+))\b')
346 while 1:
347 match = pattern.search(text, here)
348 if not match: break
349 start, end = match.span()
350 results.append(escape(text[here:start]))
351
352 all, url, scheme, rfc, rfcnum, selfdot, name = match.groups()
353 if url:
354 results.append('<a href="%s">%s</a>' % (url, escape(url)))
355 elif rfc:
356 url = 'http://www.rfc-editor.org/rfc/rfc%s.txt' % rfcnum
357 results.append('<a href="%s">%s</a>' % (url, escape(rfc)))
358 else:
359 if text[end:end+1] == '(':
360 results.append(self.namelink(name, methods, funcs, classes))
361 elif selfdot:
362 results.append('self.<strong>%s</strong>' % name)
363 else:
364 results.append(self.namelink(name, classes))
365 here = end
366 results.append(escape(text[here:]))
367 return join(results, '')
368
369 # ---------------------------------------------- type-specific routines
370
371 def doctree(self, tree, modname, classes={}, parent=None):
372 """Produce HTML for a class tree as given by inspect.getclasstree()."""
373 result = ''
374 for entry in tree:
375 if type(entry) is type(()):
376 c, bases = entry
377 result = result + '<dt><font face="helvetica, arial"><small>'
378 result = result + self.classlink(c, modname, classes)
379 if bases and bases != (parent,):
380 parents = []
381 for base in bases:
382 parents.append(self.classlink(base, modname, classes))
383 result = result + '(' + join(parents, ', ') + ')'
384 result = result + '\n</small></font></dt>'
385 elif type(entry) is type([]):
386 result = result + \
387 '<dd>\n%s</dd>\n' % self.doctree(entry, modname, classes, c)
388 return '<dl>\n%s</dl>\n' % result
389
390 def docmodule(self, object):
391 """Produce HTML documentation for a module object."""
392 name = object.__name__
393 result = ''
394 head = '<br><big><big><strong>&nbsp;%s</strong></big></big>' % name
395 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000396 path = os.path.abspath(inspect.getfile(object))
397 filelink = '<a href="file:%s">%s</a>' % (path, path)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000398 except TypeError:
399 filelink = '(built-in)'
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000400 info = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000401 if hasattr(object, '__version__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000402 version = str(object.__version__)
Ka-Ping Yee40c49912001-02-27 22:46:01 +0000403 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
404 version = strip(version[11:-1])
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000405 info.append('version %s' % self.escape(version))
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000406 if hasattr(object, '__date__'):
407 info.append(self.escape(str(object.__date__)))
408 if info:
409 head = head + ' (%s)' % join(info, ', ')
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000410 result = result + self.heading(
411 head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
412
413 second = lambda list: list[1]
414 modules = map(second, inspect.getmembers(object, inspect.ismodule))
415
416 classes, cdict = [], {}
417 for key, value in inspect.getmembers(object, inspect.isclass):
418 if (inspect.getmodule(value) or object) is object:
419 classes.append(value)
420 cdict[key] = cdict[value] = '#' + key
421 funcs, fdict = [], {}
422 for key, value in inspect.getmembers(object, inspect.isroutine):
423 if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
424 funcs.append(value)
425 fdict[key] = '#-' + key
426 if inspect.isfunction(value): fdict[value] = fdict[key]
427 for c in classes:
428 for base in c.__bases__:
429 key, modname = base.__name__, base.__module__
430 if modname != name and sys.modules.has_key(modname):
431 module = sys.modules[modname]
432 if hasattr(module, key) and getattr(module, key) is base:
433 if not cdict.has_key(key):
434 cdict[key] = cdict[base] = modname + '.html#' + key
435 constants = []
436 for key, value in inspect.getmembers(object, isconstant):
437 if key[:1] != '_':
438 constants.append((key, value))
439
440 doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
441 doc = doc and '<tt>%s</tt>' % doc
442 result = result + '<p><small>%s</small></p>\n' % doc
443
444 if hasattr(object, '__path__'):
445 modpkgs = []
446 modnames = []
447 for file in os.listdir(object.__path__[0]):
448 if file[:1] != '_':
449 path = os.path.join(object.__path__[0], file)
450 modname = modulename(file)
451 if modname and modname not in modnames:
452 modpkgs.append((modname, name, 0, 0))
453 modnames.append(modname)
454 elif ispackage(path):
Tim Peters85ba6732001-02-28 08:26:44 +0000455 modpkgs.append((file, name, 1, 0))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000456 modpkgs.sort()
457 contents = self.multicolumn(modpkgs, self.modpkglink)
458 result = result + self.bigsection(
459 'Package Contents', '#ffffff', '#aa55cc', contents)
460
461 elif modules:
462 contents = self.multicolumn(modules, self.modulelink)
463 result = result + self.bigsection(
464 'Modules', '#fffff', '#aa55cc', contents)
465
466 if classes:
467 contents = self.doctree(
468 inspect.getclasstree(classes, 1), name, cdict)
469 for item in classes:
470 contents = contents + self.document(item, fdict, cdict)
471 result = result + self.bigsection(
472 'Classes', '#ffffff', '#ee77aa', contents)
473 if funcs:
474 contents = ''
475 for item in funcs:
476 contents = contents + self.document(item, fdict, cdict)
477 result = result + self.bigsection(
478 'Functions', '#ffffff', '#eeaa77', contents)
479
480 if constants:
481 contents = ''
482 for key, value in constants:
483 contents = contents + ('<br><strong>%s</strong> = %s' %
484 (key, self.repr(value)))
485 result = result + self.bigsection(
486 'Constants', '#ffffff', '#55aa55', contents)
487
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000488 if hasattr(object, '__author__'):
489 contents = self.markup(str(object.__author__), self.preformat)
490 result = result + self.bigsection(
491 'Author', '#ffffff', '#7799ee', contents)
492
493 if hasattr(object, '__credits__'):
494 contents = self.markup(str(object.__credits__), self.preformat)
495 result = result + self.bigsection(
496 'Credits', '#ffffff', '#7799ee', contents)
497
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000498 return result
499
500 def docclass(self, object, funcs={}, classes={}):
501 """Produce HTML documentation for a class object."""
502 name = object.__name__
503 bases = object.__bases__
504 contents = ''
505
506 methods, mdict = [], {}
507 for key, value in inspect.getmembers(object, inspect.ismethod):
508 methods.append(value)
509 mdict[key] = mdict[value] = '#' + name + '-' + key
510 for item in methods:
511 contents = contents + self.document(
512 item, funcs, classes, mdict, name)
513
514 title = '<a name="%s">class <strong>%s</strong></a>' % (name, name)
515 if bases:
516 parents = []
517 for base in bases:
518 parents.append(self.classlink(base, object.__module__, classes))
519 title = title + '(%s)' % join(parents, ', ')
520 doc = self.markup(getdoc(object), self.preformat,
521 funcs, classes, mdict)
522 if doc: doc = '<small><tt>' + doc + '<br>&nbsp;</tt></small>'
523 return self.section(title, '#000000', '#ffc8d8', contents, 10, doc)
524
525 def docmethod(self, object, funcs={}, classes={}, methods={}, clname=''):
526 """Produce HTML documentation for a method object."""
527 return self.document(
528 object.im_func, funcs, classes, methods, clname)
529
530 def formatvalue(self, object):
531 """Format an argument default value as text."""
532 return ('<small><font color="#909090">=%s</font></small>' %
533 self.repr(object))
534
535 def docfunction(self, object, funcs={}, classes={}, methods={}, clname=''):
536 """Produce HTML documentation for a function object."""
537 args, varargs, varkw, defaults = inspect.getargspec(object)
538 argspec = inspect.formatargspec(
539 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
540
541 if object.__name__ == '<lambda>':
542 decl = '<em>lambda</em> ' + argspec[1:-1]
543 else:
544 anchor = clname + '-' + object.__name__
545 decl = '<a name="%s"\n><strong>%s</strong>%s</a>\n' % (
546 anchor, object.__name__, argspec)
547 doc = self.markup(getdoc(object), self.preformat,
548 funcs, classes, methods)
549 doc = replace(doc, ('<br>\n', '</tt></small\n><dd><small><tt>'))
550 doc = doc and '<tt>%s</tt>' % doc
551 return '<dl><dt>%s<dd><small>%s</small></dl>' % (decl, doc)
552
553 def docbuiltin(self, object, *extras):
554 """Produce HTML documentation for a built-in function."""
555 return '<dl><dt><strong>%s</strong>(...)</dl>' % object.__name__
556
557 def page(self, object):
558 """Produce a complete HTML page of documentation for an object."""
559 return '''<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
560<html><title>Python: %s</title>
561<body bgcolor="#ffffff">
562%s
563</body></html>
564''' % (describe(object), self.document(object))
565
566 def index(self, dir, shadowed=None):
567 """Generate an HTML index for a directory of modules."""
568 modpkgs = []
569 if shadowed is None: shadowed = {}
570 seen = {}
571 files = os.listdir(dir)
572
573 def found(name, ispackage,
574 modpkgs=modpkgs, shadowed=shadowed, seen=seen):
575 if not seen.has_key(name):
576 modpkgs.append((name, '', ispackage, shadowed.has_key(name)))
577 seen[name] = 1
578 shadowed[name] = 1
579
580 # Package spam/__init__.py takes precedence over module spam.py.
581 for file in files:
582 path = os.path.join(dir, file)
583 if ispackage(path): found(file, 1)
584 for file in files:
585 path = os.path.join(dir, file)
Tim Peters85ba6732001-02-28 08:26:44 +0000586 if file[:1] != '_' and os.path.isfile(path):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000587 modname = modulename(file)
588 if modname: found(modname, 0)
589
590 modpkgs.sort()
591 contents = self.multicolumn(modpkgs, self.modpkglink)
592 return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
593
594# -------------------------------------------- text documentation generator
595
596class TextRepr(Repr):
597 """Class for safely making a text representation of a Python object."""
598 def __init__(self):
599 Repr.__init__(self)
600 self.maxlist = self.maxtuple = self.maxdict = 10
601 self.maxstring = self.maxother = 50
602
603 def repr1(self, x, level):
604 methodname = 'repr_' + join(split(type(x).__name__), '_')
605 if hasattr(self, methodname):
606 return getattr(self, methodname)(x, level)
607 else:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000608 return cram(stripid(repr(x)), self.maxother)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000609
610 def repr_instance(self, x, level):
611 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000612 return cram(stripid(repr(x)), self.maxstring)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000613 except:
614 return '<%s instance>' % x.__class__.__name__
615
616class TextDoc(Doc):
617 """Formatter class for text documentation."""
618
619 # ------------------------------------------- text formatting utilities
620
621 _repr_instance = TextRepr()
622 repr = _repr_instance.repr
623
624 def bold(self, text):
625 """Format a string in bold by overstriking."""
626 return join(map(lambda ch: ch + '\b' + ch, text), '')
627
628 def indent(self, text, prefix=' '):
629 """Indent text by prepending a given prefix to each line."""
630 if not text: return ''
631 lines = split(text, '\n')
632 lines = map(lambda line, prefix=prefix: prefix + line, lines)
633 if lines: lines[-1] = rstrip(lines[-1])
634 return join(lines, '\n')
635
636 def section(self, title, contents):
637 """Format a section with a given heading."""
638 return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
639
640 # ---------------------------------------------- type-specific routines
641
642 def doctree(self, tree, modname, parent=None, prefix=''):
643 """Render in text a class tree as returned by inspect.getclasstree()."""
644 result = ''
645 for entry in tree:
646 if type(entry) is type(()):
647 cl, bases = entry
648 result = result + prefix + classname(cl, modname)
649 if bases and bases != (parent,):
650 parents = map(lambda cl, m=modname: classname(cl, m), bases)
651 result = result + '(%s)' % join(parents, ', ')
652 result = result + '\n'
653 elif type(entry) is type([]):
654 result = result + self.doctree(
655 entry, modname, cl, prefix + ' ')
656 return result
657
658 def docmodule(self, object):
659 """Produce text documentation for a given module object."""
660 result = ''
661
662 name = object.__name__
663 lines = split(strip(getdoc(object)), '\n')
664 if len(lines) == 1:
665 if lines[0]: name = name + ' - ' + lines[0]
666 lines = []
667 elif len(lines) >= 2 and not rstrip(lines[1]):
668 if lines[0]: name = name + ' - ' + lines[0]
669 lines = lines[2:]
670 result = result + self.section('NAME', name)
671 try: file = inspect.getfile(object) # XXX or getsourcefile?
672 except TypeError: file = None
673 result = result + self.section('FILE', file or '(built-in)')
674 if lines:
675 result = result + self.section('DESCRIPTION', join(lines, '\n'))
676
677 classes = []
678 for key, value in inspect.getmembers(object, inspect.isclass):
679 if (inspect.getmodule(value) or object) is object:
680 classes.append(value)
681 funcs = []
682 for key, value in inspect.getmembers(object, inspect.isroutine):
683 if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
684 funcs.append(value)
685 constants = []
686 for key, value in inspect.getmembers(object, isconstant):
687 if key[:1] != '_':
688 constants.append((key, value))
689
690 if hasattr(object, '__path__'):
691 modpkgs = []
692 for file in os.listdir(object.__path__[0]):
693 if file[:1] != '_':
694 path = os.path.join(object.__path__[0], file)
695 modname = modulename(file)
696 if modname and modname not in modpkgs:
697 modpkgs.append(modname)
698 elif ispackage(path):
699 modpkgs.append(file + ' (package)')
700 modpkgs.sort()
701 result = result + self.section(
702 'PACKAGE CONTENTS', join(modpkgs, '\n'))
703
704 if classes:
705 contents = self.doctree(
706 inspect.getclasstree(classes, 1), object.__name__) + '\n'
707 for item in classes:
708 contents = contents + self.document(item) + '\n'
709 result = result + self.section('CLASSES', contents)
710
711 if funcs:
712 contents = ''
713 for item in funcs:
714 contents = contents + self.document(item) + '\n'
715 result = result + self.section('FUNCTIONS', contents)
716
717 if constants:
718 contents = ''
719 for key, value in constants:
720 line = key + ' = ' + self.repr(value)
721 chop = 70 - len(line)
722 line = self.bold(key) + ' = ' + self.repr(value)
723 if chop < 0: line = line[:chop] + '...'
724 contents = contents + line + '\n'
725 result = result + self.section('CONSTANTS', contents)
726
727 if hasattr(object, '__version__'):
728 version = str(object.__version__)
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000729 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
730 version = strip(version[11:-1])
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000731 result = result + self.section('VERSION', version)
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000732 if hasattr(object, '__date__'):
733 result = result + self.section('DATE', str(object.__date__))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000734 if hasattr(object, '__author__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000735 result = result + self.section('AUTHOR', str(object.__author__))
736 if hasattr(object, '__credits__'):
737 result = result + self.section('CREDITS', str(object.__credits__))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000738 return result
739
740 def docclass(self, object):
741 """Produce text documentation for a given class object."""
742 name = object.__name__
743 bases = object.__bases__
744
745 title = 'class ' + self.bold(name)
746 if bases:
747 parents = map(lambda c, m=object.__module__: classname(c, m), bases)
748 title = title + '(%s)' % join(parents, ', ')
749
750 doc = getdoc(object)
751 contents = doc and doc + '\n'
752 methods = map(lambda (key, value): value,
753 inspect.getmembers(object, inspect.ismethod))
754 for item in methods:
755 contents = contents + '\n' + self.document(item)
756
757 if not contents: return title + '\n'
758 return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n'
759
760 def docmethod(self, object):
761 """Produce text documentation for a method object."""
762 return self.document(object.im_func)
763
764 def formatvalue(self, object):
765 """Format an argument default value as text."""
766 return '=' + self.repr(object)
767
768 def docfunction(self, object):
769 """Produce text documentation for a function object."""
770 try:
771 args, varargs, varkw, defaults = inspect.getargspec(object)
772 argspec = inspect.formatargspec(
773 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
774 except TypeError:
775 argspec = '(...)'
776
777 if object.__name__ == '<lambda>':
778 decl = '<lambda> ' + argspec[1:-1]
779 else:
780 decl = self.bold(object.__name__) + argspec
781 doc = getdoc(object)
782 if doc:
783 return decl + '\n' + rstrip(self.indent(doc)) + '\n'
784 else:
785 return decl + '\n'
786
787 def docbuiltin(self, object):
788 """Produce text documentation for a built-in function object."""
789 return (self.bold(object.__name__) + '(...)\n' +
790 rstrip(self.indent(object.__doc__)) + '\n')
791
792# --------------------------------------------------------- user interfaces
793
794def pager(text):
795 """The first time this is called, determine what kind of pager to use."""
796 global pager
797 pager = getpager()
798 pager(text)
799
800def getpager():
801 """Decide what method to use for paging through text."""
802 if type(sys.stdout) is not types.FileType:
803 return plainpager
804 if not sys.stdin.isatty() or not sys.stdout.isatty():
805 return plainpager
806 if os.environ.has_key('PAGER'):
807 return lambda a: pipepager(a, os.environ['PAGER'])
808 if sys.platform in ['win', 'win32', 'nt']:
809 return lambda a: tempfilepager(a, 'more')
810 if hasattr(os, 'system') and os.system('less 2>/dev/null') == 0:
811 return lambda a: pipepager(a, 'less')
812
813 import tempfile
814 filename = tempfile.mktemp()
815 open(filename, 'w').close()
816 try:
817 if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
818 return lambda text: pipepager(text, 'more')
819 else:
820 return ttypager
821 finally:
822 os.unlink(filename)
823
824def pipepager(text, cmd):
825 """Page through text by feeding it to another program."""
826 pipe = os.popen(cmd, 'w')
827 try:
828 pipe.write(text)
829 pipe.close()
830 except IOError:
831 # Ignore broken pipes caused by quitting the pager program.
832 pass
833
834def tempfilepager(text, cmd):
835 """Page through text by invoking a program on a temporary file."""
836 import tempfile
837 filename = tempfile.mktemp()
838 file = open(filename, 'w')
839 file.write(text)
840 file.close()
841 try:
842 os.system(cmd + ' ' + filename)
843 finally:
844 os.unlink(filename)
845
846def plain(text):
847 """Remove boldface formatting from text."""
848 return re.sub('.\b', '', text)
849
850def ttypager(text):
851 """Page through text on a text terminal."""
852 lines = split(plain(text), '\n')
853 try:
854 import tty
855 fd = sys.stdin.fileno()
856 old = tty.tcgetattr(fd)
857 tty.setcbreak(fd)
858 getchar = lambda: sys.stdin.read(1)
Ka-Ping Yee457aab22001-02-27 23:36:29 +0000859 except (ImportError, AttributeError):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000860 tty = None
861 getchar = lambda: sys.stdin.readline()[:-1][:1]
862
863 try:
864 r = inc = os.environ.get('LINES', 25) - 1
865 sys.stdout.write(join(lines[:inc], '\n') + '\n')
866 while lines[r:]:
867 sys.stdout.write('-- more --')
868 sys.stdout.flush()
869 c = getchar()
870
871 if c in ['q', 'Q']:
872 sys.stdout.write('\r \r')
873 break
874 elif c in ['\r', '\n']:
875 sys.stdout.write('\r \r' + lines[r] + '\n')
876 r = r + 1
877 continue
878 if c in ['b', 'B', '\x1b']:
879 r = r - inc - inc
880 if r < 0: r = 0
881 sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
882 r = r + inc
883
884 finally:
885 if tty:
886 tty.tcsetattr(fd, tty.TCSAFLUSH, old)
887
888def plainpager(text):
889 """Simply print unformatted text. This is the ultimate fallback."""
890 sys.stdout.write(plain(text))
891
892def describe(thing):
893 """Produce a short description of the given kind of thing."""
894 if inspect.ismodule(thing):
895 if thing.__name__ in sys.builtin_module_names:
896 return 'built-in module ' + thing.__name__
897 if hasattr(thing, '__path__'):
898 return 'package ' + thing.__name__
899 else:
900 return 'module ' + thing.__name__
901 if inspect.isbuiltin(thing):
902 return 'built-in function ' + thing.__name__
903 if inspect.isclass(thing):
904 return 'class ' + thing.__name__
905 if inspect.isfunction(thing):
906 return 'function ' + thing.__name__
907 if inspect.ismethod(thing):
908 return 'method ' + thing.__name__
909 return repr(thing)
910
911def locate(path):
912 """Locate an object by name (or dotted path), importing as necessary."""
913 if not path: # special case: imp.find_module('') strangely succeeds
914 return None, None
915 if type(path) is not types.StringType:
916 return None, path
917 if hasattr(__builtins__, path):
918 return None, getattr(__builtins__, path)
919 parts = split(path, '.')
920 n = 1
921 while n <= len(parts):
922 path = join(parts[:n], '.')
923 try:
924 module = __import__(path)
925 module = reload(module)
926 except:
927 # Did the error occur before or after we found the module?
928 if sys.modules.has_key(path):
929 filename = sys.modules[path].__file__
930 elif sys.exc_type is SyntaxError:
931 filename = sys.exc_value.filename
932 else:
933 # module not found, so stop looking
934 break
935 # error occurred in the imported module, so report it
936 raise DocImportError(filename, sys.exc_type, sys.exc_value)
937 try:
938 x = module
939 for p in parts[1:]:
940 x = getattr(x, p)
941 return join(parts[:-1], '.'), x
942 except AttributeError:
943 n = n + 1
944 continue
945 return None, None
946
947# --------------------------------------- interactive interpreter interface
948
949text = TextDoc()
950html = HTMLDoc()
951
952def doc(thing):
953 """Display documentation on an object (for interactive use)."""
954 if type(thing) is type(""):
955 try:
956 path, x = locate(thing)
957 except DocImportError, value:
958 print 'problem in %s - %s' % (value.filename, value.args)
959 return
960 if x:
961 thing = x
962 else:
963 print 'could not find or import %s' % repr(thing)
964 return
965
966 desc = describe(thing)
967 module = inspect.getmodule(thing)
968 if module and module is not thing:
969 desc = desc + ' in module ' + module.__name__
970 pager('Help on %s:\n\n' % desc + text.document(thing))
971
972def writedocs(path, pkgpath=''):
973 if os.path.isdir(path):
974 dir = path
975 for file in os.listdir(dir):
976 path = os.path.join(dir, file)
977 if os.path.isdir(path):
978 writedocs(path, file + '.' + pkgpath)
979 if os.path.isfile(path):
980 writedocs(path, pkgpath)
981 if os.path.isfile(path):
982 modname = modulename(path)
983 if modname:
984 writedoc(pkgpath + modname)
985
986def writedoc(key):
987 """Write HTML documentation to a file in the current directory."""
988 path, object = locate(key)
989 if object:
990 file = open(key + '.html', 'w')
991 file.write(html.page(object))
992 file.close()
993 print 'wrote', key + '.html'
994
995class Helper:
996 def __repr__(self):
997 return """To get help on a Python object, call help(object).
998To get help on a module or package, either import it before calling
999help(module) or call help('modulename')."""
1000
1001 def __call__(self, *args):
1002 if args:
1003 doc(args[0])
1004 else:
1005 print repr(self)
1006
1007help = Helper()
1008
1009def man(key):
1010 """Display documentation on an object in a form similar to man(1)."""
1011 path, object = locate(key)
1012 if object:
1013 title = 'Python Library Documentation: ' + describe(object)
1014 if path: title = title + ' in ' + path
1015 pager('\n' + title + '\n\n' + text.document(object))
1016 found = 1
1017 else:
1018 print 'could not find or import %s' % repr(key)
1019
1020def apropos(key):
1021 """Print all the one-line module summaries that contain a substring."""
1022 key = lower(key)
1023 for module in sys.builtin_module_names:
1024 desc = __import__(module).__doc__ or ''
1025 desc = split(desc, '\n')[0]
1026 if find(lower(module + ' ' + desc), key) >= 0:
1027 print module, '-', desc or '(no description)'
1028 modules = []
1029 for dir in pathdirs():
1030 for module, desc in index(dir):
1031 desc = desc or ''
1032 if module not in modules:
1033 modules.append(module)
1034 if find(lower(module + ' ' + desc), key) >= 0:
1035 desc = desc or '(no description)'
1036 if module[-9:] == '.__init__':
1037 print module[:-9], '(package) -', desc
1038 else:
1039 print module, '-', desc
1040
1041# --------------------------------------------------- web browser interface
1042
1043def serve(address, callback=None):
1044 import BaseHTTPServer, mimetools
1045
1046 # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
1047 class Message(mimetools.Message):
1048 def __init__(self, fp, seekable=1):
1049 Message = self.__class__
1050 Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
1051 self.encodingheader = self.getheader('content-transfer-encoding')
1052 self.typeheader = self.getheader('content-type')
1053 self.parsetype()
1054 self.parseplist()
1055
1056 class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
1057 def send_document(self, title, contents):
1058 self.send_response(200)
1059 self.send_header('Content-Type', 'text/html')
1060 self.end_headers()
1061 self.wfile.write(
1062'''<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
1063<html><title>Python: %s</title><body bgcolor="#ffffff">''' % title)
1064 self.wfile.write(contents)
1065 self.wfile.write('</body></html>')
1066
1067 def do_GET(self):
1068 path = self.path
1069 if path[-5:] == '.html': path = path[:-5]
1070 if path[:1] == '/': path = path[1:]
1071 if path and path != '.':
1072 try:
1073 p, x = locate(path)
1074 except DocImportError, value:
1075 self.send_document(path, html.escape(
1076 'problem with %s - %s' % (value.filename, value.args)))
1077 return
1078 if x:
1079 self.send_document(describe(x), html.document(x))
1080 else:
1081 self.send_document(path,
1082'There is no Python module or object named "%s".' % path)
1083 else:
1084 heading = html.heading(
1085 '<br><big><big><strong>&nbsp;'
1086 'Python: Index of Modules'
1087 '</strong></big></big>',
1088 '#ffffff', '#7799ee')
1089 builtins = []
1090 for name in sys.builtin_module_names:
1091 builtins.append('<a href="%s.html">%s</a>' % (name, name))
1092 indices = ['<p>Built-in modules: ' + join(builtins, ', ')]
1093 seen = {}
1094 for dir in pathdirs():
1095 indices.append(html.index(dir, seen))
1096 self.send_document('Index of Modules', heading + join(indices))
1097
1098 def log_message(self, *args): pass
1099
1100 class DocServer(BaseHTTPServer.HTTPServer):
1101 def __init__(self, address, callback):
1102 self.callback = callback
1103 self.base.__init__(self, address, self.handler)
1104
1105 def server_activate(self):
1106 self.base.server_activate(self)
1107 if self.callback: self.callback()
1108
1109 DocServer.base = BaseHTTPServer.HTTPServer
1110 DocServer.handler = DocHandler
1111 DocHandler.MessageClass = Message
1112 try:
1113 DocServer(address, callback).serve_forever()
1114 except KeyboardInterrupt:
1115 print 'server stopped'
1116
1117# -------------------------------------------------- command-line interface
1118
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001119def cli():
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001120 import getopt
1121 class BadUsage: pass
1122
1123 try:
1124 opts, args = getopt.getopt(sys.argv[1:], 'k:p:w')
1125 writing = 0
1126
1127 for opt, val in opts:
1128 if opt == '-k':
1129 apropos(lower(val))
1130 break
1131 if opt == '-p':
1132 try:
1133 port = int(val)
1134 except ValueError:
1135 raise BadUsage
1136 def ready(port=port):
1137 print 'server ready at http://127.0.0.1:%d/' % port
1138 serve(('127.0.0.1', port), ready)
1139 break
1140 if opt == '-w':
1141 if not args: raise BadUsage
1142 writing = 1
1143 else:
1144 if args:
1145 for arg in args:
1146 try:
1147 if os.path.isfile(arg):
1148 arg = importfile(arg)
1149 if writing:
1150 if os.path.isdir(arg): writedocs(arg)
1151 else: writedoc(arg)
1152 else: man(arg)
1153 except DocImportError, value:
1154 print 'problem in %s - %s' % (
1155 value.filename, value.args)
1156 else:
1157 if sys.platform in ['mac', 'win', 'win32', 'nt']:
1158 # GUI platforms with threading
1159 import threading
1160 ready = threading.Event()
1161 address = ('127.0.0.1', 12346)
1162 threading.Thread(
1163 target=serve, args=(address, ready.set)).start()
1164 ready.wait()
1165 import webbrowser
1166 webbrowser.open('http://127.0.0.1:12346/')
1167 else:
1168 raise BadUsage
1169
1170 except (getopt.error, BadUsage):
1171 print """%s <name> ...
1172 Show documentation on something.
1173 <name> may be the name of a Python function, module, or package,
1174 or a dotted reference to a class or function within a module or
1175 module in a package, or the filename of a Python module to import.
1176
1177%s -k <keyword>
1178 Search for a keyword in the synopsis lines of all modules.
1179
1180%s -p <port>
1181 Start an HTTP server on the given port on the local machine.
1182
1183%s -w <module> ...
1184 Write out the HTML documentation for a module to a file.
1185
1186%s -w <moduledir>
1187 Write out the HTML documentation for all modules in the tree
1188 under a given directory to files in the current directory.
1189""" % ((sys.argv[0],) * 5)
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001190
1191if __name__ == '__main__':
1192 cli()