Back to index

python3.2  3.2.2
Classes | Functions | Variables
pydoc Namespace Reference

Classes

class  ErrorDuringImport
class  Doc
class  HTMLRepr
class  HTMLDoc
class  TextRepr
class  TextDoc
class  _PlainTextDoc
class  Helper
class  Scanner
class  ModuleScanner

Functions

def pathdirs
def getdoc
def splitdoc
def classname
def isdata
def replace
def cram
def stripid
def _is_some_method
def allmethods
def _split_list
def visiblename
def classify_class_attrs
def ispackage
def source_synopsis
def synopsis
def importfile
def safeimport
def pager
def getpager
def plain
def pipepager
def tempfilepager
def ttypager
def plainpager
def describe
def locate
def resolve
def render_doc
def doc
def writedoc
def writedocs
def apropos
def serve
def gui
def _start_server
def _url_handler
def browse
def ispath
def cli

Variables

list __all__ = ['help']
string __author__ = "Ka-Ping Yee <ping@lfw.org>"
string __date__ = "26 February 2001"
string __version__ = "$Revision$"
string __credits__
tuple _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
tuple text = TextDoc()
tuple plaintext = _PlainTextDoc()
tuple html = HTMLDoc()
tuple help = Helper()
 address
 url
 callback
 quit
 window
 server
 scanner
 server_frm
 title_lbl
 open_btn
 quit_btn
 search_frm
 search_lbl
 search_ent
 stop_btn
 result_lst
 result_scr
 result_frm
 goto_btn
 hide_btn
 minwidth
 minheight
 bigminheight
 bigheight
 expanded
 bigwidth
 host
 urlhandler
 port
 serving
 error
 docserver

Function Documentation

def pydoc._is_some_method (   obj) [private]

Definition at line 139 of file pydoc.py.

00139 
00140 def _is_some_method(obj):
00141     return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)

Here is the call graph for this function:

def pydoc._split_list (   s,
  predicate 
) [private]
Split sequence s via predicate, and return pair ([true], [false]).

The return value is a 2-tuple of lists,
    ([x for x in s if predicate(x)],
     [x for x in s if not predicate(x)])

Definition at line 152 of file pydoc.py.

00152 
00153 def _split_list(s, predicate):
00154     """Split sequence s via predicate, and return pair ([true], [false]).
00155 
00156     The return value is a 2-tuple of lists,
00157         ([x for x in s if predicate(x)],
00158          [x for x in s if not predicate(x)])
00159     """
00160 
00161     yes = []
00162     no = []
00163     for x in s:
00164         if predicate(x):
00165             yes.append(x)
00166         else:
00167             no.append(x)
00168     return yes, no

def pydoc._start_server (   urlhandler,
  port 
) [private]
Start an HTTP server thread on a specific port.

Start an HTML/text server thread, so HTML or text documents can be
browsed dynamically and interactively with a Web browser.  Example use:

    >>> import time
    >>> import pydoc

    Define a URL handler.  To determine what the client is asking
    for, check the URL and content_type.

    Then get or generate some text or HTML code and return it.

    >>> def my_url_handler(url, content_type):
    ...     text = 'the URL sent was: (%s, %s)' % (url, content_type)
    ...     return text

    Start server thread on port 0.
    If you use port 0, the server will pick a random port number.
    You can then use serverthread.port to get the port number.

    >>> port = 0
    >>> serverthread = pydoc._start_server(my_url_handler, port)

    Check that the server is really started.  If it is, open browser
    and get first page.  Use serverthread.url as the starting page.

    >>> if serverthread.serving:
    ...    import webbrowser

    The next two lines are commented out so a browser doesn't open if
    doctest is run on this module.

    #...    webbrowser.open(serverthread.url)
    #True

    Let the server do its thing. We just need to monitor its status.
    Use time.sleep so the loop doesn't hog the CPU.

    >>> starttime = time.time()
    >>> timeout = 1                    #seconds

    This is a short timeout for testing purposes.

    >>> while serverthread.serving:
    ...     time.sleep(.01)
    ...     if serverthread.serving and time.time() - starttime > timeout:
    ...          serverthread.stop()
    ...          break

    Print any errors that may have occurred.

    >>> print(serverthread.error)
    None

Definition at line 2324 of file pydoc.py.

02324 
02325 def _start_server(urlhandler, port):
02326     """Start an HTTP server thread on a specific port.
02327 
02328     Start an HTML/text server thread, so HTML or text documents can be
02329     browsed dynamically and interactively with a Web browser.  Example use:
02330 
02331         >>> import time
02332         >>> import pydoc
02333 
02334         Define a URL handler.  To determine what the client is asking
02335         for, check the URL and content_type.
02336 
02337         Then get or generate some text or HTML code and return it.
02338 
02339         >>> def my_url_handler(url, content_type):
02340         ...     text = 'the URL sent was: (%s, %s)' % (url, content_type)
02341         ...     return text
02342 
02343         Start server thread on port 0.
02344         If you use port 0, the server will pick a random port number.
02345         You can then use serverthread.port to get the port number.
02346 
02347         >>> port = 0
02348         >>> serverthread = pydoc._start_server(my_url_handler, port)
02349 
02350         Check that the server is really started.  If it is, open browser
02351         and get first page.  Use serverthread.url as the starting page.
02352 
02353         >>> if serverthread.serving:
02354         ...    import webbrowser
02355 
02356         The next two lines are commented out so a browser doesn't open if
02357         doctest is run on this module.
02358 
02359         #...    webbrowser.open(serverthread.url)
02360         #True
02361 
02362         Let the server do its thing. We just need to monitor its status.
02363         Use time.sleep so the loop doesn't hog the CPU.
02364 
02365         >>> starttime = time.time()
02366         >>> timeout = 1                    #seconds
02367 
02368         This is a short timeout for testing purposes.
02369 
02370         >>> while serverthread.serving:
02371         ...     time.sleep(.01)
02372         ...     if serverthread.serving and time.time() - starttime > timeout:
02373         ...          serverthread.stop()
02374         ...          break
02375 
02376         Print any errors that may have occurred.
02377 
02378         >>> print(serverthread.error)
02379         None
02380    """
02381     import http.server
02382     import email.message
02383     import select
02384     import threading
02385 
02386     class DocHandler(http.server.BaseHTTPRequestHandler):
02387 
02388         def do_GET(self):
02389             """Process a request from an HTML browser.
02390 
02391             The URL received is in self.path.
02392             Get an HTML page from self.urlhandler and send it.
02393             """
02394             if self.path.endswith('.css'):
02395                 content_type = 'text/css'
02396             else:
02397                 content_type = 'text/html'
02398             self.send_response(200)
02399             self.send_header('Content-Type', '%s; charset=UTF-8' % content_type)
02400             self.end_headers()
02401             self.wfile.write(self.urlhandler(
02402                 self.path, content_type).encode('utf-8'))
02403 
02404         def log_message(self, *args):
02405             # Don't log messages.
02406             pass
02407 
02408     class DocServer(http.server.HTTPServer):
02409 
02410         def __init__(self, port, callback):
02411             self.host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
02412             self.address = ('', port)
02413             self.callback = callback
02414             self.base.__init__(self, self.address, self.handler)
02415             self.quit = False
02416 
02417         def serve_until_quit(self):
02418             while not self.quit:
02419                 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
02420                 if rd:
02421                     self.handle_request()
02422             self.server_close()
02423 
02424         def server_activate(self):
02425             self.base.server_activate(self)
02426             if self.callback:
02427                 self.callback(self)
02428 
02429     class ServerThread(threading.Thread):
02430 
02431         def __init__(self, urlhandler, port):
02432             self.urlhandler = urlhandler
02433             self.port = int(port)
02434             threading.Thread.__init__(self)
02435             self.serving = False
02436             self.error = None
02437 
02438         def run(self):
02439             """Start the server."""
02440             try:
02441                 DocServer.base = http.server.HTTPServer
02442                 DocServer.handler = DocHandler
02443                 DocHandler.MessageClass = email.message.Message
02444                 DocHandler.urlhandler = staticmethod(self.urlhandler)
02445                 docsvr = DocServer(self.port, self.ready)
02446                 self.docserver = docsvr
02447                 docsvr.serve_until_quit()
02448             except Exception as e:
02449                 self.error = e
02450 
02451         def ready(self, server):
02452             self.serving = True
02453             self.host = server.host
02454             self.port = server.server_port
02455             self.url = 'http://%s:%d/' % (self.host, self.port)
02456 
02457         def stop(self):
02458             """Stop the server and this thread nicely"""
02459             self.docserver.quit = True
02460             self.serving = False
02461             self.url = None
02462 
02463     thread = ServerThread(urlhandler, port)
02464     thread.start()
02465     # Wait until thread.serving is True to make sure we are
02466     # really up before returning.
02467     while not thread.error and not thread.serving:
02468         time.sleep(.01)
02469     return thread
02470 

Here is the caller graph for this function:

def pydoc._url_handler (   url,
  content_type = "text/html" 
) [private]
The pydoc url handler for use with the pydoc server.

If the content_type is 'text/css', the _pydoc.css style
sheet is read and returned if it exits.

If the content_type is 'text/html', then the result of
get_html_page(url) is returned.

Definition at line 2471 of file pydoc.py.

02471 
02472 def _url_handler(url, content_type="text/html"):
02473     """The pydoc url handler for use with the pydoc server.
02474 
02475     If the content_type is 'text/css', the _pydoc.css style
02476     sheet is read and returned if it exits.
02477 
02478     If the content_type is 'text/html', then the result of
02479     get_html_page(url) is returned.
02480     """
02481     class _HTMLDoc(HTMLDoc):
02482 
02483         def page(self, title, contents):
02484             """Format an HTML page."""
02485             css_path = "pydoc_data/_pydoc.css"
02486             css_link = (
02487                 '<link rel="stylesheet" type="text/css" href="%s">' %
02488                 css_path)
02489             return '''\
02490 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
02491 <html><head><title>Pydoc: %s</title>
02492 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
02493 %s</head><body bgcolor="#f0f0f8">%s<div style="clear:both;padding-top:.5em;">%s</div>
02494 </body></html>''' % (title, css_link, html_navbar(), contents)
02495 
02496         def filelink(self, url, path):
02497             return '<a href="getfile?key=%s">%s</a>' % (url, path)
02498 
02499 
02500     html = _HTMLDoc()
02501 
02502     def html_navbar():
02503         version = html.escape("%s [%s, %s]" % (platform.python_version(),
02504                                                platform.python_build()[0],
02505                                                platform.python_compiler()))
02506         return """
02507             <div style='float:left'>
02508                 Python %s<br>%s
02509             </div>
02510             <div style='float:right'>
02511                 <div style='text-align:center'>
02512                   <a href="index.html">Module Index</a>
02513                   : <a href="topics.html">Topics</a>
02514                   : <a href="keywords.html">Keywords</a>
02515                 </div>
02516                 <div>
02517                     <form action="get" style='display:inline;'>
02518                       <input type=text name=key size=15>
02519                       <input type=submit value="Get">
02520                     </form>&nbsp;
02521                     <form action="search" style='display:inline;'>
02522                       <input type=text name=key size=15>
02523                       <input type=submit value="Search">
02524                     </form>
02525                 </div>
02526             </div>
02527             """ % (version, html.escape(platform.platform(terse=True)))
02528 
02529     def html_index():
02530         """Module Index page."""
02531 
02532         def bltinlink(name):
02533             return '<a href="%s.html">%s</a>' % (name, name)
02534 
02535         heading = html.heading(
02536             '<big><big><strong>Index of Modules</strong></big></big>',
02537             '#ffffff', '#7799ee')
02538         names = [name for name in sys.builtin_module_names
02539                  if name != '__main__']
02540         contents = html.multicolumn(names, bltinlink)
02541         contents = [heading, '<p>' + html.bigsection(
02542             'Built-in Modules', '#ffffff', '#ee77aa', contents)]
02543 
02544         seen = {}
02545         for dir in sys.path:
02546             contents.append(html.index(dir, seen))
02547 
02548         contents.append(
02549             '<p align=right><font color="#909090" face="helvetica,'
02550             'arial"><strong>pydoc</strong> by Ka-Ping Yee'
02551             '&lt;ping@lfw.org&gt;</font>')
02552         return 'Index of Modules', ''.join(contents)
02553 
02554     def html_search(key):
02555         """Search results page."""
02556         # scan for modules
02557         search_result = []
02558 
02559         def callback(path, modname, desc):
02560             if modname[-9:] == '.__init__':
02561                 modname = modname[:-9] + ' (package)'
02562             search_result.append((modname, desc and '- ' + desc))
02563 
02564         with warnings.catch_warnings():
02565             warnings.filterwarnings('ignore') # ignore problems during import
02566             ModuleScanner().run(callback, key)
02567 
02568         # format page
02569         def bltinlink(name):
02570             return '<a href="%s.html">%s</a>' % (name, name)
02571 
02572         results = []
02573         heading = html.heading(
02574             '<big><big><strong>Search Results</strong></big></big>',
02575             '#ffffff', '#7799ee')
02576         for name, desc in search_result:
02577             results.append(bltinlink(name) + desc)
02578         contents = heading + html.bigsection(
02579             'key = %s' % key, '#ffffff', '#ee77aa', '<br>'.join(results))
02580         return 'Search Results', contents
02581 
02582     def html_getfile(path):
02583         """Get and display a source file listing safely."""
02584         path = path.replace('%20', ' ')
02585         with tokenize.open(path) as fp:
02586             lines = html.escape(fp.read())
02587         body = '<pre>%s</pre>' % lines
02588         heading = html.heading(
02589             '<big><big><strong>File Listing</strong></big></big>',
02590             '#ffffff', '#7799ee')
02591         contents = heading + html.bigsection(
02592             'File: %s' % path, '#ffffff', '#ee77aa', body)
02593         return 'getfile %s' % path, contents
02594 
02595     def html_topics():
02596         """Index of topic texts available."""
02597 
02598         def bltinlink(name):
02599             return '<a href="topic?key=%s">%s</a>' % (name, name)
02600 
02601         heading = html.heading(
02602             '<big><big><strong>INDEX</strong></big></big>',
02603             '#ffffff', '#7799ee')
02604         names = sorted(Helper.topics.keys())
02605 
02606         contents = html.multicolumn(names, bltinlink)
02607         contents = heading + html.bigsection(
02608             'Topics', '#ffffff', '#ee77aa', contents)
02609         return 'Topics', contents
02610 
02611     def html_keywords():
02612         """Index of keywords."""
02613         heading = html.heading(
02614             '<big><big><strong>INDEX</strong></big></big>',
02615             '#ffffff', '#7799ee')
02616         names = sorted(Helper.keywords.keys())
02617 
02618         def bltinlink(name):
02619             return '<a href="topic?key=%s">%s</a>' % (name, name)
02620 
02621         contents = html.multicolumn(names, bltinlink)
02622         contents = heading + html.bigsection(
02623             'Keywords', '#ffffff', '#ee77aa', contents)
02624         return 'Keywords', contents
02625 
02626     def html_topicpage(topic):
02627         """Topic or keyword help page."""
02628         buf = io.StringIO()
02629         htmlhelp = Helper(buf, buf)
02630         contents, xrefs = htmlhelp._gettopic(topic)
02631         if topic in htmlhelp.keywords:
02632             title = 'KEYWORD'
02633         else:
02634             title = 'TOPIC'
02635         heading = html.heading(
02636             '<big><big><strong>%s</strong></big></big>' % title,
02637             '#ffffff', '#7799ee')
02638         contents = '<pre>%s</pre>' % html.markup(contents)
02639         contents = html.bigsection(topic , '#ffffff','#ee77aa', contents)
02640         if xrefs:
02641             xrefs = sorted(xrefs.split())
02642 
02643             def bltinlink(name):
02644                 return '<a href="topic?key=%s">%s</a>' % (name, name)
02645 
02646             xrefs = html.multicolumn(xrefs, bltinlink)
02647             xrefs = html.section('Related help topics: ',
02648                                  '#ffffff', '#ee77aa', xrefs)
02649         return ('%s %s' % (title, topic),
02650                 ''.join((heading, contents, xrefs)))
02651 
02652     def html_getobj(url):
02653         obj = locate(url, forceload=1)
02654         if obj is None and url != 'None':
02655             raise ValueError('could not find object')
02656         title = describe(obj)
02657         content = html.document(obj, url)
02658         return title, content
02659 
02660     def html_error(url, exc):
02661         heading = html.heading(
02662             '<big><big><strong>Error</strong></big></big>',
02663             '#ffffff', '#7799ee')
02664         contents = '<br>'.join(html.escape(line) for line in
02665                                format_exception_only(type(exc), exc))
02666         contents = heading + html.bigsection(url, '#ffffff', '#bb0000',
02667                                              contents)
02668         return "Error - %s" % url, contents
02669 
02670     def get_html_page(url):
02671         """Generate an HTML page for url."""
02672         complete_url = url
02673         if url.endswith('.html'):
02674             url = url[:-5]
02675         try:
02676             if url in ("", "index"):
02677                 title, content = html_index()
02678             elif url == "topics":
02679                 title, content = html_topics()
02680             elif url == "keywords":
02681                 title, content = html_keywords()
02682             elif '=' in url:
02683                 op, _, url = url.partition('=')
02684                 if op == "search?key":
02685                     title, content = html_search(url)
02686                 elif op == "getfile?key":
02687                     title, content = html_getfile(url)
02688                 elif op == "topic?key":
02689                     # try topics first, then objects.
02690                     try:
02691                         title, content = html_topicpage(url)
02692                     except ValueError:
02693                         title, content = html_getobj(url)
02694                 elif op == "get?key":
02695                     # try objects first, then topics.
02696                     if url in ("", "index"):
02697                         title, content = html_index()
02698                     else:
02699                         try:
02700                             title, content = html_getobj(url)
02701                         except ValueError:
02702                             title, content = html_topicpage(url)
02703                 else:
02704                     raise ValueError('bad pydoc url')
02705             else:
02706                 title, content = html_getobj(url)
02707         except Exception as exc:
02708             # Catch any errors and display them in an error page.
02709             title, content = html_error(complete_url, exc)
02710         return html.page(title, content)
02711 
02712     if url.startswith('/'):
02713         url = url[1:]
02714     if content_type == 'text/css':
02715         path_here = os.path.dirname(os.path.realpath(__file__))
02716         css_path = os.path.join(path_here, url)
02717         with open(css_path) as fp:
02718             return ''.join(fp.readlines())
02719     elif content_type == 'text/html':
02720         return get_html_page(url)
02721     # Errors outside the url handler are caught by the server.
02722     raise TypeError('unknown content type %r for url %s' % (content_type, url))
02723 

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.allmethods (   cl)

Definition at line 142 of file pydoc.py.

00142 
00143 def allmethods(cl):
00144     methods = {}
00145     for key, value in inspect.getmembers(cl, _is_some_method):
00146         methods[key] = 1
00147     for base in cl.__bases__:
00148         methods.update(allmethods(base)) # all your base are belong to us
00149     for key in methods.keys():
00150         methods[key] = getattr(cl, key)
00151     return methods

Here is the call graph for this function:

def pydoc.apropos (   key)
Print all the one-line module summaries that contain a substring.

Definition at line 2044 of file pydoc.py.

02044 
02045 def apropos(key):
02046     """Print all the one-line module summaries that contain a substring."""
02047     def callback(path, modname, desc):
02048         if modname[-9:] == '.__init__':
02049             modname = modname[:-9] + ' (package)'
02050         print(modname, desc and '- ' + desc)
02051     def onerror(modname):
02052         pass
02053     with warnings.catch_warnings():
02054         warnings.filterwarnings('ignore') # ignore problems during import
02055         ModuleScanner().run(callback, key, onerror=onerror)
02056 
02057 # --------------------------------------------------- Web browser interface

def pydoc.browse (   port = 0,
  open_browser = True 
)
Start the enhanced pydoc Web server and open a Web browser.

Use port '0' to start the server on an arbitrary port.
Set open_browser to False to suppress opening a browser.

Definition at line 2724 of file pydoc.py.

02724 
02725 def browse(port=0, *, open_browser=True):
02726     """Start the enhanced pydoc Web server and open a Web browser.
02727 
02728     Use port '0' to start the server on an arbitrary port.
02729     Set open_browser to False to suppress opening a browser.
02730     """
02731     import webbrowser
02732     serverthread = _start_server(_url_handler, port)
02733     if serverthread.error:
02734         print(serverthread.error)
02735         return
02736     if serverthread.serving:
02737         server_help_msg = 'Server commands: [b]rowser, [q]uit'
02738         if open_browser:
02739             webbrowser.open(serverthread.url)
02740         try:
02741             print('Server ready at', serverthread.url)
02742             print(server_help_msg)
02743             while serverthread.serving:
02744                 cmd = input('server> ')
02745                 cmd = cmd.lower()
02746                 if cmd == 'q':
02747                     break
02748                 elif cmd == 'b':
02749                     webbrowser.open(serverthread.url)
02750                 else:
02751                     print(server_help_msg)
02752         except (KeyboardInterrupt, EOFError):
02753             print()
02754         finally:
02755             if serverthread.serving:
02756                 serverthread.stop()
02757                 print('Server stopped')
02758 
02759 
02760 # -------------------------------------------------- command-line interface

Here is the call graph for this function:

def pydoc.classify_class_attrs (   object)
Wrap inspect.classify_class_attrs, with fixup for data descriptors.

Definition at line 188 of file pydoc.py.

00188 
00189 def classify_class_attrs(object):
00190     """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
00191     results = []
00192     for (name, kind, cls, value) in inspect.classify_class_attrs(object):
00193         if inspect.isdatadescriptor(value):
00194             kind = 'data descriptor'
00195         results.append((name, kind, cls, value))
00196     return results
00197 
00198 # ----------------------------------------------------- module manipulation

Here is the call graph for this function:

def pydoc.classname (   object,
  modname 
)
Get a class name and qualify it with a module name if necessary.

Definition at line 105 of file pydoc.py.

00105 
00106 def classname(object, modname):
00107     """Get a class name and qualify it with a module name if necessary."""
00108     name = object.__name__
00109     if object.__module__ != modname:
00110         name = object.__module__ + '.' + name
00111     return name

Here is the caller graph for this function:

def pydoc.cli ( )
Command-line interface (looks at sys.argv to decide what to do).

Definition at line 2764 of file pydoc.py.

02764 
02765 def cli():
02766     """Command-line interface (looks at sys.argv to decide what to do)."""
02767     import getopt
02768     class BadUsage(Exception): pass
02769 
02770     # Scripts don't get the current directory in their path by default
02771     # unless they are run with the '-m' switch
02772     if '' not in sys.path:
02773         scriptdir = os.path.dirname(sys.argv[0])
02774         if scriptdir in sys.path:
02775             sys.path.remove(scriptdir)
02776         sys.path.insert(0, '.')
02777 
02778     try:
02779         opts, args = getopt.getopt(sys.argv[1:], 'bgk:p:w')
02780         writing = False
02781         start_server = False
02782         open_browser = False
02783         port = None
02784         for opt, val in opts:
02785             if opt == '-g':
02786                 gui()
02787                 return
02788             if opt == '-b':
02789                 start_server = True
02790                 open_browser = True
02791             if opt == '-k':
02792                 apropos(val)
02793                 return
02794             if opt == '-p':
02795                 start_server = True
02796                 port = val
02797             if opt == '-w':
02798                 writing = True
02799 
02800         if start_server == True:
02801             if port == None:
02802                 port = 0
02803             browse(port, open_browser=open_browser)
02804             return
02805 
02806         if not args: raise BadUsage
02807         for arg in args:
02808             if ispath(arg) and not os.path.exists(arg):
02809                 print('file %r does not exist' % arg)
02810                 break
02811             try:
02812                 if ispath(arg) and os.path.isfile(arg):
02813                     arg = importfile(arg)
02814                 if writing:
02815                     if ispath(arg) and os.path.isdir(arg):
02816                         writedocs(arg)
02817                     else:
02818                         writedoc(arg)
02819                 else:
02820                     help.help(arg)
02821             except ErrorDuringImport as value:
02822                 print(value)
02823 
02824     except (getopt.error, BadUsage):
02825         cmd = os.path.splitext(os.path.basename(sys.argv[0]))[0]
02826         print("""pydoc - the Python documentation tool
02827 
02828 {cmd} <name> ...
02829     Show text documentation on something.  <name> may be the name of a
02830     Python keyword, topic, function, module, or package, or a dotted
02831     reference to a class or function within a module or module in a
02832     package.  If <name> contains a '{sep}', it is used as the path to a
02833     Python source file to document. If name is 'keywords', 'topics',
02834     or 'modules', a listing of these things is displayed.
02835 
02836 {cmd} -k <keyword>
02837     Search for a keyword in the synopsis lines of all available modules.
02838 
02839 {cmd} -p <port>
02840     Start an HTTP server on the given port on the local machine.  Port
02841     number 0 can be used to get an arbitrary unused port.
02842 
02843 {cmd} -b
02844     Start an HTTP server on an arbitrary unused port and open a Web browser
02845     to interactively browse documentation.  The -p option can be used with
02846     the -b option to explicitly specify the server port.
02847 
02848 {cmd} -g
02849     Deprecated.
02850 
02851 {cmd} -w <name> ...
02852     Write out the HTML documentation for a module to a file in the current
02853     directory.  If <name> contains a '{sep}', it is treated as a filename; if
02854     it names a directory, documentation is written for all the contents.
02855 """.format(cmd=cmd, sep=os.sep))

Here is the call graph for this function:

def pydoc.cram (   text,
  maxlen 
)
Omit part of a string if needed to make it fit in a maximum length.

Definition at line 125 of file pydoc.py.

00125 
00126 def cram(text, maxlen):
00127     """Omit part of a string if needed to make it fit in a maximum length."""
00128     if len(text) > maxlen:
00129         pre = max(0, (maxlen-3)//2)
00130         post = max(0, maxlen-3-pre)
00131         return text[:pre] + '...' + text[len(text)-post:]
00132     return text

Here is the caller graph for this function:

def pydoc.describe (   thing)
Produce a short description of the given thing.

Definition at line 1448 of file pydoc.py.

01448 
01449 def describe(thing):
01450     """Produce a short description of the given thing."""
01451     if inspect.ismodule(thing):
01452         if thing.__name__ in sys.builtin_module_names:
01453             return 'built-in module ' + thing.__name__
01454         if hasattr(thing, '__path__'):
01455             return 'package ' + thing.__name__
01456         else:
01457             return 'module ' + thing.__name__
01458     if inspect.isbuiltin(thing):
01459         return 'built-in function ' + thing.__name__
01460     if inspect.isgetsetdescriptor(thing):
01461         return 'getset descriptor %s.%s.%s' % (
01462             thing.__objclass__.__module__, thing.__objclass__.__name__,
01463             thing.__name__)
01464     if inspect.ismemberdescriptor(thing):
01465         return 'member descriptor %s.%s.%s' % (
01466             thing.__objclass__.__module__, thing.__objclass__.__name__,
01467             thing.__name__)
01468     if inspect.isclass(thing):
01469         return 'class ' + thing.__name__
01470     if inspect.isfunction(thing):
01471         return 'function ' + thing.__name__
01472     if inspect.ismethod(thing):
01473         return 'method ' + thing.__name__
01474     return type(thing).__name__

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.doc (   thing,
  title = 'Python Library Documentation: %s',
  forceload = 0,
  output = None 
)
Display text documentation, given an object or a path to an object.

Definition at line 1536 of file pydoc.py.

01536 
01537         output=None):
01538     """Display text documentation, given an object or a path to an object."""
01539     try:
01540         if output is None:
01541             pager(render_doc(thing, title, forceload))
01542         else:
01543             output.write(render_doc(thing, title, forceload, plaintext))
01544     except (ImportError, ErrorDuringImport) as value:
01545         print(value)

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.getdoc (   object)
Get the doc string or comments for an object.

Definition at line 91 of file pydoc.py.

00091 
00092 def getdoc(object):
00093     """Get the doc string or comments for an object."""
00094     result = inspect.getdoc(object) or inspect.getcomments(object)
00095     return result and re.sub('^ *\n', '', result.rstrip()) or ''

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.getpager ( )
Decide what method to use for paging through text.

Definition at line 1350 of file pydoc.py.

01350 
01351 def getpager():
01352     """Decide what method to use for paging through text."""
01353     if not hasattr(sys.stdout, "isatty"):
01354         return plainpager
01355     if not sys.stdin.isatty() or not sys.stdout.isatty():
01356         return plainpager
01357     if 'PAGER' in os.environ:
01358         if sys.platform == 'win32': # pipes completely broken in Windows
01359             return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
01360         elif os.environ.get('TERM') in ('dumb', 'emacs'):
01361             return lambda text: pipepager(plain(text), os.environ['PAGER'])
01362         else:
01363             return lambda text: pipepager(text, os.environ['PAGER'])
01364     if os.environ.get('TERM') in ('dumb', 'emacs'):
01365         return plainpager
01366     if sys.platform == 'win32' or sys.platform.startswith('os2'):
01367         return lambda text: tempfilepager(plain(text), 'more <')
01368     if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
01369         return lambda text: pipepager(text, 'less')
01370 
01371     import tempfile
01372     (fd, filename) = tempfile.mkstemp()
01373     os.close(fd)
01374     try:
01375         if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
01376             return lambda text: pipepager(text, 'more')
01377         else:
01378             return ttypager
01379     finally:
01380         os.unlink(filename)

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.gui ( )
Graphical interface (starts Web server and pops up a control window).

Definition at line 2142 of file pydoc.py.

02142 
02143 def gui():
02144     """Graphical interface (starts Web server and pops up a control window)."""
02145 
02146     msg = ('the pydoc.gui() function and "pydoc -g" option are deprecated\n',
02147            'use "pydoc.browse() function and "pydoc -b" option instead.')
02148     warnings.warn(msg, DeprecationWarning, stacklevel=2)
02149 
02150     class GUI:
02151         def __init__(self, window, port=7464):
02152             self.window = window
02153             self.server = None
02154             self.scanner = None
02155 
02156             import tkinter
02157             self.server_frm = tkinter.Frame(window)
02158             self.title_lbl = tkinter.Label(self.server_frm,
02159                 text='Starting server...\n ')
02160             self.open_btn = tkinter.Button(self.server_frm,
02161                 text='open browser', command=self.open, state='disabled')
02162             self.quit_btn = tkinter.Button(self.server_frm,
02163                 text='quit serving', command=self.quit, state='disabled')
02164 
02165             self.search_frm = tkinter.Frame(window)
02166             self.search_lbl = tkinter.Label(self.search_frm, text='Search for')
02167             self.search_ent = tkinter.Entry(self.search_frm)
02168             self.search_ent.bind('<Return>', self.search)
02169             self.stop_btn = tkinter.Button(self.search_frm,
02170                 text='stop', pady=0, command=self.stop, state='disabled')
02171             if sys.platform == 'win32':
02172                 # Trying to hide and show this button crashes under Windows.
02173                 self.stop_btn.pack(side='right')
02174 
02175             self.window.title('pydoc')
02176             self.window.protocol('WM_DELETE_WINDOW', self.quit)
02177             self.title_lbl.pack(side='top', fill='x')
02178             self.open_btn.pack(side='left', fill='x', expand=1)
02179             self.quit_btn.pack(side='right', fill='x', expand=1)
02180             self.server_frm.pack(side='top', fill='x')
02181 
02182             self.search_lbl.pack(side='left')
02183             self.search_ent.pack(side='right', fill='x', expand=1)
02184             self.search_frm.pack(side='top', fill='x')
02185             self.search_ent.focus_set()
02186 
02187             font = ('helvetica', sys.platform == 'win32' and 8 or 10)
02188             self.result_lst = tkinter.Listbox(window, font=font, height=6)
02189             self.result_lst.bind('<Button-1>', self.select)
02190             self.result_lst.bind('<Double-Button-1>', self.goto)
02191             self.result_scr = tkinter.Scrollbar(window,
02192                 orient='vertical', command=self.result_lst.yview)
02193             self.result_lst.config(yscrollcommand=self.result_scr.set)
02194 
02195             self.result_frm = tkinter.Frame(window)
02196             self.goto_btn = tkinter.Button(self.result_frm,
02197                 text='go to selected', command=self.goto)
02198             self.hide_btn = tkinter.Button(self.result_frm,
02199                 text='hide results', command=self.hide)
02200             self.goto_btn.pack(side='left', fill='x', expand=1)
02201             self.hide_btn.pack(side='right', fill='x', expand=1)
02202 
02203             self.window.update()
02204             self.minwidth = self.window.winfo_width()
02205             self.minheight = self.window.winfo_height()
02206             self.bigminheight = (self.server_frm.winfo_reqheight() +
02207                                  self.search_frm.winfo_reqheight() +
02208                                  self.result_lst.winfo_reqheight() +
02209                                  self.result_frm.winfo_reqheight())
02210             self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
02211             self.expanded = 0
02212             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
02213             self.window.wm_minsize(self.minwidth, self.minheight)
02214             self.window.tk.willdispatch()
02215 
02216             import threading
02217             threading.Thread(
02218                 target=serve, args=(port, self.ready, self.quit)).start()
02219 
02220         def ready(self, server):
02221             self.server = server
02222             self.title_lbl.config(
02223                 text='Python documentation server at\n' + server.url)
02224             self.open_btn.config(state='normal')
02225             self.quit_btn.config(state='normal')
02226 
02227         def open(self, event=None, url=None):
02228             url = url or self.server.url
02229             import webbrowser
02230             webbrowser.open(url)
02231 
02232         def quit(self, event=None):
02233             if self.server:
02234                 self.server.quit = 1
02235             self.window.quit()
02236 
02237         def search(self, event=None):
02238             key = self.search_ent.get()
02239             self.stop_btn.pack(side='right')
02240             self.stop_btn.config(state='normal')
02241             self.search_lbl.config(text='Searching for "%s"...' % key)
02242             self.search_ent.forget()
02243             self.search_lbl.pack(side='left')
02244             self.result_lst.delete(0, 'end')
02245             self.goto_btn.config(state='disabled')
02246             self.expand()
02247 
02248             import threading
02249             if self.scanner:
02250                 self.scanner.quit = 1
02251             self.scanner = ModuleScanner()
02252             threading.Thread(target=self.scanner.run,
02253                              args=(self.update, key, self.done)).start()
02254 
02255         def update(self, path, modname, desc):
02256             if modname[-9:] == '.__init__':
02257                 modname = modname[:-9] + ' (package)'
02258             self.result_lst.insert('end',
02259                 modname + ' - ' + (desc or '(no description)'))
02260 
02261         def stop(self, event=None):
02262             if self.scanner:
02263                 self.scanner.quit = 1
02264                 self.scanner = None
02265 
02266         def done(self):
02267             self.scanner = None
02268             self.search_lbl.config(text='Search for')
02269             self.search_lbl.pack(side='left')
02270             self.search_ent.pack(side='right', fill='x', expand=1)
02271             if sys.platform != 'win32': self.stop_btn.forget()
02272             self.stop_btn.config(state='disabled')
02273 
02274         def select(self, event=None):
02275             self.goto_btn.config(state='normal')
02276 
02277         def goto(self, event=None):
02278             selection = self.result_lst.curselection()
02279             if selection:
02280                 modname = self.result_lst.get(selection[0]).split()[0]
02281                 self.open(url=self.server.url + modname + '.html')
02282 
02283         def collapse(self):
02284             if not self.expanded: return
02285             self.result_frm.forget()
02286             self.result_scr.forget()
02287             self.result_lst.forget()
02288             self.bigwidth = self.window.winfo_width()
02289             self.bigheight = self.window.winfo_height()
02290             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
02291             self.window.wm_minsize(self.minwidth, self.minheight)
02292             self.expanded = 0
02293 
02294         def expand(self):
02295             if self.expanded: return
02296             self.result_frm.pack(side='bottom', fill='x')
02297             self.result_scr.pack(side='right', fill='y')
02298             self.result_lst.pack(side='top', fill='both', expand=1)
02299             self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
02300             self.window.wm_minsize(self.minwidth, self.bigminheight)
02301             self.expanded = 1
02302 
02303         def hide(self, event=None):
02304             self.stop()
02305             self.collapse()
02306 
02307     import tkinter
02308     try:
02309         root = tkinter.Tk()
02310         # Tk will crash if pythonw.exe has an XP .manifest
02311         # file and the root has is not destroyed explicitly.
02312         # If the problem is ever fixed in Tk, the explicit
02313         # destroy can go.
02314         try:
02315             gui = GUI(root)
02316             root.mainloop()
02317         finally:
02318             root.destroy()
02319     except KeyboardInterrupt:
02320         pass
02321 
02322 
02323 # --------------------------------------- enhanced Web browser interface

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.importfile (   path)
Import a Python source file or compiled file given its path.

Definition at line 256 of file pydoc.py.

00256 
00257 def importfile(path):
00258     """Import a Python source file or compiled file given its path."""
00259     magic = imp.get_magic()
00260     with open(path, 'rb') as file:
00261         if file.read(len(magic)) == magic:
00262             kind = imp.PY_COMPILED
00263         else:
00264             kind = imp.PY_SOURCE
00265         file.seek(0)
00266         filename = os.path.basename(path)
00267         name, ext = os.path.splitext(filename)
00268         try:
00269             module = imp.load_module(name, file, path, (ext, 'r', kind))
00270         except:
00271             raise ErrorDuringImport(path, sys.exc_info())
00272     return module

Here is the caller graph for this function:

def pydoc.isdata (   object)
Check if an object is of a type that probably means it's data.

Definition at line 112 of file pydoc.py.

00112 
00113 def isdata(object):
00114     """Check if an object is of a type that probably means it's data."""
00115     return not (inspect.ismodule(object) or inspect.isclass(object) or
00116                 inspect.isroutine(object) or inspect.isframe(object) or
00117                 inspect.istraceback(object) or inspect.iscode(object))

Here is the call graph for this function:

def pydoc.ispackage (   path)
Guess whether a path refers to a package directory.

Definition at line 199 of file pydoc.py.

00199 
00200 def ispackage(path):
00201     """Guess whether a path refers to a package directory."""
00202     if os.path.isdir(path):
00203         for ext in ('.py', '.pyc', '.pyo'):
00204             if os.path.isfile(os.path.join(path, '__init__' + ext)):
00205                 return True
00206     return False

Here is the caller graph for this function:

def pydoc.ispath (   x)

Definition at line 2761 of file pydoc.py.

02761 
02762 def ispath(x):
02763     return isinstance(x, str) and x.find(os.sep) >= 0

Here is the caller graph for this function:

def pydoc.locate (   path,
  forceload = 0 
)
Locate an object by name or dotted path, importing as necessary.

Definition at line 1475 of file pydoc.py.

01475 
01476 def locate(path, forceload=0):
01477     """Locate an object by name or dotted path, importing as necessary."""
01478     parts = [part for part in path.split('.') if part]
01479     module, n = None, 0
01480     while n < len(parts):
01481         nextmodule = safeimport('.'.join(parts[:n+1]), forceload)
01482         if nextmodule: module, n = nextmodule, n + 1
01483         else: break
01484     if module:
01485         object = module
01486     else:
01487         object = builtins
01488     for part in parts[n:]:
01489         try:
01490             object = getattr(object, part)
01491         except AttributeError:
01492             return None
01493     return object
01494 
01495 # --------------------------------------- interactive interpreter interface

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.pager (   text)
The first time this is called, determine what kind of pager to use.

Definition at line 1344 of file pydoc.py.

01344 
01345 def pager(text):
01346     """The first time this is called, determine what kind of pager to use."""
01347     global pager
01348     pager = getpager()
01349     pager(text)

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.pathdirs ( )
Convert sys.path into a list of absolute, existing, unique paths.

Definition at line 79 of file pydoc.py.

00079 
00080 def pathdirs():
00081     """Convert sys.path into a list of absolute, existing, unique paths."""
00082     dirs = []
00083     normdirs = []
00084     for dir in sys.path:
00085         dir = os.path.abspath(dir or '.')
00086         normdir = os.path.normcase(dir)
00087         if normdir not in normdirs and os.path.isdir(dir):
00088             dirs.append(dir)
00089             normdirs.append(normdir)
00090     return dirs

def pydoc.pipepager (   text,
  cmd 
)
Page through text by feeding it to another program.

Definition at line 1385 of file pydoc.py.

01385 
01386 def pipepager(text, cmd):
01387     """Page through text by feeding it to another program."""
01388     pipe = os.popen(cmd, 'w')
01389     try:
01390         pipe.write(text)
01391         pipe.close()
01392     except IOError:
01393         pass # Ignore broken pipes caused by quitting the pager program.

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.plain (   text)
Remove boldface formatting from text.

Definition at line 1381 of file pydoc.py.

01381 
01382 def plain(text):
01383     """Remove boldface formatting from text."""
01384     return re.sub('.\b', '', text)

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.plainpager (   text)
Simply print unformatted text.  This is the ultimate fallback.

Definition at line 1444 of file pydoc.py.

01444 
01445 def plainpager(text):
01446     """Simply print unformatted text.  This is the ultimate fallback."""
01447     sys.stdout.write(plain(text))

Here is the call graph for this function:

def pydoc.render_doc (   thing,
  title = 'Python Library Documentation: %s',
  forceload = 0,
  renderer = None 
)
Render text documentation, given an object or a path to an object.

Definition at line 1511 of file pydoc.py.

01511 
01512         renderer=None):
01513     """Render text documentation, given an object or a path to an object."""
01514     if renderer is None:
01515         renderer = text
01516     object, name = resolve(thing, forceload)
01517     desc = describe(object)
01518     module = inspect.getmodule(object)
01519     if name and '.' in name:
01520         desc += ' in ' + name[:name.rfind('.')]
01521     elif module and module is not object:
01522         desc += ' in module ' + module.__name__
01523 
01524     if not (inspect.ismodule(object) or
01525               inspect.isclass(object) or
01526               inspect.isroutine(object) or
01527               inspect.isgetsetdescriptor(object) or
01528               inspect.ismemberdescriptor(object) or
01529               isinstance(object, property)):
01530         # If the passed object is a piece of data or an instance,
01531         # document its available methods instead of its value.
01532         object = type(object)
01533         desc += ' object'
01534     return title % desc + '\n\n' + renderer.document(object, name)

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.replace (   text,
  pairs 
)
Do a series of global replacements on a string.

Definition at line 118 of file pydoc.py.

00118 
00119 def replace(text, *pairs):
00120     """Do a series of global replacements on a string."""
00121     while pairs:
00122         text = pairs[1].join(text.split(pairs[0]))
00123         pairs = pairs[2:]
00124     return text

Here is the caller graph for this function:

def pydoc.resolve (   thing,
  forceload = 0 
)
Given an object or a path to an object, get the object and its name.

Definition at line 1500 of file pydoc.py.

01500 
01501 def resolve(thing, forceload=0):
01502     """Given an object or a path to an object, get the object and its name."""
01503     if isinstance(thing, str):
01504         object = locate(thing, forceload)
01505         if not object:
01506             raise ImportError('no Python documentation found for %r' % thing)
01507         return object, thing
01508     else:
01509         return thing, getattr(thing, '__name__', None)

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.safeimport (   path,
  forceload = 0,
  cache = {} 
)
Import a module; handle errors; return None if the module isn't found.

If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised.  Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning.  If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension).

Definition at line 273 of file pydoc.py.

00273 
00274 def safeimport(path, forceload=0, cache={}):
00275     """Import a module; handle errors; return None if the module isn't found.
00276 
00277     If the module *is* found but an exception occurs, it's wrapped in an
00278     ErrorDuringImport exception and reraised.  Unlike __import__, if a
00279     package path is specified, the module at the end of the path is returned,
00280     not the package at the beginning.  If the optional 'forceload' argument
00281     is 1, we reload the module from disk (unless it's a dynamic extension)."""
00282     try:
00283         # If forceload is 1 and the module has been previously loaded from
00284         # disk, we always have to reload the module.  Checking the file's
00285         # mtime isn't good enough (e.g. the module could contain a class
00286         # that inherits from another module that has changed).
00287         if forceload and path in sys.modules:
00288             if path not in sys.builtin_module_names:
00289                 # Remove the module from sys.modules and re-import to try
00290                 # and avoid problems with partially loaded modules.
00291                 # Also remove any submodules because they won't appear
00292                 # in the newly loaded module's namespace if they're already
00293                 # in sys.modules.
00294                 subs = [m for m in sys.modules if m.startswith(path + '.')]
00295                 for key in [path] + subs:
00296                     # Prevent garbage collection.
00297                     cache[key] = sys.modules[key]
00298                     del sys.modules[key]
00299         module = __import__(path)
00300     except:
00301         # Did the error occur before or after the module was found?
00302         (exc, value, tb) = info = sys.exc_info()
00303         if path in sys.modules:
00304             # An error occurred while executing the imported module.
00305             raise ErrorDuringImport(sys.modules[path].__file__, info)
00306         elif exc is SyntaxError:
00307             # A SyntaxError occurred before we could execute the module.
00308             raise ErrorDuringImport(value.filename, info)
00309         elif exc is ImportError and extract_tb(tb)[-1][2]=='safeimport':
00310             # The import error occurred directly in this function,
00311             # which means there is no such module in the path.
00312             return None
00313         else:
00314             # Some other error occurred during the importing process.
00315             raise ErrorDuringImport(path, sys.exc_info())
00316     for part in path.split('.')[1:]:
00317         try: module = getattr(module, part)
00318         except AttributeError: return None
00319     return module
00320 
00321 # ---------------------------------------------------- formatter base class

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.serve (   port,
  callback = None,
  completer = None 
)

Definition at line 2058 of file pydoc.py.

02058 
02059 def serve(port, callback=None, completer=None):
02060     import http.server, email.message, select
02061 
02062     msg = 'the pydoc.serve() function is deprecated'
02063     warnings.warn(msg, DeprecationWarning, stacklevel=2)
02064 
02065     class DocHandler(http.server.BaseHTTPRequestHandler):
02066         def send_document(self, title, contents):
02067             try:
02068                 self.send_response(200)
02069                 self.send_header('Content-Type', 'text/html; charset=UTF-8')
02070                 self.end_headers()
02071                 self.wfile.write(html.page(title, contents).encode('utf-8'))
02072             except IOError: pass
02073 
02074         def do_GET(self):
02075             path = self.path
02076             if path[-5:] == '.html': path = path[:-5]
02077             if path[:1] == '/': path = path[1:]
02078             if path and path != '.':
02079                 try:
02080                     obj = locate(path, forceload=1)
02081                 except ErrorDuringImport as value:
02082                     self.send_document(path, html.escape(str(value)))
02083                     return
02084                 if obj:
02085                     self.send_document(describe(obj), html.document(obj, path))
02086                 else:
02087                     self.send_document(path,
02088 'no Python documentation found for %s' % repr(path))
02089             else:
02090                 heading = html.heading(
02091 '<big><big><strong>Python: Index of Modules</strong></big></big>',
02092 '#ffffff', '#7799ee')
02093                 def bltinlink(name):
02094                     return '<a href="%s.html">%s</a>' % (name, name)
02095                 names = [x for x in sys.builtin_module_names if x != '__main__']
02096                 contents = html.multicolumn(names, bltinlink)
02097                 indices = ['<p>' + html.bigsection(
02098                     'Built-in Modules', '#ffffff', '#ee77aa', contents)]
02099 
02100                 seen = {}
02101                 for dir in sys.path:
02102                     indices.append(html.index(dir, seen))
02103                 contents = heading + ' '.join(indices) + '''<p align=right>
02104 <font color="#909090" face="helvetica, arial"><strong>
02105 pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>'''
02106                 self.send_document('Index of Modules', contents)
02107 
02108         def log_message(self, *args): pass
02109 
02110     class DocServer(http.server.HTTPServer):
02111         def __init__(self, port, callback):
02112             host = 'localhost'
02113             self.address = (host, port)
02114             self.url = 'http://%s:%d/' % (host, port)
02115             self.callback = callback
02116             self.base.__init__(self, self.address, self.handler)
02117 
02118         def serve_until_quit(self):
02119             import select
02120             self.quit = False
02121             while not self.quit:
02122                 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
02123                 if rd: self.handle_request()
02124             self.server_close()
02125 
02126         def server_activate(self):
02127             self.base.server_activate(self)
02128             if self.callback: self.callback(self)
02129 
02130     DocServer.base = http.server.HTTPServer
02131     DocServer.handler = DocHandler
02132     DocHandler.MessageClass = email.message.Message
02133     try:
02134         try:
02135             DocServer(port, callback).serve_until_quit()
02136         except (KeyboardInterrupt, select.error):
02137             pass
02138     finally:
02139         if completer: completer()
02140 
02141 # ----------------------------------------------------- graphical interface

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.source_synopsis (   file)

Definition at line 207 of file pydoc.py.

00207 
00208 def source_synopsis(file):
00209     line = file.readline()
00210     while line[:1] == '#' or not line.strip():
00211         line = file.readline()
00212         if not line: break
00213     line = line.strip()
00214     if line[:4] == 'r"""': line = line[1:]
00215     if line[:3] == '"""':
00216         line = line[3:]
00217         if line[-1:] == '\\': line = line[:-1]
00218         while not line.strip():
00219             line = file.readline()
00220             if not line: break
00221         result = line.split('"""')[0].strip()
00222     else: result = None
00223     return result

Here is the caller graph for this function:

def pydoc.splitdoc (   doc)
Split a doc string into a synopsis line (if any) and the rest.

Definition at line 96 of file pydoc.py.

00096 
00097 def splitdoc(doc):
00098     """Split a doc string into a synopsis line (if any) and the rest."""
00099     lines = doc.strip().split('\n')
00100     if len(lines) == 1:
00101         return lines[0], ''
00102     elif len(lines) >= 2 and not lines[1].rstrip():
00103         return lines[0], '\n'.join(lines[2:])
00104     return '', '\n'.join(lines)

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.stripid (   text)
Remove the hexadecimal id from a Python object representation.

Definition at line 134 of file pydoc.py.

00134 
00135 def stripid(text):
00136     """Remove the hexadecimal id from a Python object representation."""
00137     # The behaviour of %p is implementation-dependent in terms of case.
00138     return _re_stripid.sub(r'\1', text)

Here is the caller graph for this function:

def pydoc.synopsis (   filename,
  cache = {} 
)
Get the one-line summary out of a module file.

Definition at line 224 of file pydoc.py.

00224 
00225 def synopsis(filename, cache={}):
00226     """Get the one-line summary out of a module file."""
00227     mtime = os.stat(filename).st_mtime
00228     lastupdate, result = cache.get(filename, (None, None))
00229     if lastupdate is None or lastupdate < mtime:
00230         info = inspect.getmoduleinfo(filename)
00231         try:
00232             file = tokenize.open(filename)
00233         except IOError:
00234             # module can't be opened, so skip it
00235             return None
00236         if info and 'b' in info[2]: # binary modules have to be imported
00237             try: module = imp.load_module('__temp__', file, filename, info[1:])
00238             except: return None
00239             result = (module.__doc__ or '').splitlines()[0]
00240             del sys.modules['__temp__']
00241         else: # text modules can be directly examined
00242             result = source_synopsis(file)
00243             file.close()
00244         cache[filename] = (mtime, result)
00245     return result

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.tempfilepager (   text,
  cmd 
)
Page through text by invoking a program on a temporary file.

Definition at line 1394 of file pydoc.py.

01394 
01395 def tempfilepager(text, cmd):
01396     """Page through text by invoking a program on a temporary file."""
01397     import tempfile
01398     filename = tempfile.mktemp()
01399     file = open(filename, 'w')
01400     file.write(text)
01401     file.close()
01402     try:
01403         os.system(cmd + ' "' + filename + '"')
01404     finally:
01405         os.unlink(filename)

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.ttypager (   text)
Page through text on a text terminal.

Definition at line 1406 of file pydoc.py.

01406 
01407 def ttypager(text):
01408     """Page through text on a text terminal."""
01409     lines = plain(text).split('\n')
01410     try:
01411         import tty
01412         fd = sys.stdin.fileno()
01413         old = tty.tcgetattr(fd)
01414         tty.setcbreak(fd)
01415         getchar = lambda: sys.stdin.read(1)
01416     except (ImportError, AttributeError):
01417         tty = None
01418         getchar = lambda: sys.stdin.readline()[:-1][:1]
01419 
01420     try:
01421         r = inc = os.environ.get('LINES', 25) - 1
01422         sys.stdout.write('\n'.join(lines[:inc]) + '\n')
01423         while lines[r:]:
01424             sys.stdout.write('-- more --')
01425             sys.stdout.flush()
01426             c = getchar()
01427 
01428             if c in ('q', 'Q'):
01429                 sys.stdout.write('\r          \r')
01430                 break
01431             elif c in ('\r', '\n'):
01432                 sys.stdout.write('\r          \r' + lines[r] + '\n')
01433                 r = r + 1
01434                 continue
01435             if c in ('b', 'B', '\x1b'):
01436                 r = r - inc - inc
01437                 if r < 0: r = 0
01438             sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
01439             r = r + inc
01440 
01441     finally:
01442         if tty:
01443             tty.tcsetattr(fd, tty.TCSAFLUSH, old)

Here is the call graph for this function:

def pydoc.visiblename (   name,
  all = None,
  obj = None 
)
Decide whether to show documentation on a variable.

Definition at line 169 of file pydoc.py.

00169 
00170 def visiblename(name, all=None, obj=None):
00171     """Decide whether to show documentation on a variable."""
00172     # Certain special names are redundant.
00173     _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__',
00174                      '__module__', '__name__', '__slots__', '__package__',
00175                      '__cached__', '__author__', '__credits__', '__date__',
00176                      '__version__')
00177     if name in _hidden_names: return 0
00178     # Private names are hidden, but special names are displayed.
00179     if name.startswith('__') and name.endswith('__'): return 1
00180     # Namedtuples have public fields and methods with a single leading underscore
00181     if name.startswith('_') and hasattr(obj, '_fields'):
00182         return True
00183     if all is not None:
00184         # only document that which the programmer exported in __all__
00185         return name in all
00186     else:
00187         return not name.startswith('_')

Here is the caller graph for this function:

def pydoc.writedoc (   thing,
  forceload = 0 
)
Write HTML documentation to a file in the current directory.

Definition at line 1546 of file pydoc.py.

01546 
01547 def writedoc(thing, forceload=0):
01548     """Write HTML documentation to a file in the current directory."""
01549     try:
01550         object, name = resolve(thing, forceload)
01551         page = html.page(describe(object), html.document(object, name))
01552         file = open(name + '.html', 'w', encoding='utf-8')
01553         file.write(page)
01554         file.close()
01555         print('wrote', name + '.html')
01556     except (ImportError, ErrorDuringImport) as value:
01557         print(value)

Here is the call graph for this function:

Here is the caller graph for this function:

def pydoc.writedocs (   dir,
  pkgpath = '',
  done = None 
)
Write out HTML documentation for all modules in a directory tree.

Definition at line 1558 of file pydoc.py.

01558 
01559 def writedocs(dir, pkgpath='', done=None):
01560     """Write out HTML documentation for all modules in a directory tree."""
01561     if done is None: done = {}
01562     for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):
01563         writedoc(modname)
01564     return

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

list pydoc.__all__ = ['help']

Definition at line 41 of file pydoc.py.

string pydoc.__author__ = "Ka-Ping Yee <ping@lfw.org>"

Definition at line 42 of file pydoc.py.

Initial value:
00001 """Guido van Rossum, for an excellent programming language.
00002 Tommy Burnette, the original creator of manpy.
00003 Paul Prescod, for all his work on onlinehelp.
00004 Richard Chamberlain, for the first implementation of textdoc.
00005 """

Definition at line 46 of file pydoc.py.

string pydoc.__date__ = "26 February 2001"

Definition at line 43 of file pydoc.py.

string pydoc.__version__ = "$Revision$"

Definition at line 45 of file pydoc.py.

tuple pydoc._re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)

Definition at line 133 of file pydoc.py.

Definition at line 2112 of file pydoc.py.

Definition at line 2209 of file pydoc.py.

Definition at line 2205 of file pydoc.py.

Definition at line 2287 of file pydoc.py.

Definition at line 2114 of file pydoc.py.

Definition at line 2445 of file pydoc.py.

Definition at line 2435 of file pydoc.py.

Definition at line 2210 of file pydoc.py.

Definition at line 2195 of file pydoc.py.

tuple pydoc.help = Helper()

Definition at line 1950 of file pydoc.py.

Definition at line 2197 of file pydoc.py.

Definition at line 2410 of file pydoc.py.

tuple pydoc.html = HTMLDoc()

Definition at line 1498 of file pydoc.py.

Definition at line 2204 of file pydoc.py.

Definition at line 2203 of file pydoc.py.

Definition at line 2159 of file pydoc.py.

Definition at line 1497 of file pydoc.py.

Definition at line 2432 of file pydoc.py.

Definition at line 2119 of file pydoc.py.

Definition at line 2161 of file pydoc.py.

Definition at line 2194 of file pydoc.py.

Definition at line 2187 of file pydoc.py.

Definition at line 2190 of file pydoc.py.

Definition at line 2153 of file pydoc.py.

Definition at line 2166 of file pydoc.py.

Definition at line 2164 of file pydoc.py.

Definition at line 2165 of file pydoc.py.

Definition at line 2152 of file pydoc.py.

Definition at line 2156 of file pydoc.py.

Definition at line 2434 of file pydoc.py.

Definition at line 2168 of file pydoc.py.

tuple pydoc.text = TextDoc()

Definition at line 1496 of file pydoc.py.

Definition at line 2157 of file pydoc.py.

Definition at line 2113 of file pydoc.py.

Definition at line 2431 of file pydoc.py.

Definition at line 2151 of file pydoc.py.