Index: Lib/pydoc.py =================================================================== --- Lib/pydoc.py (revision 60757) +++ Lib/pydoc.py (working copy) @@ -20,7 +20,7 @@ local machine to generate documentation web pages. For platforms without a command line, "pydoc -g" starts the HTTP server -and also pops up a little window for controlling it. +And opens the webbrowser to an index page. Run "pydoc -w " to write out the HTML documentation for a module to a file named ".html". @@ -147,7 +147,6 @@ ([x for x in s if predicate(x)], [x for x in s if not predicate(x)]) """ - yes = [] no = [] for x in s: @@ -594,7 +593,7 @@ if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) - filelink = '%s' % (url, path) + filelink = '%s' % (url, path) except TypeError: filelink = '(built-in)' info = [] @@ -612,9 +611,7 @@ docloc = '
Module Docs' % locals() else: docloc = '' - result = self.heading( - head, '#ffffff', '#7799ee', - 'index
' + filelink + docloc) + result = self.heading(head, '#ffffff', '#7799ee', filelink + docloc) modules = inspect.getmembers(object, inspect.ismodule) @@ -1454,7 +1451,6 @@ return getattr(__builtin__, path) # --------------------------------------- interactive interpreter interface - text = TextDoc() html = HTMLDoc() @@ -1800,13 +1796,12 @@ parser.start_tr = parser.do_br parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t') parser.feed(document) - buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n ') - pager(' ' + strip(buffer) + '\n') + buffer.write('\n\n') if xrefs: - buffer = StringIO.StringIO() formatter.DumbWriter(buffer).send_flowing_data( 'Related help topics: ' + join(split(xrefs), ', ') + '\n') - self.output.write('\n%s\n' % buffer.getvalue()) + buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n ') + self.output.write('\n%s\n' % buffer) def listmodules(self, key=''): if key: @@ -1916,284 +1911,355 @@ else: warnings.filterwarnings('ignore') # ignore problems during import ModuleScanner().run(callback, key) -# --------------------------------------------------- web browser interface -def serve(port, callback=None, completer=None): - import BaseHTTPServer, mimetools, select +# ----------------------------------------------------------- HTML Server - # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded. - class Message(mimetools.Message): - def __init__(self, fp, seekable=1): - Message = self.__class__ - Message.__bases__[0].__bases__[0].__init__(self, fp, seekable) - self.encodingheader = self.getheader('content-transfer-encoding') - self.typeheader = self.getheader('content-type') - self.parsetype() - self.parseplist() +""" +A simple local HTML server. - class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler): - def send_document(self, title, contents): - try: - self.send_response(200) - self.send_header('Content-Type', 'text/html') - self.end_headers() - self.wfile.write(html.page(title, contents)) - except IOError: pass +Start an html web server so html documents can be browsed +dynamically and interactively with a web browser. - def do_GET(self): - path = self.path - if path[-5:] == '.html': path = path[:-5] - if path[:1] == '/': path = path[1:] - if path and path != '.': - try: - obj = locate(path, forceload=1) - except ErrorDuringImport, value: - self.send_document(path, html.escape(str(value))) - return - if obj: - self.send_document(describe(obj), html.document(obj, path)) - else: - self.send_document(path, -'no Python documentation found for %s' % repr(path)) - else: - heading = html.heading( -'Python: Index of Modules', -'#ffffff', '#7799ee') - def bltinlink(name): - return '%s' % (name, name) - names = filter(lambda x: x != '__main__', - sys.builtin_module_names) - contents = html.multicolumn(names, bltinlink) - indices = ['

' + html.bigsection( - 'Built-in Modules', '#ffffff', '#ee77aa', contents)] +Example use from another module. - seen = {} - for dir in sys.path: - indices.append(html.index(dir, seen)) - contents = heading + join(indices) + '''

- -pydoc by Ka-Ping Yee <ping@lfw.org>''' - self.send_document('Index of Modules', contents) + import server + import html_page_getter - def log_message(self, *args): pass + # Define a url handler. + def my_url_handler(url): + print "url: ", url + return html_page_getter.page(url) - class DocServer(BaseHTTPServer.HTTPServer): - def __init__(self, port, callback): - host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost' - self.address = ('', port) - self.url = 'http://%s:%d/' % (host, port) - self.callback = callback - self.base.__init__(self, self.address, self.handler) + # Start server thread on port 8080. + server.start(my_url_handler, 8080) + + # Open browser and get first page. + import webbrowser + webbrowser.open("http://localhost:%s/startpage.html" % port) - def serve_until_quit(self): - import select - self.quit = False - while not self.quit: - rd, wr, ex = select.select([self.socket.fileno()], [], [], 1) - if rd: self.handle_request() + while server.serving: # serve until stopped. + time.sleep(1) # keep cpu load down while we wait. - def server_activate(self): - self.base.server_activate(self) - if self.callback: self.callback(self) - DocServer.base = BaseHTTPServer.HTTPServer - DocServer.handler = DocHandler - DocHandler.MessageClass = Message - try: - try: - DocServer(port, callback).serve_until_quit() - except (KeyboardInterrupt, select.error): - pass - finally: - if completer: completer() +To stop the server thread explicitely: -# ----------------------------------------------------- graphical interface + server.stop() -def gui(): - """Graphical interface (starts web server and pops up a control window).""" - class GUI: - def __init__(self, window, port=7464): - self.window = window - self.server = None - self.scanner = None +""" +import BaseHTTPServer +import mimetools +import select +import threading +import time - import Tkinter - self.server_frm = Tkinter.Frame(window) - self.title_lbl = Tkinter.Label(self.server_frm, - text='Starting server...\n ') - self.open_btn = Tkinter.Button(self.server_frm, - text='open browser', command=self.open, state='disabled') - self.quit_btn = Tkinter.Button(self.server_frm, - text='quit serving', command=self.quit, state='disabled') +# Patch up mimetools.Message so it doesn't break if rfc822 is reloaded. +class Message(mimetools.Message): + def __init__(self, fp, seekable=1): + Message = self.__class__ + Message.__bases__[0].__bases__[0].__init__(self, fp, seekable) + self.encodingheader = self.getheader('content-transfer-encoding') + self.typeheader = self.getheader('content-type') + self.parsetype() + self.parseplist() - self.search_frm = Tkinter.Frame(window) - self.search_lbl = Tkinter.Label(self.search_frm, text='Search for') - self.search_ent = Tkinter.Entry(self.search_frm) - self.search_ent.bind('', self.search) - self.stop_btn = Tkinter.Button(self.search_frm, - text='stop', pady=0, command=self.stop, state='disabled') - if sys.platform == 'win32': - # Trying to hide and show this button crashes under Windows. - self.stop_btn.pack(side='right') +class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler): + """ Handle server requests from browser. + """ + def do_GET(self): + """ Process a request from a html browser. - self.window.title('pydoc') - self.window.protocol('WM_DELETE_WINDOW', self.quit) - self.title_lbl.pack(side='top', fill='x') - self.open_btn.pack(side='left', fill='x', expand=1) - self.quit_btn.pack(side='right', fill='x', expand=1) - self.server_frm.pack(side='top', fill='x') + The url recieved is in self.path. + Get an html page from self.urlhandler and send it. + """ + if self.path.endswith('.css'): + content_type = 'text/css' + else: + content_type = 'text/html' + self.send_response(200) + self.send_header('Content-Type', content_type) + self.end_headers() + self.wfile.write(self.urlhandler(self.path, content_type)) + def log_message(self, *args): + # Don't log messages. + pass - self.search_lbl.pack(side='left') - self.search_ent.pack(side='right', fill='x', expand=1) - self.search_frm.pack(side='top', fill='x') - self.search_ent.focus_set() +class DocServer(BaseHTTPServer.HTTPServer): + def __init__(self, port, callback): + host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost' + self.address = ('', port) + self.url = 'http://%s:%d/' % (host, port) + self.callback = callback + self.base.__init__(self, self.address, self.handler) + self.quit = False + def serve_until_quit(self): + while not self.quit: + rd, wr, ex = select.select([self.socket.fileno()], [], [], 1) + if rd: + self.handle_request() + def server_activate(self): + self.base.server_activate(self) + if self.callback: + self.callback(self) - font = ('helvetica', sys.platform == 'win32' and 8 or 10) - self.result_lst = Tkinter.Listbox(window, font=font, height=6) - self.result_lst.bind('', self.select) - self.result_lst.bind('', self.goto) - self.result_scr = Tkinter.Scrollbar(window, - orient='vertical', command=self.result_lst.yview) - self.result_lst.config(yscrollcommand=self.result_scr.set) +class ServerThread(threading.Thread): + """ Use to start the server as a thread in an application. + """ + def __init__(self, urlhandler, port): + self.urlhandler = urlhandler + self.port = int(port) + threading.Thread.__init__(self) + self.serving = False + def run(self): + """ Start the server. + """ + DocServer.base = BaseHTTPServer.HTTPServer + DocServer.handler = DocHandler + DocHandler.MessageClass = Message + DocHandler.urlhandler = staticmethod(self.urlhandler) + dsvr = DocServer(self.port, self.ready) + self.docserver = dsvr + dsvr.serve_until_quit() + def ready(self, server): + self.serving = True + self.url = server.url + def stop(self): + """ Stop the server and this thread nicely + """ + self.docserver.quit = True + self.serving = False + self.url = None - self.result_frm = Tkinter.Frame(window) - self.goto_btn = Tkinter.Button(self.result_frm, - text='go to selected', command=self.goto) - self.hide_btn = Tkinter.Button(self.result_frm, - text='hide results', command=self.hide) - self.goto_btn.pack(side='left', fill='x', expand=1) - self.hide_btn.pack(side='right', fill='x', expand=1) +def startserver(urlhandler, port): + """ Start a http server thread on a specific port. - self.window.update() - self.minwidth = self.window.winfo_width() - self.minheight = self.window.winfo_height() - self.bigminheight = (self.server_frm.winfo_reqheight() + - self.search_frm.winfo_reqheight() + - self.result_lst.winfo_reqheight() + - self.result_frm.winfo_reqheight()) - self.bigwidth, self.bigheight = self.minwidth, self.bigminheight - self.expanded = 0 - self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) - self.window.wm_minsize(self.minwidth, self.minheight) - self.window.tk.willdispatch() + Use address http://localhost:/ + """ + thread = ServerThread(urlhandler, port) + thread.start() + # make sure we are really up before returning. + while not thread.serving: + time.sleep(.01) + return thread - import threading - threading.Thread( - target=serve, args=(port, self.ready, self.quit)).start() - def ready(self, server): - self.server = server - self.title_lbl.config( - text='Python documentation server at\n' + server.url) - self.open_btn.config(state='normal') - self.quit_btn.config(state='normal') +# ----------------------------------------------- Web Browser Interface - def open(self, event=None, url=None): - url = url or self.server.url - try: - import webbrowser - webbrowser.open(url) - except ImportError: # pre-webbrowser.py compatibility - if sys.platform == 'win32': - os.system('start "%s"' % url) - elif sys.platform == 'mac': - try: import ic - except ImportError: pass - else: ic.launchurl(url) - else: - rc = os.system('netscape -remote "openURL(%s)" &' % url) - if rc: os.system('netscape "%s" &' % url) +def html_navbar(): return \ +""" + + + + + +
Python %s
+ + +
+ + +
+ Index of Modules + : Topics + : Keywords +
+""" % sys.version - def quit(self, event=None): - if self.server: - self.server.quit = 1 - self.window.quit() - def search(self, event=None): - key = self.search_ent.get() - self.stop_btn.pack(side='right') - self.stop_btn.config(state='normal') - self.search_lbl.config(text='Searching for "%s"...' % key) - self.search_ent.forget() - self.search_lbl.pack(side='left') - self.result_lst.delete(0, 'end') - self.goto_btn.config(state='disabled') - self.expand() +def html_index(): + """ Index of modules web page. """ + def bltinlink(name): + return '%s' % (name, name) - import threading - if self.scanner: - self.scanner.quit = 1 - self.scanner = ModuleScanner() - threading.Thread(target=self.scanner.run, - args=(self.update, key, self.done)).start() + heading = html.heading( + 'Index of Modules', + '#ffffff', '#7799ee') + names = filter(lambda x: x != '__main__', + sys.builtin_module_names) + contents = html.multicolumn(names, bltinlink) + indices = ['

' + html.bigsection( + 'Built-in Modules', '#ffffff', '#ee77aa', contents)] + seen = {} + for dir in sys.path: + indices.append(html.index(dir, seen)) + contents = heading + join(indices) + \ +'''

+pydoc by Ka-Ping Yee <ping@lfw.org>''' + return html.page('Index of Modules' ,contents) - def update(self, path, modname, desc): - if modname[-9:] == '.__init__': - modname = modname[:-9] + ' (package)' - self.result_lst.insert('end', - modname + ' - ' + (desc or '(no description)')) - def stop(self, event=None): - if self.scanner: - self.scanner.quit = 1 - self.scanner = None +def html_search(key): + """ Search results page. """ + # scan for modules + search_result = [] + def callback(path, modname, desc): + if modname[-9:] == '.__init__': + modname = modname[:-9] + ' (package)' + search_result.append((modname, desc and '- ' + desc)) + try: import warnings + except ImportError: pass + else: warnings.filterwarnings('ignore') # ignore problems during import + ModuleScanner().run(callback, key) + # format page + def bltinlink(name): + return '%s' % (name, name) + results = [] + heading = html.heading( + 'Search Results', + '#ffffff', '#7799ee') + for name, desc in search_result: + results.append(bltinlink(name) + desc) + contents = heading + html.bigsection( + 'key = %s' % key, '#ffffff', '#ee77aa', '
'.join(results)) + return html.page('Search Results', contents) - def done(self): - self.scanner = None - self.search_lbl.config(text='Search for') - self.search_lbl.pack(side='left') - self.search_ent.pack(side='right', fill='x', expand=1) - if sys.platform != 'win32': self.stop_btn.forget() - self.stop_btn.config(state='disabled') - def select(self, event=None): - self.goto_btn.config(state='normal') +def html_getfile(path): + """ Get a source file listing safely. + """ + path = os.sep + path.replace('%20', ' ') + try: + f = open(path, 'r') + lines = html.escape(f.read()) + finally: + f.close() + body = '

%s
' % lines + heading = html.heading( + 'File Listing', + '#ffffff', '#7799ee') + contents = heading + html.bigsection( + 'File: %s' % path, '#ffffff', '#ee77aa', body) + return html.page('getfile: %s' % path, contents) - def goto(self, event=None): - selection = self.result_lst.curselection() - if selection: - modname = split(self.result_lst.get(selection[0]))[0] - self.open(url=self.server.url + modname + '.html') - def collapse(self): - if not self.expanded: return - self.result_frm.forget() - self.result_scr.forget() - self.result_lst.forget() - self.bigwidth = self.window.winfo_width() - self.bigheight = self.window.winfo_height() - self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) - self.window.wm_minsize(self.minwidth, self.minheight) - self.expanded = 0 +def html_topics(): + """ Index of topic texts available. + """ + def bltinlink(name): + return '%s' % (name, name) + heading = html.heading( + 'INDEX', + '#ffffff', '#7799ee') + names = sorted(Helper.topics.keys()) + def bltinlink(name): + return '%s' % (name, name) + contents = html.multicolumn(names, bltinlink) + contents = heading + html.bigsection( + 'Topics', '#ffffff', '#ee77aa', contents) + return html.page('Topics', contents) - def expand(self): - if self.expanded: return - self.result_frm.pack(side='bottom', fill='x') - self.result_scr.pack(side='right', fill='y') - self.result_lst.pack(side='top', fill='both', expand=1) - self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight)) - self.window.wm_minsize(self.minwidth, self.bigminheight) - self.expanded = 1 - def hide(self, event=None): - self.stop() - self.collapse() +def html_keywords(): + """ Index of keywords. + """ + heading = html.heading( + 'INDEX', + '#ffffff', '#7799ee') + names = sorted(Helper.keywords.keys()) + def bltinlink(name): + return '%s' % (name, name) + contents = html.multicolumn(names, bltinlink) + contents = heading + html.bigsection( + 'Keywords', '#ffffff', '#ee77aa', contents) + return html.page('Keywords', contents) - import Tkinter - try: - root = Tkinter.Tk() - # Tk will crash if pythonw.exe has an XP .manifest - # file and the root has is not destroyed explicitly. - # If the problem is ever fixed in Tk, the explicit - # destroy can go. + +def html_topicpage(topic): + import StringIO + buf = StringIO.StringIO() + htmlhelp = Helper(buf, buf) + htmlhelp.showtopic(topic) + if topic in htmlhelp.keywords: + title = 'KEYWORD' + else: + title = 'TOPIC' + contents = '
%s
' % buf.getvalue() + heading = html.heading( + '%s' % title, + '#ffffff', '#7799ee') + contents = heading + html.bigsection(topic , '#ffffff', + '#ee77aa', contents) + return html.page('%s: %s' % (title, topic), contents) + + +def html_error(url): + heading = html.heading( + 'Error', + '#ffffff', '#ee0000') + return heading + url + + +def get_html_page(url): + """ Function url handler uses to get the html page to get + depending on the url. + """ + if url[-5:] == '.html': url = url[:-5] + if url[:1] == '/': url = url[1:] + if url.startswith("get?key="): + url = url[8:] + title = url + contents = '' + if url in ("", ".", "index"): + contents = html_index() + elif url == "topics": + contents = html_topics() + elif url == "keywords": + contents = html_keywords() + elif url.startswith("search?key="): + contents = html_search(url[11:]) + elif url.startswith("getfile?key="): + url = url[12:] try: - gui = GUI(root) - root.mainloop() - finally: - root.destroy() - except KeyboardInterrupt: - pass + contents = html_getfile(url) + except IOError, value: + contents = html_error('could read file %s' % repr(url)) + else: + try: + obj = locate(url, forceload=1) + except ErrorDuringImport, value: + contents = html.escape(str(value)) + if obj: + title = describe(obj) + contents = html.document(obj, url) + elif url in Helper.keywords or url in Helper.topics: + contents = html_topicpage(url) + else: + contents = html_error('no Python documentation found for %s' + % repr(url)) + return html.page(title, html_navbar() + contents) + +def gui(port=7464, browse=True): + """ Start pydoc server and web browser. + """ + import webbrowser + + def url_handler(url, content_type): + """ html server html and stylesheet requests. + """ + if url.startswith('/'): + url = url[1:] + if content_type == 'text/css': + fp = open(os.path.join(path_here, url)) + css = ''.join(fp.readlines()) + fp.close() + return css + elif content_type == 'text/html': + return get_html_page(url) + return 'Error: uknown content type ' + content_type + + serverthread = startserver(url_handler, port) + print 'Server ready at:', serverthread.url + if browse: + webbrowser.open("http://localhost:%s" % port) + try: + while serverthread.serving: + time.sleep(.01) + finally: + if serverthread.serving: + serverthread.stop() + print 'Server stopped' + + # -------------------------------------------------- command-line interface def ispath(x): @@ -2222,15 +2288,7 @@ apropos(val) return if opt == '-p': - try: - port = int(val) - except ValueError: - raise BadUsage - def ready(server): - print 'pydoc server ready at %s' % server.url - def stopped(): - print 'pydoc server stopped' - serve(port, ready, stopped) + gui(port=val, browse=False) return if opt == '-w': writing = 1 @@ -2249,7 +2307,11 @@ else: writedoc(arg) else: + import StringIO + buf = StringIO.StringIO() + help = Helper(buf, buf) help.help(arg) + pager(buf.getvalue()) except ErrorDuringImport, value: print value @@ -2272,7 +2334,7 @@ Start an HTTP server on the given port on the local machine. %s -g - Pop up a graphical interface for finding and serving documentation. + Use a web browser for interactive browsing generated documentation. %s -w ... Write out the HTML documentation for a module to a file in the current