2 # -*- coding: latin-1 -*-
3 """Generate Python documentation in HTML or text for interactive use.
5 In the Python interpreter, do "from pydoc import help" to provide online
6 help. Calling help(thing) on a Python object documents the object.
8 Or, at the shell command line outside of Python:
10 Run "pydoc <name>" to show documentation on something. <name> may be
11 the name of a function, module, package, or a dotted reference to a
12 class or function within a module or module in a package. If the
13 argument contains a path segment delimiter (e.g. slash on Unix,
14 backslash on Windows) it is treated as the path to a Python source file.
16 Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
17 of all available modules.
19 Run "pydoc -p <port>" to start an HTTP server on a given port on the
20 local machine to generate documentation web pages.
22 For platforms without a command line, "pydoc -g" starts the HTTP server
23 and also pops up a little window for controlling it.
25 Run "pydoc -w <name>" to write out the HTML documentation for a module
26 to a file named "<name>.html".
28 Module docs for core modules are assumed to be in
30 http://docs.python.org/library/
32 This can be overridden by setting the PYTHONDOCS environment variable
33 to a different URL or to a local directory containing the Library
34 Reference Manual pages.
37 __author__
= "Ka-Ping Yee <ping@lfw.org>"
38 __date__
= "26 February 2001"
40 __version__
= "$Revision$"
41 __credits__
= """Guido van Rossum, for an excellent programming language.
42 Tommy Burnette, the original creator of manpy.
43 Paul Prescod, for all his work on onlinehelp.
44 Richard Chamberlain, for the first implementation of textdoc.
47 # Known bugs that can't be fixed here:
48 # - imp.load_module() cannot be prevented from clobbering existing
49 # loaded modules, so calling synopsis() on a binary module file
50 # changes the contents of any existing module with the same name.
51 # - If the __file__ attribute on a module is a relative path and
52 # the current directory is changed with os.chdir(), an incorrect
53 # path will be displayed.
55 import sys
, imp
, os
, re
, inspect
, builtins
, pkgutil
56 from reprlib
import Repr
57 from traceback
import extract_tb
as _extract_tb
59 from collections
import deque
61 # Python 2.3 compatibility
66 # --------------------------------------------------------- common routines
69 """Convert sys.path into a list of absolute, existing, unique paths."""
73 dir = os
.path
.abspath(dir or '.')
74 normdir
= os
.path
.normcase(dir)
75 if normdir
not in normdirs
and os
.path
.isdir(dir):
77 normdirs
.append(normdir
)
81 """Get the doc string or comments for an object."""
82 result
= inspect
.getdoc(object) or inspect
.getcomments(object)
83 return result
and re
.sub('^ *\n', '', result
.rstrip()) or ''
86 """Split a doc string into a synopsis line (if any) and the rest."""
87 lines
= doc
.strip().split('\n')
90 elif len(lines
) >= 2 and not lines
[1].rstrip():
91 return lines
[0], '\n'.join(lines
[2:])
92 return '', '\n'.join(lines
)
94 def classname(object, modname
):
95 """Get a class name and qualify it with a module name if necessary."""
96 name
= object.__name
__
97 if object.__module
__ != modname
:
98 name
= object.__module
__ + '.' + name
102 """Check if an object is of a type that probably means it's data."""
103 return not (inspect
.ismodule(object) or inspect
.isclass(object) or
104 inspect
.isroutine(object) or inspect
.isframe(object) or
105 inspect
.istraceback(object) or inspect
.iscode(object))
107 def replace(text
, *pairs
):
108 """Do a series of global replacements on a string."""
110 text
= pairs
[1].join(text
.split(pairs
[0]))
114 def cram(text
, maxlen
):
115 """Omit part of a string if needed to make it fit in a maximum length."""
116 if len(text
) > maxlen
:
117 pre
= max(0, (maxlen
-3)//2)
118 post
= max(0, maxlen
-3-pre
)
119 return text
[:pre
] + '...' + text
[len(text
)-post
:]
122 _re_stripid
= re
.compile(r
' at 0x[0-9a-f]{6,16}(>+)$', re
.IGNORECASE
)
124 """Remove the hexadecimal id from a Python object representation."""
125 # The behaviour of %p is implementation-dependent in terms of case.
126 return _re_stripid
.sub(r
'\1', text
)
128 def _is_some_method(obj
):
129 return inspect
.ismethod(obj
) or inspect
.ismethoddescriptor(obj
)
133 for key
, value
in inspect
.getmembers(cl
, _is_some_method
):
135 for base
in cl
.__bases
__:
136 methods
.update(allmethods(base
)) # all your base are belong to us
137 for key
in methods
.keys():
138 methods
[key
] = getattr(cl
, key
)
141 def _split_list(s
, predicate
):
142 """Split sequence s via predicate, and return pair ([true], [false]).
144 The return value is a 2-tuple of lists,
145 ([x for x in s if predicate(x)],
146 [x for x in s if not predicate(x)])
158 def visiblename(name
, all
=None):
159 """Decide whether to show documentation on a variable."""
160 # Certain special names are redundant.
161 _hidden_names
= ('__builtins__', '__doc__', '__file__', '__path__',
162 '__module__', '__name__', '__slots__', '__package__')
163 if name
in _hidden_names
: return 0
164 # Private names are hidden, but special names are displayed.
165 if name
.startswith('__') and name
.endswith('__'): return 1
167 # only document that which the programmer exported in __all__
170 return not name
.startswith('_')
172 def classify_class_attrs(object):
173 """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
175 for (name
, kind
, cls
, value
) in inspect
.classify_class_attrs(object):
176 if inspect
.isdatadescriptor(value
):
177 kind
= 'data descriptor'
178 results
.append((name
, kind
, cls
, value
))
181 # ----------------------------------------------------- module manipulation
184 """Guess whether a path refers to a package directory."""
185 if os
.path
.isdir(path
):
186 for ext
in ('.py', '.pyc', '.pyo'):
187 if os
.path
.isfile(os
.path
.join(path
, '__init__' + ext
)):
191 def source_synopsis(file):
192 line
= file.readline()
193 while line
[:1] == '#' or not line
.strip():
194 line
= file.readline()
197 if line
[:4] == 'r"""': line
= line
[1:]
198 if line
[:3] == '"""':
200 if line
[-1:] == '\\': line
= line
[:-1]
201 while not line
.strip():
202 line
= file.readline()
204 result
= line
.split('"""')[0].strip()
208 def synopsis(filename
, cache
={}):
209 """Get the one-line summary out of a module file."""
210 mtime
= os
.stat(filename
).st_mtime
211 lastupdate
, result
= cache
.get(filename
, (0, None))
212 if lastupdate
< mtime
:
213 info
= inspect
.getmoduleinfo(filename
)
215 file = open(filename
)
217 # module can't be opened, so skip it
219 if info
and 'b' in info
[2]: # binary modules have to be imported
220 try: module
= imp
.load_module('__temp__', file, filename
, info
[1:])
222 result
= (module
.__doc
__ or '').splitlines()[0]
223 del sys
.modules
['__temp__']
224 else: # text modules can be directly examined
225 result
= source_synopsis(file)
227 cache
[filename
] = (mtime
, result
)
230 class ErrorDuringImport(Exception):
231 """Errors that occurred while trying to import something to document it."""
232 def __init__(self
, filename
, exc_info
):
233 self
.filename
= filename
234 self
.exc
, self
.value
, self
.tb
= exc_info
237 exc
= self
.exc
.__name
__
238 return 'problem in %s - %s: %s' % (self
.filename
, exc
, self
.value
)
240 def importfile(path
):
241 """Import a Python source file or compiled file given its path."""
242 magic
= imp
.get_magic()
243 file = open(path
, 'r')
244 if file.read(len(magic
)) == magic
:
245 kind
= imp
.PY_COMPILED
249 filename
= os
.path
.basename(path
)
250 name
, ext
= os
.path
.splitext(filename
)
251 file = open(path
, 'r')
253 module
= imp
.load_module(name
, file, path
, (ext
, 'r', kind
))
255 raise ErrorDuringImport(path
, sys
.exc_info())
259 def safeimport(path
, forceload
=0, cache
={}):
260 """Import a module; handle errors; return None if the module isn't found.
262 If the module *is* found but an exception occurs, it's wrapped in an
263 ErrorDuringImport exception and reraised. Unlike __import__, if a
264 package path is specified, the module at the end of the path is returned,
265 not the package at the beginning. If the optional 'forceload' argument
266 is 1, we reload the module from disk (unless it's a dynamic extension)."""
268 # If forceload is 1 and the module has been previously loaded from
269 # disk, we always have to reload the module. Checking the file's
270 # mtime isn't good enough (e.g. the module could contain a class
271 # that inherits from another module that has changed).
272 if forceload
and path
in sys
.modules
:
273 if path
not in sys
.builtin_module_names
:
274 # Remove the module from sys.modules and re-import to try
275 # and avoid problems with partially loaded modules.
276 # Also remove any submodules because they won't appear
277 # in the newly loaded module's namespace if they're already
279 subs
= [m
for m
in sys
.modules
if m
.startswith(path
+ '.')]
280 for key
in [path
] + subs
:
281 # Prevent garbage collection.
282 cache
[key
] = sys
.modules
[key
]
284 module
= __import__(path
)
286 # Did the error occur before or after the module was found?
287 (exc
, value
, tb
) = info
= sys
.exc_info()
288 if path
in sys
.modules
:
289 # An error occurred while executing the imported module.
290 raise ErrorDuringImport(sys
.modules
[path
].__file
__, info
)
291 elif exc
is SyntaxError:
292 # A SyntaxError occurred before we could execute the module.
293 raise ErrorDuringImport(value
.filename
, info
)
294 elif exc
is ImportError and _extract_tb(tb
)[-1][2]=='safeimport':
295 # The import error occurred directly in this function,
296 # which means there is no such module in the path.
299 # Some other error occurred during the importing process.
300 raise ErrorDuringImport(path
, sys
.exc_info())
301 for part
in path
.split('.')[1:]:
302 try: module
= getattr(module
, part
)
303 except AttributeError: return None
306 # ---------------------------------------------------- formatter base class
309 def document(self
, object, name
=None, *args
):
310 """Generate documentation for an object."""
311 args
= (object, name
) + args
312 # 'try' clause is to attempt to handle the possibility that inspect
313 # identifies something in a way that pydoc itself has issues handling;
314 # think 'super' and how it is a descriptor (which raises the exception
315 # by lacking a __name__ attribute) and an instance.
316 if inspect
.isgetsetdescriptor(object): return self
.docdata(*args
)
317 if inspect
.ismemberdescriptor(object): return self
.docdata(*args
)
319 if inspect
.ismodule(object): return self
.docmodule(*args
)
320 if inspect
.isclass(object): return self
.docclass(*args
)
321 if inspect
.isroutine(object): return self
.docroutine(*args
)
322 except AttributeError:
324 if isinstance(object, property): return self
.docproperty(*args
)
325 return self
.docother(*args
)
327 def fail(self
, object, name
=None, *args
):
328 """Raise an exception for unimplemented types."""
329 message
= "don't know how to document object%s of type %s" % (
330 name
and ' ' + repr(name
), type(object).__name
__)
331 raise TypeError(message
)
333 docmodule
= docclass
= docroutine
= docother
= docproperty
= docdata
= fail
335 def getdocloc(self
, object):
336 """Return the location of module docs or None"""
339 file = inspect
.getabsfile(object)
343 docloc
= os
.environ
.get("PYTHONDOCS",
344 "http://docs.python.org/library")
345 basedir
= os
.path
.join(sys
.exec_prefix
, "lib",
346 "python"+sys
.version
[0:3])
347 if (isinstance(object, type(os
)) and
348 (object.__name
__ in ('errno', 'exceptions', 'gc', 'imp',
349 'marshal', 'posix', 'signal', 'sys',
350 '_thread', 'zipimport') or
351 (file.startswith(basedir
) and
352 not file.startswith(os
.path
.join(basedir
, 'site-packages'))))):
353 if docloc
.startswith("http://"):
354 docloc
= "%s/%s" % (docloc
.rstrip("/"), object.__name
__)
356 docloc
= os
.path
.join(docloc
, object.__name
__ + ".html")
361 # -------------------------------------------- HTML documentation generator
363 class HTMLRepr(Repr
):
364 """Class for safely making an HTML representation of a Python object."""
367 self
.maxlist
= self
.maxtuple
= 20
369 self
.maxstring
= self
.maxother
= 100
371 def escape(self
, text
):
372 return replace(text
, '&', '&', '<', '<', '>', '>')
374 def repr(self
, object):
375 return Repr
.repr(self
, object)
377 def repr1(self
, x
, level
):
378 if hasattr(type(x
), '__name__'):
379 methodname
= 'repr_' + '_'.join(type(x
).__name
__.split())
380 if hasattr(self
, methodname
):
381 return getattr(self
, methodname
)(x
, level
)
382 return self
.escape(cram(stripid(repr(x
)), self
.maxother
))
384 def repr_string(self
, x
, level
):
385 test
= cram(x
, self
.maxstring
)
386 testrepr
= repr(test
)
387 if '\\' in test
and '\\' not in replace(testrepr
, r
'\\', ''):
388 # Backslashes are only literal in the string and are never
389 # needed to make any special characters, so show a raw string.
390 return 'r' + testrepr
[0] + self
.escape(test
) + testrepr
[0]
391 return re
.sub(r
'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
392 r'<font color="#c040c0">\1</font>',
393 self
.escape(testrepr
))
395 repr_str
= repr_string
397 def repr_instance(self
, x
, level
):
399 return self
.escape(cram(stripid(repr(x
)), self
.maxstring
))
401 return self
.escape('<%s instance>' % x
.__class
__.__name
__)
403 repr_unicode
= repr_string
406 """Formatter class for HTML documentation."""
408 # ------------------------------------------- HTML formatting utilities
410 _repr_instance
= HTMLRepr()
411 repr = _repr_instance
.repr
412 escape
= _repr_instance
.escape
414 def page(self
, title
, contents
):
415 """Format an HTML page."""
417 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
418 <html><head><title>Python: %s</title>
419 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
420 </head><body bgcolor="#f0f0f8">
422 </body></html>''' % (title
, contents
)
424 def heading(self
, title
, fgcol
, bgcol
, extras
=''):
425 """Format a page heading."""
427 <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
429 <td valign=bottom> <br>
430 <font color="%s" face="helvetica, arial"> <br>%s</font></td
431 ><td align=right valign=bottom
432 ><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
433 ''' % (bgcol
, fgcol
, title
, fgcol
, extras
or ' ')
435 def section(self
, title
, fgcol
, bgcol
, contents
, width
=6,
436 prelude
='', marginalia
=None, gap
=' '):
437 """Format a section with a heading."""
438 if marginalia
is None:
439 marginalia
= '<tt>' + ' ' * width
+ '</tt>'
441 <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
443 <td colspan=3 valign=bottom> <br>
444 <font color="%s" face="helvetica, arial">%s</font></td></tr>
445 ''' % (bgcol
, fgcol
, title
)
447 result
= result
+ '''
448 <tr bgcolor="%s"><td rowspan=2>%s</td>
449 <td colspan=2>%s</td></tr>
450 <tr><td>%s</td>''' % (bgcol
, marginalia
, prelude
, gap
)
452 result
= result
+ '''
453 <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol
, marginalia
, gap
)
455 return result
+ '\n<td width="100%%">%s</td></tr></table>' % contents
457 def bigsection(self
, title
, *args
):
458 """Format a section with a big heading."""
459 title
= '<big><strong>%s</strong></big>' % title
460 return self
.section(title
, *args
)
462 def preformat(self
, text
):
463 """Format literal preformatted text."""
464 text
= self
.escape(text
.expandtabs())
465 return replace(text
, '\n\n', '\n \n', '\n\n', '\n \n',
466 ' ', ' ', '\n', '<br>\n')
468 def multicolumn(self
, list, format
, cols
=4):
469 """Format a list of items into a multi-column list."""
471 rows
= (len(list)+cols
-1)//cols
472 for col
in range(cols
):
473 result
= result
+ '<td width="%d%%" valign=top>' % (100//cols
)
474 for i
in range(rows
*col
, rows
*col
+rows
):
476 result
= result
+ format(list[i
]) + '<br>\n'
477 result
= result
+ '</td>'
478 return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
480 def grey(self
, text
): return '<font color="#909090">%s</font>' % text
482 def namelink(self
, name
, *dicts
):
483 """Make a link for an identifier, given name-to-URL mappings."""
486 return '<a href="%s">%s</a>' % (dict[name
], name
)
489 def classlink(self
, object, modname
):
490 """Make a link for a class."""
491 name
, module
= object.__name
__, sys
.modules
.get(object.__module
__)
492 if hasattr(module
, name
) and getattr(module
, name
) is object:
493 return '<a href="%s.html#%s">%s</a>' % (
494 module
.__name
__, name
, classname(object, modname
))
495 return classname(object, modname
)
497 def modulelink(self
, object):
498 """Make a link for a module."""
499 return '<a href="%s.html">%s</a>' % (object.__name
__, object.__name
__)
501 def modpkglink(self
, modpkginfo
):
502 """Make a link for a module or package to display in an index."""
503 name
, path
, ispackage
, shadowed
= modpkginfo
505 return self
.grey(name
)
507 url
= '%s.%s.html' % (path
, name
)
509 url
= '%s.html' % name
511 text
= '<strong>%s</strong> (package)' % name
514 return '<a href="%s">%s</a>' % (url
, text
)
516 def markup(self
, text
, escape
=None, funcs
={}, classes
={}, methods
={}):
517 """Mark up some plain text, given a context of symbols to look for.
518 Each context dictionary maps object names to anchor names."""
519 escape
= escape
or self
.escape
522 pattern
= re
.compile(r
'\b((http|ftp)://\S+[\w/]|'
527 match
= pattern
.search(text
, here
)
529 start
, end
= match
.span()
530 results
.append(escape(text
[here
:start
]))
532 all
, scheme
, rfc
, pep
, selfdot
, name
= match
.groups()
534 url
= escape(all
).replace('"', '"')
535 results
.append('<a href="%s">%s</a>' % (url
, url
))
537 url
= 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc
)
538 results
.append('<a href="%s">%s</a>' % (url
, escape(all
)))
540 url
= 'http://www.python.org/dev/peps/pep-%04d/' % int(pep
)
541 results
.append('<a href="%s">%s</a>' % (url
, escape(all
)))
542 elif text
[end
:end
+1] == '(':
543 results
.append(self
.namelink(name
, methods
, funcs
, classes
))
545 results
.append('self.<strong>%s</strong>' % name
)
547 results
.append(self
.namelink(name
, classes
))
549 results
.append(escape(text
[here
:]))
550 return ''.join(results
)
552 # ---------------------------------------------- type-specific routines
554 def formattree(self
, tree
, modname
, parent
=None):
555 """Produce HTML for a class tree as given by inspect.getclasstree()."""
558 if type(entry
) is type(()):
560 result
= result
+ '<dt><font face="helvetica, arial">'
561 result
= result
+ self
.classlink(c
, modname
)
562 if bases
and bases
!= (parent
,):
565 parents
.append(self
.classlink(base
, modname
))
566 result
= result
+ '(' + ', '.join(parents
) + ')'
567 result
= result
+ '\n</font></dt>'
568 elif type(entry
) is type([]):
569 result
= result
+ '<dd>\n%s</dd>\n' % self
.formattree(
571 return '<dl>\n%s</dl>\n' % result
573 def docmodule(self
, object, name
=None, mod
=None, *ignored
):
574 """Produce HTML documentation for a module object."""
575 name
= object.__name
__ # ignore the passed-in name
578 except AttributeError:
580 parts
= name
.split('.')
582 for i
in range(len(parts
)-1):
584 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
585 ('.'.join(parts
[:i
+1]), parts
[i
]))
586 linkedname
= '.'.join(links
+ parts
[-1:])
587 head
= '<big><big><strong>%s</strong></big></big>' % linkedname
589 path
= inspect
.getabsfile(object)
591 if sys
.platform
== 'win32':
593 url
= nturl2path
.pathname2url(path
)
594 filelink
= '<a href="file:%s">%s</a>' % (url
, path
)
596 filelink
= '(built-in)'
598 if hasattr(object, '__version__'):
599 version
= str(object.__version
__)
600 if version
[:11] == '$' + 'Revision: ' and version
[-1:] == '$':
601 version
= version
[11:-1].strip()
602 info
.append('version %s' % self
.escape(version
))
603 if hasattr(object, '__date__'):
604 info
.append(self
.escape(str(object.__date
__)))
606 head
= head
+ ' (%s)' % ', '.join(info
)
607 docloc
= self
.getdocloc(object)
608 if docloc
is not None:
609 docloc
= '<br><a href="%(docloc)s">Module Docs</a>' % locals()
612 result
= self
.heading(
613 head
, '#ffffff', '#7799ee',
614 '<a href=".">index</a><br>' + filelink
+ docloc
)
616 modules
= inspect
.getmembers(object, inspect
.ismodule
)
618 classes
, cdict
= [], {}
619 for key
, value
in inspect
.getmembers(object, inspect
.isclass
):
620 # if __all__ exists, believe it. Otherwise use old heuristic.
621 if (all
is not None or
622 (inspect
.getmodule(value
) or object) is object):
623 if visiblename(key
, all
):
624 classes
.append((key
, value
))
625 cdict
[key
] = cdict
[value
] = '#' + key
626 for key
, value
in classes
:
627 for base
in value
.__bases
__:
628 key
, modname
= base
.__name
__, base
.__module
__
629 module
= sys
.modules
.get(modname
)
630 if modname
!= name
and module
and hasattr(module
, key
):
631 if getattr(module
, key
) is base
:
633 cdict
[key
] = cdict
[base
] = modname
+ '.html#' + key
634 funcs
, fdict
= [], {}
635 for key
, value
in inspect
.getmembers(object, inspect
.isroutine
):
636 # if __all__ exists, believe it. Otherwise use old heuristic.
637 if (all
is not None or
638 inspect
.isbuiltin(value
) or inspect
.getmodule(value
) is object):
639 if visiblename(key
, all
):
640 funcs
.append((key
, value
))
641 fdict
[key
] = '#-' + key
642 if inspect
.isfunction(value
): fdict
[value
] = fdict
[key
]
644 for key
, value
in inspect
.getmembers(object, isdata
):
645 if visiblename(key
, all
):
646 data
.append((key
, value
))
648 doc
= self
.markup(getdoc(object), self
.preformat
, fdict
, cdict
)
649 doc
= doc
and '<tt>%s</tt>' % doc
650 result
= result
+ '<p>%s</p>\n' % doc
652 if hasattr(object, '__path__'):
654 for importer
, modname
, ispkg
in pkgutil
.iter_modules(object.__path
__):
655 modpkgs
.append((modname
, name
, ispkg
, 0))
657 contents
= self
.multicolumn(modpkgs
, self
.modpkglink
)
658 result
= result
+ self
.bigsection(
659 'Package Contents', '#ffffff', '#aa55cc', contents
)
661 contents
= self
.multicolumn(
662 modules
, lambda t
: self
.modulelink(t
[1]))
663 result
= result
+ self
.bigsection(
664 'Modules', '#ffffff', '#aa55cc', contents
)
667 classlist
= [value
for (key
, value
) in classes
]
669 self
.formattree(inspect
.getclasstree(classlist
, 1), name
)]
670 for key
, value
in classes
:
671 contents
.append(self
.document(value
, key
, name
, fdict
, cdict
))
672 result
= result
+ self
.bigsection(
673 'Classes', '#ffffff', '#ee77aa', ' '.join(contents
))
676 for key
, value
in funcs
:
677 contents
.append(self
.document(value
, key
, name
, fdict
, cdict
))
678 result
= result
+ self
.bigsection(
679 'Functions', '#ffffff', '#eeaa77', ' '.join(contents
))
682 for key
, value
in data
:
683 contents
.append(self
.document(value
, key
))
684 result
= result
+ self
.bigsection(
685 'Data', '#ffffff', '#55aa55', '<br>\n'.join(contents
))
686 if hasattr(object, '__author__'):
687 contents
= self
.markup(str(object.__author
__), self
.preformat
)
688 result
= result
+ self
.bigsection(
689 'Author', '#ffffff', '#7799ee', contents
)
690 if hasattr(object, '__credits__'):
691 contents
= self
.markup(str(object.__credits
__), self
.preformat
)
692 result
= result
+ self
.bigsection(
693 'Credits', '#ffffff', '#7799ee', contents
)
697 def docclass(self
, object, name
=None, mod
=None, funcs
={}, classes
={},
699 """Produce HTML documentation for a class object."""
700 realname
= object.__name
__
701 name
= name
or realname
702 bases
= object.__bases
__
705 push
= contents
.append
707 # Cute little class to pump out a horizontal rule between sections.
708 class HorizontalRule
:
715 hr
= HorizontalRule()
717 # List the mro, if non-trivial.
718 mro
= deque(inspect
.getmro(object))
721 push('<dl><dt>Method resolution order:</dt>\n')
723 push('<dd>%s</dd>\n' % self
.classlink(base
,
727 def spill(msg
, attrs
, predicate
):
728 ok
, attrs
= _split_list(attrs
, predicate
)
732 for name
, kind
, homecls
, value
in ok
:
733 push(self
.document(getattr(object, name
), name
, mod
,
734 funcs
, classes
, mdict
, object))
738 def spilldescriptors(msg
, attrs
, predicate
):
739 ok
, attrs
= _split_list(attrs
, predicate
)
743 for name
, kind
, homecls
, value
in ok
:
744 push(self
._docdescriptor
(name
, value
, mod
))
747 def spilldata(msg
, attrs
, predicate
):
748 ok
, attrs
= _split_list(attrs
, predicate
)
752 for name
, kind
, homecls
, value
in ok
:
753 base
= self
.docother(getattr(object, name
), name
, mod
)
754 if hasattr(value
, '__call__') or inspect
.isdatadescriptor(value
):
755 doc
= getattr(value
, "__doc__", None)
759 push('<dl><dt>%s</dl>\n' % base
)
761 doc
= self
.markup(getdoc(value
), self
.preformat
,
762 funcs
, classes
, mdict
)
763 doc
= '<dd><tt>%s</tt>' % doc
764 push('<dl><dt>%s%s</dl>\n' % (base
, doc
))
768 attrs
= [(name
, kind
, cls
, value
)
769 for name
, kind
, cls
, value
in classify_class_attrs(object)
770 if visiblename(name
)]
773 for key
, kind
, homecls
, value
in attrs
:
774 mdict
[key
] = anchor
= '#' + name
+ '-' + key
775 value
= getattr(object, key
)
777 # The value may not be hashable (e.g., a data attr with
778 # a dict or list value).
779 mdict
[value
] = anchor
785 thisclass
= mro
.popleft()
787 thisclass
= attrs
[0][2]
788 attrs
, inherited
= _split_list(attrs
, lambda t
: t
[2] is thisclass
)
790 if thisclass
is builtins
.object:
793 elif thisclass
is object:
796 tag
= 'inherited from %s' % self
.classlink(thisclass
,
800 # Sort attrs by name.
801 attrs
.sort(key
=lambda t
: t
[0])
803 # Pump out the attrs, segregated by kind.
804 attrs
= spill('Methods %s' % tag
, attrs
,
805 lambda t
: t
[1] == 'method')
806 attrs
= spill('Class methods %s' % tag
, attrs
,
807 lambda t
: t
[1] == 'class method')
808 attrs
= spill('Static methods %s' % tag
, attrs
,
809 lambda t
: t
[1] == 'static method')
810 attrs
= spilldescriptors('Data descriptors %s' % tag
, attrs
,
811 lambda t
: t
[1] == 'data descriptor')
812 attrs
= spilldata('Data and other attributes %s' % tag
, attrs
,
813 lambda t
: t
[1] == 'data')
817 contents
= ''.join(contents
)
820 title
= '<a name="%s">class <strong>%s</strong></a>' % (
823 title
= '<strong>%s</strong> = <a name="%s">class %s</a>' % (
824 name
, name
, realname
)
828 parents
.append(self
.classlink(base
, object.__module
__))
829 title
= title
+ '(%s)' % ', '.join(parents
)
830 doc
= self
.markup(getdoc(object), self
.preformat
, funcs
, classes
, mdict
)
831 doc
= doc
and '<tt>%s<br> </tt>' % doc
833 return self
.section(title
, '#000000', '#ffc8d8', contents
, 3, doc
)
835 def formatvalue(self
, object):
836 """Format an argument default value as text."""
837 return self
.grey('=' + self
.repr(object))
839 def docroutine(self
, object, name
=None, mod
=None,
840 funcs
={}, classes
={}, methods
={}, cl
=None):
841 """Produce HTML documentation for a function or method object."""
842 realname
= object.__name
__
843 name
= name
or realname
844 anchor
= (cl
and cl
.__name
__ or '') + '-' + name
847 if inspect
.ismethod(object):
848 imclass
= object.__self
__.__class
__
850 if imclass
is not cl
:
851 note
= ' from ' + self
.classlink(imclass
, mod
)
853 if object.__self
__ is not None:
854 note
= ' method of %s instance' % self
.classlink(
855 object.__self
__.__class
__, mod
)
857 note
= ' unbound %s method' % self
.classlink(imclass
,mod
)
858 object = object.__func
__
861 title
= '<a name="%s"><strong>%s</strong></a>' % (anchor
, realname
)
863 if (cl
and realname
in cl
.__dict
__ and
864 cl
.__dict
__[realname
] is object):
865 reallink
= '<a href="#%s">%s</a>' % (
866 cl
.__name
__ + '-' + realname
, realname
)
870 title
= '<a name="%s"><strong>%s</strong></a> = %s' % (
871 anchor
, name
, reallink
)
872 if inspect
.isfunction(object):
873 args
, varargs
, kwonlyargs
, kwdefaults
, varkw
, defaults
, ann
= \
874 inspect
.getfullargspec(object)
875 argspec
= inspect
.formatargspec(
876 args
, varargs
, kwonlyargs
, kwdefaults
, varkw
, defaults
, ann
,
877 formatvalue
=self
.formatvalue
,
878 formatannotation
=inspect
.formatannotationrelativeto(object))
879 if realname
== '<lambda>':
880 title
= '<strong>%s</strong> <em>lambda</em> ' % name
881 # XXX lambda's won't usually have func_annotations['return']
882 # since the syntax doesn't support but it is possible.
883 # So removing parentheses isn't truly safe.
884 argspec
= argspec
[1:-1] # remove parentheses
888 decl
= title
+ argspec
+ (note
and self
.grey(
889 '<font face="helvetica, arial">%s</font>' % note
))
892 return '<dl><dt>%s</dt></dl>\n' % decl
895 getdoc(object), self
.preformat
, funcs
, classes
, methods
)
896 doc
= doc
and '<dd><tt>%s</tt></dd>' % doc
897 return '<dl><dt>%s</dt>%s</dl>\n' % (decl
, doc
)
899 def _docdescriptor(self
, name
, value
, mod
):
901 push
= results
.append
904 push('<dl><dt><strong>%s</strong></dt>\n' % name
)
905 if value
.__doc
__ is not None:
906 doc
= self
.markup(getdoc(value
), self
.preformat
)
907 push('<dd><tt>%s</tt></dd>\n' % doc
)
910 return ''.join(results
)
912 def docproperty(self
, object, name
=None, mod
=None, cl
=None):
913 """Produce html documentation for a property."""
914 return self
._docdescriptor
(name
, object, mod
)
916 def docother(self
, object, name
=None, mod
=None, *ignored
):
917 """Produce HTML documentation for a data object."""
918 lhs
= name
and '<strong>%s</strong> = ' % name
or ''
919 return lhs
+ self
.repr(object)
921 def docdata(self
, object, name
=None, mod
=None, cl
=None):
922 """Produce html documentation for a data descriptor."""
923 return self
._docdescriptor
(name
, object, mod
)
925 def index(self
, dir, shadowed
=None):
926 """Generate an HTML index for a directory of modules."""
928 if shadowed
is None: shadowed
= {}
929 for importer
, name
, ispkg
in pkgutil
.iter_modules([dir]):
930 modpkgs
.append((name
, '', ispkg
, name
in shadowed
))
934 contents
= self
.multicolumn(modpkgs
, self
.modpkglink
)
935 return self
.bigsection(dir, '#ffffff', '#ee77aa', contents
)
937 # -------------------------------------------- text documentation generator
939 class TextRepr(Repr
):
940 """Class for safely making a text representation of a Python object."""
943 self
.maxlist
= self
.maxtuple
= 20
945 self
.maxstring
= self
.maxother
= 100
947 def repr1(self
, x
, level
):
948 if hasattr(type(x
), '__name__'):
949 methodname
= 'repr_' + '_'.join(type(x
).__name
__.split())
950 if hasattr(self
, methodname
):
951 return getattr(self
, methodname
)(x
, level
)
952 return cram(stripid(repr(x
)), self
.maxother
)
954 def repr_string(self
, x
, level
):
955 test
= cram(x
, self
.maxstring
)
956 testrepr
= repr(test
)
957 if '\\' in test
and '\\' not in replace(testrepr
, r
'\\', ''):
958 # Backslashes are only literal in the string and are never
959 # needed to make any special characters, so show a raw string.
960 return 'r' + testrepr
[0] + test
+ testrepr
[0]
963 repr_str
= repr_string
965 def repr_instance(self
, x
, level
):
967 return cram(stripid(repr(x
)), self
.maxstring
)
969 return '<%s instance>' % x
.__class
__.__name
__
972 """Formatter class for text documentation."""
974 # ------------------------------------------- text formatting utilities
976 _repr_instance
= TextRepr()
977 repr = _repr_instance
.repr
979 def bold(self
, text
):
980 """Format a string in bold by overstriking."""
981 return ''.join(map(lambda ch
: ch
+ '\b' + ch
, text
))
983 def indent(self
, text
, prefix
=' '):
984 """Indent text by prepending a given prefix to each line."""
985 if not text
: return ''
986 lines
= [prefix
+ line
for line
in text
.split('\n')]
987 if lines
: lines
[-1] = lines
[-1].rstrip()
988 return '\n'.join(lines
)
990 def section(self
, title
, contents
):
991 """Format a section with a given heading."""
992 clean_contents
= self
.indent(contents
).rstrip()
993 return self
.bold(title
) + '\n' + clean_contents
+ '\n\n'
995 # ---------------------------------------------- type-specific routines
997 def formattree(self
, tree
, modname
, parent
=None, prefix
=''):
998 """Render in text a class tree as returned by inspect.getclasstree()."""
1001 if type(entry
) is type(()):
1003 result
= result
+ prefix
+ classname(c
, modname
)
1004 if bases
and bases
!= (parent
,):
1005 parents
= map(lambda c
, m
=modname
: classname(c
, m
), bases
)
1006 result
= result
+ '(%s)' % ', '.join(parents
)
1007 result
= result
+ '\n'
1008 elif type(entry
) is type([]):
1009 result
= result
+ self
.formattree(
1010 entry
, modname
, c
, prefix
+ ' ')
1013 def docmodule(self
, object, name
=None, mod
=None):
1014 """Produce text documentation for a given module object."""
1015 name
= object.__name
__ # ignore the passed-in name
1016 synop
, desc
= splitdoc(getdoc(object))
1017 result
= self
.section('NAME', name
+ (synop
and ' - ' + synop
))
1020 all
= object.__all
__
1021 except AttributeError:
1025 file = inspect
.getabsfile(object)
1028 result
= result
+ self
.section('FILE', file)
1030 docloc
= self
.getdocloc(object)
1031 if docloc
is not None:
1032 result
= result
+ self
.section('MODULE DOCS', docloc
)
1035 result
= result
+ self
.section('DESCRIPTION', desc
)
1038 for key
, value
in inspect
.getmembers(object, inspect
.isclass
):
1039 # if __all__ exists, believe it. Otherwise use old heuristic.
1041 or (inspect
.getmodule(value
) or object) is object):
1042 if visiblename(key
, all
):
1043 classes
.append((key
, value
))
1045 for key
, value
in inspect
.getmembers(object, inspect
.isroutine
):
1046 # if __all__ exists, believe it. Otherwise use old heuristic.
1047 if (all
is not None or
1048 inspect
.isbuiltin(value
) or inspect
.getmodule(value
) is object):
1049 if visiblename(key
, all
):
1050 funcs
.append((key
, value
))
1052 for key
, value
in inspect
.getmembers(object, isdata
):
1053 if visiblename(key
, all
):
1054 data
.append((key
, value
))
1057 modpkgs_names
= set()
1058 if hasattr(object, '__path__'):
1059 for importer
, modname
, ispkg
in pkgutil
.iter_modules(object.__path
__):
1060 modpkgs_names
.add(modname
)
1062 modpkgs
.append(modname
+ ' (package)')
1064 modpkgs
.append(modname
)
1067 result
= result
+ self
.section(
1068 'PACKAGE CONTENTS', '\n'.join(modpkgs
))
1070 # Detect submodules as sometimes created by C extensions
1072 for key
, value
in inspect
.getmembers(object, inspect
.ismodule
):
1073 if value
.__name
__.startswith(name
+ '.') and key
not in modpkgs_names
:
1074 submodules
.append(key
)
1077 result
= result
+ self
.section(
1078 'SUBMODULES', '\n'.join(submodules
))
1081 classlist
= [value
for key
, value
in classes
]
1082 contents
= [self
.formattree(
1083 inspect
.getclasstree(classlist
, 1), name
)]
1084 for key
, value
in classes
:
1085 contents
.append(self
.document(value
, key
, name
))
1086 result
= result
+ self
.section('CLASSES', '\n'.join(contents
))
1090 for key
, value
in funcs
:
1091 contents
.append(self
.document(value
, key
, name
))
1092 result
= result
+ self
.section('FUNCTIONS', '\n'.join(contents
))
1096 for key
, value
in data
:
1097 contents
.append(self
.docother(value
, key
, name
, maxlen
=70))
1098 result
= result
+ self
.section('DATA', '\n'.join(contents
))
1100 if hasattr(object, '__version__'):
1101 version
= str(object.__version
__)
1102 if version
[:11] == '$' + 'Revision: ' and version
[-1:] == '$':
1103 version
= version
[11:-1].strip()
1104 result
= result
+ self
.section('VERSION', version
)
1105 if hasattr(object, '__date__'):
1106 result
= result
+ self
.section('DATE', str(object.__date
__))
1107 if hasattr(object, '__author__'):
1108 result
= result
+ self
.section('AUTHOR', str(object.__author
__))
1109 if hasattr(object, '__credits__'):
1110 result
= result
+ self
.section('CREDITS', str(object.__credits
__))
1113 def docclass(self
, object, name
=None, mod
=None):
1114 """Produce text documentation for a given class object."""
1115 realname
= object.__name
__
1116 name
= name
or realname
1117 bases
= object.__bases
__
1119 def makename(c
, m
=object.__module
__):
1120 return classname(c
, m
)
1122 if name
== realname
:
1123 title
= 'class ' + self
.bold(realname
)
1125 title
= self
.bold(name
) + ' = class ' + realname
1127 parents
= map(makename
, bases
)
1128 title
= title
+ '(%s)' % ', '.join(parents
)
1130 doc
= getdoc(object)
1131 contents
= doc
and [doc
+ '\n'] or []
1132 push
= contents
.append
1134 # List the mro, if non-trivial.
1135 mro
= deque(inspect
.getmro(object))
1137 push("Method resolution order:")
1139 push(' ' + makename(base
))
1142 # Cute little class to pump out a horizontal rule between sections.
1143 class HorizontalRule
:
1150 hr
= HorizontalRule()
1152 def spill(msg
, attrs
, predicate
):
1153 ok
, attrs
= _split_list(attrs
, predicate
)
1157 for name
, kind
, homecls
, value
in ok
:
1158 push(self
.document(getattr(object, name
),
1162 def spilldescriptors(msg
, attrs
, predicate
):
1163 ok
, attrs
= _split_list(attrs
, predicate
)
1167 for name
, kind
, homecls
, value
in ok
:
1168 push(self
._docdescriptor
(name
, value
, mod
))
1171 def spilldata(msg
, attrs
, predicate
):
1172 ok
, attrs
= _split_list(attrs
, predicate
)
1176 for name
, kind
, homecls
, value
in ok
:
1177 if hasattr(value
, '__call__') or inspect
.isdatadescriptor(value
):
1181 push(self
.docother(getattr(object, name
),
1182 name
, mod
, maxlen
=70, doc
=doc
) + '\n')
1185 attrs
= [(name
, kind
, cls
, value
)
1186 for name
, kind
, cls
, value
in classify_class_attrs(object)
1187 if visiblename(name
)]
1191 thisclass
= mro
.popleft()
1193 thisclass
= attrs
[0][2]
1194 attrs
, inherited
= _split_list(attrs
, lambda t
: t
[2] is thisclass
)
1196 if thisclass
is builtins
.object:
1199 elif thisclass
is object:
1200 tag
= "defined here"
1202 tag
= "inherited from %s" % classname(thisclass
,
1205 # Sort attrs by name.
1208 # Pump out the attrs, segregated by kind.
1209 attrs
= spill("Methods %s:\n" % tag
, attrs
,
1210 lambda t
: t
[1] == 'method')
1211 attrs
= spill("Class methods %s:\n" % tag
, attrs
,
1212 lambda t
: t
[1] == 'class method')
1213 attrs
= spill("Static methods %s:\n" % tag
, attrs
,
1214 lambda t
: t
[1] == 'static method')
1215 attrs
= spilldescriptors("Data descriptors %s:\n" % tag
, attrs
,
1216 lambda t
: t
[1] == 'data descriptor')
1217 attrs
= spilldata("Data and other attributes %s:\n" % tag
, attrs
,
1218 lambda t
: t
[1] == 'data')
1222 contents
= '\n'.join(contents
)
1225 return title
+ '\n' + self
.indent(contents
.rstrip(), ' | ') + '\n'
1227 def formatvalue(self
, object):
1228 """Format an argument default value as text."""
1229 return '=' + self
.repr(object)
1231 def docroutine(self
, object, name
=None, mod
=None, cl
=None):
1232 """Produce text documentation for a function or method object."""
1233 realname
= object.__name
__
1234 name
= name
or realname
1237 if inspect
.ismethod(object):
1238 imclass
= object.__self
__.__class
__
1240 if imclass
is not cl
:
1241 note
= ' from ' + classname(imclass
, mod
)
1243 if object.__self
__ is not None:
1244 note
= ' method of %s instance' % classname(
1245 object.__self
__.__class
__, mod
)
1247 note
= ' unbound %s method' % classname(imclass
,mod
)
1248 object = object.__func
__
1250 if name
== realname
:
1251 title
= self
.bold(realname
)
1253 if (cl
and realname
in cl
.__dict
__ and
1254 cl
.__dict
__[realname
] is object):
1256 title
= self
.bold(name
) + ' = ' + realname
1257 if inspect
.isfunction(object):
1258 args
, varargs
, varkw
, defaults
, kwonlyargs
, kwdefaults
, ann
= \
1259 inspect
.getfullargspec(object)
1260 argspec
= inspect
.formatargspec(
1261 args
, varargs
, varkw
, defaults
, kwonlyargs
, kwdefaults
, ann
,
1262 formatvalue
=self
.formatvalue
,
1263 formatannotation
=inspect
.formatannotationrelativeto(object))
1264 if realname
== '<lambda>':
1265 title
= self
.bold(name
) + ' lambda '
1266 # XXX lambda's won't usually have func_annotations['return']
1267 # since the syntax doesn't support but it is possible.
1268 # So removing parentheses isn't truly safe.
1269 argspec
= argspec
[1:-1] # remove parentheses
1272 decl
= title
+ argspec
+ note
1277 doc
= getdoc(object) or ''
1278 return decl
+ '\n' + (doc
and self
.indent(doc
).rstrip() + '\n')
1280 def _docdescriptor(self
, name
, value
, mod
):
1282 push
= results
.append
1285 push(self
.bold(name
))
1287 doc
= getdoc(value
) or ''
1289 push(self
.indent(doc
))
1291 return ''.join(results
)
1293 def docproperty(self
, object, name
=None, mod
=None, cl
=None):
1294 """Produce text documentation for a property."""
1295 return self
._docdescriptor
(name
, object, mod
)
1297 def docdata(self
, object, name
=None, mod
=None, cl
=None):
1298 """Produce text documentation for a data descriptor."""
1299 return self
._docdescriptor
(name
, object, mod
)
1301 def docother(self
, object, name
=None, mod
=None, parent
=None, maxlen
=None, doc
=None):
1302 """Produce text documentation for a data object."""
1303 repr = self
.repr(object)
1305 line
= (name
and name
+ ' = ' or '') + repr
1306 chop
= maxlen
- len(line
)
1307 if chop
< 0: repr = repr[:chop
] + '...'
1308 line
= (name
and self
.bold(name
) + ' = ' or '') + repr
1310 line
+= '\n' + self
.indent(str(doc
))
1313 # --------------------------------------------------------- user interfaces
1316 """The first time this is called, determine what kind of pager to use."""
1322 """Decide what method to use for paging through text."""
1323 if not hasattr(sys
.stdout
, "isatty"):
1325 if not sys
.stdin
.isatty() or not sys
.stdout
.isatty():
1327 if 'PAGER' in os
.environ
:
1328 if sys
.platform
== 'win32': # pipes completely broken in Windows
1329 return lambda text
: tempfilepager(plain(text
), os
.environ
['PAGER'])
1330 elif os
.environ
.get('TERM') in ('dumb', 'emacs'):
1331 return lambda text
: pipepager(plain(text
), os
.environ
['PAGER'])
1333 return lambda text
: pipepager(text
, os
.environ
['PAGER'])
1334 if os
.environ
.get('TERM') in ('dumb', 'emacs'):
1336 if sys
.platform
== 'win32' or sys
.platform
.startswith('os2'):
1337 return lambda text
: tempfilepager(plain(text
), 'more <')
1338 if hasattr(os
, 'system') and os
.system('(less) 2>/dev/null') == 0:
1339 return lambda text
: pipepager(text
, 'less')
1342 (fd
, filename
) = tempfile
.mkstemp()
1345 if hasattr(os
, 'system') and os
.system('more "%s"' % filename
) == 0:
1346 return lambda text
: pipepager(text
, 'more')
1353 """Remove boldface formatting from text."""
1354 return re
.sub('.\b', '', text
)
1356 def pipepager(text
, cmd
):
1357 """Page through text by feeding it to another program."""
1358 pipe
= os
.popen(cmd
, 'w')
1363 pass # Ignore broken pipes caused by quitting the pager program.
1365 def tempfilepager(text
, cmd
):
1366 """Page through text by invoking a program on a temporary file."""
1368 filename
= tempfile
.mktemp()
1369 file = open(filename
, 'w')
1373 os
.system(cmd
+ ' "' + filename
+ '"')
1378 """Page through text on a text terminal."""
1379 lines
= plain(text
).split('\n')
1382 fd
= sys
.stdin
.fileno()
1383 old
= tty
.tcgetattr(fd
)
1385 getchar
= lambda: sys
.stdin
.read(1)
1386 except (ImportError, AttributeError):
1388 getchar
= lambda: sys
.stdin
.readline()[:-1][:1]
1391 r
= inc
= os
.environ
.get('LINES', 25) - 1
1392 sys
.stdout
.write('\n'.join(lines
[:inc
]) + '\n')
1394 sys
.stdout
.write('-- more --')
1399 sys
.stdout
.write('\r \r')
1401 elif c
in ('\r', '\n'):
1402 sys
.stdout
.write('\r \r' + lines
[r
] + '\n')
1405 if c
in ('b', 'B', '\x1b'):
1408 sys
.stdout
.write('\n' + '\n'.join(lines
[r
:r
+inc
]) + '\n')
1413 tty
.tcsetattr(fd
, tty
.TCSAFLUSH
, old
)
1415 def plainpager(text
):
1416 """Simply print unformatted text. This is the ultimate fallback."""
1417 sys
.stdout
.write(plain(text
))
1419 def describe(thing
):
1420 """Produce a short description of the given thing."""
1421 if inspect
.ismodule(thing
):
1422 if thing
.__name
__ in sys
.builtin_module_names
:
1423 return 'built-in module ' + thing
.__name
__
1424 if hasattr(thing
, '__path__'):
1425 return 'package ' + thing
.__name
__
1427 return 'module ' + thing
.__name
__
1428 if inspect
.isbuiltin(thing
):
1429 return 'built-in function ' + thing
.__name
__
1430 if inspect
.isgetsetdescriptor(thing
):
1431 return 'getset descriptor %s.%s.%s' % (
1432 thing
.__objclass
__.__module
__, thing
.__objclass
__.__name
__,
1434 if inspect
.ismemberdescriptor(thing
):
1435 return 'member descriptor %s.%s.%s' % (
1436 thing
.__objclass
__.__module
__, thing
.__objclass
__.__name
__,
1438 if inspect
.isclass(thing
):
1439 return 'class ' + thing
.__name
__
1440 if inspect
.isfunction(thing
):
1441 return 'function ' + thing
.__name
__
1442 if inspect
.ismethod(thing
):
1443 return 'method ' + thing
.__name
__
1444 return type(thing
).__name
__
1446 def locate(path
, forceload
=0):
1447 """Locate an object by name or dotted path, importing as necessary."""
1448 parts
= [part
for part
in path
.split('.') if part
]
1450 while n
< len(parts
):
1451 nextmodule
= safeimport('.'.join(parts
[:n
+1]), forceload
)
1452 if nextmodule
: module
, n
= nextmodule
, n
+ 1
1456 for part
in parts
[n
:]:
1457 try: object = getattr(object, part
)
1458 except AttributeError: return None
1461 if hasattr(builtins
, path
):
1462 return getattr(builtins
, path
)
1464 # --------------------------------------- interactive interpreter interface
1469 def resolve(thing
, forceload
=0):
1470 """Given an object or a path to an object, get the object and its name."""
1471 if isinstance(thing
, str):
1472 object = locate(thing
, forceload
)
1474 raise ImportError('no Python documentation found for %r' % thing
)
1475 return object, thing
1477 return thing
, getattr(thing
, '__name__', None)
1479 def render_doc(thing
, title
='Python Library Documentation: %s', forceload
=0):
1480 """Render text documentation, given an object or a path to an object."""
1481 object, name
= resolve(thing
, forceload
)
1482 desc
= describe(object)
1483 module
= inspect
.getmodule(object)
1484 if name
and '.' in name
:
1485 desc
+= ' in ' + name
[:name
.rfind('.')]
1486 elif module
and module
is not object:
1487 desc
+= ' in module ' + module
.__name
__
1489 if not (inspect
.ismodule(object) or
1490 inspect
.isclass(object) or
1491 inspect
.isroutine(object) or
1492 inspect
.isgetsetdescriptor(object) or
1493 inspect
.ismemberdescriptor(object) or
1494 isinstance(object, property)):
1495 # If the passed object is a piece of data or an instance,
1496 # document its available methods instead of its value.
1497 object = type(object)
1499 return title
% desc
+ '\n\n' + text
.document(object, name
)
1501 def doc(thing
, title
='Python Library Documentation: %s', forceload
=0):
1502 """Display text documentation, given an object or a path to an object."""
1504 pager(render_doc(thing
, title
, forceload
))
1505 except (ImportError, ErrorDuringImport
) as value
:
1508 def writedoc(thing
, forceload
=0):
1509 """Write HTML documentation to a file in the current directory."""
1511 object, name
= resolve(thing
, forceload
)
1512 page
= html
.page(describe(object), html
.document(object, name
))
1513 file = open(name
+ '.html', 'w', encoding
='utf-8')
1516 print('wrote', name
+ '.html')
1517 except (ImportError, ErrorDuringImport
) as value
:
1520 def writedocs(dir, pkgpath
='', done
=None):
1521 """Write out HTML documentation for all modules in a directory tree."""
1522 if done
is None: done
= {}
1523 for importer
, modname
, ispkg
in pkgutil
.walk_packages([dir], pkgpath
):
1529 # These dictionaries map a topic name to either an alias, or a tuple
1530 # (label, seealso-items). The "label" is the label of the corresponding
1531 # section in the .rst file under Doc/ and an index into the dictionary
1532 # in pydoc_data/topics.py.
1534 # CAUTION: if you change one of these dictionaries, be sure to adapt the
1535 # list of needed labels in Doc/tools/sphinxext/pyspecific.py and
1536 # regenerate the pydoc_data/topics.py file by running
1538 # in Doc/ and copying the output file into the Lib/ directory.
1543 'assert': ('assert', ''),
1544 'break': ('break', 'while for'),
1545 'class': ('class', 'CLASSES SPECIALMETHODS'),
1546 'continue': ('continue', 'while for'),
1547 'def': ('function', ''),
1548 'del': ('del', 'BASICMETHODS'),
1550 'else': ('else', 'while for'),
1553 'for': ('for', 'break continue while'),
1555 'global': ('global', 'NAMESPACES'),
1556 'if': ('if', 'TRUTHVALUE'),
1557 'import': ('import', 'MODULES'),
1558 'in': ('in', 'SEQUENCEMETHODS'),
1560 'lambda': ('lambda', 'FUNCTIONS'),
1563 'pass': ('pass', ''),
1564 'raise': ('raise', 'EXCEPTIONS'),
1565 'return': ('return', 'FUNCTIONS'),
1566 'try': ('try', 'EXCEPTIONS'),
1567 'while': ('while', 'break continue if TRUTHVALUE'),
1568 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
1569 'yield': ('yield', ''),
1571 # Either add symbols to this dictionary or to the symbols dictionary
1572 # directly: Whichever is easier. They are merged later.
1573 _symbols_inverse
= {
1574 'STRINGS' : ("'", "'''", "r'", "b'", '"""', '"', 'r"', 'b"'),
1575 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',
1576 '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
1577 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),
1578 'UNARY' : ('-', '~'),
1579 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',
1580 '^=', '<<=', '>>=', '**=', '//='),
1581 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),
1582 'COMPLEX' : ('j', 'J')
1585 '%': 'OPERATORS FORMATTING',
1587 ',': 'TUPLES LISTS FUNCTIONS',
1588 '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
1590 ':': 'SLICINGS DICTIONARYLITERALS',
1593 '_': 'PRIVATENAMES',
1594 '__': 'PRIVATENAMES SPECIALMETHODS',
1596 '(': 'TUPLES FUNCTIONS CALLS',
1597 ')': 'TUPLES FUNCTIONS CALLS',
1598 '[': 'LISTS SUBSCRIPTS SLICINGS',
1599 ']': 'LISTS SUBSCRIPTS SLICINGS'
1601 for topic
, symbols_
in _symbols_inverse
.items():
1602 for symbol
in symbols_
:
1603 topics
= symbols
.get(symbol
, topic
)
1604 if topic
not in topics
:
1605 topics
= topics
+ ' ' + topic
1606 symbols
[symbol
] = topics
1609 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
1610 'FUNCTIONS CLASSES MODULES FILES inspect'),
1611 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS '
1612 'FORMATTING TYPES'),
1613 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
1614 'FORMATTING': ('formatstrings', 'OPERATORS'),
1615 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '
1616 'FORMATTING TYPES'),
1617 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
1618 'INTEGER': ('integers', 'int range'),
1619 'FLOAT': ('floating', 'float math'),
1620 'COMPLEX': ('imaginary', 'complex cmath'),
1621 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING range LISTS'),
1622 'MAPPINGS': 'DICTIONARIES',
1623 'FUNCTIONS': ('typesfunctions', 'def TYPES'),
1624 'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
1625 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
1626 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
1627 'FRAMEOBJECTS': 'TYPES',
1628 'TRACEBACKS': 'TYPES',
1629 'NONE': ('bltin-null-object', ''),
1630 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
1631 'FILES': ('bltin-file-objects', ''),
1632 'SPECIALATTRIBUTES': ('specialattrs', ''),
1633 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
1634 'MODULES': ('typesmodules', 'import'),
1635 'PACKAGES': 'import',
1636 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '
1637 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '
1638 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '
1639 'LISTS DICTIONARIES'),
1640 'OPERATORS': 'EXPRESSIONS',
1641 'PRECEDENCE': 'EXPRESSIONS',
1642 'OBJECTS': ('objects', 'TYPES'),
1643 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '
1644 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS '
1645 'NUMBERMETHODS CLASSES'),
1646 'BASICMETHODS': ('customization', 'hash repr str SPECIALMETHODS'),
1647 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
1648 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
1649 'SEQUENCEMETHODS': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS '
1651 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
1652 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
1654 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
1655 'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
1656 'DYNAMICFEATURES': ('dynamic-features', ''),
1657 'SCOPING': 'NAMESPACES',
1658 'FRAMES': 'NAMESPACES',
1659 'EXCEPTIONS': ('exceptions', 'try except finally raise'),
1660 'CONVERSIONS': ('conversions', ''),
1661 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
1662 'SPECIALIDENTIFIERS': ('id-classes', ''),
1663 'PRIVATENAMES': ('atom-identifiers', ''),
1664 'LITERALS': ('atom-literals', 'STRINGS NUMBERS TUPLELITERALS '
1665 'LISTLITERALS DICTIONARYLITERALS'),
1666 'TUPLES': 'SEQUENCES',
1667 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
1668 'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
1669 'LISTLITERALS': ('lists', 'LISTS LITERALS'),
1670 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
1671 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
1672 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
1673 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS'),
1674 'SLICINGS': ('slicings', 'SEQUENCEMETHODS'),
1675 'CALLS': ('calls', 'EXPRESSIONS'),
1676 'POWER': ('power', 'EXPRESSIONS'),
1677 'UNARY': ('unary', 'EXPRESSIONS'),
1678 'BINARY': ('binary', 'EXPRESSIONS'),
1679 'SHIFTING': ('shifting', 'EXPRESSIONS'),
1680 'BITWISE': ('bitwise', 'EXPRESSIONS'),
1681 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
1682 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
1683 'ASSERTION': 'assert',
1684 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
1685 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
1687 'RETURNING': 'return',
1688 'IMPORTING': 'import',
1689 'CONDITIONAL': 'if',
1690 'LOOPING': ('compound', 'for while break continue'),
1691 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
1692 'DEBUGGING': ('debugger', 'pdb'),
1693 'CONTEXTMANAGERS': ('context-managers', 'with'),
1696 def __init__(self
, input, output
):
1698 self
.output
= output
1701 if inspect
.stack()[1][3] == '?':
1704 return '<pydoc.Helper instance>'
1706 def __call__(self
, request
=None):
1707 if request
is not None:
1712 self
.output
.write('''
1713 You are now leaving help and returning to the Python interpreter.
1714 If you want to ask for help on a particular object directly from the
1715 interpreter, you can type "help(object)". Executing "help('string')"
1716 has the same effect as typing a particular string at the help> prompt.
1720 self
.output
.write('\n')
1723 request
= self
.getline('help> ')
1724 if not request
: break
1725 except (KeyboardInterrupt, EOFError):
1727 request
= replace(request
, '"', '', "'", '').strip()
1728 if request
.lower() in ('q', 'quit'): break
1731 def getline(self
, prompt
):
1732 """Read one line, using input() when appropriate."""
1733 if self
.input is sys
.stdin
:
1734 return input(prompt
)
1736 self
.output
.write(prompt
)
1738 return self
.input.readline()
1740 def help(self
, request
):
1741 if type(request
) is type(''):
1742 request
= request
.strip()
1743 if request
== 'help': self
.intro()
1744 elif request
== 'keywords': self
.listkeywords()
1745 elif request
== 'symbols': self
.listsymbols()
1746 elif request
== 'topics': self
.listtopics()
1747 elif request
== 'modules': self
.listmodules()
1748 elif request
[:8] == 'modules ':
1749 self
.listmodules(request
.split()[1])
1750 elif request
in self
.symbols
: self
.showsymbol(request
)
1751 elif request
in self
.keywords
: self
.showtopic(request
)
1752 elif request
in self
.topics
: self
.showtopic(request
)
1753 elif request
: doc(request
, 'Help on %s:')
1754 elif isinstance(request
, Helper
): self()
1755 else: doc(request
, 'Help on %s:')
1756 self
.output
.write('\n')
1759 self
.output
.write('''
1760 Welcome to Python %s! This is the online help utility.
1762 If this is your first time using Python, you should definitely check out
1763 the tutorial on the Internet at http://docs.python.org/tutorial/.
1765 Enter the name of any module, keyword, or topic to get help on writing
1766 Python programs and using Python modules. To quit this help utility and
1767 return to the interpreter, just type "quit".
1769 To get a list of available modules, keywords, or topics, type "modules",
1770 "keywords", or "topics". Each module also comes with a one-line summary
1771 of what it does; to list the modules whose summaries contain a given word
1772 such as "spam", type "modules spam".
1773 ''' % sys
.version
[:3])
1775 def list(self
, items
, columns
=4, width
=80):
1776 items
= list(sorted(items
))
1777 colw
= width
// columns
1778 rows
= (len(items
) + columns
- 1) // columns
1779 for row
in range(rows
):
1780 for col
in range(columns
):
1781 i
= col
* rows
+ row
1783 self
.output
.write(items
[i
])
1784 if col
< columns
- 1:
1785 self
.output
.write(' ' + ' ' * (colw
- 1 - len(items
[i
])))
1786 self
.output
.write('\n')
1788 def listkeywords(self
):
1789 self
.output
.write('''
1790 Here is a list of the Python keywords. Enter any keyword to get more help.
1793 self
.list(self
.keywords
.keys())
1795 def listsymbols(self
):
1796 self
.output
.write('''
1797 Here is a list of the punctuation symbols which Python assigns special meaning
1798 to. Enter any symbol to get more help.
1801 self
.list(self
.symbols
.keys())
1803 def listtopics(self
):
1804 self
.output
.write('''
1805 Here is a list of available topics. Enter any topic name to get more help.
1808 self
.list(self
.topics
.keys())
1810 def showtopic(self
, topic
, more_xrefs
=''):
1812 import pydoc_data
.topics
1814 self
.output
.write('''
1815 Sorry, topic and keyword documentation is not available because the
1816 module "pydoc_data.topics" could not be found.
1819 target
= self
.topics
.get(topic
, self
.keywords
.get(topic
))
1821 self
.output
.write('no documentation found for %s\n' % repr(topic
))
1823 if type(target
) is type(''):
1824 return self
.showtopic(target
, more_xrefs
)
1826 label
, xrefs
= target
1828 doc
= pydoc_data
.topics
.topics
[label
]
1830 self
.output
.write('no documentation found for %s\n' % repr(topic
))
1832 pager(doc
.strip() + '\n')
1834 xrefs
= (xrefs
or '') + ' ' + more_xrefs
1836 import io
, formatter
1837 buffer = io
.StringIO()
1838 formatter
.DumbWriter(buffer).send_flowing_data(
1839 'Related help topics: ' + ', '.join(xrefs
.split()) + '\n')
1840 self
.output
.write('\n%s\n' % buffer.getvalue())
1842 def showsymbol(self
, symbol
):
1843 target
= self
.symbols
[symbol
]
1844 topic
, _
, xrefs
= target
.partition(' ')
1845 self
.showtopic(topic
, xrefs
)
1847 def listmodules(self
, key
=''):
1849 self
.output
.write('''
1850 Here is a list of matching modules. Enter any module name to get more help.
1855 self
.output
.write('''
1856 Please wait a moment while I gather a list of all available modules...
1860 def callback(path
, modname
, desc
, modules
=modules
):
1861 if modname
and modname
[-9:] == '.__init__':
1862 modname
= modname
[:-9] + ' (package)'
1863 if modname
.find('.') < 0:
1864 modules
[modname
] = 1
1865 def onerror(modname
):
1866 callback(None, modname
, None)
1867 ModuleScanner().run(callback
, onerror
=onerror
)
1868 self
.list(modules
.keys())
1869 self
.output
.write('''
1870 Enter any module name to get more help. Or, type "modules spam" to search
1871 for modules whose descriptions contain the word "spam".
1874 help = Helper(sys
.stdin
, sys
.stdout
)
1877 """A generic tree iterator."""
1878 def __init__(self
, roots
, children
, descendp
):
1879 self
.roots
= roots
[:]
1881 self
.children
= children
1882 self
.descendp
= descendp
1888 root
= self
.roots
.pop(0)
1889 self
.state
= [(root
, self
.children(root
))]
1890 node
, children
= self
.state
[-1]
1894 child
= children
.pop(0)
1895 if self
.descendp(child
):
1896 self
.state
.append((child
, self
.children(child
)))
1900 class ModuleScanner
:
1901 """An interruptible scanner that searches module synopses."""
1903 def run(self
, callback
, key
=None, completer
=None, onerror
=None):
1904 if key
: key
= key
.lower()
1908 for modname
in sys
.builtin_module_names
:
1909 if modname
!= '__main__':
1912 callback(None, modname
, '')
1914 name
= __import__(modname
).__doc
__ or ''
1915 desc
= name
.split('\n')[0]
1916 name
= modname
+ ' - ' + desc
1917 if name
.lower().find(key
) >= 0:
1918 callback(None, modname
, desc
)
1920 for importer
, modname
, ispkg
in pkgutil
.walk_packages(onerror
=onerror
):
1924 callback(None, modname
, '')
1927 loader
= importer
.find_module(modname
)
1929 # raised by tests for bad coding cookies or BOM
1931 if hasattr(loader
, 'get_source'):
1933 source
= loader
.get_source(modname
)
1934 except UnicodeDecodeError:
1939 desc
= source_synopsis(io
.StringIO(source
)) or ''
1940 if hasattr(loader
, 'get_filename'):
1941 path
= loader
.get_filename(modname
)
1946 module
= loader
.load_module(modname
)
1951 desc
= (module
.__doc
__ or '').splitlines()[0]
1952 path
= getattr(module
,'__file__',None)
1953 name
= modname
+ ' - ' + desc
1954 if name
.lower().find(key
) >= 0:
1955 callback(path
, modname
, desc
)
1961 """Print all the one-line module summaries that contain a substring."""
1962 def callback(path
, modname
, desc
):
1963 if modname
[-9:] == '.__init__':
1964 modname
= modname
[:-9] + ' (package)'
1965 print(modname
, desc
and '- ' + desc
)
1966 def onerror(modname
):
1968 try: import warnings
1969 except ImportError: pass
1970 else: warnings
.filterwarnings('ignore') # ignore problems during import
1971 ModuleScanner().run(callback
, key
, onerror
=onerror
)
1973 # --------------------------------------------------- web browser interface
1975 def serve(port
, callback
=None, completer
=None):
1976 import http
.server
, email
.message
, select
1978 class DocHandler(http
.server
.BaseHTTPRequestHandler
):
1979 def send_document(self
, title
, contents
):
1981 self
.send_response(200)
1982 self
.send_header('Content-Type', 'text/html; charset=UTF-8')
1984 self
.wfile
.write(html
.page(title
, contents
).encode('utf-8'))
1985 except IOError: pass
1989 if path
[-5:] == '.html': path
= path
[:-5]
1990 if path
[:1] == '/': path
= path
[1:]
1991 if path
and path
!= '.':
1993 obj
= locate(path
, forceload
=1)
1994 except ErrorDuringImport
as value
:
1995 self
.send_document(path
, html
.escape(str(value
)))
1998 self
.send_document(describe(obj
), html
.document(obj
, path
))
2000 self
.send_document(path
,
2001 'no Python documentation found for %s' % repr(path
))
2003 heading
= html
.heading(
2004 '<big><big><strong>Python: Index of Modules</strong></big></big>',
2005 '#ffffff', '#7799ee')
2006 def bltinlink(name
):
2007 return '<a href="%s.html">%s</a>' % (name
, name
)
2008 names
= [x
for x
in sys
.builtin_module_names
if x
!= '__main__']
2009 contents
= html
.multicolumn(names
, bltinlink
)
2010 indices
= ['<p>' + html
.bigsection(
2011 'Built-in Modules', '#ffffff', '#ee77aa', contents
)]
2014 for dir in sys
.path
:
2015 indices
.append(html
.index(dir, seen
))
2016 contents
= heading
+ ' '.join(indices
) + '''<p align=right>
2017 <font color="#909090" face="helvetica, arial"><strong>
2018 pydoc</strong> by Ka-Ping Yee <ping@lfw.org></font>'''
2019 self
.send_document('Index of Modules', contents
)
2021 def log_message(self
, *args
): pass
2023 class DocServer(http
.server
.HTTPServer
):
2024 def __init__(self
, port
, callback
):
2025 host
= (sys
.platform
== 'mac') and '127.0.0.1' or 'localhost'
2026 self
.address
= ('', port
)
2027 self
.url
= 'http://%s:%d/' % (host
, port
)
2028 self
.callback
= callback
2029 self
.base
.__init
__(self
, self
.address
, self
.handler
)
2031 def serve_until_quit(self
):
2034 while not self
.quit
:
2035 rd
, wr
, ex
= select
.select([self
.socket
.fileno()], [], [], 1)
2036 if rd
: self
.handle_request()
2038 def server_activate(self
):
2039 self
.base
.server_activate(self
)
2040 if self
.callback
: self
.callback(self
)
2042 DocServer
.base
= http
.server
.HTTPServer
2043 DocServer
.handler
= DocHandler
2044 DocHandler
.MessageClass
= email
.message
.Message
2047 DocServer(port
, callback
).serve_until_quit()
2048 except (KeyboardInterrupt, select
.error
):
2051 if completer
: completer()
2053 # ----------------------------------------------------- graphical interface
2056 """Graphical interface (starts web server and pops up a control window)."""
2058 def __init__(self
, window
, port
=7464):
2059 self
.window
= window
2064 self
.server_frm
= tkinter
.Frame(window
)
2065 self
.title_lbl
= tkinter
.Label(self
.server_frm
,
2066 text
='Starting server...\n ')
2067 self
.open_btn
= tkinter
.Button(self
.server_frm
,
2068 text
='open browser', command
=self
.open, state
='disabled')
2069 self
.quit_btn
= tkinter
.Button(self
.server_frm
,
2070 text
='quit serving', command
=self
.quit
, state
='disabled')
2072 self
.search_frm
= tkinter
.Frame(window
)
2073 self
.search_lbl
= tkinter
.Label(self
.search_frm
, text
='Search for')
2074 self
.search_ent
= tkinter
.Entry(self
.search_frm
)
2075 self
.search_ent
.bind('<Return>', self
.search
)
2076 self
.stop_btn
= tkinter
.Button(self
.search_frm
,
2077 text
='stop', pady
=0, command
=self
.stop
, state
='disabled')
2078 if sys
.platform
== 'win32':
2079 # Trying to hide and show this button crashes under Windows.
2080 self
.stop_btn
.pack(side
='right')
2082 self
.window
.title('pydoc')
2083 self
.window
.protocol('WM_DELETE_WINDOW', self
.quit
)
2084 self
.title_lbl
.pack(side
='top', fill
='x')
2085 self
.open_btn
.pack(side
='left', fill
='x', expand
=1)
2086 self
.quit_btn
.pack(side
='right', fill
='x', expand
=1)
2087 self
.server_frm
.pack(side
='top', fill
='x')
2089 self
.search_lbl
.pack(side
='left')
2090 self
.search_ent
.pack(side
='right', fill
='x', expand
=1)
2091 self
.search_frm
.pack(side
='top', fill
='x')
2092 self
.search_ent
.focus_set()
2094 font
= ('helvetica', sys
.platform
== 'win32' and 8 or 10)
2095 self
.result_lst
= tkinter
.Listbox(window
, font
=font
, height
=6)
2096 self
.result_lst
.bind('<Button-1>', self
.select
)
2097 self
.result_lst
.bind('<Double-Button-1>', self
.goto
)
2098 self
.result_scr
= tkinter
.Scrollbar(window
,
2099 orient
='vertical', command
=self
.result_lst
.yview
)
2100 self
.result_lst
.config(yscrollcommand
=self
.result_scr
.set)
2102 self
.result_frm
= tkinter
.Frame(window
)
2103 self
.goto_btn
= tkinter
.Button(self
.result_frm
,
2104 text
='go to selected', command
=self
.goto
)
2105 self
.hide_btn
= tkinter
.Button(self
.result_frm
,
2106 text
='hide results', command
=self
.hide
)
2107 self
.goto_btn
.pack(side
='left', fill
='x', expand
=1)
2108 self
.hide_btn
.pack(side
='right', fill
='x', expand
=1)
2110 self
.window
.update()
2111 self
.minwidth
= self
.window
.winfo_width()
2112 self
.minheight
= self
.window
.winfo_height()
2113 self
.bigminheight
= (self
.server_frm
.winfo_reqheight() +
2114 self
.search_frm
.winfo_reqheight() +
2115 self
.result_lst
.winfo_reqheight() +
2116 self
.result_frm
.winfo_reqheight())
2117 self
.bigwidth
, self
.bigheight
= self
.minwidth
, self
.bigminheight
2119 self
.window
.wm_geometry('%dx%d' % (self
.minwidth
, self
.minheight
))
2120 self
.window
.wm_minsize(self
.minwidth
, self
.minheight
)
2121 self
.window
.tk
.willdispatch()
2125 target
=serve
, args
=(port
, self
.ready
, self
.quit
)).start()
2127 def ready(self
, server
):
2128 self
.server
= server
2129 self
.title_lbl
.config(
2130 text
='Python documentation server at\n' + server
.url
)
2131 self
.open_btn
.config(state
='normal')
2132 self
.quit_btn
.config(state
='normal')
2134 def open(self
, event
=None, url
=None):
2135 url
= url
or self
.server
.url
2138 webbrowser
.open(url
)
2139 except ImportError: # pre-webbrowser.py compatibility
2140 if sys
.platform
== 'win32':
2141 os
.system('start "%s"' % url
)
2142 elif sys
.platform
== 'mac':
2144 except ImportError: pass
2145 else: ic
.launchurl(url
)
2147 rc
= os
.system('netscape -remote "openURL(%s)" &' % url
)
2148 if rc
: os
.system('netscape "%s" &' % url
)
2150 def quit(self
, event
=None):
2152 self
.server
.quit
= 1
2155 def search(self
, event
=None):
2156 key
= self
.search_ent
.get()
2157 self
.stop_btn
.pack(side
='right')
2158 self
.stop_btn
.config(state
='normal')
2159 self
.search_lbl
.config(text
='Searching for "%s"...' % key
)
2160 self
.search_ent
.forget()
2161 self
.search_lbl
.pack(side
='left')
2162 self
.result_lst
.delete(0, 'end')
2163 self
.goto_btn
.config(state
='disabled')
2168 self
.scanner
.quit
= 1
2169 self
.scanner
= ModuleScanner()
2170 threading
.Thread(target
=self
.scanner
.run
,
2171 args
=(self
.update
, key
, self
.done
)).start()
2173 def update(self
, path
, modname
, desc
):
2174 if modname
[-9:] == '.__init__':
2175 modname
= modname
[:-9] + ' (package)'
2176 self
.result_lst
.insert('end',
2177 modname
+ ' - ' + (desc
or '(no description)'))
2179 def stop(self
, event
=None):
2181 self
.scanner
.quit
= 1
2186 self
.search_lbl
.config(text
='Search for')
2187 self
.search_lbl
.pack(side
='left')
2188 self
.search_ent
.pack(side
='right', fill
='x', expand
=1)
2189 if sys
.platform
!= 'win32': self
.stop_btn
.forget()
2190 self
.stop_btn
.config(state
='disabled')
2192 def select(self
, event
=None):
2193 self
.goto_btn
.config(state
='normal')
2195 def goto(self
, event
=None):
2196 selection
= self
.result_lst
.curselection()
2198 modname
= self
.result_lst
.get(selection
[0]).split()[0]
2199 self
.open(url
=self
.server
.url
+ modname
+ '.html')
2202 if not self
.expanded
: return
2203 self
.result_frm
.forget()
2204 self
.result_scr
.forget()
2205 self
.result_lst
.forget()
2206 self
.bigwidth
= self
.window
.winfo_width()
2207 self
.bigheight
= self
.window
.winfo_height()
2208 self
.window
.wm_geometry('%dx%d' % (self
.minwidth
, self
.minheight
))
2209 self
.window
.wm_minsize(self
.minwidth
, self
.minheight
)
2213 if self
.expanded
: return
2214 self
.result_frm
.pack(side
='bottom', fill
='x')
2215 self
.result_scr
.pack(side
='right', fill
='y')
2216 self
.result_lst
.pack(side
='top', fill
='both', expand
=1)
2217 self
.window
.wm_geometry('%dx%d' % (self
.bigwidth
, self
.bigheight
))
2218 self
.window
.wm_minsize(self
.minwidth
, self
.bigminheight
)
2221 def hide(self
, event
=None):
2228 # Tk will crash if pythonw.exe has an XP .manifest
2229 # file and the root has is not destroyed explicitly.
2230 # If the problem is ever fixed in Tk, the explicit
2237 except KeyboardInterrupt:
2240 # -------------------------------------------------- command-line interface
2243 return isinstance(x
, str) and x
.find(os
.sep
) >= 0
2246 """Command-line interface (looks at sys.argv to decide what to do)."""
2248 class BadUsage(Exception): pass
2250 # Scripts don't get the current directory in their path by default
2251 # unless they are run with the '-m' switch
2252 if '' not in sys
.path
:
2253 scriptdir
= os
.path
.dirname(sys
.argv
[0])
2254 if scriptdir
in sys
.path
:
2255 sys
.path
.remove(scriptdir
)
2256 sys
.path
.insert(0, '.')
2259 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'gk:p:w')
2262 for opt
, val
in opts
:
2275 print('pydoc server ready at %s' % server
.url
)
2277 print('pydoc server stopped')
2278 serve(port
, ready
, stopped
)
2283 if not args
: raise BadUsage
2285 if ispath(arg
) and not os
.path
.exists(arg
):
2286 print('file %r does not exist' % arg
)
2289 if ispath(arg
) and os
.path
.isfile(arg
):
2290 arg
= importfile(arg
)
2292 if ispath(arg
) and os
.path
.isdir(arg
):
2298 except ErrorDuringImport
as value
:
2301 except (getopt
.error
, BadUsage
):
2302 cmd
= os
.path
.basename(sys
.argv
[0])
2303 print("""pydoc - the Python documentation tool
2306 Show text documentation on something. <name> may be the name of a
2307 Python keyword, topic, function, module, or package, or a dotted
2308 reference to a class or function within a module or module in a
2309 package. If <name> contains a '%s', it is used as the path to a
2310 Python source file to document. If name is 'keywords', 'topics',
2311 or 'modules', a listing of these things is displayed.
2314 Search for a keyword in the synopsis lines of all available modules.
2317 Start an HTTP server on the given port on the local machine.
2320 Pop up a graphical interface for finding and serving documentation.
2323 Write out the HTML documentation for a module to a file in the current
2324 directory. If <name> contains a '%s', it is treated as a filename; if
2325 it names a directory, documentation is written for all the contents.
2326 """ % (cmd
, os
.sep
, cmd
, cmd
, cmd
, cmd
, os
.sep
))
2328 if __name__
== '__main__': cli()