rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
stats = os.stat(localfile)
def open_local_file(self, req): host = req.get_host() file = req.get_selector() localfile = url2pathname(file) stats = os.stat(localfile) size = stats[stat.ST_SIZE] modified = rfc822.formatdate(stats[stat.ST_MTIME]) mtype = mimetypes.guess_type(file)[0] stats = os.stat(localfile) headers = mimetools.Message(StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if host: host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) raise URLError('file not on local host')
def index(dir): """Return a list of (module-name, synopsis) pairs for a directory tree.""" results = [] for entry in os.listdir(dir): path = os.path.join(dir, entry) if ispackage(path): results.extend(map( lambda (m, s), pkg=entry: (pkg + '.' + m, s), index(path))) elif os.path.isfile(path) and entry[-3:] == '.py': results.append((entry[:-3], synopsis(path))) return results
def index(dir): """Return a list of (module-name, synopsis) pairs for a directory tree.""" results = [] for entry in os.listdir(dir): path = os.path.join(dir, entry) if ispackage(path): results.extend(map( lambda (m, s), pkg=entry: (pkg + '.' + m, s), index(path))) elif os.path.isfile(path) and entry[-3:] == '.py': results.append((entry[:-3], synopsis(path))) return results
elif lower(filename[-4:]) == '.pyc':
elif lower(filename[-4:]) in ['.pyc', '.pyd', '.pyo']:
def modulename(path): """Return the Python module name for a given path, or None.""" filename = os.path.basename(path) if lower(filename[-3:]) == '.py': return filename[:-3] elif lower(filename[-4:]) == '.pyc': return filename[:-4] elif lower(filename[-11:]) == 'module.so': return filename[:-11] elif lower(filename[-13:]) == 'module.so.1': return filename[:-13]
if inspect.ismethod(object): return apply(self.docmethod, args) if inspect.isbuiltin(object): return apply(self.docbuiltin, args) if inspect.isfunction(object): return apply(self.docfunction, args)
if inspect.isroutine(object): return apply(self.docroutine, args)
def document(self, object, *args): """Generate documentation for an object.""" args = (object,) + args if inspect.ismodule(object): return apply(self.docmodule, args) if inspect.isclass(object): return apply(self.docclass, args) if inspect.ismethod(object): return apply(self.docmethod, args) if inspect.isbuiltin(object): return apply(self.docbuiltin, args) if inspect.isfunction(object): return apply(self.docfunction, args) raise TypeError, "don't know how to document objects of type " + \ type(object).__name__
<tr bgcolor="%s"><td colspan=3 valign=bottom><small><small><br></small></small ><font color="%s" face="helvetica, arial">&nbsp;%s</font></td
<tr bgcolor="%s"><td>&nbsp;</td> <td valign=bottom><small><small><br></small></small ><font color="%s" face="helvetica"><br>&nbsp;%s</font></td
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return """
><font color="%s" face="helvetica, arial">&nbsp;%s</font></td></tr></table> """ % (bgcol, fgcol, title, fgcol, extras)
><font color="%s" face="helvetica">%s</font></td><td>&nbsp;</td></tr></table> """ % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return """
<tr bgcolor="%s"><td colspan=3 valign=bottom><small><small><br></small></small
<tr bgcolor="%s"><td rowspan=2>&nbsp;</td> <td colspan=3 valign=bottom><small><small><br></small></small
def section(self, title, fgcol, bgcol, contents, width=20, prelude='', marginalia=None, gap='&nbsp;&nbsp;&nbsp;'): """Format a section with a heading.""" if marginalia is None: marginalia = '&nbsp;' * width result = """
def footer(self): return """ <table width="100%"><tr><td align=right> <font face="helvetica, arial"><small><small>generated with <strong>htmldoc</strong> by Ka-Ping Yee</a></small></small></font> </td></tr></table> """
def bigsection(self, title, *args): """Format a section with a big heading.""" title = '<big><strong>%s</strong></big>' % title return apply(self.section, (title,) + args)
result = '' head = '<br><big><big><strong>&nbsp;%s</strong></big></big>' % name
parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color=" (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ result = '' head = '<br><big><big><strong>&nbsp;%s</strong></big></big>' % name try: path = os.path.abspath(inspect.getfile(object)) filelink = '<a href="file:%s">%s</a>' % (path, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') result = result + self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
result = result + self.heading(
result = self.heading(
def docmodule(self, object): """Produce HTML documentation for a module object.""" name = object.__name__ result = '' head = '<br><big><big><strong>&nbsp;%s</strong></big></big>' % name try: path = os.path.abspath(inspect.getfile(object)) filelink = '<a href="file:%s">%s</a>' % (path, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') result = result + self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
if doc: doc = '<small><tt>' + doc + '<br>&nbsp;</tt></small>'
if doc: doc = '<small><tt>' + doc + '</tt></small>'
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
def docmethod(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a method object.""" return self.document( object.im_func, funcs, classes, methods, clname)
def docclass(self, object, funcs={}, classes={}): """Produce HTML documentation for a class object.""" name = object.__name__ bases = object.__bases__ contents = ''
def docfunction(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function object.""" args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if object.__name__ == '<lambda>': decl = '<em>lambda</em> ' + argspec[1:-1]
def docroutine(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function or method object.""" if inspect.ismethod(object): object = object.im_func if inspect.isbuiltin(object): decl = '<a name="%s"><strong>%s</strong>(...)</a>\n' % ( clname + '-' + object.__name__, object.__name__)
def docfunction(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function object.""" args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue)
anchor = clname + '-' + object.__name__ decl = '<a name="%s"\n><strong>%s</strong>%s</a>\n' % ( anchor, object.__name__, argspec)
args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if object.__name__ == '<lambda>': decl = '<em>lambda</em> ' + argspec[1:-1] else: anchor = clname + '-' + object.__name__ decl = '<a name="%s"\n><strong>%s</strong>%s</a>\n' % ( anchor, object.__name__, argspec)
def docfunction(self, object, funcs={}, classes={}, methods={}, clname=''): """Produce HTML documentation for a function object.""" args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue)
def docbuiltin(self, object, *extras): """Produce HTML documentation for a built-in function.""" return '<dl><dt><strong>%s</strong>(...)</dl>' % object.__name__
def docbuiltin(self, object, *extras): """Produce HTML documentation for a built-in function.""" return '<dl><dt><strong>%s</strong>(...)</dl>' % object.__name__
def docmethod(self, object): """Produce text documentation for a method object.""" return self.document(object.im_func)
def docmethod(self, object): """Produce text documentation for a method object.""" return self.document(object.im_func)
def docfunction(self, object): """Produce text documentation for a function object.""" try:
def docroutine(self, object): """Produce text documentation for a function or method object.""" if inspect.ismethod(object): object = object.im_func if inspect.isbuiltin(object): decl = self.bold(object.__name__) + '(...)' else:
def docfunction(self, object): """Produce text documentation for a function object.""" try: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) except TypeError: argspec = '(...)'
except TypeError: argspec = '(...)' if object.__name__ == '<lambda>': decl = '<lambda> ' + argspec[1:-1] else: decl = self.bold(object.__name__) + argspec
if object.__name__ == '<lambda>': decl = '<lambda> ' + argspec[1:-1] else: decl = self.bold(object.__name__) + argspec
def docfunction(self, object): """Produce text documentation for a function object.""" try: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) except TypeError: argspec = '(...)'
def docbuiltin(self, object): """Produce text documentation for a built-in function object.""" return (self.bold(object.__name__) + '(...)\n' + rstrip(self.indent(object.__doc__)) + '\n')
def docfunction(self, object): """Produce text documentation for a function object.""" try: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) except TypeError: argspec = '(...)'
if hasattr(__builtins__, path): return None, getattr(__builtins__, path)
def locate(path): """Locate an object by name (or dotted path), importing as necessary.""" if not path: # special case: imp.find_module('') strangely succeeds return None, None if type(path) is not types.StringType: return None, path if hasattr(__builtins__, path): return None, getattr(__builtins__, path) parts = split(path, '.') n = 1 while n <= len(parts): path = join(parts[:n], '.') try: module = __import__(path) module = reload(module) except: # Did the error occur before or after we found the module? if sys.modules.has_key(path): filename = sys.modules[path].__file__ elif sys.exc_type is SyntaxError: filename = sys.exc_value.filename else: # module not found, so stop looking break # error occurred in the imported module, so report it raise DocImportError(filename, sys.exc_type, sys.exc_value) try: x = module for p in parts[1:]: x = getattr(x, p) return join(parts[:-1], '.'), x except AttributeError: n = n + 1 continue return None, None
print 'problem in %s - %s' % (value.filename, value.args)
print 'Problem in %s - %s' % (value.filename, value.args)
def doc(thing): """Display documentation on an object (for interactive use).""" if type(thing) is type(""): try: path, x = locate(thing) except DocImportError, value: print 'problem in %s - %s' % (value.filename, value.args) return if x: thing = x else: print 'could not find or import %s' % repr(thing) return desc = describe(thing) module = inspect.getmodule(thing) if module and module is not thing: desc = desc + ' in module ' + module.__name__ pager('Help on %s:\n\n' % desc + text.document(thing))
print 'could not find or import %s' % repr(thing)
print 'No Python documentation found for %s.' % repr(thing)
def doc(thing): """Display documentation on an object (for interactive use).""" if type(thing) is type(""): try: path, x = locate(thing) except DocImportError, value: print 'problem in %s - %s' % (value.filename, value.args) return if x: thing = x else: print 'could not find or import %s' % repr(thing) return desc = describe(thing) module = inspect.getmodule(thing) if module and module is not thing: desc = desc + ' in module ' + module.__name__ pager('Help on %s:\n\n' % desc + text.document(thing))
def writedocs(path, pkgpath=''): if os.path.isdir(path): dir = path for file in os.listdir(dir): path = os.path.join(dir, file) if os.path.isdir(path): writedocs(path, file + '.' + pkgpath) if os.path.isfile(path): writedocs(path, pkgpath) if os.path.isfile(path): modname = modulename(path) if modname: writedoc(pkgpath + modname)
def doc(thing): """Display documentation on an object (for interactive use).""" if type(thing) is type(""): try: path, x = locate(thing) except DocImportError, value: print 'problem in %s - %s' % (value.filename, value.args) return if x: thing = x else: print 'could not find or import %s' % repr(thing) return desc = describe(thing) module = inspect.getmodule(thing) if module and module is not thing: desc = desc + ' in module ' + module.__name__ pager('Help on %s:\n\n' % desc + text.document(thing))
print 'could not find or import %s' % repr(key)
print 'No Python documentation found for %s.' % repr(key) class Scanner: """A generic tree iterator.""" def __init__(self, roots, children, recurse): self.roots = roots[:] self.state = [] self.children = children self.recurse = recurse def next(self): if not self.state: if not self.roots: return None root = self.roots.pop(0) self.state = [(root, self.children(root))] node, children = self.state[-1] if not children: self.state.pop() return self.next() child = children.pop(0) if self.recurse(child): self.state.append((child, self.children(child))) return child class ModuleScanner(Scanner): """An interruptible scanner that searches module synopses.""" def __init__(self): roots = map(lambda dir: (dir, ''), pathdirs()) Scanner.__init__(self, roots, self.submodules, self.ispackage) def submodules(self, (dir, package)): children = [] for file in os.listdir(dir): path = os.path.join(dir, file) if ispackage(path): children.append((path, package + (package and '.') + file)) else: children.append((path, package)) children.sort() return children def ispackage(self, (dir, package)): return ispackage(dir) def run(self, key, callback, completer=None): self.quit = 0 seen = {} for modname in sys.builtin_module_names: seen[modname] = 1 desc = split(__import__(modname).__doc__ or '', '\n')[0] if find(lower(modname + ' - ' + desc), lower(key)) >= 0: callback(None, modname, desc) while not self.quit: node = self.next() if not node: break path, package = node modname = modulename(path) if os.path.isfile(path) and modname: modname = package + (package and '.') + modname if not seen.has_key(modname): seen[modname] = 1 desc = synopsis(path) or '' if find(lower(modname + ' - ' + desc), lower(key)) >= 0: callback(path, modname, desc) if completer: completer()
def man(key): """Display documentation on an object in a form similar to man(1).""" path, object = locate(key) if object: title = 'Python Library Documentation: ' + describe(object) if path: title = title + ' in ' + path pager('\n' + title + '\n\n' + text.document(object)) found = 1 else: print 'could not find or import %s' % repr(key)
key = lower(key) for module in sys.builtin_module_names: desc = __import__(module).__doc__ or '' desc = split(desc, '\n')[0] if find(lower(module + ' ' + desc), key) >= 0: print module, '-', desc or '(no description)' modules = [] for dir in pathdirs(): for module, desc in index(dir): desc = desc or '' if module not in modules: modules.append(module) if find(lower(module + ' ' + desc), key) >= 0: desc = desc or '(no description)' if module[-9:] == '.__init__': print module[:-9], '(package) -', desc else: print module, '-', desc
def callback(path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' print modname, '-', desc or '(no description)' ModuleScanner().run(key, callback)
def apropos(key): """Print all the one-line module summaries that contain a substring.""" key = lower(key) for module in sys.builtin_module_names: desc = __import__(module).__doc__ or '' desc = split(desc, '\n')[0] if find(lower(module + ' ' + desc), key) >= 0: print module, '-', desc or '(no description)' modules = [] for dir in pathdirs(): for module, desc in index(dir): desc = desc or '' if module not in modules: modules.append(module) if find(lower(module + ' ' + desc), key) >= 0: desc = desc or '(no description)' if module[-9:] == '.__init__': print module[:-9], '(package) -', desc else: print module, '-', desc
def serve(address, callback=None): import BaseHTTPServer, mimetools
def serve(port, callback=None): import BaseHTTPServer, mimetools, select
def serve(address, callback=None): import BaseHTTPServer, mimetools # 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() class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler): def send_document(self, title, contents): self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(
self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write( '''<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><title>Python: %s</title><body bgcolor=" self.wfile.write(contents) self.wfile.write('</body></html>')
try: self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(''' <!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><title>Python: %s</title><body bgcolor=" %s </body></html>''' % (title, contents)) except IOError: pass
def send_document(self, title, contents): self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(
'problem with %s - %s' % (value.filename, value.args)))
'Problem in %s - %s' % (value.filename, value.args)))
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: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
'There is no Python module or object named "%s".' % path)
'No Python documentation found for %s.' % repr(path))
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: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
'<br><big><big><strong>&nbsp;' 'Python: Index of Modules' '</strong></big></big>', '
'<big><big><strong>Python: Index of Modules</strong></big></big>', '
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: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
self.send_document('Index of Modules', heading + join(indices))
contents = heading + join(indices) + """<p align=right> <small><small><font color=" pydoc</strong> by Ka-Ping Yee &lt;[email protected]&gt;</font></small></small>""" self.send_document('Index of Modules', contents)
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: p, x = locate(path) except DocImportError, value: self.send_document(path, html.escape( 'problem with %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
def __init__(self, address, callback):
def __init__(self, port, callback): self.address = ('127.0.0.1', port) self.url = 'http://127.0.0.1:%d/' % port
def __init__(self, address, callback): self.callback = callback self.base.__init__(self, address, self.handler)
self.base.__init__(self, address, self.handler)
self.base.__init__(self, self.address, self.handler) def serve_until_quit(self): import select self.quit = 0 while not self.quit: rd, wr, ex = select.select([self.socket.fileno()], [], [], 1) if rd: self.handle_request()
def __init__(self, address, callback): self.callback = callback self.base.__init__(self, address, self.handler)
if self.callback: self.callback()
if self.callback: self.callback(self)
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback()
DocServer(address, callback).serve_forever()
DocServer(port, callback).serve_until_quit() except (KeyboardInterrupt, select.error): pass print 'server stopped' 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 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') 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('<Return>', self.search) self.stop_btn = Tkinter.Button(self.search_frm, text='stop', pady=0, command=self.stop, state='disabled') if sys.platform == 'win32': self.stop_btn.pack(side='right') 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') 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() self.result_lst = Tkinter.Listbox(window, font=('helvetica', 8), height=6) self.result_lst.bind('<Button-1>', self.select) self.result_lst.bind('<Double-Button-1>', self.goto) self.result_scr = Tkinter.Scrollbar(window, orient='vertical', command=self.result_lst.yview) self.result_lst.config(yscrollcommand=self.result_scr.set) 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) 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) import threading threading.Thread(target=serve, args=(port, self.ready)).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') def open(self, event=None): import webbrowser webbrowser.open(self.server.url) 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() import threading if self.scanner: self.scanner.quit = 1 self.scanner = ModuleScanner() threading.Thread(target=self.scanner.run, args=(key, self.update, self.done)).start() 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 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 goto(self, event=None): selection = self.result_lst.curselection() if selection: import webbrowser modname = split(self.result_lst.get(selection[0]))[0] webbrowser.open(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 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() import Tkinter try: gui = GUI(Tkinter.Tk()) Tkinter.mainloop()
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback()
print 'server stopped'
pass
def server_activate(self): self.base.server_activate(self) if self.callback: self.callback()
opts, args = getopt.getopt(sys.argv[1:], 'k:p:w')
if sys.platform in ['mac', 'win', 'win32', 'nt'] and not sys.argv[1:]: gui() return opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
def cli(): import getopt class BadUsage: pass try: opts, args = getopt.getopt(sys.argv[1:], 'k:p:w') writing = 0 for opt, val in opts: if opt == '-k': apropos(lower(val)) break if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port serve(('127.0.0.1', port), ready) break if opt == '-w': if not args: raise BadUsage writing = 1 else: if args: for arg in args: try: if os.path.isfile(arg): arg = importfile(arg) if writing: if os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: man(arg) except DocImportError, value: print 'problem in %s - %s' % ( value.filename, value.args) else: if sys.platform in ['mac', 'win', 'win32', 'nt']: # GUI platforms with threading import threading ready = threading.Event() address = ('127.0.0.1', 12346) threading.Thread( target=serve, args=(address, ready.set)).start() ready.wait() import webbrowser webbrowser.open('http://127.0.0.1:12346/') else: raise BadUsage except (getopt.error, BadUsage): print """%s <name> ... Show documentation on something. <name> may be the name of a Python function, module, or package, or a dotted reference to a class or function within a module or module in a package, or the filename of a Python module to import.
apropos(lower(val)) break
apropos(val) return
def cli(): import getopt class BadUsage: pass try: opts, args = getopt.getopt(sys.argv[1:], 'k:p:w') writing = 0 for opt, val in opts: if opt == '-k': apropos(lower(val)) break if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port serve(('127.0.0.1', port), ready) break if opt == '-w': if not args: raise BadUsage writing = 1 else: if args: for arg in args: try: if os.path.isfile(arg): arg = importfile(arg) if writing: if os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: man(arg) except DocImportError, value: print 'problem in %s - %s' % ( value.filename, value.args) else: if sys.platform in ['mac', 'win', 'win32', 'nt']: # GUI platforms with threading import threading ready = threading.Event() address = ('127.0.0.1', 12346) threading.Thread( target=serve, args=(address, ready.set)).start() ready.wait() import webbrowser webbrowser.open('http://127.0.0.1:12346/') else: raise BadUsage except (getopt.error, BadUsage): print """%s <name> ... Show documentation on something. <name> may be the name of a Python function, module, or package, or a dotted reference to a class or function within a module or module in a package, or the filename of a Python module to import.
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port serve(('127.0.0.1', port), ready) break
def ready(server): print 'server ready at %s' % server.url serve(port, ready) return
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
if not args: raise BadUsage
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
else: if args: for arg in args: try: if os.path.isfile(arg): arg = importfile(arg) if writing: if os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: man(arg) except DocImportError, value: print 'problem in %s - %s' % ( value.filename, value.args) else: if sys.platform in ['mac', 'win', 'win32', 'nt']: import threading ready = threading.Event() address = ('127.0.0.1', 12346) threading.Thread( target=serve, args=(address, ready.set)).start() ready.wait() import webbrowser webbrowser.open('http://127.0.0.1:12346/') else: raise BadUsage
if not args: raise BadUsage for arg in args: try: if find(arg, os.sep) >= 0 and os.path.isfile(arg): arg = importfile(arg) if writing: writedoc(arg) else: man(arg) except DocImportError, value: print 'Problem in %s - %s' % (value.filename, value.args)
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
print """%s <name> ... Show documentation on something. <name> may be the name of a Python function, module, or package, or a dotted reference to a class or function within a module or module in a package, or the filename of a Python module to import.
cmd = sys.argv[0] print """pydoc - the Python documentation tool %s <name> ... Show text documentation on something. <name> may be the name of a function, module, or package, or a dotted reference to a class or function within a module or module in a package. If <name> contains a '%s', it is used as the path to a Python source file to document.
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
Search for a keyword in the synopsis lines of all modules.
Search for a keyword in the synopsis lines of all available modules.
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
%s -w <module> ... Write out the HTML documentation for a module to a file. %s -w <moduledir> Write out the HTML documentation for all modules in the tree under a given directory to files in the current directory. """ % ((sys.argv[0],) * 5) if __name__ == '__main__': cli()
%s -g Pop up a graphical interface for serving and finding documentation. %s -w <name> ... Write out the HTML documentation for a module to a file in the current directory. If <name> contains a '%s', it is treated as a filename. """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep) if __name__ == '__main__': cli()
def ready(port=port): print 'server ready at http://127.0.0.1:%d/' % port
sys.stderr.write("*** %s\n" % s)
ewrite("*** %s\n" % s)
def para_msg(s): sys.stderr.write("*** %s\n" % s)
def find_all_elements_from_set(doc, gi_set, nodes=None): if nodes is None: nodes = []
def find_all_child_elements(doc, gi): nodes = [] for child in doc.childNodes: if child.nodeType == ELEMENT: if child.tagName == gi: nodes.append(child) return nodes def find_all_elements_from_set(doc, gi_set): return __find_all_elements_from_set(doc, gi_set, []) def __find_all_elements_from_set(doc, gi_set, nodes):
def find_all_elements_from_set(doc, gi_set, nodes=None): if nodes is None: nodes = [] if doc.nodeType == ELEMENT and doc.tagName in gi_set: nodes.append(doc) for child in doc.childNodes: if child.nodeType == ELEMENT: find_all_elements_from_set(child, gi_set, nodes) return nodes
find_all_elements_from_set(child, gi_set, nodes)
__find_all_elements_from_set(child, gi_set, nodes)
def find_all_elements_from_set(doc, gi_set, nodes=None): if nodes is None: nodes = [] if doc.nodeType == ELEMENT and doc.tagName in gi_set: nodes.append(doc) for child in doc.childNodes: if child.nodeType == ELEMENT: find_all_elements_from_set(child, gi_set, nodes) return nodes
descriptor.setAttribute("index", "noindex")
descriptor.setAttribute("index", "no")
def rewrite_descriptor(doc, descriptor): # # Do these things: # 1. Add an "index=noindex" attribute to the element if the tagName # ends in 'ni', removing the 'ni' from the name. # 2. Create a <signature> from the name attribute and <args>. # 3. Create additional <signature>s from <*line{,ni}> elements, # if found. # 4. If a <versionadded> is found, move it to an attribute on the # descriptor. # 5. Move remaining child nodes to a <description> element. # 6. Put it back together. # descname = descriptor.tagName index = 1 if descname[-2:] == "ni": descname = descname[:-2] descriptor.setAttribute("index", "noindex") descriptor._node.name = descname index = 0 desctype = descname[:-4] # remove 'desc' linename = desctype + "line" if not index: linename = linename + "ni" # 2. signature = doc.createElement("signature") name = doc.createElement("name") signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(name) name.appendChild(doc.createTextNode(descriptor.getAttribute("name"))) descriptor.removeAttribute("name") if descriptor.attributes.has_key("var"): variable = descriptor.getAttribute("var") if variable: args = doc.createElement("args") args.appendChild(doc.createTextNode(variable)) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) descriptor.removeAttribute("var") newchildren = [signature] children = descriptor.childNodes pos = skip_leading_nodes(children, 0) if pos < len(children): child = children[pos] if child.nodeType == ELEMENT and child.tagName == "args": # create an <args> in <signature>: args = doc.createElement("args") argchildren = [] map(argchildren.append, child.childNodes) for n in argchildren: child.removeChild(n) args.appendChild(n) signature.appendChild(doc.createTextNode("\n ")) signature.appendChild(args) signature.appendChild(doc.createTextNode("\n ")) # 3, 4. pos = skip_leading_nodes(children, pos + 1) while pos < len(children) \ and children[pos].nodeType == ELEMENT \ and children[pos].tagName in (linename, "versionadded"): if children[pos].tagName == linename: # this is really a supplemental signature, create <signature> sig = methodline_to_signature(doc, children[pos]) newchildren.append(sig) else: # <versionadded added=...> descriptor.setAttribute( "added", children[pos].getAttribute("version")) pos = skip_leading_nodes(children, pos + 1) # 5. description = doc.createElement("description") description.appendChild(doc.createTextNode("\n")) newchildren.append(description) move_children(descriptor, description, pos) last = description.childNodes[-1] if last.nodeType == TEXT: last.data = string.rstrip(last.data) + "\n " # 6. # should have nothing but whitespace and signature lines in <descriptor>; # discard them while descriptor.childNodes: descriptor.removeChild(descriptor.childNodes[0]) for node in newchildren: descriptor.appendChild(doc.createTextNode("\n ")) descriptor.appendChild(node) descriptor.appendChild(doc.createTextNode("\n"))
sys.stderr.write( "module name in title doesn't match" " <declaremodule>; no <short-synopsis>\n")
ewrite("module name in title doesn't match" " <declaremodule/>; no <short-synopsis/>\n")
def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return node._node.name = "synopsis" lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: modauthor._node.name = "author" modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeType == ELEMENT \ and children[0].tagName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) title._node.name = "short-synopsis" if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: sys.stderr.write( "module name in title doesn't match" " <declaremodule>; no <short-synopsis>\n") else: sys.stderr.write( "Unexpected condition: <section> without <title>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated SGML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeType == ELEMENT \ and node.tagName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data)
sys.stderr.write( "Unexpected condition: <section> without <title>\n")
ewrite("Unexpected condition: <section/> without <title/>\n")
def create_module_info(doc, section): # Heavy. node = extract_first_element(section, "modulesynopsis") if node is None: return node._node.name = "synopsis" lastchild = node.childNodes[-1] if lastchild.nodeType == TEXT \ and lastchild.data[-1:] == ".": lastchild.data = lastchild.data[:-1] modauthor = extract_first_element(section, "moduleauthor") if modauthor: modauthor._node.name = "author" modauthor.appendChild(doc.createTextNode( modauthor.getAttribute("name"))) modauthor.removeAttribute("name") platform = extract_first_element(section, "platform") if section.tagName == "section": modinfo_pos = 2 modinfo = doc.createElement("moduleinfo") moddecl = extract_first_element(section, "declaremodule") name = None if moddecl: modinfo.appendChild(doc.createTextNode("\n ")) name = moddecl.attributes["name"].value namenode = doc.createElement("name") namenode.appendChild(doc.createTextNode(name)) modinfo.appendChild(namenode) type = moddecl.attributes.get("type") if type: type = type.value modinfo.appendChild(doc.createTextNode("\n ")) typenode = doc.createElement("type") typenode.appendChild(doc.createTextNode(type)) modinfo.appendChild(typenode) versionadded = extract_first_element(section, "versionadded") if versionadded: modinfo.setAttribute("added", versionadded.getAttribute("version")) title = get_first_element(section, "title") if title: children = title.childNodes if len(children) >= 2 \ and children[0].nodeType == ELEMENT \ and children[0].tagName == "module" \ and children[0].childNodes[0].data == name: # this is it; morph the <title> into <short-synopsis> first_data = children[1] if first_data.data[:4] == " ---": first_data.data = string.lstrip(first_data.data[4:]) title._node.name = "short-synopsis" if children[-1].nodeType == TEXT \ and children[-1].data[-1:] == ".": children[-1].data = children[-1].data[:-1] section.removeChild(title) section.removeChild(section.childNodes[0]) title.removeChild(children[0]) modinfo_pos = 0 else: sys.stderr.write( "module name in title doesn't match" " <declaremodule>; no <short-synopsis>\n") else: sys.stderr.write( "Unexpected condition: <section> without <title>\n") modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(node) if title and not contents_match(title, node): # The short synopsis is actually different, # and needs to be stored: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(title) if modauthor: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(modauthor) if platform: modinfo.appendChild(doc.createTextNode("\n ")) modinfo.appendChild(platform) modinfo.appendChild(doc.createTextNode("\n ")) section.insertBefore(modinfo, section.childNodes[modinfo_pos]) section.insertBefore(doc.createTextNode("\n "), modinfo) # # The rest of this removes extra newlines from where we cut out # a lot of elements. A lot of code for minimal value, but keeps # keeps the generated SGML from being too funny looking. # section.normalize() children = section.childNodes for i in range(len(children)): node = children[i] if node.nodeType == ELEMENT \ and node.tagName == "moduleinfo": nextnode = children[i+1] if nextnode.nodeType == TEXT: data = nextnode.data if len(string.lstrip(data)) < (len(data) - 4): nextnode.data = "\n\n\n" + string.lstrip(data)
def cleanup_synopses(doc): for node in find_all_elements(doc, "section"):
def cleanup_synopses(doc, fragment): for node in find_all_elements(fragment, "section"):
def cleanup_synopses(doc): for node in find_all_elements(doc, "section"): create_module_info(doc, node)
"moduleauthor",
"moduleauthor", "indexterm",
def move_elements_by_name(doc, source, dest, name, sep=None): nodes = [] for child in source.childNodes: if child.nodeType == ELEMENT and child.tagName == name: nodes.append(child) for node in nodes: source.removeChild(node) dest.appendChild(node) if sep: dest.appendChild(doc.createTextNode(sep))
parent.insertBefore(para, parent.childNodes[start])
nextnode = parent.childNodes[start] if nextnode.nodeType == TEXT: if nextnode.data and nextnode.data[0] != "\n": nextnode.data = "\n" + nextnode.data else: newnode = doc.createTextNode("\n") parent.insertBefore(newnode, nextnode) nextnode = newnode start = start + 1 parent.insertBefore(para, nextnode)
def build_para(doc, parent, start, i): children = parent.childNodes after = start + 1 have_last = 0 BREAK_ELEMENTS = PARA_LEVEL_ELEMENTS + RECURSE_INTO_PARA_CONTAINERS # Collect all children until \n\n+ is found in a text node or a # member of BREAK_ELEMENTS is found. for j in range(start, i): after = j + 1 child = children[j] nodeType = child.nodeType if nodeType == ELEMENT: if child.tagName in BREAK_ELEMENTS: after = j break elif nodeType == TEXT: pos = string.find(child.data, "\n\n") if pos == 0: after = j break if pos >= 1: child.splitText(pos) break else: have_last = 1 if (start + 1) > after: raise ConversionError( "build_para() could not identify content to turn into a paragraph") if children[after - 1].nodeType == TEXT: # we may need to split off trailing white space: child = children[after - 1] data = child.data if string.rstrip(data) != data: have_last = 0 child.splitText(len(string.rstrip(data))) para = doc.createElement(PARA_ELEMENT) prev = None indexes = range(start, after) indexes.reverse() for j in indexes: node = parent.childNodes[j] parent.removeChild(node) para.insertBefore(node, prev) prev = node if have_last: parent.appendChild(para) return len(parent.childNodes) else: parent.insertBefore(para, parent.childNodes[start]) return start + 1
sys.stderr.write("--- fixup_refmodindexes_chunk(%s)\n" % container)
bwrite("--- fixup_refmodindexes_chunk(%s)\n" % container)
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: sys.stderr.write("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_from_set(container, REFMODINDEX_ELEMENTS) removes = [] for entry in index_entries: children = entry.childNodes if len(children) != 0: sys.stderr.write( "--- unexpected number of children for %s node:\n" % entry.tagName) sys.stderr.write(entry.toxml() + "\n") continue found = 0 module_name = entry.getAttribute("name") for node in module_entries: if len(node.childNodes) != 1: continue this_name = node.childNodes[0].data if this_name == module_name: found = 1 node.setAttribute("index", "index") if found: removes.append(entry) for node in removes: container.removeChild(node)
sys.stderr.write( "--- unexpected number of children for %s node:\n" % entry.tagName) sys.stderr.write(entry.toxml() + "\n")
bwrite("--- unexpected number of children for %s node:\n" % entry.tagName) ewrite(entry.toxml() + "\n")
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: sys.stderr.write("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_from_set(container, REFMODINDEX_ELEMENTS) removes = [] for entry in index_entries: children = entry.childNodes if len(children) != 0: sys.stderr.write( "--- unexpected number of children for %s node:\n" % entry.tagName) sys.stderr.write(entry.toxml() + "\n") continue found = 0 module_name = entry.getAttribute("name") for node in module_entries: if len(node.childNodes) != 1: continue this_name = node.childNodes[0].data if this_name == module_name: found = 1 node.setAttribute("index", "index") if found: removes.append(entry) for node in removes: container.removeChild(node)
node.setAttribute("index", "index")
node.setAttribute("index", "yes")
def fixup_refmodindexes_chunk(container): # node is probably a <para>; let's see how often it isn't: if container.tagName != PARA_ELEMENT: sys.stderr.write("--- fixup_refmodindexes_chunk(%s)\n" % container) module_entries = find_all_elements(container, "module") if not module_entries: return index_entries = find_all_elements_from_set(container, REFMODINDEX_ELEMENTS) removes = [] for entry in index_entries: children = entry.childNodes if len(children) != 0: sys.stderr.write( "--- unexpected number of children for %s node:\n" % entry.tagName) sys.stderr.write(entry.toxml() + "\n") continue found = 0 module_name = entry.getAttribute("name") for node in module_entries: if len(node.childNodes) != 1: continue this_name = node.childNodes[0].data if this_name == module_name: found = 1 node.setAttribute("index", "index") if found: removes.append(entry) for node in removes: container.removeChild(node)
entries = find_all_elements(container, "bifuncindex") function_entries = find_all_elements(container, "function")
entries = find_all_child_elements(container, "bifuncindex") function_entries = find_all_child_elements(container, "function")
def fixup_bifuncindexes_chunk(container): removes = [] entries = find_all_elements(container, "bifuncindex") function_entries = find_all_elements(container, "function") for entry in entries: function_name = entry.getAttribute("name") found = 0 for func_entry in function_entries: t2 = func_entry.childNodes[0].data if t2[-2:] != "()": continue t2 = t2[:-2] if t2 == function_name: func_entry.setAttribute("index", "index") func_entry.setAttribute("module", "__builtin__") if not found: removes.append(entry) found = 1 for entry in removes: container.removeChild(entry)
func_entry.setAttribute("index", "index")
func_entry.setAttribute("index", "yes")
def fixup_bifuncindexes_chunk(container): removes = [] entries = find_all_elements(container, "bifuncindex") function_entries = find_all_elements(container, "function") for entry in entries: function_name = entry.getAttribute("name") found = 0 for func_entry in function_entries: t2 = func_entry.childNodes[0].data if t2[-2:] != "()": continue t2 = t2[:-2] if t2 == function_name: func_entry.setAttribute("index", "index") func_entry.setAttribute("module", "__builtin__") if not found: removes.append(entry) found = 1 for entry in removes: container.removeChild(entry)
found = 1
def fixup_bifuncindexes_chunk(container): removes = [] entries = find_all_elements(container, "bifuncindex") function_entries = find_all_elements(container, "function") for entry in entries: function_name = entry.getAttribute("name") found = 0 for func_entry in function_entries: t2 = func_entry.childNodes[0].data if t2[-2:] != "()": continue t2 = t2[:-2] if t2 == function_name: func_entry.setAttribute("index", "index") func_entry.setAttribute("module", "__builtin__") if not found: removes.append(entry) found = 1 for entry in removes: container.removeChild(entry)
cleanup_trailing_parens(doc, ["function", "method", "cfunction"]) cleanup_synopses(doc)
cleanup_trailing_parens(fragment, ["function", "method", "cfunction"]) cleanup_synopses(doc, fragment)
def convert(ifp, ofp): p = esistools.ExtendedEsisBuilder() p.feed(ifp.read()) doc = p.document fragment = p.fragment normalize(fragment) simplify(doc, fragment) handle_labels(doc, fragment) handle_appendix(doc, fragment) fixup_trailing_whitespace(doc, { "abstract": "\n", "title": "", "chapter": "\n\n", "section": "\n\n", "subsection": "\n\n", "subsubsection": "\n\n", "paragraph": "\n\n", "subparagraph": "\n\n", }) cleanup_root_text(doc) cleanup_trailing_parens(doc, ["function", "method", "cfunction"]) cleanup_synopses(doc) fixup_descriptors(doc, fragment) fixup_verbatims(fragment) normalize(fragment) fixup_paras(doc, fragment) fixup_sectionauthors(doc, fragment) remap_element_names(fragment, { "tableii": ("table", {"cols": "2"}), "tableiii": ("table", {"cols": "3"}), "tableiv": ("table", {"cols": "4"}), "lineii": ("row", {}), "lineiii": ("row", {}), "lineiv": ("row", {}), "refmodule": ("module", {"link": "link"}), }) fixup_table_structures(doc, fragment) fixup_rfc_references(doc, fragment) fixup_signatures(doc, fragment) add_node_ids(fragment) fixup_refmodindexes(fragment) fixup_bifuncindexes(fragment) # d = {} for gi in p.get_empties(): d[gi] = gi if d.has_key("rfc"): del d["rfc"] knownempty = d.has_key # try: write_esis(fragment, ofp, knownempty) except IOError, (err, msg): # Ignore EPIPE; it just means that whoever we're writing to stopped # reading. The rest of the output would be ignored. All other errors # should still be reported, if err != errno.EPIPE: raise
self.check_extension_list()
def get_source_files (self):
if len (words) != 2:
if len (words) < 2:
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
"'%s' expects a single <pattern>" %
"'%s' expects <pattern1> <pattern2> ..." %
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
pattern = native_path (words[1])
pattern_list = map(native_path, words[1:])
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
if len (words) != 3:
if len (words) < 3:
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
"'%s' expects <dir> <pattern>" %
"'%s' expects <dir> <pattern1> <pattern2> ..." %
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
(dir, pattern) = map (native_path, words[1:3])
dir = native_path(words[1]) pattern_list = map (native_path, words[2:])
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
print "include", pattern files = select_pattern (all_files, pattern, anchor=1) if not files: template.warn ("no files found matching '%s'" % pattern) else: self.files.extend (files)
print "include", string.join(pattern_list) for pattern in pattern_list: files = select_pattern (all_files, pattern, anchor=1) if not files: template.warn ("no files found matching '%s'" % pattern) else: self.files.extend (files)
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
print "exclude", pattern num = exclude_pattern (self.files, pattern, anchor=1) if num == 0: template.warn \ ("no previously-included files found matching '%s'" % pattern)
print "exclude", string.join(pattern_list) for pattern in pattern_list: num = exclude_pattern (self.files, pattern, anchor=1) if num == 0: template.warn ( "no previously-included files found matching '%s'"% pattern)
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
print "global-include", pattern files = select_pattern (all_files, pattern, anchor=0) if not files: template.warn (("no files found matching '%s' " + "anywhere in distribution") % pattern) else: self.files.extend (files)
print "global-include", string.join(pattern_list) for pattern in pattern_list: files = select_pattern (all_files, pattern, anchor=0) if not files: template.warn (("no files found matching '%s' " + "anywhere in distribution") % pattern) else: self.files.extend (files)
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
print "global-exclude", pattern num = exclude_pattern (self.files, pattern, anchor=0) if num == 0: template.warn \ (("no previously-included files matching '%s' " + "found anywhere in distribution") % pattern)
print "global-exclude", string.join(pattern_list) for pattern in pattern_list: num = exclude_pattern (self.files, pattern, anchor=0) if num == 0: template.warn \ (("no previously-included files matching '%s' " + "found anywhere in distribution") % pattern)
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
print "recursive-include", dir, pattern files = select_pattern (all_files, pattern, prefix=dir) if not files: template.warn (("no files found matching '%s' " + "under directory '%s'") % (pattern, dir)) else: self.files.extend (files)
print "recursive-include", dir, string.join(pattern_list) for pattern in pattern_list: files = select_pattern (all_files, pattern, prefix=dir) if not files: template.warn (("no files found matching '%s' " + "under directory '%s'") % (pattern, dir)) else: self.files.extend (files)
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
print "recursive-exclude", dir, pattern num = exclude_pattern (self.files, pattern, prefix=dir) if num == 0: template.warn \ (("no previously-included files matching '%s' " + "found under directory '%s'") % (pattern, dir))
print "recursive-exclude", dir, string.join(pattern_list) for pattern in pattern_list: num = exclude_pattern (self.files, pattern, prefix=dir) if num == 0: template.warn \ (("no previously-included files matching '%s' " + "found under directory '%s'") % (pattern, dir))
def read_template (self): """Read and parse the manifest template file named by 'self.template' (usually "MANIFEST.in"). Process all file specifications (include and exclude) in the manifest template and add the resulting filenames to 'self.files'."""
file(foo_path, 'w').close() file(bar_path, 'w').close()
f = open(foo_path, 'w') f.write("@") f.close() f = open(bar_path, 'w') f.write("@") f.close()
def test_clean(self): # Remove old files from 'tmp' foo_path = os.path.join(self._path, 'tmp', 'foo') bar_path = os.path.join(self._path, 'tmp', 'bar') file(foo_path, 'w').close() file(bar_path, 'w').close() self._box.clean() self.assert_(os.path.exists(foo_path)) self.assert_(os.path.exists(bar_path)) foo_stat = os.stat(foo_path) os.utime(os.path.join(foo_path), (time.time() - 129600 - 2, foo_stat.st_mtime)) self._box.clean() self.assert_(not os.path.exists(foo_path)) self.assert_(os.path.exists(bar_path))
os.utime(os.path.join(foo_path), (time.time() - 129600 - 2, foo_stat.st_mtime))
os.utime(foo_path, (time.time() - 129600 - 2, foo_stat.st_mtime))
def test_clean(self): # Remove old files from 'tmp' foo_path = os.path.join(self._path, 'tmp', 'foo') bar_path = os.path.join(self._path, 'tmp', 'bar') file(foo_path, 'w').close() file(bar_path, 'w').close() self._box.clean() self.assert_(os.path.exists(foo_path)) self.assert_(os.path.exists(bar_path)) foo_stat = os.stat(foo_path) os.utime(os.path.join(foo_path), (time.time() - 129600 - 2, foo_stat.st_mtime)) self._box.clean() self.assert_(not os.path.exists(foo_path)) self.assert_(os.path.exists(bar_path))
st = os.lstat(name)
try: st = os.lstat(name) except os.error: continue
def walk(top, func, arg): """walk(top,func,arg) calls func(arg, d, files) for each directory "d" in the tree rooted at "top" (including "top" itself). "files" is a list of all the files and subdirs in directory "d". """ try: names = os.listdir(top) except os.error: return func(arg, top, names) for name in names: name = join(top, name) st = os.lstat(name) if stat.S_ISDIR(st[stat.ST_MODE]): walk(name, func, arg)
s = "Module(%r" % % (self.__name__,)
s = "Module(%r" % (self.__name__,)
def __repr__(self): s = "Module(%r" % % (self.__name__,) if self.__file__ is not None: s = s + ", %r" % (self.__file__,) if self.__path__ is not None: s = s + ", %r" % (self.__path__,) s = s + ")" return s
(run, run == 1 and "" or "s", timeTaken))
(run, run != 1 and "s" or "", timeTaken))
def run(self, test): "Run the given test case or test suite." result = self._makeResult() startTime = time.time() test(result) stopTime = time.time() timeTaken = float(stopTime - startTime) result.printErrors() self.stream.writeln(result.separator2) run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % (run, run == 1 and "" or "s", timeTaken)) self.stream.writeln() if not result.wasSuccessful(): self.stream.write("FAILED (") failed, errored = map(len, (result.failures, result.errors)) if failed: self.stream.write("failures=%d" % failed) if errored: if failed: self.stream.write(", ") self.stream.write("errors=%d" % errored) self.stream.writeln(")") else: self.stream.writeln("OK") return result
def IN_CLASSA(a): return ((((in_addr_t)(a)) & 0x80000000) == 0) IN_CLASSA_NET = 0xff000000
def IN_CLASSA(a): return ((((in_addr_t)(a)) & (-2147483648)) == 0) IN_CLASSA_NET = (-16777216)
def IN_CLASSA(a): return ((((in_addr_t)(a)) & 0x80000000) == 0)
IN_CLASSA_HOST = (0xffffffff & ~IN_CLASSA_NET)
IN_CLASSA_HOST = ((-1) & ~IN_CLASSA_NET)
def IN_CLASSA(a): return ((((in_addr_t)(a)) & 0x80000000) == 0)
def IN_CLASSB(a): return ((((in_addr_t)(a)) & 0xc0000000) == 0x80000000) IN_CLASSB_NET = 0xffff0000
def IN_CLASSB(a): return ((((in_addr_t)(a)) & (-1073741824)) == (-2147483648)) IN_CLASSB_NET = (-65536)
def IN_CLASSB(a): return ((((in_addr_t)(a)) & 0xc0000000) == 0x80000000)
IN_CLASSB_HOST = (0xffffffff & ~IN_CLASSB_NET)
IN_CLASSB_HOST = ((-1) & ~IN_CLASSB_NET)
def IN_CLASSB(a): return ((((in_addr_t)(a)) & 0xc0000000) == 0x80000000)
def IN_CLASSC(a): return ((((in_addr_t)(a)) & 0xe0000000) == 0xc0000000) IN_CLASSC_NET = 0xffffff00
def IN_CLASSC(a): return ((((in_addr_t)(a)) & (-536870912)) == (-1073741824)) IN_CLASSC_NET = (-256)
def IN_CLASSC(a): return ((((in_addr_t)(a)) & 0xe0000000) == 0xc0000000)
IN_CLASSC_HOST = (0xffffffff & ~IN_CLASSC_NET) def IN_CLASSD(a): return ((((in_addr_t)(a)) & 0xf0000000) == 0xe0000000)
IN_CLASSC_HOST = ((-1) & ~IN_CLASSC_NET) def IN_CLASSD(a): return ((((in_addr_t)(a)) & (-268435456)) == (-536870912))
def IN_CLASSC(a): return ((((in_addr_t)(a)) & 0xe0000000) == 0xc0000000)
def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & 0xe0000000) == 0xe0000000) def IN_BADCLASS(a): return ((((in_addr_t)(a)) & 0xf0000000) == 0xf0000000)
def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & (-536870912)) == (-536870912)) def IN_BADCLASS(a): return ((((in_addr_t)(a)) & (-268435456)) == (-268435456))
def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & 0xe0000000) == 0xe0000000)
PATH_MAX = 4095
PATH_MAX = 4096
def IN_BADCLASS(a): return ((((in_addr_t)(a)) & 0xf0000000) == 0xf0000000)
SSIZE_MAX = INT_MAX
SSIZE_MAX = LONG_MAX
def IN_BADCLASS(a): return ((((in_addr_t)(a)) & 0xf0000000) == 0xf0000000)
FILENAME_MAX = 4095
FILENAME_MAX = 4096
def IN_BADCLASS(a): return ((((in_addr_t)(a)) & 0xf0000000) == 0xf0000000)
fp = open(pathname)
fp = open(pathname, "U")
def run_script(self, pathname): self.msg(2, "run_script", pathname) fp = open(pathname) stuff = ("", "r", imp.PY_SOURCE) self.load_module('__main__', fp, pathname, stuff)
fp = open(pathname)
fp = open(pathname, "U")
def load_file(self, pathname): dir, name = os.path.split(pathname) name, ext = os.path.splitext(name) fp = open(pathname) stuff = (ext, "r", imp.PY_SOURCE) self.load_module(name, fp, pathname, stuff)
args['linker_so'] = linker_so + ' -shared'
if platform == 'darwin1': args['linker_so'] = linker_so else: args['linker_so'] = linker_so + ' -shared'
def build_extensions(self):
self.read_multi()
self.read_multi(environ, keep_blank_values, strict_parsing)
def __init__(self, fp=None, headers=None, outerboundary="", environ=os.environ, keep_blank_values=0, strict_parsing=0): """Constructor. Read multipart/* until last part.
def read_multi(self):
def read_multi(self, environ, keep_blank_values, strict_parsing):
def read_multi(self): """Internal: read a part that is itself multipart.""" self.list = [] part = self.__class__(self.fp, {}, self.innerboundary) # Throw first part away while not part.done: headers = rfc822.Message(self.fp) part = self.__class__(self.fp, headers, self.innerboundary) self.list.append(part) self.skip_lines()
part = self.__class__(self.fp, {}, self.innerboundary)
part = self.__class__(self.fp, {}, self.innerboundary, environ, keep_blank_values, strict_parsing)
def read_multi(self): """Internal: read a part that is itself multipart.""" self.list = [] part = self.__class__(self.fp, {}, self.innerboundary) # Throw first part away while not part.done: headers = rfc822.Message(self.fp) part = self.__class__(self.fp, headers, self.innerboundary) self.list.append(part) self.skip_lines()
part = self.__class__(self.fp, headers, self.innerboundary)
part = self.__class__(self.fp, headers, self.innerboundary, environ, keep_blank_values, strict_parsing)
def read_multi(self): """Internal: read a part that is itself multipart.""" self.list = [] part = self.__class__(self.fp, {}, self.innerboundary) # Throw first part away while not part.done: headers = rfc822.Message(self.fp) part = self.__class__(self.fp, headers, self.innerboundary) self.list.append(part) self.skip_lines()
tests = [ GeneralModuleTests, BasicTCPTest ]
tests = [GeneralModuleTests, BasicTCPTest, TCPTimeoutTest, TestExceptions]
def test_main(): tests = [ GeneralModuleTests, BasicTCPTest ] if sys.platform != 'mac': tests.append(BasicUDPTest) tests.extend([ NonBlockingTCPTests, FileObjectClassTestCase, UnbufferedFileObjectClassTestCase, LineBufferedFileObjectClassTestCase, SmallBufferedFileObjectClassTestCase ]) test_support.run_unittest(*tests)
tests.append(BasicUDPTest)
tests.extend([ BasicUDPTest, UDPTimeoutTest ])
def test_main(): tests = [ GeneralModuleTests, BasicTCPTest ] if sys.platform != 'mac': tests.append(BasicUDPTest) tests.extend([ NonBlockingTCPTests, FileObjectClassTestCase, UnbufferedFileObjectClassTestCase, LineBufferedFileObjectClassTestCase, SmallBufferedFileObjectClassTestCase ]) test_support.run_unittest(*tests)
user_pass = base64.encodestring(unquote(user_pass)).strip() req.add_header('Proxy-Authorization', 'Basic '+user_pass)
if ':' in user_pass: user, password = user_pass.split(':', 1) user_pass = base64.encodestring('%s:%s' % (unquote(user), unquote(password))) req.add_header('Proxy-Authorization', 'Basic ' + user_pass)
def proxy_open(self, req, proxy, type): orig_type = req.get_type() type, r_type = splittype(proxy) host, XXX = splithost(r_type) if '@' in host: user_pass, host = host.split('@', 1) user_pass = base64.encodestring(unquote(user_pass)).strip() req.add_header('Proxy-Authorization', 'Basic '+user_pass) host = unquote(host) req.set_proxy(host, type) if orig_type == type: # let other handlers take care of it # XXX this only makes sense if the proxy is before the # other handlers return None else: # need to start over, because the other handlers don't # grok the proxy's URL type return self.parent.open(req)
h.putheader('Host', host)
scheme, sel = splittype(req.get_selector()) sel_host, sel_path = splithost(sel) h.putheader('Host', sel_host or host)
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
print "open", askopenfilename(filetypes=[("all filez", "*")]).encode(enc)
print "open", askopenfilename(filetypes=[("all files", "*")]).encode(enc)
def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show()