blob: 3b5c20abb7465642f69091c8fc83d932b8f067f6 [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
Ka-Ping Yeedd175342001-02-27 14:43:46 +00004In the Python interpreter, do "from pydoc import help" to provide online
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00005help. Calling help(thing) on a Python object documents the object.
6
7At the shell command line outside of Python:
8 Run "pydoc <name>" to show documentation on something. <name> may be
9 the name of a function, module, package, or a dotted reference to a
10 class or function within a module or module in a package. If the
11 argument contains a path segment delimiter (e.g. slash on Unix,
12 backslash on Windows) it is treated as the path to a Python source file.
13
14 Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
15 of all available modules.
16
17 Run "pydoc -p <port>" to start an HTTP server on a given port on the
18 local machine to generate documentation web pages.
19
20 For platforms without a command line, "pydoc -g" starts the HTTP server
21 and also pops up a little window for controlling it.
22
23 Run "pydoc -w <name>" to write out the HTML documentation for a module
24 to a file named "<name>.html".
25"""
Ka-Ping Yeedd175342001-02-27 14:43:46 +000026
27__author__ = "Ka-Ping Yee <ping@lfw.org>"
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000028__date__ = "26 February 2001"
Ka-Ping Yee09d7d9a2001-02-27 22:43:48 +000029__version__ = "$Revision$"
Ka-Ping Yee5e2b1732001-02-27 23:35:09 +000030__credits__ = """Guido van Rossum, for an excellent programming language.
31Tommy Burnette, the original creator of manpy.
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +000032Paul Prescod, for all his work on onlinehelp.
33Richard Chamberlain, for the first implementation of textdoc.
34
Ka-Ping Yee5e2b1732001-02-27 23:35:09 +000035Mynd you, møøse bites Kan be pretty nasti..."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +000036
Ka-Ping Yee66efbc72001-03-01 13:55:20 +000037# Note: this module is designed to deploy instantly and run under any
38# version of Python from 1.5 and up. That's why it's a single file and
39# some 2.0 features (like string methods) are conspicuously avoided.
40
Ka-Ping Yeedd175342001-02-27 14:43:46 +000041import sys, imp, os, stat, re, types, inspect
42from repr import Repr
43from string import expandtabs, find, join, lower, split, strip, rstrip
44
45# --------------------------------------------------------- common routines
46
47def synopsis(filename, cache={}):
48 """Get the one-line summary out of a module file."""
49 mtime = os.stat(filename)[stat.ST_MTIME]
50 lastupdate, result = cache.get(filename, (0, None))
51 if lastupdate < mtime:
52 file = open(filename)
53 line = file.readline()
54 while line[:1] == '#' or strip(line) == '':
55 line = file.readline()
56 if not line: break
57 if line[-2:] == '\\\n':
58 line = line[:-2] + file.readline()
59 line = strip(line)
60 if line[:3] == '"""':
61 line = line[3:]
62 while strip(line) == '':
63 line = file.readline()
64 if not line: break
Ka-Ping Yee239432a2001-03-02 02:45:08 +000065 result = strip(split(line, '"""')[0])
Ka-Ping Yeedd175342001-02-27 14:43:46 +000066 else: result = None
67 file.close()
68 cache[filename] = (mtime, result)
69 return result
70
Ka-Ping Yeedd175342001-02-27 14:43:46 +000071def pathdirs():
72 """Convert sys.path into a list of absolute, existing, unique paths."""
73 dirs = []
Ka-Ping Yee1d384632001-03-01 00:24:32 +000074 normdirs = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +000075 for dir in sys.path:
76 dir = os.path.abspath(dir or '.')
Ka-Ping Yee1d384632001-03-01 00:24:32 +000077 normdir = os.path.normcase(dir)
78 if normdir not in normdirs and os.path.isdir(dir):
Ka-Ping Yeedd175342001-02-27 14:43:46 +000079 dirs.append(dir)
Ka-Ping Yee1d384632001-03-01 00:24:32 +000080 normdirs.append(normdir)
Ka-Ping Yeedd175342001-02-27 14:43:46 +000081 return dirs
82
83def getdoc(object):
84 """Get the doc string or comments for an object."""
85 result = inspect.getdoc(object)
86 if not result:
87 try: result = inspect.getcomments(object)
88 except: pass
Ka-Ping Yee239432a2001-03-02 02:45:08 +000089 return result and re.sub('^ *\n', '', rstrip(result)) or ''
Ka-Ping Yeedd175342001-02-27 14:43:46 +000090
91def classname(object, modname):
92 """Get a class name and qualify it with a module name if necessary."""
93 name = object.__name__
94 if object.__module__ != modname:
95 name = object.__module__ + '.' + name
96 return name
97
98def isconstant(object):
99 """Check if an object is of a type that probably means it's a constant."""
100 return type(object) in [
101 types.FloatType, types.IntType, types.ListType, types.LongType,
102 types.StringType, types.TupleType, types.TypeType,
103 hasattr(types, 'UnicodeType') and types.UnicodeType or 0]
104
105def replace(text, *pairs):
106 """Do a series of global replacements on a string."""
107 for old, new in pairs:
108 text = join(split(text, old), new)
109 return text
110
111def cram(text, maxlen):
112 """Omit part of a string if needed to make it fit in a maximum length."""
113 if len(text) > maxlen:
114 pre = max(0, (maxlen-3)/2)
115 post = max(0, maxlen-3-pre)
116 return text[:pre] + '...' + text[len(text)-post:]
117 return text
118
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000119def stripid(text):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000120 """Remove the hexadecimal id from a Python object representation."""
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000121 # The behaviour of %p is implementation-dependent, so we need an example.
122 for pattern in [' at 0x[0-9a-f]{6,}>$', ' at [0-9A-F]{8,}>$']:
123 if re.search(pattern, repr(Exception)):
124 return re.sub(pattern, '>', text)
125 return text
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000126
127def modulename(path):
128 """Return the Python module name for a given path, or None."""
129 filename = os.path.basename(path)
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000130 suffixes = map(lambda (suffix, mode, kind): (len(suffix), suffix),
131 imp.get_suffixes())
132 suffixes.sort()
133 suffixes.reverse() # try longest suffixes first, in case they overlap
134 for length, suffix in suffixes:
135 if len(filename) > length and filename[-length:] == suffix:
136 return filename[:-length]
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000137
138class DocImportError(Exception):
139 """Class for errors while trying to import something to document it."""
140 def __init__(self, filename, etype, evalue):
141 self.filename = filename
142 self.etype = etype
143 self.evalue = evalue
144 if type(etype) is types.ClassType:
145 etype = etype.__name__
146 self.args = '%s: %s' % (etype, evalue)
147
148def importfile(path):
149 """Import a Python source file or compiled file given its path."""
150 magic = imp.get_magic()
151 file = open(path, 'r')
152 if file.read(len(magic)) == magic:
153 kind = imp.PY_COMPILED
154 else:
155 kind = imp.PY_SOURCE
156 file.close()
157 filename = os.path.basename(path)
158 name, ext = os.path.splitext(filename)
159 file = open(path, 'r')
160 try:
161 module = imp.load_module(name, file, path, (ext, 'r', kind))
162 except:
163 raise DocImportError(path, sys.exc_type, sys.exc_value)
164 file.close()
165 return module
166
167def ispackage(path):
168 """Guess whether a path refers to a package directory."""
169 if os.path.isdir(path):
170 init = os.path.join(path, '__init__.py')
171 initc = os.path.join(path, '__init__.pyc')
172 if os.path.isfile(init) or os.path.isfile(initc):
173 return 1
174
175# ---------------------------------------------------- formatter base class
176
177class Doc:
178 def document(self, object, *args):
179 """Generate documentation for an object."""
180 args = (object,) + args
181 if inspect.ismodule(object): return apply(self.docmodule, args)
182 if inspect.isclass(object): return apply(self.docclass, args)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000183 if inspect.isroutine(object): return apply(self.docroutine, args)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000184 raise TypeError, "don't know how to document objects of type " + \
185 type(object).__name__
186
187# -------------------------------------------- HTML documentation generator
188
189class HTMLRepr(Repr):
190 """Class for safely making an HTML representation of a Python object."""
191 def __init__(self):
192 Repr.__init__(self)
193 self.maxlist = self.maxtuple = self.maxdict = 10
194 self.maxstring = self.maxother = 50
195
196 def escape(self, text):
197 return replace(text, ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'))
198
199 def repr(self, object):
200 result = Repr.repr(self, object)
201 return result
202
203 def repr1(self, x, level):
204 methodname = 'repr_' + join(split(type(x).__name__), '_')
205 if hasattr(self, methodname):
206 return getattr(self, methodname)(x, level)
207 else:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000208 return self.escape(cram(stripid(repr(x)), self.maxother))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000209
210 def repr_string(self, x, level):
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000211 test = cram(x, self.maxstring)
212 testrepr = repr(test)
213 if '\\' in test and '\\' not in replace(testrepr, (r'\\', '')):
214 # Backslashes are only literal in the string and are never
215 # needed to make any special characters, so show a raw string.
216 return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
217 return re.sub(r'((\\[\\abfnrtv\'"]|\\x..|\\u....)+)',
218 r'<font color="#c040c0">\1</font>',
219 self.escape(testrepr))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000220
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>
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000261<tr bgcolor="%s"><td>&nbsp;</td>
262<td valign=bottom><small><small><br></small></small
263><font color="%s" face="helvetica"><br>&nbsp;%s</font></td
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000264><td align=right valign=bottom
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000265><font color="%s" face="helvetica">%s</font></td><td>&nbsp;</td></tr></table>
266 """ % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000267
268 def section(self, title, fgcol, bgcol, contents, width=20,
269 prelude='', marginalia=None, gap='&nbsp;&nbsp;&nbsp;'):
270 """Format a section with a heading."""
271 if marginalia is None:
272 marginalia = '&nbsp;' * width
273 result = """
274<p><table width="100%%" cellspacing=0 cellpadding=0 border=0>
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000275<tr bgcolor="%s"><td rowspan=2>&nbsp;</td>
276<td colspan=3 valign=bottom><small><small><br></small></small
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000277><font color="%s" face="helvetica, arial">&nbsp;%s</font></td></tr>
278 """ % (bgcol, fgcol, title)
279 if prelude:
280 result = result + """
281<tr><td bgcolor="%s">%s</td>
282<td bgcolor="%s" colspan=2>%s</td></tr>
283 """ % (bgcol, marginalia, bgcol, prelude)
284 result = result + """
285<tr><td bgcolor="%s">%s</td><td>%s</td>
286 """ % (bgcol, marginalia, gap)
287
288 result = result + '<td width="100%%">%s</td></tr></table>' % contents
289 return result
290
291 def bigsection(self, title, *args):
292 """Format a section with a big heading."""
293 title = '<big><strong>%s</strong></big>' % title
294 return apply(self.section, (title,) + args)
295
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000296 def namelink(self, name, *dicts):
297 """Make a link for an identifier, given name-to-URL mappings."""
298 for dict in dicts:
299 if dict.has_key(name):
300 return '<a href="%s">%s</a>' % (dict[name], name)
301 return name
302
303 def classlink(self, object, modname, *dicts):
304 """Make a link for a class."""
305 name = object.__name__
306 if object.__module__ != modname:
307 name = object.__module__ + '.' + name
308 for dict in dicts:
309 if dict.has_key(object):
310 return '<a href="%s">%s</a>' % (dict[object], name)
311 return name
312
313 def modulelink(self, object):
314 """Make a link for a module."""
315 return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
316
317 def modpkglink(self, (name, path, ispackage, shadowed)):
318 """Make a link for a module or package to display in an index."""
319 if shadowed:
320 return '<font color="#909090">%s</font>' % name
321 if path:
322 url = '%s.%s.html' % (path, name)
323 else:
324 url = '%s.html' % name
325 if ispackage:
326 text = '<strong>%s</strong>&nbsp;(package)' % name
327 else:
328 text = name
329 return '<a href="%s">%s</a>' % (url, text)
330
331 def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
332 """Mark up some plain text, given a context of symbols to look for.
333 Each context dictionary maps object names to anchor names."""
334 escape = escape or self.escape
335 results = []
336 here = 0
337 pattern = re.compile(r'\b(((http|ftp)://\S+[\w/])|'
338 r'(RFC[- ]?(\d+))|'
339 r'(self\.)?(\w+))\b')
340 while 1:
341 match = pattern.search(text, here)
342 if not match: break
343 start, end = match.span()
344 results.append(escape(text[here:start]))
345
346 all, url, scheme, rfc, rfcnum, selfdot, name = match.groups()
347 if url:
348 results.append('<a href="%s">%s</a>' % (url, escape(url)))
349 elif rfc:
350 url = 'http://www.rfc-editor.org/rfc/rfc%s.txt' % rfcnum
351 results.append('<a href="%s">%s</a>' % (url, escape(rfc)))
352 else:
353 if text[end:end+1] == '(':
354 results.append(self.namelink(name, methods, funcs, classes))
355 elif selfdot:
356 results.append('self.<strong>%s</strong>' % name)
357 else:
358 results.append(self.namelink(name, classes))
359 here = end
360 results.append(escape(text[here:]))
361 return join(results, '')
362
363 # ---------------------------------------------- type-specific routines
364
365 def doctree(self, tree, modname, classes={}, parent=None):
366 """Produce HTML for a class tree as given by inspect.getclasstree()."""
367 result = ''
368 for entry in tree:
369 if type(entry) is type(()):
370 c, bases = entry
371 result = result + '<dt><font face="helvetica, arial"><small>'
372 result = result + self.classlink(c, modname, classes)
373 if bases and bases != (parent,):
374 parents = []
375 for base in bases:
376 parents.append(self.classlink(base, modname, classes))
377 result = result + '(' + join(parents, ', ') + ')'
378 result = result + '\n</small></font></dt>'
379 elif type(entry) is type([]):
380 result = result + \
381 '<dd>\n%s</dd>\n' % self.doctree(entry, modname, classes, c)
382 return '<dl>\n%s</dl>\n' % result
383
384 def docmodule(self, object):
385 """Produce HTML documentation for a module object."""
386 name = object.__name__
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000387 parts = split(name, '.')
388 links = []
389 for i in range(len(parts)-1):
390 links.append(
391 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
392 (join(parts[:i+1], '.'), parts[i]))
393 linkedname = join(links + parts[-1:], '.')
394 head = '<big><big><strong>%s</strong></big></big>' % linkedname
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000395 try:
Ka-Ping Yee239432a2001-03-02 02:45:08 +0000396 path = inspect.getabsfile(object)
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000397 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 Yee66efbc72001-03-01 13:55:20 +0000410 result = self.heading(
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000411 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)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000522 if doc: doc = '<small><tt>' + doc + '</tt></small>'
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000523 return self.section(title, '#000000', '#ffc8d8', contents, 10, doc)
524
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000525 def formatvalue(self, object):
526 """Format an argument default value as text."""
527 return ('<small><font color="#909090">=%s</font></small>' %
528 self.repr(object))
529
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000530 def docroutine(self, object, funcs={}, classes={}, methods={}, clname=''):
531 """Produce HTML documentation for a function or method object."""
532 if inspect.ismethod(object): object = object.im_func
533 if inspect.isbuiltin(object):
534 decl = '<a name="%s"><strong>%s</strong>(...)</a>\n' % (
535 clname + '-' + object.__name__, object.__name__)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000536 else:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000537 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)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000547 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
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000553 def page(self, object):
554 """Produce a complete HTML page of documentation for an object."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000555 return '''
556<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
557<html><title>Python: %s</title><body bgcolor="#ffffff">
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000558%s
559</body></html>
560''' % (describe(object), self.document(object))
561
562 def index(self, dir, shadowed=None):
563 """Generate an HTML index for a directory of modules."""
564 modpkgs = []
565 if shadowed is None: shadowed = {}
566 seen = {}
567 files = os.listdir(dir)
568
569 def found(name, ispackage,
570 modpkgs=modpkgs, shadowed=shadowed, seen=seen):
571 if not seen.has_key(name):
572 modpkgs.append((name, '', ispackage, shadowed.has_key(name)))
573 seen[name] = 1
574 shadowed[name] = 1
575
576 # Package spam/__init__.py takes precedence over module spam.py.
577 for file in files:
578 path = os.path.join(dir, file)
579 if ispackage(path): found(file, 1)
580 for file in files:
581 path = os.path.join(dir, file)
Tim Peters85ba6732001-02-28 08:26:44 +0000582 if file[:1] != '_' and os.path.isfile(path):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000583 modname = modulename(file)
584 if modname: found(modname, 0)
585
586 modpkgs.sort()
587 contents = self.multicolumn(modpkgs, self.modpkglink)
588 return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
589
590# -------------------------------------------- text documentation generator
591
592class TextRepr(Repr):
593 """Class for safely making a text representation of a Python object."""
594 def __init__(self):
595 Repr.__init__(self)
596 self.maxlist = self.maxtuple = self.maxdict = 10
597 self.maxstring = self.maxother = 50
598
599 def repr1(self, x, level):
600 methodname = 'repr_' + join(split(type(x).__name__), '_')
601 if hasattr(self, methodname):
602 return getattr(self, methodname)(x, level)
603 else:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000604 return cram(stripid(repr(x)), self.maxother)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000605
Ka-Ping Yeea2fe1032001-03-02 01:19:14 +0000606 def repr_string(self, x, level):
607 test = cram(x, self.maxstring)
608 testrepr = repr(test)
609 if '\\' in test and '\\' not in replace(testrepr, (r'\\', '')):
610 # Backslashes are only literal in the string and are never
611 # needed to make any special characters, so show a raw string.
612 return 'r' + testrepr[0] + test + testrepr[0]
613 return testrepr
614
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000615 def repr_instance(self, x, level):
616 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000617 return cram(stripid(repr(x)), self.maxstring)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000618 except:
619 return '<%s instance>' % x.__class__.__name__
620
621class TextDoc(Doc):
622 """Formatter class for text documentation."""
623
624 # ------------------------------------------- text formatting utilities
625
626 _repr_instance = TextRepr()
627 repr = _repr_instance.repr
628
629 def bold(self, text):
630 """Format a string in bold by overstriking."""
631 return join(map(lambda ch: ch + '\b' + ch, text), '')
632
633 def indent(self, text, prefix=' '):
634 """Indent text by prepending a given prefix to each line."""
635 if not text: return ''
636 lines = split(text, '\n')
637 lines = map(lambda line, prefix=prefix: prefix + line, lines)
638 if lines: lines[-1] = rstrip(lines[-1])
639 return join(lines, '\n')
640
641 def section(self, title, contents):
642 """Format a section with a given heading."""
643 return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
644
645 # ---------------------------------------------- type-specific routines
646
647 def doctree(self, tree, modname, parent=None, prefix=''):
648 """Render in text a class tree as returned by inspect.getclasstree()."""
649 result = ''
650 for entry in tree:
651 if type(entry) is type(()):
652 cl, bases = entry
653 result = result + prefix + classname(cl, modname)
654 if bases and bases != (parent,):
655 parents = map(lambda cl, m=modname: classname(cl, m), bases)
656 result = result + '(%s)' % join(parents, ', ')
657 result = result + '\n'
658 elif type(entry) is type([]):
659 result = result + self.doctree(
660 entry, modname, cl, prefix + ' ')
661 return result
662
663 def docmodule(self, object):
664 """Produce text documentation for a given module object."""
665 result = ''
666
667 name = object.__name__
668 lines = split(strip(getdoc(object)), '\n')
669 if len(lines) == 1:
670 if lines[0]: name = name + ' - ' + lines[0]
671 lines = []
672 elif len(lines) >= 2 and not rstrip(lines[1]):
673 if lines[0]: name = name + ' - ' + lines[0]
674 lines = lines[2:]
675 result = result + self.section('NAME', name)
Ka-Ping Yee239432a2001-03-02 02:45:08 +0000676 try: file = inspect.getabsfile(object)
677 except TypeError: file = '(built-in)'
678 result = result + self.section('FILE', file)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000679 if lines:
680 result = result + self.section('DESCRIPTION', join(lines, '\n'))
681
682 classes = []
683 for key, value in inspect.getmembers(object, inspect.isclass):
684 if (inspect.getmodule(value) or object) is object:
685 classes.append(value)
686 funcs = []
687 for key, value in inspect.getmembers(object, inspect.isroutine):
688 if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
689 funcs.append(value)
690 constants = []
691 for key, value in inspect.getmembers(object, isconstant):
692 if key[:1] != '_':
693 constants.append((key, value))
694
695 if hasattr(object, '__path__'):
696 modpkgs = []
697 for file in os.listdir(object.__path__[0]):
698 if file[:1] != '_':
699 path = os.path.join(object.__path__[0], file)
700 modname = modulename(file)
701 if modname and modname not in modpkgs:
702 modpkgs.append(modname)
703 elif ispackage(path):
704 modpkgs.append(file + ' (package)')
705 modpkgs.sort()
706 result = result + self.section(
707 'PACKAGE CONTENTS', join(modpkgs, '\n'))
708
709 if classes:
710 contents = self.doctree(
711 inspect.getclasstree(classes, 1), object.__name__) + '\n'
712 for item in classes:
713 contents = contents + self.document(item) + '\n'
714 result = result + self.section('CLASSES', contents)
715
716 if funcs:
717 contents = ''
718 for item in funcs:
719 contents = contents + self.document(item) + '\n'
720 result = result + self.section('FUNCTIONS', contents)
721
722 if constants:
723 contents = ''
724 for key, value in constants:
725 line = key + ' = ' + self.repr(value)
726 chop = 70 - len(line)
727 line = self.bold(key) + ' = ' + self.repr(value)
728 if chop < 0: line = line[:chop] + '...'
729 contents = contents + line + '\n'
730 result = result + self.section('CONSTANTS', contents)
731
732 if hasattr(object, '__version__'):
733 version = str(object.__version__)
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000734 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
735 version = strip(version[11:-1])
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000736 result = result + self.section('VERSION', version)
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000737 if hasattr(object, '__date__'):
738 result = result + self.section('DATE', str(object.__date__))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000739 if hasattr(object, '__author__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000740 result = result + self.section('AUTHOR', str(object.__author__))
741 if hasattr(object, '__credits__'):
742 result = result + self.section('CREDITS', str(object.__credits__))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000743 return result
744
745 def docclass(self, object):
746 """Produce text documentation for a given class object."""
747 name = object.__name__
748 bases = object.__bases__
749
750 title = 'class ' + self.bold(name)
751 if bases:
752 parents = map(lambda c, m=object.__module__: classname(c, m), bases)
753 title = title + '(%s)' % join(parents, ', ')
754
755 doc = getdoc(object)
756 contents = doc and doc + '\n'
757 methods = map(lambda (key, value): value,
758 inspect.getmembers(object, inspect.ismethod))
759 for item in methods:
760 contents = contents + '\n' + self.document(item)
761
762 if not contents: return title + '\n'
763 return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n'
764
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000765 def formatvalue(self, object):
766 """Format an argument default value as text."""
767 return '=' + self.repr(object)
768
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000769 def docroutine(self, object):
770 """Produce text documentation for a function or method object."""
771 if inspect.ismethod(object): object = object.im_func
772 if inspect.isbuiltin(object):
773 decl = self.bold(object.__name__) + '(...)'
774 else:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000775 args, varargs, varkw, defaults = inspect.getargspec(object)
776 argspec = inspect.formatargspec(
777 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000778 if object.__name__ == '<lambda>':
779 decl = '<lambda> ' + argspec[1:-1]
780 else:
781 decl = self.bold(object.__name__) + argspec
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000782 doc = getdoc(object)
783 if doc:
784 return decl + '\n' + rstrip(self.indent(doc)) + '\n'
785 else:
786 return decl + '\n'
787
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000788# --------------------------------------------------------- user interfaces
789
790def pager(text):
791 """The first time this is called, determine what kind of pager to use."""
792 global pager
793 pager = getpager()
794 pager(text)
795
796def getpager():
797 """Decide what method to use for paging through text."""
798 if type(sys.stdout) is not types.FileType:
799 return plainpager
800 if not sys.stdin.isatty() or not sys.stdout.isatty():
801 return plainpager
802 if os.environ.has_key('PAGER'):
803 return lambda a: pipepager(a, os.environ['PAGER'])
804 if sys.platform in ['win', 'win32', 'nt']:
805 return lambda a: tempfilepager(a, 'more')
806 if hasattr(os, 'system') and os.system('less 2>/dev/null') == 0:
807 return lambda a: pipepager(a, 'less')
808
809 import tempfile
810 filename = tempfile.mktemp()
811 open(filename, 'w').close()
812 try:
813 if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
814 return lambda text: pipepager(text, 'more')
815 else:
816 return ttypager
817 finally:
818 os.unlink(filename)
819
820def pipepager(text, cmd):
821 """Page through text by feeding it to another program."""
822 pipe = os.popen(cmd, 'w')
823 try:
824 pipe.write(text)
825 pipe.close()
826 except IOError:
827 # Ignore broken pipes caused by quitting the pager program.
828 pass
829
830def tempfilepager(text, cmd):
831 """Page through text by invoking a program on a temporary file."""
832 import tempfile
833 filename = tempfile.mktemp()
834 file = open(filename, 'w')
835 file.write(text)
836 file.close()
837 try:
838 os.system(cmd + ' ' + filename)
839 finally:
840 os.unlink(filename)
841
842def plain(text):
843 """Remove boldface formatting from text."""
844 return re.sub('.\b', '', text)
845
846def ttypager(text):
847 """Page through text on a text terminal."""
848 lines = split(plain(text), '\n')
849 try:
850 import tty
851 fd = sys.stdin.fileno()
852 old = tty.tcgetattr(fd)
853 tty.setcbreak(fd)
854 getchar = lambda: sys.stdin.read(1)
Ka-Ping Yee457aab22001-02-27 23:36:29 +0000855 except (ImportError, AttributeError):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000856 tty = None
857 getchar = lambda: sys.stdin.readline()[:-1][:1]
858
859 try:
860 r = inc = os.environ.get('LINES', 25) - 1
861 sys.stdout.write(join(lines[:inc], '\n') + '\n')
862 while lines[r:]:
863 sys.stdout.write('-- more --')
864 sys.stdout.flush()
865 c = getchar()
866
867 if c in ['q', 'Q']:
868 sys.stdout.write('\r \r')
869 break
870 elif c in ['\r', '\n']:
871 sys.stdout.write('\r \r' + lines[r] + '\n')
872 r = r + 1
873 continue
874 if c in ['b', 'B', '\x1b']:
875 r = r - inc - inc
876 if r < 0: r = 0
877 sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
878 r = r + inc
879
880 finally:
881 if tty:
882 tty.tcsetattr(fd, tty.TCSAFLUSH, old)
883
884def plainpager(text):
885 """Simply print unformatted text. This is the ultimate fallback."""
886 sys.stdout.write(plain(text))
887
888def describe(thing):
889 """Produce a short description of the given kind of thing."""
890 if inspect.ismodule(thing):
891 if thing.__name__ in sys.builtin_module_names:
892 return 'built-in module ' + thing.__name__
893 if hasattr(thing, '__path__'):
894 return 'package ' + thing.__name__
895 else:
896 return 'module ' + thing.__name__
897 if inspect.isbuiltin(thing):
898 return 'built-in function ' + thing.__name__
899 if inspect.isclass(thing):
900 return 'class ' + thing.__name__
901 if inspect.isfunction(thing):
902 return 'function ' + thing.__name__
903 if inspect.ismethod(thing):
904 return 'method ' + thing.__name__
905 return repr(thing)
906
907def locate(path):
908 """Locate an object by name (or dotted path), importing as necessary."""
909 if not path: # special case: imp.find_module('') strangely succeeds
910 return None, None
911 if type(path) is not types.StringType:
912 return None, path
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000913 parts = split(path, '.')
914 n = 1
915 while n <= len(parts):
916 path = join(parts[:n], '.')
917 try:
918 module = __import__(path)
919 module = reload(module)
920 except:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000921 # determine if error occurred before or after module was found
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000922 if sys.modules.has_key(path):
923 filename = sys.modules[path].__file__
924 elif sys.exc_type is SyntaxError:
925 filename = sys.exc_value.filename
926 else:
927 # module not found, so stop looking
928 break
929 # error occurred in the imported module, so report it
930 raise DocImportError(filename, sys.exc_type, sys.exc_value)
931 try:
932 x = module
933 for p in parts[1:]:
934 x = getattr(x, p)
935 return join(parts[:-1], '.'), x
936 except AttributeError:
937 n = n + 1
938 continue
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000939 if hasattr(__builtins__, path):
940 return None, getattr(__builtins__, path)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000941 return None, None
942
943# --------------------------------------- interactive interpreter interface
944
945text = TextDoc()
946html = HTMLDoc()
947
948def doc(thing):
949 """Display documentation on an object (for interactive use)."""
950 if type(thing) is type(""):
951 try:
952 path, x = locate(thing)
953 except DocImportError, value:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000954 print 'Problem in %s - %s' % (value.filename, value.args)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000955 return
956 if x:
957 thing = x
958 else:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000959 print 'No Python documentation found for %s.' % repr(thing)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000960 return
961
962 desc = describe(thing)
963 module = inspect.getmodule(thing)
964 if module and module is not thing:
965 desc = desc + ' in module ' + module.__name__
966 pager('Help on %s:\n\n' % desc + text.document(thing))
967
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000968def writedoc(key):
969 """Write HTML documentation to a file in the current directory."""
970 path, object = locate(key)
971 if object:
972 file = open(key + '.html', 'w')
973 file.write(html.page(object))
974 file.close()
975 print 'wrote', key + '.html'
976
977class Helper:
978 def __repr__(self):
979 return """To get help on a Python object, call help(object).
980To get help on a module or package, either import it before calling
981help(module) or call help('modulename')."""
982
983 def __call__(self, *args):
984 if args:
985 doc(args[0])
986 else:
987 print repr(self)
988
989help = Helper()
990
991def man(key):
992 """Display documentation on an object in a form similar to man(1)."""
993 path, object = locate(key)
994 if object:
995 title = 'Python Library Documentation: ' + describe(object)
996 if path: title = title + ' in ' + path
997 pager('\n' + title + '\n\n' + text.document(object))
998 found = 1
999 else:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001000 print 'No Python documentation found for %s.' % repr(key)
1001
1002class Scanner:
1003 """A generic tree iterator."""
1004 def __init__(self, roots, children, recurse):
1005 self.roots = roots[:]
1006 self.state = []
1007 self.children = children
1008 self.recurse = recurse
1009
1010 def next(self):
1011 if not self.state:
1012 if not self.roots:
1013 return None
1014 root = self.roots.pop(0)
1015 self.state = [(root, self.children(root))]
1016 node, children = self.state[-1]
1017 if not children:
1018 self.state.pop()
1019 return self.next()
1020 child = children.pop(0)
1021 if self.recurse(child):
1022 self.state.append((child, self.children(child)))
1023 return child
1024
1025class ModuleScanner(Scanner):
1026 """An interruptible scanner that searches module synopses."""
1027 def __init__(self):
1028 roots = map(lambda dir: (dir, ''), pathdirs())
1029 Scanner.__init__(self, roots, self.submodules, self.ispackage)
1030
1031 def submodules(self, (dir, package)):
1032 children = []
1033 for file in os.listdir(dir):
1034 path = os.path.join(dir, file)
1035 if ispackage(path):
1036 children.append((path, package + (package and '.') + file))
1037 else:
1038 children.append((path, package))
1039 children.sort()
1040 return children
1041
1042 def ispackage(self, (dir, package)):
1043 return ispackage(dir)
1044
1045 def run(self, key, callback, completer=None):
1046 self.quit = 0
1047 seen = {}
1048
1049 for modname in sys.builtin_module_names:
Ka-Ping Yee239432a2001-03-02 02:45:08 +00001050 if modname != '__main__':
1051 seen[modname] = 1
1052 desc = split(__import__(modname).__doc__ or '', '\n')[0]
1053 if find(lower(modname + ' - ' + desc), lower(key)) >= 0:
1054 callback(None, modname, desc)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001055
1056 while not self.quit:
1057 node = self.next()
1058 if not node: break
1059 path, package = node
1060 modname = modulename(path)
1061 if os.path.isfile(path) and modname:
1062 modname = package + (package and '.') + modname
1063 if not seen.has_key(modname):
1064 seen[modname] = 1
1065 desc = synopsis(path) or ''
1066 if find(lower(modname + ' - ' + desc), lower(key)) >= 0:
1067 callback(path, modname, desc)
1068 if completer: completer()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001069
1070def apropos(key):
1071 """Print all the one-line module summaries that contain a substring."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001072 def callback(path, modname, desc):
1073 if modname[-9:] == '.__init__':
1074 modname = modname[:-9] + ' (package)'
1075 print modname, '-', desc or '(no description)'
1076 ModuleScanner().run(key, callback)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001077
1078# --------------------------------------------------- web browser interface
1079
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001080def serve(port, callback=None):
1081 import BaseHTTPServer, mimetools, select
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001082
1083 # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
1084 class Message(mimetools.Message):
1085 def __init__(self, fp, seekable=1):
1086 Message = self.__class__
1087 Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
1088 self.encodingheader = self.getheader('content-transfer-encoding')
1089 self.typeheader = self.getheader('content-type')
1090 self.parsetype()
1091 self.parseplist()
1092
1093 class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
1094 def send_document(self, title, contents):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001095 try:
1096 self.send_response(200)
1097 self.send_header('Content-Type', 'text/html')
1098 self.end_headers()
1099 self.wfile.write('''
1100<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
1101<html><title>Python: %s</title><body bgcolor="#ffffff">
1102%s
1103</body></html>''' % (title, contents))
1104 except IOError: pass
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001105
1106 def do_GET(self):
1107 path = self.path
1108 if path[-5:] == '.html': path = path[:-5]
1109 if path[:1] == '/': path = path[1:]
1110 if path and path != '.':
1111 try:
1112 p, x = locate(path)
1113 except DocImportError, value:
1114 self.send_document(path, html.escape(
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001115 'Problem in %s - %s' % (value.filename, value.args)))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001116 return
1117 if x:
1118 self.send_document(describe(x), html.document(x))
1119 else:
1120 self.send_document(path,
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001121'No Python documentation found for %s.' % repr(path))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001122 else:
1123 heading = html.heading(
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001124'<big><big><strong>Python: Index of Modules</strong></big></big>',
1125'#ffffff', '#7799ee')
Ka-Ping Yee239432a2001-03-02 02:45:08 +00001126 def bltinlink(name):
1127 return '<a href="%s.html">%s</a>' % (name, name)
1128 names = filter(lambda x: x != '__main__', sys.builtin_module_names)
1129 contents = html.multicolumn(names, bltinlink)
1130 indices = ['<p>' + html.bigsection(
1131 'Built-in Modules', '#ffffff', '#ee77aa', contents)]
1132
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001133 seen = {}
1134 for dir in pathdirs():
1135 indices.append(html.index(dir, seen))
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001136 contents = heading + join(indices) + """<p align=right>
1137<small><small><font color="#909090" face="helvetica, arial"><strong>
1138pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font></small></small>"""
1139 self.send_document('Index of Modules', contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001140
1141 def log_message(self, *args): pass
1142
1143 class DocServer(BaseHTTPServer.HTTPServer):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001144 def __init__(self, port, callback):
1145 self.address = ('127.0.0.1', port)
1146 self.url = 'http://127.0.0.1:%d/' % port
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001147 self.callback = callback
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001148 self.base.__init__(self, self.address, self.handler)
1149
1150 def serve_until_quit(self):
1151 import select
1152 self.quit = 0
1153 while not self.quit:
1154 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
1155 if rd: self.handle_request()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001156
1157 def server_activate(self):
1158 self.base.server_activate(self)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001159 if self.callback: self.callback(self)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001160
1161 DocServer.base = BaseHTTPServer.HTTPServer
1162 DocServer.handler = DocHandler
1163 DocHandler.MessageClass = Message
1164 try:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001165 DocServer(port, callback).serve_until_quit()
1166 except (KeyboardInterrupt, select.error):
1167 pass
1168 print 'server stopped'
1169
1170# ----------------------------------------------------- graphical interface
1171
1172def gui():
1173 """Graphical interface (starts web server and pops up a control window)."""
1174 class GUI:
1175 def __init__(self, window, port=7464):
1176 self.window = window
1177 self.server = None
1178 self.scanner = None
1179
1180 import Tkinter
1181 self.server_frm = Tkinter.Frame(window)
1182 self.title_lbl = Tkinter.Label(self.server_frm,
1183 text='Starting server...\n ')
1184 self.open_btn = Tkinter.Button(self.server_frm,
1185 text='open browser', command=self.open, state='disabled')
1186 self.quit_btn = Tkinter.Button(self.server_frm,
1187 text='quit serving', command=self.quit, state='disabled')
1188
1189 self.search_frm = Tkinter.Frame(window)
1190 self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
1191 self.search_ent = Tkinter.Entry(self.search_frm)
1192 self.search_ent.bind('<Return>', self.search)
1193 self.stop_btn = Tkinter.Button(self.search_frm,
1194 text='stop', pady=0, command=self.stop, state='disabled')
1195 if sys.platform == 'win32':
1196 # Attempting to hide and show this button crashes under Windows.
1197 self.stop_btn.pack(side='right')
1198
1199 self.window.title('pydoc')
1200 self.window.protocol('WM_DELETE_WINDOW', self.quit)
1201 self.title_lbl.pack(side='top', fill='x')
1202 self.open_btn.pack(side='left', fill='x', expand=1)
1203 self.quit_btn.pack(side='right', fill='x', expand=1)
1204 self.server_frm.pack(side='top', fill='x')
1205
1206 self.search_lbl.pack(side='left')
1207 self.search_ent.pack(side='right', fill='x', expand=1)
1208 self.search_frm.pack(side='top', fill='x')
1209 self.search_ent.focus_set()
1210
Ka-Ping Yee239432a2001-03-02 02:45:08 +00001211 font = ('helvetica', sys.platform in ['win32', 'win', 'nt'] and 8 or 10)
1212 self.result_lst = Tkinter.Listbox(window, font=font, height=6)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001213 self.result_lst.bind('<Button-1>', self.select)
1214 self.result_lst.bind('<Double-Button-1>', self.goto)
1215 self.result_scr = Tkinter.Scrollbar(window,
1216 orient='vertical', command=self.result_lst.yview)
1217 self.result_lst.config(yscrollcommand=self.result_scr.set)
1218
1219 self.result_frm = Tkinter.Frame(window)
1220 self.goto_btn = Tkinter.Button(self.result_frm,
1221 text='go to selected', command=self.goto)
1222 self.hide_btn = Tkinter.Button(self.result_frm,
1223 text='hide results', command=self.hide)
1224 self.goto_btn.pack(side='left', fill='x', expand=1)
1225 self.hide_btn.pack(side='right', fill='x', expand=1)
1226
1227 self.window.update()
1228 self.minwidth = self.window.winfo_width()
1229 self.minheight = self.window.winfo_height()
1230 self.bigminheight = (self.server_frm.winfo_reqheight() +
1231 self.search_frm.winfo_reqheight() +
1232 self.result_lst.winfo_reqheight() +
1233 self.result_frm.winfo_reqheight())
1234 self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
1235 self.expanded = 0
1236 self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
1237 self.window.wm_minsize(self.minwidth, self.minheight)
1238
1239 import threading
1240 threading.Thread(target=serve, args=(port, self.ready)).start()
1241
1242 def ready(self, server):
1243 self.server = server
1244 self.title_lbl.config(
1245 text='Python documentation server at\n' + server.url)
1246 self.open_btn.config(state='normal')
1247 self.quit_btn.config(state='normal')
1248
Ka-Ping Yee239432a2001-03-02 02:45:08 +00001249 def open(self, event=None, url=None):
1250 url = url or self.server.url
1251 try:
1252 import webbrowser
1253 webbrowser.open(url)
1254 except ImportError: # pre-webbrowser.py compatibility
1255 if sys.platform in ['win', 'win32', 'nt']:
1256 os.system('start "%s"' % url)
1257 elif sys.platform == 'mac':
1258 try:
1259 import ic
1260 ic.launchurl(url)
1261 except ImportError: pass
1262 else:
1263 rc = os.system('netscape -remote "openURL(%s)" &' % url)
1264 if rc: os.system('netscape "%s" &' % url)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001265
1266 def quit(self, event=None):
1267 if self.server:
1268 self.server.quit = 1
1269 self.window.quit()
1270
1271 def search(self, event=None):
1272 key = self.search_ent.get()
1273 self.stop_btn.pack(side='right')
1274 self.stop_btn.config(state='normal')
1275 self.search_lbl.config(text='Searching for "%s"...' % key)
1276 self.search_ent.forget()
1277 self.search_lbl.pack(side='left')
1278 self.result_lst.delete(0, 'end')
1279 self.goto_btn.config(state='disabled')
1280 self.expand()
1281
1282 import threading
1283 if self.scanner:
1284 self.scanner.quit = 1
1285 self.scanner = ModuleScanner()
1286 threading.Thread(target=self.scanner.run,
1287 args=(key, self.update, self.done)).start()
1288
1289 def update(self, path, modname, desc):
1290 if modname[-9:] == '.__init__':
1291 modname = modname[:-9] + ' (package)'
1292 self.result_lst.insert('end',
1293 modname + ' - ' + (desc or '(no description)'))
1294
1295 def stop(self, event=None):
1296 if self.scanner:
1297 self.scanner.quit = 1
1298 self.scanner = None
1299
1300 def done(self):
1301 self.scanner = None
1302 self.search_lbl.config(text='Search for')
1303 self.search_lbl.pack(side='left')
1304 self.search_ent.pack(side='right', fill='x', expand=1)
1305 if sys.platform != 'win32': self.stop_btn.forget()
1306 self.stop_btn.config(state='disabled')
1307
1308 def select(self, event=None):
1309 self.goto_btn.config(state='normal')
1310
1311 def goto(self, event=None):
1312 selection = self.result_lst.curselection()
1313 if selection:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001314 modname = split(self.result_lst.get(selection[0]))[0]
Ka-Ping Yee239432a2001-03-02 02:45:08 +00001315 self.open(url=self.server.url + modname + '.html')
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001316
1317 def collapse(self):
1318 if not self.expanded: return
1319 self.result_frm.forget()
1320 self.result_scr.forget()
1321 self.result_lst.forget()
1322 self.bigwidth = self.window.winfo_width()
1323 self.bigheight = self.window.winfo_height()
1324 self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
1325 self.window.wm_minsize(self.minwidth, self.minheight)
1326 self.expanded = 0
1327
1328 def expand(self):
1329 if self.expanded: return
1330 self.result_frm.pack(side='bottom', fill='x')
1331 self.result_scr.pack(side='right', fill='y')
1332 self.result_lst.pack(side='top', fill='both', expand=1)
1333 self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
1334 self.window.wm_minsize(self.minwidth, self.bigminheight)
1335 self.expanded = 1
1336
1337 def hide(self, event=None):
1338 self.stop()
1339 self.collapse()
1340
1341 import Tkinter
1342 try:
1343 gui = GUI(Tkinter.Tk())
1344 Tkinter.mainloop()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001345 except KeyboardInterrupt:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001346 pass
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001347
1348# -------------------------------------------------- command-line interface
1349
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001350def cli():
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001351 """Command-line interface (looks at sys.argv to decide what to do)."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001352 import getopt
1353 class BadUsage: pass
1354
1355 try:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001356 if sys.platform in ['mac', 'win', 'win32', 'nt'] and not sys.argv[1:]:
1357 # CLI-less platforms
1358 gui()
1359 return
1360
1361 opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001362 writing = 0
1363
1364 for opt, val in opts:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001365 if opt == '-g':
1366 gui()
1367 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001368 if opt == '-k':
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001369 apropos(val)
1370 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001371 if opt == '-p':
1372 try:
1373 port = int(val)
1374 except ValueError:
1375 raise BadUsage
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001376 def ready(server):
1377 print 'server ready at %s' % server.url
1378 serve(port, ready)
1379 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001380 if opt == '-w':
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001381 writing = 1
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001382
1383 if not args: raise BadUsage
1384 for arg in args:
1385 try:
1386 if find(arg, os.sep) >= 0 and os.path.isfile(arg):
1387 arg = importfile(arg)
1388 if writing: writedoc(arg)
1389 else: man(arg)
1390 except DocImportError, value:
1391 print 'Problem in %s - %s' % (value.filename, value.args)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001392
1393 except (getopt.error, BadUsage):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001394 cmd = sys.argv[0]
1395 print """pydoc - the Python documentation tool
1396
1397%s <name> ...
1398 Show text documentation on something. <name> may be the name of a
1399 function, module, or package, or a dotted reference to a class or
1400 function within a module or module in a package. If <name> contains
1401 a '%s', it is used as the path to a Python source file to document.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001402
1403%s -k <keyword>
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001404 Search for a keyword in the synopsis lines of all available modules.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001405
1406%s -p <port>
1407 Start an HTTP server on the given port on the local machine.
1408
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001409%s -g
1410 Pop up a graphical interface for serving and finding documentation.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001411
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001412%s -w <name> ...
1413 Write out the HTML documentation for a module to a file in the current
1414 directory. If <name> contains a '%s', it is treated as a filename.
1415""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001416
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001417if __name__ == '__main__': cli()
1418
1419