rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
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) doc = self.markup(getdoc(object), self.preformat, funcs, classes, methods)
if realname == '<lambda>': decl = '<em>lambda</em>' argspec = argspec[1:-1] decl = title + argspec + note doc = self.markup( getdoc(object), self.preformat, funcs, classes, methods)
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__) else: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue)
return '<dl><dt>%s<dd><small>%s</small></dl>' % (decl, doc) def page(self, object): """Produce a complete HTML page of documentation for an object.""" return ''' <!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><title>Python: %s</title><body bgcolor=" %s </body></html> ''' % (describe(object), self.document(object))
return '<dl><dt>%s<dd>%s</dl>' % (decl, self.small(doc)) def docother(self, object, name=None): """Produce HTML documentation for a data object.""" return '<strong>%s</strong> = %s' % (name, self.repr(object))
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__) else: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue)
def doctree(self, tree, modname, parent=None, prefix=''):
def formattree(self, tree, modname, parent=None, prefix=''):
def doctree(self, tree, modname, parent=None, prefix=''): """Render in text a class tree as returned by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): cl, bases = entry result = result + prefix + classname(cl, modname) if bases and bases != (parent,): parents = map(lambda cl, m=modname: classname(cl, m), bases) result = result + '(%s)' % join(parents, ', ') result = result + '\n' elif type(entry) is type([]): result = result + self.doctree( entry, modname, cl, prefix + ' ') return result
cl, bases = entry result = result + prefix + classname(cl, modname)
c, bases = entry result = result + prefix + classname(c, modname)
def doctree(self, tree, modname, parent=None, prefix=''): """Render in text a class tree as returned by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): cl, bases = entry result = result + prefix + classname(cl, modname) if bases and bases != (parent,): parents = map(lambda cl, m=modname: classname(cl, m), bases) result = result + '(%s)' % join(parents, ', ') result = result + '\n' elif type(entry) is type([]): result = result + self.doctree( entry, modname, cl, prefix + ' ') return result
parents = map(lambda cl, m=modname: classname(cl, m), bases)
parents = map(lambda c, m=modname: classname(c, m), bases)
def doctree(self, tree, modname, parent=None, prefix=''): """Render in text a class tree as returned by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): cl, bases = entry result = result + prefix + classname(cl, modname) if bases and bases != (parent,): parents = map(lambda cl, m=modname: classname(cl, m), bases) result = result + '(%s)' % join(parents, ', ') result = result + '\n' elif type(entry) is type([]): result = result + self.doctree( entry, modname, cl, prefix + ' ') return result
result = result + self.doctree( entry, modname, cl, prefix + ' ')
result = result + self.formattree( entry, modname, c, prefix + ' ')
def doctree(self, tree, modname, parent=None, prefix=''): """Render in text a class tree as returned by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): cl, bases = entry result = result + prefix + classname(cl, modname) if bases and bases != (parent,): parents = map(lambda cl, m=modname: classname(cl, m), bases) result = result + '(%s)' % join(parents, ', ') result = result + '\n' elif type(entry) is type([]): result = result + self.doctree( entry, modname, cl, prefix + ' ') return result
def docmodule(self, object):
def docmodule(self, object, name=None):
def docmodule(self, object): """Produce text documentation for a given module object.""" result = ''
result = '' name = object.__name__
name = object.__name__
def docmodule(self, object): """Produce text documentation for a given module object.""" result = ''
result = result + self.section('NAME', name) try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)'
result = self.section('NAME', name) try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)'
def docmodule(self, object): """Produce text documentation for a given module object.""" result = ''
classes.append(value)
classes.append((key, value))
def docmodule(self, object): """Produce text documentation for a given module object.""" result = ''
funcs.append(value)
funcs.append((key, value))
def docmodule(self, object): """Produce text documentation for a given module object.""" result = ''
contents = self.doctree( inspect.getclasstree(classes, 1), object.__name__) + '\n' for item in classes: contents = contents + self.document(item) + '\n' result = result + self.section('CLASSES', contents)
classlist = map(lambda (key, value): value, classes) contents = [self.formattree( inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key)) result = result + self.section('CLASSES', join(contents, '\n'))
def docmodule(self, object): """Produce text documentation for a given module object.""" result = ''
contents = '' for item in funcs: contents = contents + self.document(item) + '\n' result = result + self.section('FUNCTIONS', contents)
contents = [] for key, value in funcs: contents.append(self.document(value, key)) result = result + self.section('FUNCTIONS', join(contents, '\n'))
def docmodule(self, object): """Produce text documentation for a given module object.""" result = ''
contents = ''
contents = []
def docmodule(self, object): """Produce text documentation for a given module object.""" result = ''
line = key + ' = ' + self.repr(value) chop = 70 - len(line) line = self.bold(key) + ' = ' + self.repr(value) if chop < 0: line = line[:chop] + '...' contents = contents + line + '\n' result = result + self.section('CONSTANTS', contents)
contents.append(self.docother(value, key, 70)) result = result + self.section('CONSTANTS', join(contents, '\n'))
def docmodule(self, object): """Produce text documentation for a given module object.""" result = ''
def docclass(self, object):
def docclass(self, object, name=None):
def docclass(self, object): """Produce text documentation for a given class object.""" name = object.__name__ bases = object.__bases__
name = object.__name__
realname = object.__name__ name = name or realname
def docclass(self, object): """Produce text documentation for a given class object.""" name = object.__name__ bases = object.__bases__
title = 'class ' + self.bold(name)
if name == realname: title = 'class ' + self.bold(realname) else: title = self.bold(name) + ' = class ' + realname
def docclass(self, object): """Produce text documentation for a given class object.""" name = object.__name__ bases = object.__bases__
methods = map(lambda (key, value): value, inspect.getmembers(object, inspect.ismethod)) for item in methods: contents = contents + '\n' + self.document(item)
for key, value in inspect.getmembers(object, inspect.ismethod): contents = contents + '\n' + self.document(value, key, name)
def docclass(self, object): """Produce text documentation for a given class object.""" name = object.__name__ bases = object.__bases__
def docroutine(self, object):
def docroutine(self, object, name=None, clname=None):
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: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if object.__name__ == '<lambda>': decl = '<lambda> ' + argspec[1:-1] else: decl = self.bold(object.__name__) + argspec doc = getdoc(object) if doc: return decl + '\n' + rstrip(self.indent(doc)) + '\n' else: return decl + '\n'
if inspect.ismethod(object): object = object.im_func
realname = object.__name__ name = name or realname note = '' if inspect.ismethod(object): if not clname: if object.im_self: note = ' method of %s' % self.repr(object.im_self) else: note = ' unbound %s method' % object.im_class.__name__ object = object.im_func if name == realname: title = self.bold(realname) else: title = self.bold(name) + ' = ' + realname
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: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if object.__name__ == '<lambda>': decl = '<lambda> ' + argspec[1:-1] else: decl = self.bold(object.__name__) + argspec doc = getdoc(object) if doc: return decl + '\n' + rstrip(self.indent(doc)) + '\n' else: return decl + '\n'
decl = self.bold(object.__name__) + '(...)'
argspec = '(...)'
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: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if object.__name__ == '<lambda>': decl = '<lambda> ' + argspec[1:-1] else: decl = self.bold(object.__name__) + argspec doc = getdoc(object) if doc: return decl + '\n' + rstrip(self.indent(doc)) + '\n' else: return decl + '\n'
if object.__name__ == '<lambda>': decl = '<lambda> ' + argspec[1:-1] else: decl = self.bold(object.__name__) + argspec
if realname == '<lambda>': title = 'lambda' argspec = argspec[1:-1] decl = title + argspec + note
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: args, varargs, varkw, defaults = inspect.getargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=self.formatvalue) if object.__name__ == '<lambda>': decl = '<lambda> ' + argspec[1:-1] else: decl = self.bold(object.__name__) + argspec doc = getdoc(object) if doc: return decl + '\n' + rstrip(self.indent(doc)) + '\n' else: return decl + '\n'
return repr(thing)
if type(thing) is types.InstanceType: return 'instance of ' + thing.__class__.__name__ return type(thing).__name__ def freshimp(path, cache={}): """Import a module, reloading it if the source file has changed.""" module = __import__(path) if hasattr(module, '__file__'): file = module.__file__ info = (file, os.path.getmtime(file), os.path.getsize(file)) if cache.has_key(path): if cache[path] != info: module = reload(module) cache[path] = info return module
def describe(thing): """Produce a short description of the given kind of thing.""" if inspect.ismodule(thing): if thing.__name__ in sys.builtin_module_names: return 'built-in module ' + thing.__name__ if hasattr(thing, '__path__'): return 'package ' + thing.__name__ else: return 'module ' + thing.__name__ if inspect.isbuiltin(thing): return 'built-in function ' + thing.__name__ if inspect.isclass(thing): return 'class ' + thing.__name__ if inspect.isfunction(thing): return 'function ' + thing.__name__ if inspect.ismethod(thing): return 'method ' + thing.__name__ return repr(thing)
module = __import__(path) module = reload(module)
module = freshimp(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 parts = split(path, '.') n = 1 while n <= len(parts): path = join(parts[:n], '.') try: module = __import__(path) module = reload(module) except: # determine if error occurred before or after module was found 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 if hasattr(__builtins__, path): return None, getattr(__builtins__, path) return None, None
raise DocImportError(filename, sys.exc_type, sys.exc_value)
raise DocImportError(filename, sys.exc_info())
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 parts = split(path, '.') n = 1 while n <= len(parts): path = join(parts[:n], '.') try: module = __import__(path) module = reload(module) except: # determine if error occurred before or after module was found 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 if hasattr(__builtins__, path): return None, getattr(__builtins__, path) return None, None
print 'Problem in %s - %s' % (value.filename, value.args)
print value
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 'No Python documentation found for %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 'No Python documentation found for %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 'No Python documentation found for %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))
path, object = locate(key) if object: file = open(key + '.html', 'w') file.write(html.page(object)) file.close() print 'wrote', key + '.html'
try: path, object = locate(key) except DocImportError, value: print value else: if object: page = html.page('Python: ' + describe(object), html.document(object, object.__name__)) file = open(key + '.html', 'w') file.write(page) file.close() print 'wrote', key + '.html' else: print 'no Python documentation found for %s' % repr(key) def writedocs(dir, pkgpath='', done={}): """Write out HTML documentation for all modules in a directory tree.""" for file in os.listdir(dir): path = os.path.join(dir, file) if ispackage(path): writedocs(path, pkgpath + file + '.') elif os.path.isfile(path): modname = modulename(path) if modname: modname = pkgpath + modname if not done.has_key(modname): done[modname] = 1 writedoc(modname)
def writedoc(key): """Write HTML documentation to a file in the current directory.""" path, object = locate(key) if object: file = open(key + '.html', 'w') file.write(html.page(object)) file.close() print 'wrote', key + '.html'
return """To get help on a Python object, call help(object).
return '''To get help on a Python object, call help(object).
def __repr__(self): return """To get help on a Python object, call help(object).
help(module) or call help('modulename')."""
help(module) or call help('modulename').'''
def __repr__(self): return """To get help on a Python object, call help(object).
pager('\n' + title + '\n\n' + text.document(object))
pager('\n' + title + '\n\n' + text.document(object, key))
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 'No Python documentation found for %s.' % repr(key)
print 'No Python documentation found for %s.' % repr(key)
print 'no Python documentation found for %s' % repr(key)
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 'No Python documentation found for %s.' % repr(key)
desc = split(__import__(modname).__doc__ or '', '\n')[0]
desc = split(freshimp(modname).__doc__ or '', '\n')[0]
def run(self, key, callback, completer=None): self.quit = 0 seen = {}
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))
self.wfile.write(html.page(title, contents))
def send_document(self, title, contents): try: self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write('''
self.send_document(path, html.escape( 'Problem in %s - %s' % (value.filename, value.args)))
self.send_document(path, html.escape(str(value)))
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 in %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(describe(x), html.document(x))
self.send_document(describe(x), html.document(x, 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 in %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
'No Python documentation found for %s.' % repr(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 in %s - %s' % (value.filename, value.args))) return if x: self.send_document(describe(x), html.document(x)) else: self.send_document(path,
contents = heading + join(indices) + """<p align=right>
contents = heading + join(indices) + '''<p align=right>
def bltinlink(name): return '<a href="%s.html">%s</a>' % (name, name)
pydoc</strong> by Ka-Ping Yee &lt;[email protected]&gt;</font></small></small>"""
pydoc</strong> by Ka-Ping Yee &lt;[email protected]&gt;</font></small></small>'''
def bltinlink(name): return '<a href="%s.html">%s</a>' % (name, name)
self.address = (host, port)
self.address = ('', port)
def __init__(self, port, callback): host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost' self.address = (host, port) self.url = 'http://%s:%d/' % (host, port) self.callback = callback self.base.__init__(self, self.address, self.handler)
if find(arg, os.sep) >= 0 and os.path.isfile(arg):
if ispath(arg) and os.path.isfile(arg):
def ready(server): print 'server ready at %s' % server.url
if writing: writedoc(arg) else: man(arg)
if writing: if ispath(arg) and os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: man(arg)
def ready(server): print 'server ready at %s' % server.url
print 'Problem in %s - %s' % (value.filename, value.args)
print value
def ready(server): print 'server ready at %s' % server.url
sys.stderr.write("WARNING: %s can not be found - standard extensions may not be found" % mapFileName)
sys.stderr.write("WARNING: %s can not be found - standard extensions may not be found\n" % defaultMapName)
def checkextensions(unknown, extra_inis, prefix): # Create a table of frozen extensions defaultMapName = os.path.join( os.path.split(sys.argv[0])[0], "extensions_win32.ini") if not os.path.isfile(defaultMapName): sys.stderr.write("WARNING: %s can not be found - standard extensions may not be found" % mapFileName) else: # must go on end, so other inis can override. extra_inis.append(defaultMapName) ret = [] for mod in unknown: for ini in extra_inis:
nodes = []
nodesl = []
def expr_stmt(self, nodelist): # augassign testlist | testlist ('=' testlist)* en = nodelist[-1] exprNode = self.lookup_node(en)(en[1:]) if len(nodelist) == 1: n = Discard(exprNode) n.lineno = exprNode.lineno return n if nodelist[1][0] == token.EQUAL: nodes = [] for i in range(0, len(nodelist) - 2, 2): nodes.append(self.com_assign(nodelist[i], OP_ASSIGN)) n = Assign(nodes, exprNode) n.lineno = nodelist[1][2] else: lval = self.com_augassign(nodelist[0]) op = self.com_augassign_op(nodelist[1]) n = AugAssign(lval, op[1], exprNode) n.lineno = op[2] return n
nodes.append(self.com_assign(nodelist[i], OP_ASSIGN)) n = Assign(nodes, exprNode)
nodesl.append(self.com_assign(nodelist[i], OP_ASSIGN)) n = Assign(nodesl, exprNode)
def expr_stmt(self, nodelist): # augassign testlist | testlist ('=' testlist)* en = nodelist[-1] exprNode = self.lookup_node(en)(en[1:]) if len(nodelist) == 1: n = Discard(exprNode) n.lineno = exprNode.lineno return n if nodelist[1][0] == token.EQUAL: nodes = [] for i in range(0, len(nodelist) - 2, 2): nodes.append(self.com_assign(nodelist[i], OP_ASSIGN)) n = Assign(nodes, exprNode) n.lineno = nodelist[1][2] else: lval = self.com_augassign(nodelist[0]) op = self.com_augassign_op(nodelist[1]) n = AugAssign(lval, op[1], exprNode) n.lineno = op[2] return n
import sys, os, tempfile
import sys, os, tempfile, time
def test_bug737473(self): import sys, os, tempfile savedpath = sys.path[:] testdir = tempfile.mkdtemp() try: sys.path.insert(0, testdir) testfile = os.path.join(testdir, 'test_bug737473.py') print >> open(testfile, 'w'), """\
os.utime(testfile, (0, 0))
past = time.time() - 3 os.utime(testfile, (past, past))
def test(): raise ValueError""" if hasattr(os, 'utime'): os.utime(testfile, (0, 0)) else: import time time.sleep(3) # not to stay in same mtime. if 'test_bug737473' in sys.modules: del sys.modules['test_bug737473'] import test_bug737473 try: test_bug737473.test() except ValueError: # this loads source code to linecache traceback.extract_tb(sys.exc_traceback) print >> open(testfile, 'w'), """\
if os.name !='riscos': TESTFN = '@test'
if os.name == 'java': TESTFN = '$test' elif os.name != 'riscos': TESTFN = '@test'
def fcmp(x, y): # fuzzy comparison function if type(x) == type(0.0) or type(y) == type(0.0): try: x, y = coerce(x, y) fuzz = (abs(x) + abs(y)) * FUZZ if abs(x-y) <= fuzz: return 0 except: pass elif type(x) == type(y) and type(x) in (type(()), type([])): for i in range(min(len(x), len(y))): outcome = fcmp(x[i], y[i]) if outcome != 0: return outcome return cmp(len(x), len(y)) return cmp(x, y)
if os.path.isdir (name):
if os.path.isdir (name) or name == '':
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) if os.path.isdir (name): return if PATH_CREATED.get (name): return (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) except os.error, (errno, errstr): raise DistutilsFileError, "%s: %s" % (head, errstr) PATH_CREATED[head] = 1
raise DistutilsFileError, "%s: %s" % (head, errstr)
raise DistutilsFileError, "'%s': %s" % (head, errstr)
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) if os.path.isdir (name): return if PATH_CREATED.get (name): return (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) except os.error, (errno, errstr): raise DistutilsFileError, "%s: %s" % (head, errstr) PATH_CREATED[head] = 1
raise DistutilsFileError, "could not open %s: %s" % (src, errstr)
raise DistutilsFileError, \ "could not open '%s': %s" % (src, errstr)
def _copy_file_contents (src, dst, buffer_size=16*1024): """Copy the file 'src' to 'dst'; both must be filenames. Any error opening either file, reading from 'src', or writing to 'dst', raises DistutilsFileError. Data is read/written in chunks of 'buffer_size' bytes (default 16k). No attempt is made to handle anything apart from regular files.""" # Stolen from shutil module in the standard library, but with # custom error-handling added. fsrc = None fdst = None try: try: fsrc = open(src, 'rb') except os.error, (errno, errstr): raise DistutilsFileError, "could not open %s: %s" % (src, errstr) try: fdst = open(dst, 'wb') except os.error, (errno, errstr): raise DistutilsFileError, "could not create %s: %s" % (dst, errstr) while 1: try: buf = fsrc.read (buffer_size) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not read from %s: %s" % (src, errstr) if not buf: break try: fdst.write(buf) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not write to %s: %s" % (dst, errstr) finally: if fdst: fdst.close() if fsrc: fsrc.close()
raise DistutilsFileError, "could not create %s: %s" % (dst, errstr)
raise DistutilsFileError, \ "could not create '%s': %s" % (dst, errstr)
def _copy_file_contents (src, dst, buffer_size=16*1024): """Copy the file 'src' to 'dst'; both must be filenames. Any error opening either file, reading from 'src', or writing to 'dst', raises DistutilsFileError. Data is read/written in chunks of 'buffer_size' bytes (default 16k). No attempt is made to handle anything apart from regular files.""" # Stolen from shutil module in the standard library, but with # custom error-handling added. fsrc = None fdst = None try: try: fsrc = open(src, 'rb') except os.error, (errno, errstr): raise DistutilsFileError, "could not open %s: %s" % (src, errstr) try: fdst = open(dst, 'wb') except os.error, (errno, errstr): raise DistutilsFileError, "could not create %s: %s" % (dst, errstr) while 1: try: buf = fsrc.read (buffer_size) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not read from %s: %s" % (src, errstr) if not buf: break try: fdst.write(buf) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not write to %s: %s" % (dst, errstr) finally: if fdst: fdst.close() if fsrc: fsrc.close()
"could not read from %s: %s" % (src, errstr)
"could not read from '%s': %s" % (src, errstr)
def _copy_file_contents (src, dst, buffer_size=16*1024): """Copy the file 'src' to 'dst'; both must be filenames. Any error opening either file, reading from 'src', or writing to 'dst', raises DistutilsFileError. Data is read/written in chunks of 'buffer_size' bytes (default 16k). No attempt is made to handle anything apart from regular files.""" # Stolen from shutil module in the standard library, but with # custom error-handling added. fsrc = None fdst = None try: try: fsrc = open(src, 'rb') except os.error, (errno, errstr): raise DistutilsFileError, "could not open %s: %s" % (src, errstr) try: fdst = open(dst, 'wb') except os.error, (errno, errstr): raise DistutilsFileError, "could not create %s: %s" % (dst, errstr) while 1: try: buf = fsrc.read (buffer_size) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not read from %s: %s" % (src, errstr) if not buf: break try: fdst.write(buf) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not write to %s: %s" % (dst, errstr) finally: if fdst: fdst.close() if fsrc: fsrc.close()
"could not write to %s: %s" % (dst, errstr)
"could not write to '%s': %s" % (dst, errstr)
def _copy_file_contents (src, dst, buffer_size=16*1024): """Copy the file 'src' to 'dst'; both must be filenames. Any error opening either file, reading from 'src', or writing to 'dst', raises DistutilsFileError. Data is read/written in chunks of 'buffer_size' bytes (default 16k). No attempt is made to handle anything apart from regular files.""" # Stolen from shutil module in the standard library, but with # custom error-handling added. fsrc = None fdst = None try: try: fsrc = open(src, 'rb') except os.error, (errno, errstr): raise DistutilsFileError, "could not open %s: %s" % (src, errstr) try: fdst = open(dst, 'wb') except os.error, (errno, errstr): raise DistutilsFileError, "could not create %s: %s" % (dst, errstr) while 1: try: buf = fsrc.read (buffer_size) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not read from %s: %s" % (src, errstr) if not buf: break try: fdst.write(buf) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not write to %s: %s" % (dst, errstr) finally: if fdst: fdst.close() if fsrc: fsrc.close()
"can't copy %s: not a regular file" % src
"can't copy '%s': not a regular file" % src
def copy_file (src, dst, preserve_mode=1, preserve_times=1, update=0, verbose=0, dry_run=0): """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is copied there with the same name; otherwise, it must be a filename. (If the file exists, it will be ruthlessly clobbered.) If 'preserve_mode' is true (the default), the file's mode (type and permission bits, or whatever is analogous on the current platform) is copied. If 'preserve_times' is true (the default), the last-modified and last-access times are copied as well. If 'update' is true, 'src' will only be copied if 'dst' does not exist, or if 'dst' does exist but is older than 'src'. If 'verbose' is true, then a one-line summary of the copy will be printed to stdout. Return true if the file was copied (or would have been copied), false otherwise (ie. 'update' was true and the destination is up-to-date).""" # XXX doesn't copy Mac-specific metadata from stat import * if not os.path.isfile (src): raise DistutilsFileError, \ "can't copy %s: not a regular file" % src if os.path.isdir (dst): dir = dst dst = os.path.join (dst, os.path.basename (src)) else: dir = os.path.dirname (dst) if update and not newer (src, dst): if verbose: print "not copying %s (output up-to-date)" % src return 0 if verbose: print "copying %s -> %s" % (src, dir) if dry_run: return 1 _copy_file_contents (src, dst) if preserve_mode or preserve_times: st = os.stat (src) # According to David Ascher <[email protected]>, utime() should be done # before chmod() (at least under NT). if preserve_times: os.utime (dst, (st[ST_ATIME], st[ST_MTIME])) if preserve_mode: os.chmod (dst, S_IMODE (st[ST_MODE])) return 1
"cannot copy tree %s: not a directory" % src
"cannot copy tree '%s': not a directory" % src
def copy_tree (src, dst, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0): """Copy an entire directory tree 'src' to a new location 'dst'. Both 'src' and 'dst' must be directory names. If 'src' is not a directory, raise DistutilsFileError. If 'dst' does not exist, it is created with 'mkpath()'. The end result of the copy is that every file in 'src' is copied to 'dst', and directories under 'src' are recursively copied to 'dst'. Return the list of files copied (under their output names) -- note that if 'update' is true, this might be less than the list of files considered. Return value is not affected by 'dry_run'. 'preserve_mode' and 'preserve_times' are the same as for 'copy_file'; note that they only apply to regular files, not to directories. If 'preserve_symlinks' is true, symlinks will be copied as symlinks (on platforms that support them!); otherwise (the default), the destination of the symlink will be copied. 'update' and 'verbose' are the same as for 'copy_file'.""" if not dry_run and not os.path.isdir (src): raise DistutilsFileError, \ "cannot copy tree %s: not a directory" % src try: names = os.listdir (src) except os.error, (errno, errstr): if dry_run: names = [] else: raise DistutilsFileError, \ "error listing files in %s: %s" % (src, errstr) if not dry_run: mkpath (dst, verbose=verbose) outputs = [] for n in names: src_name = os.path.join (src, n) dst_name = os.path.join (dst, n) if preserve_symlinks and os.path.islink (src_name): link_dest = os.readlink (src_name) if verbose: print "linking %s -> %s" % (dst_name, link_dest) if not dry_run: os.symlink (link_dest, dst_name) outputs.append (dst_name) elif os.path.isdir (src_name): outputs.extend ( copy_tree (src_name, dst_name, preserve_mode, preserve_times, preserve_symlinks, update, verbose, dry_run)) else: if (copy_file (src_name, dst_name, preserve_mode, preserve_times, update, verbose, dry_run)): outputs.append (dst_name) return outputs
"error listing files in %s: %s" % (src, errstr)
"error listing files in '%s': %s" % (src, errstr)
def copy_tree (src, dst, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0): """Copy an entire directory tree 'src' to a new location 'dst'. Both 'src' and 'dst' must be directory names. If 'src' is not a directory, raise DistutilsFileError. If 'dst' does not exist, it is created with 'mkpath()'. The end result of the copy is that every file in 'src' is copied to 'dst', and directories under 'src' are recursively copied to 'dst'. Return the list of files copied (under their output names) -- note that if 'update' is true, this might be less than the list of files considered. Return value is not affected by 'dry_run'. 'preserve_mode' and 'preserve_times' are the same as for 'copy_file'; note that they only apply to regular files, not to directories. If 'preserve_symlinks' is true, symlinks will be copied as symlinks (on platforms that support them!); otherwise (the default), the destination of the symlink will be copied. 'update' and 'verbose' are the same as for 'copy_file'.""" if not dry_run and not os.path.isdir (src): raise DistutilsFileError, \ "cannot copy tree %s: not a directory" % src try: names = os.listdir (src) except os.error, (errno, errstr): if dry_run: names = [] else: raise DistutilsFileError, \ "error listing files in %s: %s" % (src, errstr) if not dry_run: mkpath (dst, verbose=verbose) outputs = [] for n in names: src_name = os.path.join (src, n) dst_name = os.path.join (dst, n) if preserve_symlinks and os.path.islink (src_name): link_dest = os.readlink (src_name) if verbose: print "linking %s -> %s" % (dst_name, link_dest) if not dry_run: os.symlink (link_dest, dst_name) outputs.append (dst_name) elif os.path.isdir (src_name): outputs.extend ( copy_tree (src_name, dst_name, preserve_mode, preserve_times, preserve_symlinks, update, verbose, dry_run)) else: if (copy_file (src_name, dst_name, preserve_mode, preserve_times, update, verbose, dry_run)): outputs.append (dst_name) return outputs
try:
def __repr__ (self): try: status = [self.__class__.__module__+"."+self.__class__.__name__] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: if type(self.addr) == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s at %#x>' % (' '.join (status), id (self)) except: pass
if self.addr: if type(self.addr) == types.TupleType:
if self.addr is not None: try:
def __repr__ (self): try: status = [self.__class__.__module__+"."+self.__class__.__name__] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: if type(self.addr) == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s at %#x>' % (' '.join (status), id (self)) except: pass
else: status.append (self.addr)
except TypeError: status.append (repr(self.addr))
def __repr__ (self): try: status = [self.__class__.__module__+"."+self.__class__.__name__] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: if type(self.addr) == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s at %#x>' % (' '.join (status), id (self)) except: pass
except: pass try: ar = repr (self.addr) except AttributeError: ar = 'no self.addr!' return '<__repr__() failed for %s instance at %x (addr=%s)>' % \ (self.__class__.__name__, id (self), ar)
def __repr__ (self): try: status = [self.__class__.__module__+"."+self.__class__.__name__] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: if type(self.addr) == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s at %#x>' % (' '.join (status), id (self)) except: pass
self._parser = expat.ParserCreate(None, " ",
self._parser = expat.ParserCreate(self._source.getEncoding(), " ",
def reset(self): if self._namespaces: self._parser = expat.ParserCreate(None, " ", intern=self._interning) self._parser.namespace_prefixes = 1 self._parser.StartElementHandler = self.start_element_ns self._parser.EndElementHandler = self.end_element_ns else: self._parser = expat.ParserCreate(intern = self._interning) self._parser.StartElementHandler = self.start_element self._parser.EndElementHandler = self.end_element
self._parser = expat.ParserCreate(intern = self._interning)
self._parser = expat.ParserCreate(self._source.getEncoding(), intern = self._interning)
def reset(self): if self._namespaces: self._parser = expat.ParserCreate(None, " ", intern=self._interning) self._parser.namespace_prefixes = 1 self._parser.StartElementHandler = self.start_element_ns self._parser.EndElementHandler = self.end_element_ns else: self._parser = expat.ParserCreate(intern = self._interning) self._parser.StartElementHandler = self.start_element self._parser.EndElementHandler = self.end_element
try: temp = open(tempname, 'w') except IOError: print '*** Cannot create temp file', `tempname` return
temp = open(tempname, 'w')
def pipethrough(input, command, output): tempname = tempfile.mktemp() try: temp = open(tempname, 'w') except IOError: print '*** Cannot create temp file', `tempname` return copyliteral(input, temp) temp.close() pipe = os.popen(command + ' <' + tempname, 'r') copybinary(pipe, output) pipe.close() os.unlink(tempname)
def __init__(self, filename):
def __init__(self, filename, config={}):
def __init__(self, filename): self.items = {} self.filename = filename self.fp = open(filename) self.lineno = 0 self.resolving = {} self.resolved = {} self.pushback = None
rv.append((lineno, pre+'\n'))
rv.append((lineno, pre))
def _readitem(self): """Read the definition of an item. Insert #line where needed. """ rv = [] while 1: lineno, line = self._readline() if not line: break if ENDDEFINITION.search(line): break if BEGINDEFINITION.match(line): self.pushback = lineno, line break mo = USEDEFINITION.match(line) if mo: pre = mo.group('pre') if pre: rv.append((lineno, pre+'\n')) rv.append((lineno, line)) # For simplicity we add #line directives now, if # needed. if mo: post = mo.group('post') if post and post != '\n': rv.append((lineno, post)) return rv
pass
if self.gencomments: if savedcomment or line.strip(): savedcomment.append((lineno, '// '+line)) def _extendlines(self, comment): rv = [] for lineno, line in comment: line = line[:-1] if len(line) < 75: line = line + (75-len(line))*' ' line = line + '\n' rv.append((lineno, line)) return rv
def read(self): """Read the source file and store all definitions""" while 1: lineno, line = self._readline() if not line: break mo = BEGINDEFINITION.search(line) if mo: name = mo.group('name') value = self._readitem() self._define(name, value) else: pass # We could output the TeX code but we don't bother.
if line and line != '\n' and lineno != curlineno:
if self.genlinedirectives and line and line != '\n' and lineno != curlineno:
def _addlinedirectives(self, data): curlineno = -100 rv = [] for lineno, line in data: curlineno = curlineno + 1 if line and line != '\n' and lineno != curlineno: rv.append(self._linedirective(lineno)) curlineno = lineno rv.append(line) return rv
pr = Processor(file)
pr = Processor(file, config)
def process(file, config): pr = Processor(file) pr.read() pr.resolve() for pattern, folder in config: pr.save(folder, pattern)
for pattern, folder in config:
for pattern, folder in config['config']:
def process(file, config): pr = Processor(file) pr.read() pr.resolve() for pattern, folder in config: pr.save(folder, pattern)
confstr = """config = [ ("^.*\.cp$", ":unweave-src"), ("^.*\.h$", ":unweave-include"), ]"""
confstr = DEFAULT_CONFIG
def readconfig(): """Read a configuration file, if it doesn't exist create it.""" configname = sys.argv[0] + '.config' if not os.path.exists(configname): confstr = """config = [ ("^.*\.cp$", ":unweave-src"), ("^.*\.h$", ":unweave-include"),
return namespace['config']
return namespace
def readconfig(): """Read a configuration file, if it doesn't exist create it.""" configname = sys.argv[0] + '.config' if not os.path.exists(configname): confstr = """config = [ ("^.*\.cp$", ":unweave-src"), ("^.*\.h$", ":unweave-include"),
process(fss.as_pathname())
process(fss.as_pathname(), config)
def main(): config = readconfig() if len(sys.argv) > 1: for file in sys.argv[1:]: if file[-3:] == '.nw': print "Processing", file process(file, config) else: print "Skipping", file else: fss, ok = macfs.PromptGetFile("Select .nw source file", "TEXT") if not ok: sys.exit(0) process(fss.as_pathname())
if data is None: return self.open(newurl) else: return self.open(newurl, data)
return self.open(newurl)
def redirect_internal(self, url, fp, errcode, errmsg, headers, data): if 'location' in headers: newurl = headers['location'] elif 'uri' in headers: newurl = headers['uri'] else: return void = fp.read() fp.close() # In case the server sent a relative URL, join with original: newurl = basejoin(self.type + ":" + url, newurl) if data is None: return self.open(newurl) else: return self.open(newurl, data)
self.rfile.flush()
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2 or self.have_popen3): self.send_error(403, "CGI script is not a Python script (%s)" % `scriptname`) return if not self.is_executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return
if remote_background:
if self.remote_background:
def _remote(self, url, action, autoraise): autoraise = int(bool(autoraise)) # always 0/1 raise_opt = self.raise_opts and self.raise_opts[autoraise] or '' cmd = "%s %s %s '%s' >/dev/null 2>&1" % (self.name, raise_opt, self.remote_cmd, action) if remote_background: cmd += ' &' rc = os.system(cmd) if rc: # bad return status, try again with simpler command rc = os.system("%s %s" % (self.name, url)) return not rc
if os.environ.get("DISPLAY"):
def register_X_browsers():
def open(self, url, new=0, autoraise=1): if new: ok = self._remote("LOADNEW " + url) else: ok = self._remote("LOAD " + url) return ok
if tarinfo.chksum not in calc_chksums(buf): self._dbg(1, "tarfile: Bad Checksum %r" % tarinfo.name)
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
return self.inner(it, self.timer)
gcold = gc.isenabled() gc.disable() timing = self.inner(it, self.timer) if gcold: gc.enable() return timing
def timeit(self, number=default_number): """Time 'number' executions of the main statement.
modname = modname + dirname + '.'
modname = dirname + '.' + modname
def getenvironment(self): if self.path: file = self.path dir = os.path.dirname(file) # check if we're part of a package modname = "" while os.path.exists(os.path.join(dir, "__init__.py")): dir, dirname = os.path.split(dir) modname = modname + dirname + '.' subname = _filename_as_modname(self.title) if modname: if subname == "__init__": modname = modname[:-1] # strip trailing period else: modname = modname + subname else: modname = subname if sys.modules.has_key(modname): globals = sys.modules[modname].__dict__ self.globals = {} else: globals = self.globals else: file = '<%s>' % self.title globals = self.globals modname = file return globals, file, modname
def _verify(name, expected): computed = eval(name)
def _verify(name, computed, expected):
def _verify(name, expected): computed = eval(name) if abs(computed - expected) > 1e-7: raise ValueError( "computed value for %s deviates too much " "(computed %g, expected %g)" % (name, computed, expected))
_verify('NV_MAGICCONST', 1.71552776992141)
_verify('NV_MAGICCONST', NV_MAGICCONST, 1.71552776992141)
def _verify(name, expected): computed = eval(name) if abs(computed - expected) > 1e-7: raise ValueError( "computed value for %s deviates too much " "(computed %g, expected %g)" % (name, computed, expected))
_verify('TWOPI', 6.28318530718)
_verify('TWOPI', TWOPI, 6.28318530718)
def _verify(name, expected): computed = eval(name) if abs(computed - expected) > 1e-7: raise ValueError( "computed value for %s deviates too much " "(computed %g, expected %g)" % (name, computed, expected))
_verify('LOG4', 1.38629436111989)
_verify('LOG4', LOG4, 1.38629436111989)
def _verify(name, expected): computed = eval(name) if abs(computed - expected) > 1e-7: raise ValueError( "computed value for %s deviates too much " "(computed %g, expected %g)" % (name, computed, expected))
_verify('SG_MAGICCONST', 2.50407739677627)
_verify('SG_MAGICCONST', SG_MAGICCONST, 2.50407739677627)
def _verify(name, expected): computed = eval(name) if abs(computed - expected) > 1e-7: raise ValueError( "computed value for %s deviates too much " "(computed %g, expected %g)" % (name, computed, expected))
if self.debugging: print '*welcome*', `self.welcome`
if self.debugging: print '*welcome*', self.sanitize(self.welcome)
def getwelcome(self): if self.debugging: print '*welcome*', `self.welcome` return self.welcome
if self.debugging > 1: print '*put*', `line`
if self.debugging > 1: print '*put*', self.sanitize(line)
def putline(self, line): line = line + CRLF if self.debugging > 1: print '*put*', `line` self.sock.send(line)
if self.debugging: print '*cmd*', `line`
if self.debugging: print '*cmd*', self.sanitize(line)
def putcmd(self, line): if self.debugging: print '*cmd*', `line` self.putline(line)
print '*get*', `line`
print '*get*', self.sanitize(line)
def getline(self): line = self.file.readline() if self.debugging > 1: print '*get*', `line` if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] return line
if self.debugging: print '*resp*', `resp`
if self.debugging: print '*resp*', self.sanitize(resp)
def getresp(self): resp = self.getmultiline() if self.debugging: print '*resp*', `resp` self.lastresp = resp[:3] c = resp[:1] if c == '4': raise error_temp, resp if c == '5': raise error_perm, resp if c not in '123': raise error_proto, resp return resp
if self.debugging > 1: print '*put urgent*', `line`
if self.debugging > 1: print '*put urgent*', self.sanitize(line)
def abort(self): line = 'ABOR' + CRLF if self.debugging > 1: print '*put urgent*', `line` self.sock.send(line, MSG_OOB) resp = self.getmultiline() if resp[:3] not in ('426', '226'): raise error_proto, resp
else: boundary = ""
if not valid_boundary(boundary): raise ValueError, ('Invalid boundary in multipart form: %s' % `ib`)
def parse_multipart(fp, pdict): """Parse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of conten-type header Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. This is easy to use but not much good if you are expecting megabytes to be uploaded -- in that case, use the FieldStorage class instead which is much more flexible. Note that content-type is the raw, unparsed contents of the content-type header. XXX This does not parse nested multipart parts -- use FieldStorage for that. XXX This should really be subsumed by FieldStorage altogether -- no point in having two implementations of the same parsing algorithm. """ if pdict.has_key('boundary'): boundary = pdict['boundary'] else: boundary = "" nextpart = "--" + boundary lastpart = "--" + boundary + "--" partdict = {} terminator = "" while terminator != lastpart: bytes = -1 data = None if terminator: # At start of next part. Read headers first. headers = mimetools.Message(fp) clength = headers.getheader('content-length') if clength: try: bytes = int(clength) except ValueError: pass if bytes > 0: if maxlen and bytes > maxlen: raise ValueError, 'Maximum content length exceeded' data = fp.read(bytes) else: data = "" # Read lines until end of part. lines = [] while 1: line = fp.readline() if not line: terminator = lastpart # End outer loop break if line[:2] == "--": terminator = line.strip() if terminator in (nextpart, lastpart): break lines.append(line) # Done with part. if data is None: continue if bytes < 0: if lines: # Strip final line terminator line = lines[-1] if line[-2:] == "\r\n": line = line[:-2] elif line[-1:] == "\n": line = line[:-1] lines[-1] = line data = "".join(lines) line = headers['content-disposition'] if not line: continue key, params = parse_header(line) if key != 'form-data': continue if params.has_key('name'): name = params['name'] else: continue if partdict.has_key(name): partdict[name].append(data) else: partdict[name] = [data] return partdict
part = klass(self.fp, {}, self.innerboundary,
part = klass(self.fp, {}, ib,
def read_multi(self, environ, keep_blank_values, strict_parsing): """Internal: read a part that is itself multipart.""" self.list = [] klass = self.FieldStorageClass or self.__class__ part = klass(self.fp, {}, self.innerboundary, environ, keep_blank_values, strict_parsing) # Throw first part away while not part.done: headers = rfc822.Message(self.fp) part = klass(self.fp, headers, self.innerboundary, environ, keep_blank_values, strict_parsing) self.list.append(part) self.skip_lines()
part = klass(self.fp, headers, self.innerboundary,
part = klass(self.fp, headers, ib,
def read_multi(self, environ, keep_blank_values, strict_parsing): """Internal: read a part that is itself multipart.""" self.list = [] klass = self.FieldStorageClass or self.__class__ part = klass(self.fp, {}, self.innerboundary, environ, keep_blank_values, strict_parsing) # Throw first part away while not part.done: headers = rfc822.Message(self.fp) part = klass(self.fp, headers, self.innerboundary, environ, keep_blank_values, strict_parsing) self.list.append(part) self.skip_lines()
if line == '?': line = 'help' elif line == '!':
if not line: return self.emptyline() elif line[0] == '?': line = 'help ' + line[1:] elif line[0] == '!':
def onecmd(self, line): line = string.strip(line) if line == '?': line = 'help' elif line == '!': if hasattr(self, 'do_shell'): line = 'shell' else: return self.default(line) elif not line: return self.emptyline() self.lastcmd = line i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], string.strip(line[i:]) if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg)
line = 'shell'
line = 'shell ' + line[1:]
def onecmd(self, line): line = string.strip(line) if line == '?': line = 'help' elif line == '!': if hasattr(self, 'do_shell'): line = 'shell' else: return self.default(line) elif not line: return self.emptyline() self.lastcmd = line i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], string.strip(line[i:]) if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg)
elif not line: return self.emptyline()
def onecmd(self, line): line = string.strip(line) if line == '?': line = 'help' elif line == '!': if hasattr(self, 'do_shell'): line = 'shell' else: return self.default(line) elif not line: return self.emptyline() self.lastcmd = line i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], string.strip(line[i:]) if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg)
chunk.skip()
if formlength > 0: chunk.skip()
def initfp(self, file): self._file = file self._version = 0 self._decomp = None self._markers = [] self._soundpos = 0 form = self._file.read(4) if form != 'FORM': raise Error, 'file does not start with FORM id' formlength = _read_long(self._file) if formlength <= 0: raise Error, 'invalid FORM chunk data size' formdata = self._file.read(4) formlength = formlength - 4 if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC': self._aifc = 1 else: raise Error, 'not an AIFF or AIFF-C file' self._comm_chunk_read = 0 while formlength > 0: self._ssnd_seek_needed = 1 chunk = Chunk().init(self._file) formlength = formlength - 8 - chunk.chunksize if chunk.chunksize & 1: formlength = formlength - 1 if chunk.chunkname == 'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunk.chunkname == 'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunk.chunkname == 'FVER': self._version = _read_long(chunk) elif chunk.chunkname == 'MARK': self._readmark(chunk) elif chunk.chunkname in _skiplist: pass else: raise Error, 'unrecognized chunk type '+chunk.chunkname chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error, 'COMM chunk and/or SSND chunk missing' if self._aifc and self._decomp: params = [CL.ORIGINAL_FORMAT, 0, \ CL.BITS_PER_COMPONENT, 0, \ CL.FRAME_RATE, self._framerate] if self._nchannels == AL.MONO: params[1] = CL.MONO else: params[1] = CL.STEREO_INTERLEAVED if self._sampwidth == AL.SAMPLE_8: params[3] = 8 elif self._sampwidth == AL.SAMPLE_16: params[3] = 16 else: params[3] = 24 self._decomp.SetParams(params) return self