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