blob: ee08e3beeb1c47eab3c7acd87d6eba36dda3d22a [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
65 result = split(line, '"""')[0]
66 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
89 return result and rstrip(result) or ''
90
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)
130 if lower(filename[-3:]) == '.py':
131 return filename[:-3]
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000132 elif lower(filename[-4:]) in ['.pyc', '.pyd', '.pyo']:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000133 return filename[:-4]
134 elif lower(filename[-11:]) == 'module.so':
135 return filename[:-11]
136 elif lower(filename[-13:]) == 'module.so.1':
137 return filename[:-13]
138
139class DocImportError(Exception):
140 """Class for errors while trying to import something to document it."""
141 def __init__(self, filename, etype, evalue):
142 self.filename = filename
143 self.etype = etype
144 self.evalue = evalue
145 if type(etype) is types.ClassType:
146 etype = etype.__name__
147 self.args = '%s: %s' % (etype, evalue)
148
149def importfile(path):
150 """Import a Python source file or compiled file given its path."""
151 magic = imp.get_magic()
152 file = open(path, 'r')
153 if file.read(len(magic)) == magic:
154 kind = imp.PY_COMPILED
155 else:
156 kind = imp.PY_SOURCE
157 file.close()
158 filename = os.path.basename(path)
159 name, ext = os.path.splitext(filename)
160 file = open(path, 'r')
161 try:
162 module = imp.load_module(name, file, path, (ext, 'r', kind))
163 except:
164 raise DocImportError(path, sys.exc_type, sys.exc_value)
165 file.close()
166 return module
167
168def ispackage(path):
169 """Guess whether a path refers to a package directory."""
170 if os.path.isdir(path):
171 init = os.path.join(path, '__init__.py')
172 initc = os.path.join(path, '__init__.pyc')
173 if os.path.isfile(init) or os.path.isfile(initc):
174 return 1
175
176# ---------------------------------------------------- formatter base class
177
178class Doc:
179 def document(self, object, *args):
180 """Generate documentation for an object."""
181 args = (object,) + args
182 if inspect.ismodule(object): return apply(self.docmodule, args)
183 if inspect.isclass(object): return apply(self.docclass, args)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000184 if inspect.isroutine(object): return apply(self.docroutine, args)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000185 raise TypeError, "don't know how to document objects of type " + \
186 type(object).__name__
187
188# -------------------------------------------- HTML documentation generator
189
190class HTMLRepr(Repr):
191 """Class for safely making an HTML representation of a Python object."""
192 def __init__(self):
193 Repr.__init__(self)
194 self.maxlist = self.maxtuple = self.maxdict = 10
195 self.maxstring = self.maxother = 50
196
197 def escape(self, text):
198 return replace(text, ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'))
199
200 def repr(self, object):
201 result = Repr.repr(self, object)
202 return result
203
204 def repr1(self, x, level):
205 methodname = 'repr_' + join(split(type(x).__name__), '_')
206 if hasattr(self, methodname):
207 return getattr(self, methodname)(x, level)
208 else:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000209 return self.escape(cram(stripid(repr(x)), self.maxother))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000210
211 def repr_string(self, x, level):
212 text = self.escape(cram(x, self.maxstring))
213 return re.sub(r'((\\[\\abfnrtv]|\\x..|\\u....)+)',
214 r'<font color="#c040c0">\1</font>', repr(text))
215
216 def repr_instance(self, x, level):
217 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000218 return cram(stripid(repr(x)), self.maxstring)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000219 except:
220 return self.escape('<%s instance>' % x.__class__.__name__)
221
222 repr_unicode = repr_string
223
224class HTMLDoc(Doc):
225 """Formatter class for HTML documentation."""
226
227 # ------------------------------------------- HTML formatting utilities
228
229 _repr_instance = HTMLRepr()
230 repr = _repr_instance.repr
231 escape = _repr_instance.escape
232
233 def preformat(self, text):
234 """Format literal preformatted text."""
235 text = self.escape(expandtabs(text))
236 return replace(text, ('\n\n', '\n \n'), ('\n\n', '\n \n'),
237 (' ', '&nbsp;'), ('\n', '<br>\n'))
238
239 def multicolumn(self, list, format, cols=4):
240 """Format a list of items into a multi-column list."""
241 result = ''
242 rows = (len(list)+cols-1)/cols
243
244 for col in range(cols):
245 result = result + '<td width="%d%%" valign=top>' % (100/cols)
246 for i in range(rows*col, rows*col+rows):
247 if i < len(list):
248 result = result + format(list[i]) + '<br>'
249 result = result + '</td>'
250 return '<table width="100%%"><tr>%s</tr></table>' % result
251
252 def heading(self, title, fgcol, bgcol, extras=''):
253 """Format a page heading."""
254 return """
255<p><table width="100%%" cellspacing=0 cellpadding=0 border=0>
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000256<tr bgcolor="%s"><td>&nbsp;</td>
257<td valign=bottom><small><small><br></small></small
258><font color="%s" face="helvetica"><br>&nbsp;%s</font></td
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000259><td align=right valign=bottom
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000260><font color="%s" face="helvetica">%s</font></td><td>&nbsp;</td></tr></table>
261 """ % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000262
263 def section(self, title, fgcol, bgcol, contents, width=20,
264 prelude='', marginalia=None, gap='&nbsp;&nbsp;&nbsp;'):
265 """Format a section with a heading."""
266 if marginalia is None:
267 marginalia = '&nbsp;' * width
268 result = """
269<p><table width="100%%" cellspacing=0 cellpadding=0 border=0>
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000270<tr bgcolor="%s"><td rowspan=2>&nbsp;</td>
271<td colspan=3 valign=bottom><small><small><br></small></small
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000272><font color="%s" face="helvetica, arial">&nbsp;%s</font></td></tr>
273 """ % (bgcol, fgcol, title)
274 if prelude:
275 result = result + """
276<tr><td bgcolor="%s">%s</td>
277<td bgcolor="%s" colspan=2>%s</td></tr>
278 """ % (bgcol, marginalia, bgcol, prelude)
279 result = result + """
280<tr><td bgcolor="%s">%s</td><td>%s</td>
281 """ % (bgcol, marginalia, gap)
282
283 result = result + '<td width="100%%">%s</td></tr></table>' % contents
284 return result
285
286 def bigsection(self, title, *args):
287 """Format a section with a big heading."""
288 title = '<big><strong>%s</strong></big>' % title
289 return apply(self.section, (title,) + args)
290
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000291 def namelink(self, name, *dicts):
292 """Make a link for an identifier, given name-to-URL mappings."""
293 for dict in dicts:
294 if dict.has_key(name):
295 return '<a href="%s">%s</a>' % (dict[name], name)
296 return name
297
298 def classlink(self, object, modname, *dicts):
299 """Make a link for a class."""
300 name = object.__name__
301 if object.__module__ != modname:
302 name = object.__module__ + '.' + name
303 for dict in dicts:
304 if dict.has_key(object):
305 return '<a href="%s">%s</a>' % (dict[object], name)
306 return name
307
308 def modulelink(self, object):
309 """Make a link for a module."""
310 return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
311
312 def modpkglink(self, (name, path, ispackage, shadowed)):
313 """Make a link for a module or package to display in an index."""
314 if shadowed:
315 return '<font color="#909090">%s</font>' % name
316 if path:
317 url = '%s.%s.html' % (path, name)
318 else:
319 url = '%s.html' % name
320 if ispackage:
321 text = '<strong>%s</strong>&nbsp;(package)' % name
322 else:
323 text = name
324 return '<a href="%s">%s</a>' % (url, text)
325
326 def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
327 """Mark up some plain text, given a context of symbols to look for.
328 Each context dictionary maps object names to anchor names."""
329 escape = escape or self.escape
330 results = []
331 here = 0
332 pattern = re.compile(r'\b(((http|ftp)://\S+[\w/])|'
333 r'(RFC[- ]?(\d+))|'
334 r'(self\.)?(\w+))\b')
335 while 1:
336 match = pattern.search(text, here)
337 if not match: break
338 start, end = match.span()
339 results.append(escape(text[here:start]))
340
341 all, url, scheme, rfc, rfcnum, selfdot, name = match.groups()
342 if url:
343 results.append('<a href="%s">%s</a>' % (url, escape(url)))
344 elif rfc:
345 url = 'http://www.rfc-editor.org/rfc/rfc%s.txt' % rfcnum
346 results.append('<a href="%s">%s</a>' % (url, escape(rfc)))
347 else:
348 if text[end:end+1] == '(':
349 results.append(self.namelink(name, methods, funcs, classes))
350 elif selfdot:
351 results.append('self.<strong>%s</strong>' % name)
352 else:
353 results.append(self.namelink(name, classes))
354 here = end
355 results.append(escape(text[here:]))
356 return join(results, '')
357
358 # ---------------------------------------------- type-specific routines
359
360 def doctree(self, tree, modname, classes={}, parent=None):
361 """Produce HTML for a class tree as given by inspect.getclasstree()."""
362 result = ''
363 for entry in tree:
364 if type(entry) is type(()):
365 c, bases = entry
366 result = result + '<dt><font face="helvetica, arial"><small>'
367 result = result + self.classlink(c, modname, classes)
368 if bases and bases != (parent,):
369 parents = []
370 for base in bases:
371 parents.append(self.classlink(base, modname, classes))
372 result = result + '(' + join(parents, ', ') + ')'
373 result = result + '\n</small></font></dt>'
374 elif type(entry) is type([]):
375 result = result + \
376 '<dd>\n%s</dd>\n' % self.doctree(entry, modname, classes, c)
377 return '<dl>\n%s</dl>\n' % result
378
379 def docmodule(self, object):
380 """Produce HTML documentation for a module object."""
381 name = object.__name__
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000382 parts = split(name, '.')
383 links = []
384 for i in range(len(parts)-1):
385 links.append(
386 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
387 (join(parts[:i+1], '.'), parts[i]))
388 linkedname = join(links + parts[-1:], '.')
389 head = '<big><big><strong>%s</strong></big></big>' % linkedname
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000390 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000391 path = os.path.abspath(inspect.getfile(object))
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000392 sourcepath = os.path.abspath(inspect.getsourcefile(object))
393 if os.path.isfile(sourcepath): path = sourcepath
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000394 filelink = '<a href="file:%s">%s</a>' % (path, path)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000395 except TypeError:
396 filelink = '(built-in)'
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000397 info = []
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000398 if hasattr(object, '__version__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000399 version = str(object.__version__)
Ka-Ping Yee40c49912001-02-27 22:46:01 +0000400 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
401 version = strip(version[11:-1])
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000402 info.append('version %s' % self.escape(version))
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000403 if hasattr(object, '__date__'):
404 info.append(self.escape(str(object.__date__)))
405 if info:
406 head = head + ' (%s)' % join(info, ', ')
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000407 result = self.heading(
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000408 head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
409
410 second = lambda list: list[1]
411 modules = map(second, inspect.getmembers(object, inspect.ismodule))
412
413 classes, cdict = [], {}
414 for key, value in inspect.getmembers(object, inspect.isclass):
415 if (inspect.getmodule(value) or object) is object:
416 classes.append(value)
417 cdict[key] = cdict[value] = '#' + key
418 funcs, fdict = [], {}
419 for key, value in inspect.getmembers(object, inspect.isroutine):
420 if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
421 funcs.append(value)
422 fdict[key] = '#-' + key
423 if inspect.isfunction(value): fdict[value] = fdict[key]
424 for c in classes:
425 for base in c.__bases__:
426 key, modname = base.__name__, base.__module__
427 if modname != name and sys.modules.has_key(modname):
428 module = sys.modules[modname]
429 if hasattr(module, key) and getattr(module, key) is base:
430 if not cdict.has_key(key):
431 cdict[key] = cdict[base] = modname + '.html#' + key
432 constants = []
433 for key, value in inspect.getmembers(object, isconstant):
434 if key[:1] != '_':
435 constants.append((key, value))
436
437 doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
438 doc = doc and '<tt>%s</tt>' % doc
439 result = result + '<p><small>%s</small></p>\n' % doc
440
441 if hasattr(object, '__path__'):
442 modpkgs = []
443 modnames = []
444 for file in os.listdir(object.__path__[0]):
445 if file[:1] != '_':
446 path = os.path.join(object.__path__[0], file)
447 modname = modulename(file)
448 if modname and modname not in modnames:
449 modpkgs.append((modname, name, 0, 0))
450 modnames.append(modname)
451 elif ispackage(path):
Tim Peters85ba6732001-02-28 08:26:44 +0000452 modpkgs.append((file, name, 1, 0))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000453 modpkgs.sort()
454 contents = self.multicolumn(modpkgs, self.modpkglink)
455 result = result + self.bigsection(
456 'Package Contents', '#ffffff', '#aa55cc', contents)
457
458 elif modules:
459 contents = self.multicolumn(modules, self.modulelink)
460 result = result + self.bigsection(
461 'Modules', '#fffff', '#aa55cc', contents)
462
463 if classes:
464 contents = self.doctree(
465 inspect.getclasstree(classes, 1), name, cdict)
466 for item in classes:
467 contents = contents + self.document(item, fdict, cdict)
468 result = result + self.bigsection(
469 'Classes', '#ffffff', '#ee77aa', contents)
470 if funcs:
471 contents = ''
472 for item in funcs:
473 contents = contents + self.document(item, fdict, cdict)
474 result = result + self.bigsection(
475 'Functions', '#ffffff', '#eeaa77', contents)
476
477 if constants:
478 contents = ''
479 for key, value in constants:
480 contents = contents + ('<br><strong>%s</strong> = %s' %
481 (key, self.repr(value)))
482 result = result + self.bigsection(
483 'Constants', '#ffffff', '#55aa55', contents)
484
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000485 if hasattr(object, '__author__'):
486 contents = self.markup(str(object.__author__), self.preformat)
487 result = result + self.bigsection(
488 'Author', '#ffffff', '#7799ee', contents)
489
490 if hasattr(object, '__credits__'):
491 contents = self.markup(str(object.__credits__), self.preformat)
492 result = result + self.bigsection(
493 'Credits', '#ffffff', '#7799ee', contents)
494
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000495 return result
496
497 def docclass(self, object, funcs={}, classes={}):
498 """Produce HTML documentation for a class object."""
499 name = object.__name__
500 bases = object.__bases__
501 contents = ''
502
503 methods, mdict = [], {}
504 for key, value in inspect.getmembers(object, inspect.ismethod):
505 methods.append(value)
506 mdict[key] = mdict[value] = '#' + name + '-' + key
507 for item in methods:
508 contents = contents + self.document(
509 item, funcs, classes, mdict, name)
510
511 title = '<a name="%s">class <strong>%s</strong></a>' % (name, name)
512 if bases:
513 parents = []
514 for base in bases:
515 parents.append(self.classlink(base, object.__module__, classes))
516 title = title + '(%s)' % join(parents, ', ')
517 doc = self.markup(getdoc(object), self.preformat,
518 funcs, classes, mdict)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000519 if doc: doc = '<small><tt>' + doc + '</tt></small>'
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000520 return self.section(title, '#000000', '#ffc8d8', contents, 10, doc)
521
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000522 def formatvalue(self, object):
523 """Format an argument default value as text."""
524 return ('<small><font color="#909090">=%s</font></small>' %
525 self.repr(object))
526
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000527 def docroutine(self, object, funcs={}, classes={}, methods={}, clname=''):
528 """Produce HTML documentation for a function or method object."""
529 if inspect.ismethod(object): object = object.im_func
530 if inspect.isbuiltin(object):
531 decl = '<a name="%s"><strong>%s</strong>(...)</a>\n' % (
532 clname + '-' + object.__name__, object.__name__)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000533 else:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000534 args, varargs, varkw, defaults = inspect.getargspec(object)
535 argspec = inspect.formatargspec(
536 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
537
538 if object.__name__ == '<lambda>':
539 decl = '<em>lambda</em> ' + argspec[1:-1]
540 else:
541 anchor = clname + '-' + object.__name__
542 decl = '<a name="%s"\n><strong>%s</strong>%s</a>\n' % (
543 anchor, object.__name__, argspec)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000544 doc = self.markup(getdoc(object), self.preformat,
545 funcs, classes, methods)
546 doc = replace(doc, ('<br>\n', '</tt></small\n><dd><small><tt>'))
547 doc = doc and '<tt>%s</tt>' % doc
548 return '<dl><dt>%s<dd><small>%s</small></dl>' % (decl, doc)
549
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000550 def page(self, object):
551 """Produce a complete HTML page of documentation for an object."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000552 return '''
553<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
554<html><title>Python: %s</title><body bgcolor="#ffffff">
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000555%s
556</body></html>
557''' % (describe(object), self.document(object))
558
559 def index(self, dir, shadowed=None):
560 """Generate an HTML index for a directory of modules."""
561 modpkgs = []
562 if shadowed is None: shadowed = {}
563 seen = {}
564 files = os.listdir(dir)
565
566 def found(name, ispackage,
567 modpkgs=modpkgs, shadowed=shadowed, seen=seen):
568 if not seen.has_key(name):
569 modpkgs.append((name, '', ispackage, shadowed.has_key(name)))
570 seen[name] = 1
571 shadowed[name] = 1
572
573 # Package spam/__init__.py takes precedence over module spam.py.
574 for file in files:
575 path = os.path.join(dir, file)
576 if ispackage(path): found(file, 1)
577 for file in files:
578 path = os.path.join(dir, file)
Tim Peters85ba6732001-02-28 08:26:44 +0000579 if file[:1] != '_' and os.path.isfile(path):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000580 modname = modulename(file)
581 if modname: found(modname, 0)
582
583 modpkgs.sort()
584 contents = self.multicolumn(modpkgs, self.modpkglink)
585 return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
586
587# -------------------------------------------- text documentation generator
588
589class TextRepr(Repr):
590 """Class for safely making a text representation of a Python object."""
591 def __init__(self):
592 Repr.__init__(self)
593 self.maxlist = self.maxtuple = self.maxdict = 10
594 self.maxstring = self.maxother = 50
595
596 def repr1(self, x, level):
597 methodname = 'repr_' + join(split(type(x).__name__), '_')
598 if hasattr(self, methodname):
599 return getattr(self, methodname)(x, level)
600 else:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000601 return cram(stripid(repr(x)), self.maxother)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000602
603 def repr_instance(self, x, level):
604 try:
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000605 return cram(stripid(repr(x)), self.maxstring)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000606 except:
607 return '<%s instance>' % x.__class__.__name__
608
609class TextDoc(Doc):
610 """Formatter class for text documentation."""
611
612 # ------------------------------------------- text formatting utilities
613
614 _repr_instance = TextRepr()
615 repr = _repr_instance.repr
616
617 def bold(self, text):
618 """Format a string in bold by overstriking."""
619 return join(map(lambda ch: ch + '\b' + ch, text), '')
620
621 def indent(self, text, prefix=' '):
622 """Indent text by prepending a given prefix to each line."""
623 if not text: return ''
624 lines = split(text, '\n')
625 lines = map(lambda line, prefix=prefix: prefix + line, lines)
626 if lines: lines[-1] = rstrip(lines[-1])
627 return join(lines, '\n')
628
629 def section(self, title, contents):
630 """Format a section with a given heading."""
631 return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
632
633 # ---------------------------------------------- type-specific routines
634
635 def doctree(self, tree, modname, parent=None, prefix=''):
636 """Render in text a class tree as returned by inspect.getclasstree()."""
637 result = ''
638 for entry in tree:
639 if type(entry) is type(()):
640 cl, bases = entry
641 result = result + prefix + classname(cl, modname)
642 if bases and bases != (parent,):
643 parents = map(lambda cl, m=modname: classname(cl, m), bases)
644 result = result + '(%s)' % join(parents, ', ')
645 result = result + '\n'
646 elif type(entry) is type([]):
647 result = result + self.doctree(
648 entry, modname, cl, prefix + ' ')
649 return result
650
651 def docmodule(self, object):
652 """Produce text documentation for a given module object."""
653 result = ''
654
655 name = object.__name__
656 lines = split(strip(getdoc(object)), '\n')
657 if len(lines) == 1:
658 if lines[0]: name = name + ' - ' + lines[0]
659 lines = []
660 elif len(lines) >= 2 and not rstrip(lines[1]):
661 if lines[0]: name = name + ' - ' + lines[0]
662 lines = lines[2:]
663 result = result + self.section('NAME', name)
664 try: file = inspect.getfile(object) # XXX or getsourcefile?
665 except TypeError: file = None
666 result = result + self.section('FILE', file or '(built-in)')
667 if lines:
668 result = result + self.section('DESCRIPTION', join(lines, '\n'))
669
670 classes = []
671 for key, value in inspect.getmembers(object, inspect.isclass):
672 if (inspect.getmodule(value) or object) is object:
673 classes.append(value)
674 funcs = []
675 for key, value in inspect.getmembers(object, inspect.isroutine):
676 if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
677 funcs.append(value)
678 constants = []
679 for key, value in inspect.getmembers(object, isconstant):
680 if key[:1] != '_':
681 constants.append((key, value))
682
683 if hasattr(object, '__path__'):
684 modpkgs = []
685 for file in os.listdir(object.__path__[0]):
686 if file[:1] != '_':
687 path = os.path.join(object.__path__[0], file)
688 modname = modulename(file)
689 if modname and modname not in modpkgs:
690 modpkgs.append(modname)
691 elif ispackage(path):
692 modpkgs.append(file + ' (package)')
693 modpkgs.sort()
694 result = result + self.section(
695 'PACKAGE CONTENTS', join(modpkgs, '\n'))
696
697 if classes:
698 contents = self.doctree(
699 inspect.getclasstree(classes, 1), object.__name__) + '\n'
700 for item in classes:
701 contents = contents + self.document(item) + '\n'
702 result = result + self.section('CLASSES', contents)
703
704 if funcs:
705 contents = ''
706 for item in funcs:
707 contents = contents + self.document(item) + '\n'
708 result = result + self.section('FUNCTIONS', contents)
709
710 if constants:
711 contents = ''
712 for key, value in constants:
713 line = key + ' = ' + self.repr(value)
714 chop = 70 - len(line)
715 line = self.bold(key) + ' = ' + self.repr(value)
716 if chop < 0: line = line[:chop] + '...'
717 contents = contents + line + '\n'
718 result = result + self.section('CONSTANTS', contents)
719
720 if hasattr(object, '__version__'):
721 version = str(object.__version__)
Ka-Ping Yee1d384632001-03-01 00:24:32 +0000722 if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
723 version = strip(version[11:-1])
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000724 result = result + self.section('VERSION', version)
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000725 if hasattr(object, '__date__'):
726 result = result + self.section('DATE', str(object.__date__))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000727 if hasattr(object, '__author__'):
Ka-Ping Yee6f3f9a42001-02-27 22:42:36 +0000728 result = result + self.section('AUTHOR', str(object.__author__))
729 if hasattr(object, '__credits__'):
730 result = result + self.section('CREDITS', str(object.__credits__))
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000731 return result
732
733 def docclass(self, object):
734 """Produce text documentation for a given class object."""
735 name = object.__name__
736 bases = object.__bases__
737
738 title = 'class ' + self.bold(name)
739 if bases:
740 parents = map(lambda c, m=object.__module__: classname(c, m), bases)
741 title = title + '(%s)' % join(parents, ', ')
742
743 doc = getdoc(object)
744 contents = doc and doc + '\n'
745 methods = map(lambda (key, value): value,
746 inspect.getmembers(object, inspect.ismethod))
747 for item in methods:
748 contents = contents + '\n' + self.document(item)
749
750 if not contents: return title + '\n'
751 return title + '\n' + self.indent(rstrip(contents), ' | ') + '\n'
752
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000753 def formatvalue(self, object):
754 """Format an argument default value as text."""
755 return '=' + self.repr(object)
756
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000757 def docroutine(self, object):
758 """Produce text documentation for a function or method object."""
759 if inspect.ismethod(object): object = object.im_func
760 if inspect.isbuiltin(object):
761 decl = self.bold(object.__name__) + '(...)'
762 else:
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000763 args, varargs, varkw, defaults = inspect.getargspec(object)
764 argspec = inspect.formatargspec(
765 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000766 if object.__name__ == '<lambda>':
767 decl = '<lambda> ' + argspec[1:-1]
768 else:
769 decl = self.bold(object.__name__) + argspec
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000770 doc = getdoc(object)
771 if doc:
772 return decl + '\n' + rstrip(self.indent(doc)) + '\n'
773 else:
774 return decl + '\n'
775
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000776# --------------------------------------------------------- user interfaces
777
778def pager(text):
779 """The first time this is called, determine what kind of pager to use."""
780 global pager
781 pager = getpager()
782 pager(text)
783
784def getpager():
785 """Decide what method to use for paging through text."""
786 if type(sys.stdout) is not types.FileType:
787 return plainpager
788 if not sys.stdin.isatty() or not sys.stdout.isatty():
789 return plainpager
790 if os.environ.has_key('PAGER'):
791 return lambda a: pipepager(a, os.environ['PAGER'])
792 if sys.platform in ['win', 'win32', 'nt']:
793 return lambda a: tempfilepager(a, 'more')
794 if hasattr(os, 'system') and os.system('less 2>/dev/null') == 0:
795 return lambda a: pipepager(a, 'less')
796
797 import tempfile
798 filename = tempfile.mktemp()
799 open(filename, 'w').close()
800 try:
801 if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
802 return lambda text: pipepager(text, 'more')
803 else:
804 return ttypager
805 finally:
806 os.unlink(filename)
807
808def pipepager(text, cmd):
809 """Page through text by feeding it to another program."""
810 pipe = os.popen(cmd, 'w')
811 try:
812 pipe.write(text)
813 pipe.close()
814 except IOError:
815 # Ignore broken pipes caused by quitting the pager program.
816 pass
817
818def tempfilepager(text, cmd):
819 """Page through text by invoking a program on a temporary file."""
820 import tempfile
821 filename = tempfile.mktemp()
822 file = open(filename, 'w')
823 file.write(text)
824 file.close()
825 try:
826 os.system(cmd + ' ' + filename)
827 finally:
828 os.unlink(filename)
829
830def plain(text):
831 """Remove boldface formatting from text."""
832 return re.sub('.\b', '', text)
833
834def ttypager(text):
835 """Page through text on a text terminal."""
836 lines = split(plain(text), '\n')
837 try:
838 import tty
839 fd = sys.stdin.fileno()
840 old = tty.tcgetattr(fd)
841 tty.setcbreak(fd)
842 getchar = lambda: sys.stdin.read(1)
Ka-Ping Yee457aab22001-02-27 23:36:29 +0000843 except (ImportError, AttributeError):
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000844 tty = None
845 getchar = lambda: sys.stdin.readline()[:-1][:1]
846
847 try:
848 r = inc = os.environ.get('LINES', 25) - 1
849 sys.stdout.write(join(lines[:inc], '\n') + '\n')
850 while lines[r:]:
851 sys.stdout.write('-- more --')
852 sys.stdout.flush()
853 c = getchar()
854
855 if c in ['q', 'Q']:
856 sys.stdout.write('\r \r')
857 break
858 elif c in ['\r', '\n']:
859 sys.stdout.write('\r \r' + lines[r] + '\n')
860 r = r + 1
861 continue
862 if c in ['b', 'B', '\x1b']:
863 r = r - inc - inc
864 if r < 0: r = 0
865 sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
866 r = r + inc
867
868 finally:
869 if tty:
870 tty.tcsetattr(fd, tty.TCSAFLUSH, old)
871
872def plainpager(text):
873 """Simply print unformatted text. This is the ultimate fallback."""
874 sys.stdout.write(plain(text))
875
876def describe(thing):
877 """Produce a short description of the given kind of thing."""
878 if inspect.ismodule(thing):
879 if thing.__name__ in sys.builtin_module_names:
880 return 'built-in module ' + thing.__name__
881 if hasattr(thing, '__path__'):
882 return 'package ' + thing.__name__
883 else:
884 return 'module ' + thing.__name__
885 if inspect.isbuiltin(thing):
886 return 'built-in function ' + thing.__name__
887 if inspect.isclass(thing):
888 return 'class ' + thing.__name__
889 if inspect.isfunction(thing):
890 return 'function ' + thing.__name__
891 if inspect.ismethod(thing):
892 return 'method ' + thing.__name__
893 return repr(thing)
894
895def locate(path):
896 """Locate an object by name (or dotted path), importing as necessary."""
897 if not path: # special case: imp.find_module('') strangely succeeds
898 return None, None
899 if type(path) is not types.StringType:
900 return None, path
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000901 parts = split(path, '.')
902 n = 1
903 while n <= len(parts):
904 path = join(parts[:n], '.')
905 try:
906 module = __import__(path)
907 module = reload(module)
908 except:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000909 # determine if error occurred before or after module was found
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000910 if sys.modules.has_key(path):
911 filename = sys.modules[path].__file__
912 elif sys.exc_type is SyntaxError:
913 filename = sys.exc_value.filename
914 else:
915 # module not found, so stop looking
916 break
917 # error occurred in the imported module, so report it
918 raise DocImportError(filename, sys.exc_type, sys.exc_value)
919 try:
920 x = module
921 for p in parts[1:]:
922 x = getattr(x, p)
923 return join(parts[:-1], '.'), x
924 except AttributeError:
925 n = n + 1
926 continue
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000927 if hasattr(__builtins__, path):
928 return None, getattr(__builtins__, path)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000929 return None, None
930
931# --------------------------------------- interactive interpreter interface
932
933text = TextDoc()
934html = HTMLDoc()
935
936def doc(thing):
937 """Display documentation on an object (for interactive use)."""
938 if type(thing) is type(""):
939 try:
940 path, x = locate(thing)
941 except DocImportError, value:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000942 print 'Problem in %s - %s' % (value.filename, value.args)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000943 return
944 if x:
945 thing = x
946 else:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000947 print 'No Python documentation found for %s.' % repr(thing)
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000948 return
949
950 desc = describe(thing)
951 module = inspect.getmodule(thing)
952 if module and module is not thing:
953 desc = desc + ' in module ' + module.__name__
954 pager('Help on %s:\n\n' % desc + text.document(thing))
955
Ka-Ping Yeedd175342001-02-27 14:43:46 +0000956def writedoc(key):
957 """Write HTML documentation to a file in the current directory."""
958 path, object = locate(key)
959 if object:
960 file = open(key + '.html', 'w')
961 file.write(html.page(object))
962 file.close()
963 print 'wrote', key + '.html'
964
965class Helper:
966 def __repr__(self):
967 return """To get help on a Python object, call help(object).
968To get help on a module or package, either import it before calling
969help(module) or call help('modulename')."""
970
971 def __call__(self, *args):
972 if args:
973 doc(args[0])
974 else:
975 print repr(self)
976
977help = Helper()
978
979def man(key):
980 """Display documentation on an object in a form similar to man(1)."""
981 path, object = locate(key)
982 if object:
983 title = 'Python Library Documentation: ' + describe(object)
984 if path: title = title + ' in ' + path
985 pager('\n' + title + '\n\n' + text.document(object))
986 found = 1
987 else:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +0000988 print 'No Python documentation found for %s.' % repr(key)
989
990class Scanner:
991 """A generic tree iterator."""
992 def __init__(self, roots, children, recurse):
993 self.roots = roots[:]
994 self.state = []
995 self.children = children
996 self.recurse = recurse
997
998 def next(self):
999 if not self.state:
1000 if not self.roots:
1001 return None
1002 root = self.roots.pop(0)
1003 self.state = [(root, self.children(root))]
1004 node, children = self.state[-1]
1005 if not children:
1006 self.state.pop()
1007 return self.next()
1008 child = children.pop(0)
1009 if self.recurse(child):
1010 self.state.append((child, self.children(child)))
1011 return child
1012
1013class ModuleScanner(Scanner):
1014 """An interruptible scanner that searches module synopses."""
1015 def __init__(self):
1016 roots = map(lambda dir: (dir, ''), pathdirs())
1017 Scanner.__init__(self, roots, self.submodules, self.ispackage)
1018
1019 def submodules(self, (dir, package)):
1020 children = []
1021 for file in os.listdir(dir):
1022 path = os.path.join(dir, file)
1023 if ispackage(path):
1024 children.append((path, package + (package and '.') + file))
1025 else:
1026 children.append((path, package))
1027 children.sort()
1028 return children
1029
1030 def ispackage(self, (dir, package)):
1031 return ispackage(dir)
1032
1033 def run(self, key, callback, completer=None):
1034 self.quit = 0
1035 seen = {}
1036
1037 for modname in sys.builtin_module_names:
1038 seen[modname] = 1
1039 desc = split(__import__(modname).__doc__ or '', '\n')[0]
1040 if find(lower(modname + ' - ' + desc), lower(key)) >= 0:
1041 callback(None, modname, desc)
1042
1043 while not self.quit:
1044 node = self.next()
1045 if not node: break
1046 path, package = node
1047 modname = modulename(path)
1048 if os.path.isfile(path) and modname:
1049 modname = package + (package and '.') + modname
1050 if not seen.has_key(modname):
1051 seen[modname] = 1
1052 desc = synopsis(path) or ''
1053 if find(lower(modname + ' - ' + desc), lower(key)) >= 0:
1054 callback(path, modname, desc)
1055 if completer: completer()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001056
1057def apropos(key):
1058 """Print all the one-line module summaries that contain a substring."""
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001059 def callback(path, modname, desc):
1060 if modname[-9:] == '.__init__':
1061 modname = modname[:-9] + ' (package)'
1062 print modname, '-', desc or '(no description)'
1063 ModuleScanner().run(key, callback)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001064
1065# --------------------------------------------------- web browser interface
1066
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001067def serve(port, callback=None):
1068 import BaseHTTPServer, mimetools, select
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001069
1070 # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
1071 class Message(mimetools.Message):
1072 def __init__(self, fp, seekable=1):
1073 Message = self.__class__
1074 Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
1075 self.encodingheader = self.getheader('content-transfer-encoding')
1076 self.typeheader = self.getheader('content-type')
1077 self.parsetype()
1078 self.parseplist()
1079
1080 class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
1081 def send_document(self, title, contents):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001082 try:
1083 self.send_response(200)
1084 self.send_header('Content-Type', 'text/html')
1085 self.end_headers()
1086 self.wfile.write('''
1087<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
1088<html><title>Python: %s</title><body bgcolor="#ffffff">
1089%s
1090</body></html>''' % (title, contents))
1091 except IOError: pass
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001092
1093 def do_GET(self):
1094 path = self.path
1095 if path[-5:] == '.html': path = path[:-5]
1096 if path[:1] == '/': path = path[1:]
1097 if path and path != '.':
1098 try:
1099 p, x = locate(path)
1100 except DocImportError, value:
1101 self.send_document(path, html.escape(
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001102 'Problem in %s - %s' % (value.filename, value.args)))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001103 return
1104 if x:
1105 self.send_document(describe(x), html.document(x))
1106 else:
1107 self.send_document(path,
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001108'No Python documentation found for %s.' % repr(path))
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001109 else:
1110 heading = html.heading(
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001111'<big><big><strong>Python: Index of Modules</strong></big></big>',
1112'#ffffff', '#7799ee')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001113 builtins = []
1114 for name in sys.builtin_module_names:
1115 builtins.append('<a href="%s.html">%s</a>' % (name, name))
1116 indices = ['<p>Built-in modules: ' + join(builtins, ', ')]
1117 seen = {}
1118 for dir in pathdirs():
1119 indices.append(html.index(dir, seen))
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001120 contents = heading + join(indices) + """<p align=right>
1121<small><small><font color="#909090" face="helvetica, arial"><strong>
1122pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font></small></small>"""
1123 self.send_document('Index of Modules', contents)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001124
1125 def log_message(self, *args): pass
1126
1127 class DocServer(BaseHTTPServer.HTTPServer):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001128 def __init__(self, port, callback):
1129 self.address = ('127.0.0.1', port)
1130 self.url = 'http://127.0.0.1:%d/' % port
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001131 self.callback = callback
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001132 self.base.__init__(self, self.address, self.handler)
1133
1134 def serve_until_quit(self):
1135 import select
1136 self.quit = 0
1137 while not self.quit:
1138 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
1139 if rd: self.handle_request()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001140
1141 def server_activate(self):
1142 self.base.server_activate(self)
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001143 if self.callback: self.callback(self)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001144
1145 DocServer.base = BaseHTTPServer.HTTPServer
1146 DocServer.handler = DocHandler
1147 DocHandler.MessageClass = Message
1148 try:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001149 DocServer(port, callback).serve_until_quit()
1150 except (KeyboardInterrupt, select.error):
1151 pass
1152 print 'server stopped'
1153
1154# ----------------------------------------------------- graphical interface
1155
1156def gui():
1157 """Graphical interface (starts web server and pops up a control window)."""
1158 class GUI:
1159 def __init__(self, window, port=7464):
1160 self.window = window
1161 self.server = None
1162 self.scanner = None
1163
1164 import Tkinter
1165 self.server_frm = Tkinter.Frame(window)
1166 self.title_lbl = Tkinter.Label(self.server_frm,
1167 text='Starting server...\n ')
1168 self.open_btn = Tkinter.Button(self.server_frm,
1169 text='open browser', command=self.open, state='disabled')
1170 self.quit_btn = Tkinter.Button(self.server_frm,
1171 text='quit serving', command=self.quit, state='disabled')
1172
1173 self.search_frm = Tkinter.Frame(window)
1174 self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
1175 self.search_ent = Tkinter.Entry(self.search_frm)
1176 self.search_ent.bind('<Return>', self.search)
1177 self.stop_btn = Tkinter.Button(self.search_frm,
1178 text='stop', pady=0, command=self.stop, state='disabled')
1179 if sys.platform == 'win32':
1180 # Attempting to hide and show this button crashes under Windows.
1181 self.stop_btn.pack(side='right')
1182
1183 self.window.title('pydoc')
1184 self.window.protocol('WM_DELETE_WINDOW', self.quit)
1185 self.title_lbl.pack(side='top', fill='x')
1186 self.open_btn.pack(side='left', fill='x', expand=1)
1187 self.quit_btn.pack(side='right', fill='x', expand=1)
1188 self.server_frm.pack(side='top', fill='x')
1189
1190 self.search_lbl.pack(side='left')
1191 self.search_ent.pack(side='right', fill='x', expand=1)
1192 self.search_frm.pack(side='top', fill='x')
1193 self.search_ent.focus_set()
1194
1195 self.result_lst = Tkinter.Listbox(window,
1196 font=('helvetica', 8), height=6)
1197 self.result_lst.bind('<Button-1>', self.select)
1198 self.result_lst.bind('<Double-Button-1>', self.goto)
1199 self.result_scr = Tkinter.Scrollbar(window,
1200 orient='vertical', command=self.result_lst.yview)
1201 self.result_lst.config(yscrollcommand=self.result_scr.set)
1202
1203 self.result_frm = Tkinter.Frame(window)
1204 self.goto_btn = Tkinter.Button(self.result_frm,
1205 text='go to selected', command=self.goto)
1206 self.hide_btn = Tkinter.Button(self.result_frm,
1207 text='hide results', command=self.hide)
1208 self.goto_btn.pack(side='left', fill='x', expand=1)
1209 self.hide_btn.pack(side='right', fill='x', expand=1)
1210
1211 self.window.update()
1212 self.minwidth = self.window.winfo_width()
1213 self.minheight = self.window.winfo_height()
1214 self.bigminheight = (self.server_frm.winfo_reqheight() +
1215 self.search_frm.winfo_reqheight() +
1216 self.result_lst.winfo_reqheight() +
1217 self.result_frm.winfo_reqheight())
1218 self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
1219 self.expanded = 0
1220 self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
1221 self.window.wm_minsize(self.minwidth, self.minheight)
1222
1223 import threading
1224 threading.Thread(target=serve, args=(port, self.ready)).start()
1225
1226 def ready(self, server):
1227 self.server = server
1228 self.title_lbl.config(
1229 text='Python documentation server at\n' + server.url)
1230 self.open_btn.config(state='normal')
1231 self.quit_btn.config(state='normal')
1232
1233 def open(self, event=None):
1234 import webbrowser
1235 webbrowser.open(self.server.url)
1236
1237 def quit(self, event=None):
1238 if self.server:
1239 self.server.quit = 1
1240 self.window.quit()
1241
1242 def search(self, event=None):
1243 key = self.search_ent.get()
1244 self.stop_btn.pack(side='right')
1245 self.stop_btn.config(state='normal')
1246 self.search_lbl.config(text='Searching for "%s"...' % key)
1247 self.search_ent.forget()
1248 self.search_lbl.pack(side='left')
1249 self.result_lst.delete(0, 'end')
1250 self.goto_btn.config(state='disabled')
1251 self.expand()
1252
1253 import threading
1254 if self.scanner:
1255 self.scanner.quit = 1
1256 self.scanner = ModuleScanner()
1257 threading.Thread(target=self.scanner.run,
1258 args=(key, self.update, self.done)).start()
1259
1260 def update(self, path, modname, desc):
1261 if modname[-9:] == '.__init__':
1262 modname = modname[:-9] + ' (package)'
1263 self.result_lst.insert('end',
1264 modname + ' - ' + (desc or '(no description)'))
1265
1266 def stop(self, event=None):
1267 if self.scanner:
1268 self.scanner.quit = 1
1269 self.scanner = None
1270
1271 def done(self):
1272 self.scanner = None
1273 self.search_lbl.config(text='Search for')
1274 self.search_lbl.pack(side='left')
1275 self.search_ent.pack(side='right', fill='x', expand=1)
1276 if sys.platform != 'win32': self.stop_btn.forget()
1277 self.stop_btn.config(state='disabled')
1278
1279 def select(self, event=None):
1280 self.goto_btn.config(state='normal')
1281
1282 def goto(self, event=None):
1283 selection = self.result_lst.curselection()
1284 if selection:
1285 import webbrowser
1286 modname = split(self.result_lst.get(selection[0]))[0]
1287 webbrowser.open(self.server.url + modname + '.html')
1288
1289 def collapse(self):
1290 if not self.expanded: return
1291 self.result_frm.forget()
1292 self.result_scr.forget()
1293 self.result_lst.forget()
1294 self.bigwidth = self.window.winfo_width()
1295 self.bigheight = self.window.winfo_height()
1296 self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
1297 self.window.wm_minsize(self.minwidth, self.minheight)
1298 self.expanded = 0
1299
1300 def expand(self):
1301 if self.expanded: return
1302 self.result_frm.pack(side='bottom', fill='x')
1303 self.result_scr.pack(side='right', fill='y')
1304 self.result_lst.pack(side='top', fill='both', expand=1)
1305 self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
1306 self.window.wm_minsize(self.minwidth, self.bigminheight)
1307 self.expanded = 1
1308
1309 def hide(self, event=None):
1310 self.stop()
1311 self.collapse()
1312
1313 import Tkinter
1314 try:
1315 gui = GUI(Tkinter.Tk())
1316 Tkinter.mainloop()
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001317 except KeyboardInterrupt:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001318 pass
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001319
1320# -------------------------------------------------- command-line interface
1321
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001322def cli():
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001323 """Command-line interface (looks at sys.argv to decide what to do)."""
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001324 import getopt
1325 class BadUsage: pass
1326
1327 try:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001328 if sys.platform in ['mac', 'win', 'win32', 'nt'] and not sys.argv[1:]:
1329 # CLI-less platforms
1330 gui()
1331 return
1332
1333 opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001334 writing = 0
1335
1336 for opt, val in opts:
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001337 if opt == '-g':
1338 gui()
1339 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001340 if opt == '-k':
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001341 apropos(val)
1342 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001343 if opt == '-p':
1344 try:
1345 port = int(val)
1346 except ValueError:
1347 raise BadUsage
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001348 def ready(server):
1349 print 'server ready at %s' % server.url
1350 serve(port, ready)
1351 return
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001352 if opt == '-w':
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001353 writing = 1
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001354
1355 if not args: raise BadUsage
1356 for arg in args:
1357 try:
1358 if find(arg, os.sep) >= 0 and os.path.isfile(arg):
1359 arg = importfile(arg)
1360 if writing: writedoc(arg)
1361 else: man(arg)
1362 except DocImportError, value:
1363 print 'Problem in %s - %s' % (value.filename, value.args)
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001364
1365 except (getopt.error, BadUsage):
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001366 cmd = sys.argv[0]
1367 print """pydoc - the Python documentation tool
1368
1369%s <name> ...
1370 Show text documentation on something. <name> may be the name of a
1371 function, module, or package, or a dotted reference to a class or
1372 function within a module or module in a package. If <name> contains
1373 a '%s', it is used as the path to a Python source file to document.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001374
1375%s -k <keyword>
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001376 Search for a keyword in the synopsis lines of all available modules.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001377
1378%s -p <port>
1379 Start an HTTP server on the given port on the local machine.
1380
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001381%s -g
1382 Pop up a graphical interface for serving and finding documentation.
Ka-Ping Yeedd175342001-02-27 14:43:46 +00001383
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001384%s -w <name> ...
1385 Write out the HTML documentation for a module to a file in the current
1386 directory. If <name> contains a '%s', it is treated as a filename.
1387""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
Ka-Ping Yee1d384632001-03-01 00:24:32 +00001388
Ka-Ping Yee66efbc72001-03-01 13:55:20 +00001389if __name__ == '__main__': cli()
1390
1391