rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
elif isinstance(check, types.InstanceType): if isinstance(check, klass): skip.append(klass)
elif isinstance(check, klass): skip.append(klass)
def build_opener(*handlers): """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP and FTP. If there is a ProxyHandler, it must be at the front of the list of handlers. (Yuck.) If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler] if hasattr(httplib, 'HTTPS'): default_classes.append(HTTPSHandler) skip = [] for klass in default_classes: for check in handlers: if isinstance(check, types.ClassType): if issubclass(check, klass): skip.append(klass) elif isinstance(check, types.InstanceType): if isinstance(check, klass): skip.append(klass) for klass in skip: default_classes.remove(klass) for klass in default_classes: opener.add_handler(klass()) for h in handlers: if isinstance(h, types.ClassType): h = h() opener.add_handler(h) return opener
if isinstance(h, types.ClassType):
if inspect.isclass(h):
def build_opener(*handlers): """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP and FTP. If there is a ProxyHandler, it must be at the front of the list of handlers. (Yuck.) If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler] if hasattr(httplib, 'HTTPS'): default_classes.append(HTTPSHandler) skip = [] for klass in default_classes: for check in handlers: if isinstance(check, types.ClassType): if issubclass(check, klass): skip.append(klass) elif isinstance(check, types.InstanceType): if isinstance(check, klass): skip.append(klass) for klass in skip: default_classes.remove(klass) for klass in default_classes: opener.add_handler(klass()) for h in handlers: if isinstance(h, types.ClassType): h = h() opener.add_handler(h) return opener
if isinstance(uri, types.StringType):
if isinstance(uri, (types.StringType, types.UnicodeType)):
def add_password(self, realm, uri, user, passwd): # uri could be a single URI or a sequence if isinstance(uri, types.StringType): uri = [uri] uri = tuple(map(self.reduce_uri, uri)) if not self.passwd.has_key(realm): self.passwd[realm] = {} self.passwd[realm][uri] = (user, passwd)
if isinstance(ph, types.ClassType):
if inspect.isclass(ph):
def build_opener(self): opener = OpenerDirector() for ph in self.proxy_handlers: if isinstance(ph, types.ClassType): ph = ph() opener.add_handler(ph)
'ftp://www.python.org/pub/tmp/httplib.py', 'ftp://www.python.org/pub/tmp/imageop.c',
'ftp://www.python.org/pub/python/misc/sousa.au',
def build_opener(self): opener = OpenerDirector() for ph in self.proxy_handlers: if isinstance(ph, types.ClassType): ph = ph() opener.add_handler(ph)
('http://grail.cnri.reston.va.us/cgi-bin/faqw.py',
('http://www.python.org/cgi-bin/faqw.py',
def build_opener(self): opener = OpenerDirector() for ph in self.proxy_handlers: if isinstance(ph, types.ClassType): ph = ph() opener.add_handler(ph)
'ftp://prep.ai.mit.edu/welcome.msg', 'ftp://www.python.org/pub/tmp/figure.prn', 'ftp://www.python.org/pub/tmp/interp.pl', 'http://checkproxy.cnri.reston.va.us/test/test.html',
'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC/research-reports/00README-Legal-Rules-Regs',
def build_opener(self): opener = OpenerDirector() for ph in self.proxy_handlers: if isinstance(ph, types.ClassType): ph = ph() opener.add_handler(ph)
if localhost is not None: urls = urls + [ 'file://%s/etc/passwd' % localhost, 'http://%s/simple/' % localhost, 'http://%s/digest/' % localhost, 'http://%s/not/found.h' % localhost, ] bauth = HTTPBasicAuthHandler() bauth.add_password('basic_test_realm', localhost, 'jhylton', 'password') dauth = HTTPDigestAuthHandler() dauth.add_password('digest_test_realm', localhost, 'jhylton', 'password')
def build_opener(self): opener = OpenerDirector() for ph in self.proxy_handlers: if isinstance(ph, types.ClassType): ph = ph() opener.add_handler(ph)
def at_cnri(req): host = req.get_host() print host if host[-18:] == '.cnri.reston.va.us': return 1 p = CustomProxy('http', at_cnri, 'proxy.cnri.reston.va.us') ph = CustomProxyHandler(p)
install_opener(build_opener(cfh, GopherHandler))
def build_opener(self): opener = OpenerDirector() for ph in self.proxy_handlers: if isinstance(ph, types.ClassType): ph = ph() opener.add_handler(ph)
self.assertRaises( RuntimeError, winsound.PlaySound, 'SystemQuestion', winsound.SND_ALIAS | winsound.SND_NOSTOP )
try: winsound.PlaySound( 'SystemQuestion', winsound.SND_ALIAS | winsound.SND_NOSTOP ) except RuntimeError: pass else: pass
def test_stopasync(self): winsound.PlaySound( 'SystemQuestion', winsound.SND_ALIAS | winsound.SND_ASYNC | winsound.SND_LOOP ) time.sleep(0.5) self.assertRaises( RuntimeError, winsound.PlaySound, 'SystemQuestion', winsound.SND_ALIAS | winsound.SND_NOSTOP ) winsound.PlaySound(None, winsound.SND_PURGE)
def handler1(): print "handler1"
One public function, register, is defined. """
def handler1(): print "handler1"
def handler2(*args, **kargs): print "handler2", args, kargs
_exithandlers = [] def _run_exitfuncs(): """run any registered exit functions
def handler2(*args, **kargs): print "handler2", args, kargs
_exithandlers = atexit._exithandlers atexit._exithandlers = []
_exithandlers is traversed in reverse order so functions are executed last in, first out. """ while _exithandlers: func, targs, kargs = _exithandlers[-1] apply(func, targs, kargs) _exithandlers.remove(_exithandlers[-1])
def handler2(*args, **kargs): print "handler2", args, kargs
atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc")
def register(func, *targs, **kargs): """register a function to be executed upon normal program termination
def handler2(*args, **kargs): print "handler2", args, kargs
atexit._run_exitfuncs()
func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func """ _exithandlers.append((func, targs, kargs))
def handler2(*args, **kargs): print "handler2", args, kargs
atexit._exithandlers = _exithandlers
import sys try: x = sys.exitfunc except AttributeError: sys.exitfunc = _run_exitfuncs else: if x != _run_exitfuncs: register(x) del sys if __name__ == "__main__": def x1(): print "running x1" def x2(n): print "running x2(%s)" % `n` def x3(n, kwd=None): print "running x3(%s, kwd=%s)" % (`n`, `kwd`) register(x1) register(x2, 12) register(x3, 5, "bar") register(x3, "no kwd args")
def handler2(*args, **kargs): print "handler2", args, kargs
t0 = time.millitimer()
t0 = time.time()
def record(v, info, filename, audiofilename, mono, grey, greybits, \ monotreshold, fields, preallocspace): import thread format, x, y, qsize, rate = info fps = 59.64 # Fields per second # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) tpf = 1000.0 / fps # Time per field in msec if filename: vout = VFile.VoutFile(filename) if mono: format = 'mono' elif grey and greybits == 8: format = 'grey' elif grey: format = 'grey'+`abs(greybits)` else: format = 'rgb8' vout.setformat(format) vout.setsize(x, y) if fields: vout.setpf((1, -2)) vout.writeheader() if preallocspace: print 'Preallocating space...' vout.prealloc(preallocspace) print 'done.' MAXSIZE = 20 # XXX should be a user option import Queue queue = Queue.Queue(MAXSIZE) done = thread.allocate_lock() done.acquire_lock() convertor = None if grey: if greybits == 2: convertor = imageop.grey2grey2 elif greybits == 4: convertor = imageop.grey2grey4 elif greybits == -2: convertor = imageop.dither2grey2 thread.start_new_thread(saveframes, \ (vout, queue, done, mono, monotreshold, convertor)) if audiofilename: audiodone = thread.allocate_lock() audiodone.acquire_lock() audiostop = [] initaudio(audiofilename, audiostop, audiodone) gl.wintitle('(rec) ' + filename) lastid = 0 t0 = time.millitimer() count = 0 ids = [] v.InitContinuousCapture(info) while not gl.qtest(): try: cd, id = v.GetCaptureData() except sv.error: #time.millisleep(10) # XXX is this necessary? sgi.nap(1) # XXX Try by Jack continue ids.append(id) id = id + 2*rate
t1 = time.millitimer()
t1 = time.time()
def record(v, info, filename, audiofilename, mono, grey, greybits, \ monotreshold, fields, preallocspace): import thread format, x, y, qsize, rate = info fps = 59.64 # Fields per second # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) tpf = 1000.0 / fps # Time per field in msec if filename: vout = VFile.VoutFile(filename) if mono: format = 'mono' elif grey and greybits == 8: format = 'grey' elif grey: format = 'grey'+`abs(greybits)` else: format = 'rgb8' vout.setformat(format) vout.setsize(x, y) if fields: vout.setpf((1, -2)) vout.writeheader() if preallocspace: print 'Preallocating space...' vout.prealloc(preallocspace) print 'done.' MAXSIZE = 20 # XXX should be a user option import Queue queue = Queue.Queue(MAXSIZE) done = thread.allocate_lock() done.acquire_lock() convertor = None if grey: if greybits == 2: convertor = imageop.grey2grey2 elif greybits == 4: convertor = imageop.grey2grey4 elif greybits == -2: convertor = imageop.dither2grey2 thread.start_new_thread(saveframes, \ (vout, queue, done, mono, monotreshold, convertor)) if audiofilename: audiodone = thread.allocate_lock() audiodone.acquire_lock() audiostop = [] initaudio(audiofilename, audiostop, audiodone) gl.wintitle('(rec) ' + filename) lastid = 0 t0 = time.millitimer() count = 0 ids = [] v.InitContinuousCapture(info) while not gl.qtest(): try: cd, id = v.GetCaptureData() except sv.error: #time.millisleep(10) # XXX is this necessary? sgi.nap(1) # XXX Try by Jack continue ids.append(id) id = id + 2*rate
print lastid, 'fields in', t1-t0, 'msec', print '--', 0.1 * int(lastid * 10000.0 / (t1-t0)), 'fields/sec'
print lastid, 'fields in', round(t1-t0, 3), 'sec', print '--', round(lastid/(t1-t0), 1), 'fields/sec'
def record(v, info, filename, audiofilename, mono, grey, greybits, \ monotreshold, fields, preallocspace): import thread format, x, y, qsize, rate = info fps = 59.64 # Fields per second # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) tpf = 1000.0 / fps # Time per field in msec if filename: vout = VFile.VoutFile(filename) if mono: format = 'mono' elif grey and greybits == 8: format = 'grey' elif grey: format = 'grey'+`abs(greybits)` else: format = 'rgb8' vout.setformat(format) vout.setsize(x, y) if fields: vout.setpf((1, -2)) vout.writeheader() if preallocspace: print 'Preallocating space...' vout.prealloc(preallocspace) print 'done.' MAXSIZE = 20 # XXX should be a user option import Queue queue = Queue.Queue(MAXSIZE) done = thread.allocate_lock() done.acquire_lock() convertor = None if grey: if greybits == 2: convertor = imageop.grey2grey2 elif greybits == 4: convertor = imageop.grey2grey4 elif greybits == -2: convertor = imageop.dither2grey2 thread.start_new_thread(saveframes, \ (vout, queue, done, mono, monotreshold, convertor)) if audiofilename: audiodone = thread.allocate_lock() audiodone.acquire_lock() audiostop = [] initaudio(audiofilename, audiostop, audiodone) gl.wintitle('(rec) ' + filename) lastid = 0 t0 = time.millitimer() count = 0 ids = [] v.InitContinuousCapture(info) while not gl.qtest(): try: cd, id = v.GetCaptureData() except sv.error: #time.millisleep(10) # XXX is this necessary? sgi.nap(1) # XXX Try by Jack continue ids.append(id) id = id + 2*rate
print 0.1*int(count*20000.0/(t1-t0)), 'f/s',
print round(count*2/(t1-t0), 1), 'f/s',
def record(v, info, filename, audiofilename, mono, grey, greybits, \ monotreshold, fields, preallocspace): import thread format, x, y, qsize, rate = info fps = 59.64 # Fields per second # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) tpf = 1000.0 / fps # Time per field in msec if filename: vout = VFile.VoutFile(filename) if mono: format = 'mono' elif grey and greybits == 8: format = 'grey' elif grey: format = 'grey'+`abs(greybits)` else: format = 'rgb8' vout.setformat(format) vout.setsize(x, y) if fields: vout.setpf((1, -2)) vout.writeheader() if preallocspace: print 'Preallocating space...' vout.prealloc(preallocspace) print 'done.' MAXSIZE = 20 # XXX should be a user option import Queue queue = Queue.Queue(MAXSIZE) done = thread.allocate_lock() done.acquire_lock() convertor = None if grey: if greybits == 2: convertor = imageop.grey2grey2 elif greybits == 4: convertor = imageop.grey2grey4 elif greybits == -2: convertor = imageop.dither2grey2 thread.start_new_thread(saveframes, \ (vout, queue, done, mono, monotreshold, convertor)) if audiofilename: audiodone = thread.allocate_lock() audiodone.acquire_lock() audiostop = [] initaudio(audiofilename, audiostop, audiodone) gl.wintitle('(rec) ' + filename) lastid = 0 t0 = time.millitimer() count = 0 ids = [] v.InitContinuousCapture(info) while not gl.qtest(): try: cd, id = v.GetCaptureData() except sv.error: #time.millisleep(10) # XXX is this necessary? sgi.nap(1) # XXX Try by Jack continue ids.append(id) id = id + 2*rate
print count*200.0/lastid, '%,', print count*rate*200.0/lastid, '% of wanted rate',
print '(', print round(count*200.0/lastid), '%, or', print round(count*rate*200.0/lastid), '% of wanted rate )',
def record(v, info, filename, audiofilename, mono, grey, greybits, \ monotreshold, fields, preallocspace): import thread format, x, y, qsize, rate = info fps = 59.64 # Fields per second # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) tpf = 1000.0 / fps # Time per field in msec if filename: vout = VFile.VoutFile(filename) if mono: format = 'mono' elif grey and greybits == 8: format = 'grey' elif grey: format = 'grey'+`abs(greybits)` else: format = 'rgb8' vout.setformat(format) vout.setsize(x, y) if fields: vout.setpf((1, -2)) vout.writeheader() if preallocspace: print 'Preallocating space...' vout.prealloc(preallocspace) print 'done.' MAXSIZE = 20 # XXX should be a user option import Queue queue = Queue.Queue(MAXSIZE) done = thread.allocate_lock() done.acquire_lock() convertor = None if grey: if greybits == 2: convertor = imageop.grey2grey2 elif greybits == 4: convertor = imageop.grey2grey4 elif greybits == -2: convertor = imageop.dither2grey2 thread.start_new_thread(saveframes, \ (vout, queue, done, mono, monotreshold, convertor)) if audiofilename: audiodone = thread.allocate_lock() audiodone.acquire_lock() audiostop = [] initaudio(audiofilename, audiostop, audiodone) gl.wintitle('(rec) ' + filename) lastid = 0 t0 = time.millitimer() count = 0 ids = [] v.InitContinuousCapture(info) while not gl.qtest(): try: cd, id = v.GetCaptureData() except sv.error: #time.millisleep(10) # XXX is this necessary? sgi.nap(1) # XXX Try by Jack continue ids.append(id) id = id + 2*rate
byte_increments = [ord(c) for c in co.co_lnotab[0::2]] line_increments = [ord(c) for c in co.co_lnotab[1::2]] table_length = len(byte_increments) lineno = co.co_firstlineno table_index = 0 while (table_index < table_length and byte_increments[table_index] == 0): lineno += line_increments[table_index] table_index += 1 addr = 0 line_incr = 0
def disassemble(co, lasti=-1): """Disassemble a code object.""" code = co.co_code byte_increments = [ord(c) for c in co.co_lnotab[0::2]] line_increments = [ord(c) for c in co.co_lnotab[1::2]] table_length = len(byte_increments) # == len(line_increments) lineno = co.co_firstlineno table_index = 0 while (table_index < table_length and byte_increments[table_index] == 0): lineno += line_increments[table_index] table_index += 1 addr = 0 line_incr = 0 labels = findlabels(code) n = len(code) i = 0 extended_arg = 0 free = None while i < n: c = code[i] op = ord(c) if i >= addr: lineno += line_incr while table_index < table_length: addr += byte_increments[table_index] line_incr = line_increments[table_index] table_index += 1 if line_incr: break else: addr = sys.maxint if i > 0: print print "%3d"%lineno, else: print ' ', if i == lasti: print '-->', else: print ' ', if i in labels: print '>>', else: print ' ', print `i`.rjust(4), print opname[op].ljust(20), i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg extended_arg = 0 i = i+2 if op == EXTENDED_ARG: extended_arg = oparg*65536L print `oparg`.rjust(5), if op in hasconst: print '(' + `co.co_consts[oparg]` + ')', elif op in hasname: print '(' + co.co_names[oparg] + ')', elif op in hasjrel: print '(to ' + `i + oparg` + ')', elif op in haslocal: print '(' + co.co_varnames[oparg] + ')', elif op in hascompare: print '(' + cmp_op[oparg] + ')', elif op in hasfree: if free is None: free = co.co_cellvars + co.co_freevars print '(' + free[oparg] + ')', print
if i >= addr: lineno += line_incr while table_index < table_length: addr += byte_increments[table_index] line_incr = line_increments[table_index] table_index += 1 if line_incr: break else: addr = sys.maxint
if i in linestarts:
def disassemble(co, lasti=-1): """Disassemble a code object.""" code = co.co_code byte_increments = [ord(c) for c in co.co_lnotab[0::2]] line_increments = [ord(c) for c in co.co_lnotab[1::2]] table_length = len(byte_increments) # == len(line_increments) lineno = co.co_firstlineno table_index = 0 while (table_index < table_length and byte_increments[table_index] == 0): lineno += line_increments[table_index] table_index += 1 addr = 0 line_incr = 0 labels = findlabels(code) n = len(code) i = 0 extended_arg = 0 free = None while i < n: c = code[i] op = ord(c) if i >= addr: lineno += line_incr while table_index < table_length: addr += byte_increments[table_index] line_incr = line_increments[table_index] table_index += 1 if line_incr: break else: addr = sys.maxint if i > 0: print print "%3d"%lineno, else: print ' ', if i == lasti: print '-->', else: print ' ', if i in labels: print '>>', else: print ' ', print `i`.rjust(4), print opname[op].ljust(20), i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg extended_arg = 0 i = i+2 if op == EXTENDED_ARG: extended_arg = oparg*65536L print `oparg`.rjust(5), if op in hasconst: print '(' + `co.co_consts[oparg]` + ')', elif op in hasname: print '(' + co.co_names[oparg] + ')', elif op in hasjrel: print '(to ' + `i + oparg` + ')', elif op in haslocal: print '(' + co.co_varnames[oparg] + ')', elif op in hascompare: print '(' + cmp_op[oparg] + ')', elif op in hasfree: if free is None: free = co.co_cellvars + co.co_freevars print '(' + free[oparg] + ')', print
print "%3d"%lineno,
print "%3d" % linestarts[i],
def disassemble(co, lasti=-1): """Disassemble a code object.""" code = co.co_code byte_increments = [ord(c) for c in co.co_lnotab[0::2]] line_increments = [ord(c) for c in co.co_lnotab[1::2]] table_length = len(byte_increments) # == len(line_increments) lineno = co.co_firstlineno table_index = 0 while (table_index < table_length and byte_increments[table_index] == 0): lineno += line_increments[table_index] table_index += 1 addr = 0 line_incr = 0 labels = findlabels(code) n = len(code) i = 0 extended_arg = 0 free = None while i < n: c = code[i] op = ord(c) if i >= addr: lineno += line_incr while table_index < table_length: addr += byte_increments[table_index] line_incr = line_increments[table_index] table_index += 1 if line_incr: break else: addr = sys.maxint if i > 0: print print "%3d"%lineno, else: print ' ', if i == lasti: print '-->', else: print ' ', if i in labels: print '>>', else: print ' ', print `i`.rjust(4), print opname[op].ljust(20), i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg extended_arg = 0 i = i+2 if op == EXTENDED_ARG: extended_arg = oparg*65536L print `oparg`.rjust(5), if op in hasconst: print '(' + `co.co_consts[oparg]` + ')', elif op in hasname: print '(' + co.co_names[oparg] + ')', elif op in hasjrel: print '(to ' + `i + oparg` + ')', elif op in haslocal: print '(' + co.co_varnames[oparg] + ')', elif op in hascompare: print '(' + cmp_op[oparg] + ')', elif op in hasfree: if free is None: free = co.co_cellvars + co.co_freevars print '(' + free[oparg] + ')', print
if op == opmap['SET_LINENO'] and i > 0: print
def disassemble_string(code, lasti=-1, varnames=None, names=None, constants=None): labels = findlabels(code) n = len(code) i = 0 while i < n: c = code[i] op = ord(c) if op == opmap['SET_LINENO'] and i > 0: print # Extra blank line if i == lasti: print '-->', else: print ' ', if i in labels: print '>>', else: print ' ', print `i`.rjust(4), print opname[op].ljust(15), i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 print `oparg`.rjust(5), if op in hasconst: if constants: print '(' + `constants[oparg]` + ')', else: print '(%d)'%oparg, elif op in hasname: if names is not None: print '(' + names[oparg] + ')', else: print '(%d)'%oparg, elif op in hasjrel: print '(to ' + `i + oparg` + ')', elif op in haslocal: if varnames: print '(' + varnames[oparg] + ')', else: print '(%d)' % oparg, elif op in hascompare: print '(' + cmp_op[oparg] + ')', print
for h in root.handlers:
for h in root.handlers[:]:
def fileConfig(fname, defaults=None): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). In versions of ConfigParser which have the readfp method [typically shipped in 2.x versions of Python], you can pass in a file-like object rather than a filename, in which case the file-like object will be read using readfp. """ import ConfigParser cp = ConfigParser.ConfigParser(defaults) if hasattr(cp, 'readfp') and hasattr(fname, 'readline'): cp.readfp(fname) else: cp.read(fname) #first, do the formatters... flist = cp.get("formatters", "keys") if len(flist): flist = string.split(flist, ",") formatters = {} for form in flist: sectname = "formatter_%s" % form opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) else: fs = None if "datefmt" in opts: dfs = cp.get(sectname, "datefmt", 1) else: dfs = None f = logging.Formatter(fs, dfs) formatters[form] = f #next, do the handlers... #critical section... logging._acquireLock() try: try: #first, lose the existing handlers... logging._handlers.clear() #now set up the new ones... hlist = cp.get("handlers", "keys") if len(hlist): hlist = string.split(hlist, ",") handlers = {} fixups = [] #for inter-handler references for hand in hlist: sectname = "handler_%s" % hand klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: fmt = cp.get(sectname, "formatter") else: fmt = "" klass = eval(klass, vars(logging)) args = cp.get(sectname, "args") args = eval(args, vars(logging)) h = apply(klass, args) if "level" in opts: level = cp.get(sectname, "level") h.setLevel(logging._levelNames[level]) if len(fmt): h.setFormatter(formatters[fmt]) #temporary hack for FileHandler and MemoryHandler. if klass == logging.handlers.MemoryHandler: if "target" in opts: target = cp.get(sectname,"target") else: target = "" if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for fixup in fixups: h = fixup[0] t = fixup[1] h.setTarget(handlers[t]) #at last, the loggers...first the root... llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1 except: import traceback ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr) del ei finally: logging._releaseLock()
for h in logger.handlers:
for h in logger.handlers[:]:
def fileConfig(fname, defaults=None): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). In versions of ConfigParser which have the readfp method [typically shipped in 2.x versions of Python], you can pass in a file-like object rather than a filename, in which case the file-like object will be read using readfp. """ import ConfigParser cp = ConfigParser.ConfigParser(defaults) if hasattr(cp, 'readfp') and hasattr(fname, 'readline'): cp.readfp(fname) else: cp.read(fname) #first, do the formatters... flist = cp.get("formatters", "keys") if len(flist): flist = string.split(flist, ",") formatters = {} for form in flist: sectname = "formatter_%s" % form opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) else: fs = None if "datefmt" in opts: dfs = cp.get(sectname, "datefmt", 1) else: dfs = None f = logging.Formatter(fs, dfs) formatters[form] = f #next, do the handlers... #critical section... logging._acquireLock() try: try: #first, lose the existing handlers... logging._handlers.clear() #now set up the new ones... hlist = cp.get("handlers", "keys") if len(hlist): hlist = string.split(hlist, ",") handlers = {} fixups = [] #for inter-handler references for hand in hlist: sectname = "handler_%s" % hand klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: fmt = cp.get(sectname, "formatter") else: fmt = "" klass = eval(klass, vars(logging)) args = cp.get(sectname, "args") args = eval(args, vars(logging)) h = apply(klass, args) if "level" in opts: level = cp.get(sectname, "level") h.setLevel(logging._levelNames[level]) if len(fmt): h.setFormatter(formatters[fmt]) #temporary hack for FileHandler and MemoryHandler. if klass == logging.handlers.MemoryHandler: if "target" in opts: target = cp.get(sectname,"target") else: target = "" if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for fixup in fixups: h = fixup[0] t = fixup[1] h.setTarget(handlers[t]) #at last, the loggers...first the root... llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1 except: import traceback ei = sys.exc_info() traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr) del ei finally: logging._releaseLock()
test_support.run_unittest(TestBug1385040)
pass
def test_main(): test_support.run_unittest(TestBug1385040)
ci.append(-2.5, -3.7, 1.0) ci.append(-1.5, -3.7, 3.0) ci.append(1.5, -3.7, -2.5) ci.append(2.5, -3.7, -0.75)
ci.append((-2.5, -3.7, 1.0)) ci.append((-1.5, -3.7, 3.0)) ci.append((1.5, -3.7, -2.5)) ci.append((2.5, -3.7, -0.75))
def make_ctlpoints(): c = [] # ci = [] ci.append(-2.5, -3.7, 1.0) ci.append(-1.5, -3.7, 3.0) ci.append(1.5, -3.7, -2.5) ci.append(2.5, -3.7, -0.75) c.append(ci) # ci = [] ci.append(-2.5, -2.0, 3.0) ci.append(-1.5, -2.0, 4.0) ci.append(1.5, -2.0, -3.0) ci.append(2.5, -2.0, 0.0) c.append(ci) # ci = [] ci.append(-2.5, 2.0, 1.0) ci.append(-1.5, 2.0, 0.0) ci.append(1.5, 2.0, -1.0) ci.append(2.5, 2.0, 2.0) c.append(ci) # ci = [] ci.append(-2.5, 2.7, 1.25) ci.append(-1.5, 2.7, 0.1) ci.append(1.5, 2.7, -0.6) ci.append(2.5, 2.7, 0.2) c.append(ci) # return c
ci.append(-2.5, -2.0, 3.0) ci.append(-1.5, -2.0, 4.0) ci.append(1.5, -2.0, -3.0) ci.append(2.5, -2.0, 0.0)
ci.append((-2.5, -2.0, 3.0)) ci.append((-1.5, -2.0, 4.0)) ci.append((1.5, -2.0, -3.0)) ci.append((2.5, -2.0, 0.0))
def make_ctlpoints(): c = [] # ci = [] ci.append(-2.5, -3.7, 1.0) ci.append(-1.5, -3.7, 3.0) ci.append(1.5, -3.7, -2.5) ci.append(2.5, -3.7, -0.75) c.append(ci) # ci = [] ci.append(-2.5, -2.0, 3.0) ci.append(-1.5, -2.0, 4.0) ci.append(1.5, -2.0, -3.0) ci.append(2.5, -2.0, 0.0) c.append(ci) # ci = [] ci.append(-2.5, 2.0, 1.0) ci.append(-1.5, 2.0, 0.0) ci.append(1.5, 2.0, -1.0) ci.append(2.5, 2.0, 2.0) c.append(ci) # ci = [] ci.append(-2.5, 2.7, 1.25) ci.append(-1.5, 2.7, 0.1) ci.append(1.5, 2.7, -0.6) ci.append(2.5, 2.7, 0.2) c.append(ci) # return c
ci.append(-2.5, 2.0, 1.0) ci.append(-1.5, 2.0, 0.0) ci.append(1.5, 2.0, -1.0) ci.append(2.5, 2.0, 2.0)
ci.append((-2.5, 2.0, 1.0)) ci.append((-1.5, 2.0, 0.0)) ci.append((1.5, 2.0, -1.0)) ci.append((2.5, 2.0, 2.0))
def make_ctlpoints(): c = [] # ci = [] ci.append(-2.5, -3.7, 1.0) ci.append(-1.5, -3.7, 3.0) ci.append(1.5, -3.7, -2.5) ci.append(2.5, -3.7, -0.75) c.append(ci) # ci = [] ci.append(-2.5, -2.0, 3.0) ci.append(-1.5, -2.0, 4.0) ci.append(1.5, -2.0, -3.0) ci.append(2.5, -2.0, 0.0) c.append(ci) # ci = [] ci.append(-2.5, 2.0, 1.0) ci.append(-1.5, 2.0, 0.0) ci.append(1.5, 2.0, -1.0) ci.append(2.5, 2.0, 2.0) c.append(ci) # ci = [] ci.append(-2.5, 2.7, 1.25) ci.append(-1.5, 2.7, 0.1) ci.append(1.5, 2.7, -0.6) ci.append(2.5, 2.7, 0.2) c.append(ci) # return c
ci.append(-2.5, 2.7, 1.25) ci.append(-1.5, 2.7, 0.1) ci.append(1.5, 2.7, -0.6) ci.append(2.5, 2.7, 0.2)
ci.append((-2.5, 2.7, 1.25)) ci.append((-1.5, 2.7, 0.1)) ci.append((1.5, 2.7, -0.6)) ci.append((2.5, 2.7, 0.2))
def make_ctlpoints(): c = [] # ci = [] ci.append(-2.5, -3.7, 1.0) ci.append(-1.5, -3.7, 3.0) ci.append(1.5, -3.7, -2.5) ci.append(2.5, -3.7, -0.75) c.append(ci) # ci = [] ci.append(-2.5, -2.0, 3.0) ci.append(-1.5, -2.0, 4.0) ci.append(1.5, -2.0, -3.0) ci.append(2.5, -2.0, 0.0) c.append(ci) # ci = [] ci.append(-2.5, 2.0, 1.0) ci.append(-1.5, 2.0, 0.0) ci.append(1.5, 2.0, -1.0) ci.append(2.5, 2.0, 2.0) c.append(ci) # ci = [] ci.append(-2.5, 2.7, 1.25) ci.append(-1.5, 2.7, 0.1) ci.append(1.5, 2.7, -0.6) ci.append(2.5, 2.7, 0.2) c.append(ci) # return c
c.append(1.0, 0.0, 1.0) c.append(1.0, 1.0, 1.0) c.append(0.0, 2.0, 2.0) c.append(-1.0, 1.0, 1.0) c.append(-1.0, 0.0, 1.0) c.append(-1.0, -1.0, 1.0) c.append(0.0, -2.0, 2.0) c.append(1.0, -1.0, 1.0) c.append(1.0, 0.0, 1.0)
c.append((1.0, 0.0, 1.0)) c.append((1.0, 1.0, 1.0)) c.append((0.0, 2.0, 2.0)) c.append((-1.0, 1.0, 1.0)) c.append((-1.0, 0.0, 1.0)) c.append((-1.0, -1.0, 1.0)) c.append((0.0, -2.0, 2.0)) c.append((1.0, -1.0, 1.0) ) c.append((1.0, 0.0, 1.0))
def make_trimpoints(): c = [] c.append(1.0, 0.0, 1.0) c.append(1.0, 1.0, 1.0) c.append(0.0, 2.0, 2.0) c.append(-1.0, 1.0, 1.0) c.append(-1.0, 0.0, 1.0) c.append(-1.0, -1.0, 1.0) c.append(0.0, -2.0, 2.0) c.append(1.0, -1.0, 1.0) c.append(1.0, 0.0, 1.0) return c
from distutils.util import get_platform s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
s = "build/lib.%s-%.3s" % ("linux-i686", sys.version)
def makepath(*paths): dir = os.path.abspath(os.path.join(*paths)) return dir, os.path.normcase(dir)
del get_platform, s
def makepath(*paths): dir = os.path.abspath(os.path.join(*paths)) return dir, os.path.normcase(dir)
self.__msg = msg
self._msg = msg
def __init__(self, msg=''): self.__msg = msg
return self.__msg
return self._msg
def __repr__(self): return self.__msg
on the defaults passed into the constructor.
on the defaults passed into the constructor, unless the optional argument `raw' is true.
def get(self, section, option, raw=0): """Get an option value for a given section.
if line[0] in ' \t' and cursect <> None and optname:
if line[0] in ' \t' and cursect is not None and optname:
def __read(self, fp): """Parse a sectioned setup file.
cursect = cursect[optname] + '\n ' + value elif secthead_cre.match(line) >= 0: sectname = secthead_cre.group(1) if self.__sections.has_key(sectname): cursect = self.__sections[sectname] elif sectname == DEFAULTSECT: cursect = self.__defaults
cursect[optname] = cursect[optname] + '\n ' + value else: mo = self.__SECTCRE.match(line) if mo: sectname = mo.group('header') if self.__sections.has_key(sectname): cursect = self.__sections[sectname] elif sectname == DEFAULTSECT: cursect = self.__defaults else: cursect = {} self.__sections[sectname] = cursect optname = None elif cursect is None: raise MissingSectionHeaderError(fp.name, lineno, `line`)
def __read(self, fp): """Parse a sectioned setup file.
cursect = {'name': sectname} self.__sections[sectname] = cursect optname = None elif option_cre.match(line) >= 0: optname, optval = option_cre.group(1, 3) optname = string.lower(optname) optval = string.strip(optval) if optval == '""': optval = '' cursect[optname] = optval else: print 'Error in %s at %d: %s', (fp.name, lineno, `line`)
mo = self.__OPTCRE.match(line) if mo: optname, optval = mo.group('option', 'value') optname = string.lower(optname) optval = string.strip(optval) if optval == '""': optval = '' cursect[optname] = optval else: if not e: e = ParsingError(fp.name) e.append(lineno, `line`) if e: raise e
def __read(self, fp): """Parse a sectioned setup file.
class _MultiCallMethod: def __init__(self, call_list, name): self.__call_list = call_list self.__name = name def __getattr__(self, name): return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name)) def __call__(self, *args): self.__call_list.append((self.__name, args)) def MultiCallIterator(results): """Iterates over the results of a multicall. Exceptions are thrown in response to xmlrpc faults.""" for i in results: if type(i) == type({}): raise Fault(i['faultCode'], i['faultString']) elif type(i) == type([]): yield i[0] else: raise ValueError,\ "unexpected type in multicall result" class MultiCall: """server -> a object used to boxcar method calls server should be a ServerProxy object. Methods can be added to the MultiCall using normal method call syntax e.g.: multicall = MultiCall(server_proxy) multicall.add(2,3) multicall.get_address("Guido") To execute the multicall, call the MultiCall object e.g.: add_result, address = multicall() """ def __init__(self, server): self.__server = server self.__call_list = [] def __repr__(self): return "<MultiCall at %x>" % id(self) __str__ = __repr__ def __getattr__(self, name): return _MultiCallMethod(self.__call_list, name) def __call__(self): marshalled_list = [] for name, args in self.__call_list: marshalled_list.append({'methodName' : name, 'params' : args}) return MultiCallIterator(self.__server.system.multicall(marshalled_list))
def end_methodName(self, data): if self._encoding: data = _decode(data, self._encoding) self._methodname = data self._type = "methodName" # no params
exts.append( Extension('unicodedata', ['unicodedata.c', 'unicodedatabase.c']) )
exts.append( Extension('unicodedata', ['unicodedata.c']) )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
if hasattr(m, "__file__"):
if hasattr(m, "__file__") and m.__file__:
def makepath(*paths): dir = os.path.join(*paths) return os.path.normcase(os.path.abspath(dir))
[here, os.path.join(here, os.pardir), os.curdir])
[os.path.join(here, os.pardir), here, os.curdir])
def __call__(self): self.__setup() prompt = 'Hit Return for more, or q (and Return) to quit: ' lineno = 0 while 1: try: for i in range(lineno, lineno + self.MAXLINES): print self.__lines[i] except IndexError: break else: lineno += self.MAXLINES key = None while key is None: key = raw_input(prompt) if key not in ('', 'q'): key = None if key == 'q': break
if __name__ == "__main__": import glob f = glob.glob("command/*.py") byte_compile(f, optimize=0, prefix="command/", base_dir="/usr/lib/python")
def byte_compile (py_files, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None): """Byte-compile a collection of Python source files to either .pyc or .pyo files in the same directory. 'py_files' is a list of files to compile; any files that don't end in ".py" are silently skipped. 'optimize' must be one of the following: 0 - don't optimize (generate .pyc) 1 - normal optimization (like "python -O") 2 - extra optimization (like "python -OO") If 'force' is true, all files are recompiled regardless of timestamps. The source filename encoded in each bytecode file defaults to the filenames listed in 'py_files'; you can modify these with 'prefix' and 'basedir'. 'prefix' is a string that will be stripped off of each source filename, and 'base_dir' is a directory name that will be prepended (after 'prefix' is stripped). You can supply either or both (or neither) of 'prefix' and 'base_dir', as you wish. If 'verbose' is true, prints out a report of each file. If 'dry_run' is true, doesn't actually do anything that would affect the filesystem. Byte-compilation is either done directly in this interpreter process with the standard py_compile module, or indirectly by writing a temporary script and executing it. Normally, you should let 'byte_compile()' figure out to use direct compilation or not (see the source for details). The 'direct' flag is used by the script generated in indirect mode; unless you know what you're doing, leave it set to None. """ # First, if the caller didn't force us into direct or indirect mode, # figure out which mode we should be in. We take a conservative # approach: choose direct mode *only* if the current interpreter is # in debug mode and optimize is 0. If we're not in debug mode (-O # or -OO), we don't know which level of optimization this # interpreter is running with, so we can't do direct # byte-compilation and be certain that it's the right thing. Thus, # always compile indirectly if the current interpreter is in either # optimize mode, or if either optimization level was requested by # the caller. if direct is None: direct = (__debug__ and optimize == 0) # "Indirect" byte-compilation: write a temporary script and then # run it with the appropriate flags. if not direct: from tempfile import mktemp script_name = mktemp(".py") if verbose: print "writing byte-compilation script '%s'" % script_name if not dry_run: script = open(script_name, "w") script.write("""\
default_compiler = { 'posix': 'unix', 'nt': 'msvc', 'mac': 'mwerks', }
_default_compilers = ( ('cygwin.*', 'cygwin'), ('posix', 'unix'), ('nt', 'msvc'), ('mac', 'mwerks'), ) def get_default_compiler(osname=None, platform=None): """ Determine the default compiler to use for the given platform. osname should be one of the standard Python OS names (i.e. the ones returned by os.name) and platform the common value returned by sys.platform for the platform in question. The default values are os.name and sys.platform in case the parameters are not given. """ if osname is None: osname = os.name if platform is None: platform = sys.platform for pattern, compiler in _default_compilers: if re.match(pattern, platform) is not None or \ re.match(pattern, osname) is not None: return compiler return 'unix'
def mkpath (self, name, mode=0777): mkpath (name, mode, self.verbose, self.dry_run)
compiler = default_compiler[plat]
compiler = get_default_compiler(plat)
def new_compiler (plat=None, compiler=None, verbose=0, dry_run=0, force=0): """Generate an instance of some CCompiler subclass for the supplied platform/compiler combination. 'plat' defaults to 'os.name' (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler for that platform. Currently only 'posix' and 'nt' are supported, and the default compilers are "traditional Unix interface" (UnixCCompiler class) and Visual C++ (MSVCCompiler class). Note that it's perfectly possible to ask for a Unix compiler object under Windows, and a Microsoft compiler object under Unix -- if you supply a value for 'compiler', 'plat' is ignored. """ if plat is None: plat = os.name try: if compiler is None: compiler = default_compiler[plat] (module_name, class_name, long_description) = compiler_class[compiler] except KeyError: msg = "don't know how to compile C/C++ code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler" % compiler raise DistutilsPlatformError, msg try: module_name = "distutils." + module_name __import__ (module_name) module = sys.modules[module_name] klass = vars(module)[class_name] except ImportError: raise DistutilsModuleError, \ "can't compile C/C++ code: unable to load module '%s'" % \ module_name except KeyError: raise DistutilsModuleError, \ ("can't compile C/C++ code: unable to find class '%s' " + "in module '%s'") % (class_name, module_name) return klass (verbose, dry_run, force)
coords = self._canvas.bbox(self._TAG)
coords = self._canvas.coords(self._TAG)
def _x(self): coords = self._canvas.bbox(self._TAG) assert coords return coords[2] - 6 # BAW: kludge
return coords[2] - 6
return coords[0] + self._ARROWWIDTH
def _x(self): coords = self._canvas.bbox(self._TAG) assert coords return coords[2] - 6 # BAW: kludge
":build.macppc.shared:PythonCore.",
":build.macppc.shared:PythonCorePPC.",
def buildapplet(top, dummy, list): """Create a PPC python applet""" template = mkapplet.findtemplate() for src in list: if src[-3:] != '.py': raise 'Should end in .py', src base = os.path.basename(src) dst = os.path.join(top, base)[:-3] src = os.path.join(top, src) try: os.unlink(dst) except os.error: pass print 'Building applet', dst mkapplet.process(template, src, dst)
":build.macppc.shared:PythonApplet.",
":build.macppc.shared:PythonAppletPPC.",
def buildapplet(top, dummy, list): """Create a PPC python applet""" template = mkapplet.findtemplate() for src in list: if src[-3:] != '.py': raise 'Should end in .py', src base = os.path.basename(src) dst = os.path.join(top, base)[:-3] src = os.path.join(top, src) try: os.unlink(dst) except os.error: pass print 'Building applet', dst mkapplet.process(template, src, dst)
":PlugIns:ctbmodule.ppc.",
":PlugIns:ctb.ppc.",
def buildapplet(top, dummy, list): """Create a PPC python applet""" template = mkapplet.findtemplate() for src in list: if src[-3:] != '.py': raise 'Should end in .py', src base = os.path.basename(src) dst = os.path.join(top, base)[:-3] src = os.path.join(top, src) try: os.unlink(dst) except os.error: pass print 'Building applet', dst mkapplet.process(template, src, dst)
":PlugIns:macspeechmodule.ppc.",
":PlugIns:macspeech.ppc.",
def buildapplet(top, dummy, list): """Create a PPC python applet""" template = mkapplet.findtemplate() for src in list: if src[-3:] != '.py': raise 'Should end in .py', src base = os.path.basename(src) dst = os.path.join(top, base)[:-3] src = os.path.join(top, src) try: os.unlink(dst) except os.error: pass print 'Building applet', dst mkapplet.process(template, src, dst)
":PlugIns:wastemodule.ppc.", ":PlugIns:_tkintermodule.ppc.",
":PlugIns:qtmodules.ppc.", ":PlugIns:waste.ppc.", ":PlugIns:_tkinter.ppc.",
def buildapplet(top, dummy, list): """Create a PPC python applet""" template = mkapplet.findtemplate() for src in list: if src[-3:] != '.py': raise 'Should end in .py', src base = os.path.basename(src) dst = os.path.join(top, base)[:-3] src = os.path.join(top, src) try: os.unlink(dst) except os.error: pass print 'Building applet', dst mkapplet.process(template, src, dst)
":PlugIns:ctbmodule.CFM68K.",
":PlugIns:ctb.CFM68K.", ":PlugIns:imgmodules.ppc.",
def buildapplet(top, dummy, list): """Create a PPC python applet""" template = mkapplet.findtemplate() for src in list: if src[-3:] != '.py': raise 'Should end in .py', src base = os.path.basename(src) dst = os.path.join(top, base)[:-3] src = os.path.join(top, src) try: os.unlink(dst) except os.error: pass print 'Building applet', dst mkapplet.process(template, src, dst)
":PlugIns:wastemodule.CFM68K.", ":PlugIns:_tkintermodule.CFM68K.",
":PlugIns:qtmodules.CFM68K.", ":PlugIns:waste.CFM68K.", ":PlugIns:_tkinter.CFM68K.",
def buildapplet(top, dummy, list): """Create a PPC python applet""" template = mkapplet.findtemplate() for src in list: if src[-3:] != '.py': raise 'Should end in .py', src base = os.path.basename(src) dst = os.path.join(top, base)[:-3] src = os.path.join(top, src) try: os.unlink(dst) except os.error: pass print 'Building applet', dst mkapplet.process(template, src, dst)
The function prototype can be called in three ways to create a
The function prototype can be called in different ways to create a
def CFUNCTYPE(restype, *argtypes): """CFUNCTYPE(restype, *argtypes) -> function prototype. restype: the result type argtypes: a sequence specifying the argument types The function prototype can be called in three ways to create a callable object: prototype(integer address) -> foreign function prototype(callable) -> create and return a C callable function from callable prototype(integer index, method name[, paramflags]) -> foreign function calling a COM method prototype((ordinal number, dll object)[, paramflags]) -> foreign function exported by ordinal prototype((function name, dll object)[, paramflags]) -> foreign function exported by name """ try: return _c_functype_cache[(restype, argtypes)] except KeyError: class CFunctionType(_CFuncPtr): _argtypes_ = argtypes _restype_ = restype _flags_ = _FUNCFLAG_CDECL _c_functype_cache[(restype, argtypes)] = CFunctionType return CFunctionType
(to an older frame)."""
(to a newer frame)."""
def help_d(self): print """d(own)
(to a newer frame)."""
(to an older frame)."""
def help_u(self): print """u(p)
def add_windows_to_menu(menu): registry.add_windows_to_menu(menu)
add_windows_to_menu = registry.add_windows_to_menu register_callback = registry.register_callback unregister_callback = registry.unregister_callback call_callbacks = registry.call_callbacks
def add_windows_to_menu(menu): registry.add_windows_to_menu(menu)
client address as self.client_request, and the server (in case it
client address as self.client_address, and the server (in case it
def process_request(self, request, client_address): """Start a new thread to process the request.""" import thread thread.start_new_thread(self.finish_request, (request, client_address))
if not included: self._version = dict.get('Version', '0.1') if self._version != PIMP_VERSION: sys.stderr.write("Warning: database version %s does not match %s\n"
if included: version = dict.get('Version') if version and version > self._version: sys.stderr.write("Warning: included database %s is for pimp version %s\n" % (url, version)) else: self._version = dict.get('Version') if not self._version: sys.stderr.write("Warning: database has no Version information\n") elif self._version > PIMP_VERSION: sys.stderr.write("Warning: database version %s newer than pimp version %s\n"
def appendURL(self, url, included=0): """Append packages from the database with the given URL. Only the first database should specify included=0, so the global information (maintainer, description) get stored.""" if url in self._urllist: return self._urllist.append(url) fp = urllib2.urlopen(url).fp dict = plistlib.Plist.fromFile(fp) # Test here for Pimp version, etc if not included: self._version = dict.get('Version', '0.1') if self._version != PIMP_VERSION: sys.stderr.write("Warning: database version %s does not match %s\n" % (self._version, PIMP_VERSION)) self._maintainer = dict.get('Maintainer', '') self._description = dict.get('Description', '') self._appendPackages(dict['Packages']) others = dict.get('Include', []) for url in others: self.appendURL(url, included=1)
print " -D dir Set destination directory (default: site-packages)"
print " -D dir Set destination directory" print " (default: %s)" % DEFAULT_INSTALLDIR print " -u url URL for database" print " (default: %s)" % DEFAULT_PIMPDATABASE
def _help(): print "Usage: pimp [options] -s [package ...] List installed status" print " pimp [options] -l [package ...] Show package information" print " pimp [options] -i package ... Install packages" print " pimp -d Dump database to stdout" print "Options:" print " -v Verbose" print " -f Force installation" print " -D dir Set destination directory (default: site-packages)" sys.exit(1)
opts, args = getopt.getopt(sys.argv[1:], "slifvdD:") except getopt.Error:
opts, args = getopt.getopt(sys.argv[1:], "slifvdD:Vu:") except getopt.GetoptError:
def _help(): print "Usage: pimp [options] -s [package ...] List installed status" print " pimp [options] -l [package ...] Show package information" print " pimp [options] -i package ... Install packages" print " pimp -d Dump database to stdout" print "Options:" print " -v Verbose" print " -f Force installation" print " -D dir Set destination directory (default: site-packages)" sys.exit(1)
_run(mode, verbose, force, args, prefargs)
if mode == 'version': print 'Pimp version %s; module name is %s' % (PIMP_VERSION, __name__) else: _run(mode, verbose, force, args, prefargs) if __name__ != 'pimp_update': try: import pimp_update except ImportError: pass else: if pimp_update.PIMP_VERSION <= PIMP_VERSION: import warnings warnings.warn("pimp_update is version %s, not newer than pimp version %s" % (pimp_update.PIMP_VERSION, PIMP_VERSION)) else: from pimp_update import *
def _help(): print "Usage: pimp [options] -s [package ...] List installed status" print " pimp [options] -l [package ...] Show package information" print " pimp [options] -i package ... Install packages" print " pimp -d Dump database to stdout" print "Options:" print " -v Verbose" print " -f Force installation" print " -D dir Set destination directory (default: site-packages)" sys.exit(1)
if os.path.exists (self.build_bdist)
if os.path.exists (self.build_bdist):
def run(self): # remove the build/temp.<plat> directory (unless it's already # gone) if os.path.exists (self.build_temp): remove_tree (self.build_temp, self.verbose, self.dry_run)
base = path[len(longest) + 1:].replace("/", ".")
if longest: base = path[len(longest) + 1:] else: base = path base = base.replace("/", ".")
def fullmodname(path): """Return a plausible module name for the path.""" # If the file 'path' is part of a package, then the filename isn't # enough to uniquely identify it. Try to do the right thing by # looking in sys.path for the longest matching prefix. We'll # assume that the rest is the package name. longest = "" for dir in sys.path: if path.startswith(dir) and path[len(dir)] == os.path.sep: if len(dir) > len(longest): longest = dir base = path[len(longest) + 1:].replace("/", ".") filename, ext = os.path.splitext(base) return filename
from pprint import pprint print "options (after parsing config files):" pprint (self.command_options)
parser.__init__()
def parse_config_files (self, filenames=None):
if opts.help:
if hasattr(opts, 'help') and opts.help:
def _parse_command_opts (self, parser, args):
cmd_opts[command] = ("command line", value)
cmd_opts[name] = ("command line", value)
def _parse_command_opts (self, parser, args):
cmd_obj = self.command_obj[command] = klass() self.command_run[command] = 0
cmd_obj = self.command_obj[command] = klass(self) self.have_run[command] = 0 options = self.command_options.get(command) if options: print " setting options:" for (option, (source, value)) in options.items(): print " %s = %s (from %s)" % (option, value, source) setattr(cmd_obj, option, value)
def get_command_obj (self, command, create=1): """Return the command object for 'command'. Normally this object is cached on a previous call to 'get_command_obj()'; if no comand object for 'command' is in the cache, then we either create and return it (if 'create' is true) or return None. """ cmd_obj = self.command_obj.get(command) if not cmd_obj and create: klass = self.get_command_class(command) cmd_obj = self.command_obj[command] = klass() self.command_run[command] = 0
self.default(line) return
return self.default(line)
def onecmd(self, line): line = string.strip(line) if line == '?': line = 'help' elif line == '!': if hasattr(self, 'do_shell'): line = 'shell' else: self.default(line) return elif not line: self.emptyline() return 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)
self.emptyline() return
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: self.default(line) return elif not line: self.emptyline() return 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)
left = resp.find('(') if left < 0: raise error_proto, resp right = resp.find(')', left + 1) if right < 0: raise error_proto, resp numbers = resp[left+1:right].split(',') if len(numbers) != 6:
global _227_re if _227_re is None: import re _227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)') m = _227_re.search(resp) if not m:
def parse227(resp): '''Parse the '227' response for a PASV request. Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] != '227': raise error_reply, resp left = resp.find('(') if left < 0: raise error_proto, resp right = resp.find(')', left + 1) if right < 0: raise error_proto, resp # should contain '(h1,h2,h3,h4,p1,p2)' numbers = resp[left+1:right].split(',') if len(numbers) != 6: raise error_proto, resp host = '.'.join(numbers[:4]) port = (int(numbers[4]) << 8) + int(numbers[5]) return host, port
contents = doc and doc + '\n' methods = allmethods(object).items() methods.sort() for key, value in methods: contents = contents + '\n' + self.document(value, key, mod, object) if not contents: return title + '\n'
contents = doc and [doc + '\n'] or [] push = contents.append def spill(msg, attrs, predicate): ok, attrs = _split_class_attrs(attrs, predicate) if ok: push(msg) for name, kind, homecls, value in ok: push(self.document(getattr(object, name), name, mod, object)) return attrs def spillproperties(msg, attrs): ok, attrs = _split_class_attrs(attrs, lambda t: t[1] == 'property') if ok: push(msg) for name, kind, homecls, value in ok: push(name + '\n') return attrs def spilldata(msg, attrs): ok, attrs = _split_class_attrs(attrs, lambda t: t[1] == 'data') if ok: push(msg) for name, kind, homecls, value in ok: doc = getattr(value, "__doc__", None) push(self.docother(getattr(object, name), name, mod, 70, doc) + '\n') return attrs attrs = inspect.classify_class_attrs(object) attrs, inherited = _split_class_attrs(attrs, lambda t: t[2] is object) inherited.sort(lambda t1, t2: cmp(t1[2].__name__, t2[2].__name__)) thisclass = object while attrs or inherited: if thisclass is object: tag = "defined here" else: tag = "inherited from class %s" % classname(thisclass, object.__module__) attrs.sort(lambda t1, t2: cmp(t1[0], t2[0])) attrs = spill("Methods %s:\n" % tag, attrs, lambda t: t[1] == 'method') attrs = spill("Class methods %s:\n" % tag, attrs, lambda t: t[1] == 'class method') attrs = spill("Static methods %s:\n" % tag, attrs, lambda t: t[1] == 'static method') attrs = spillproperties("Properties %s:\n" % tag, attrs) attrs = spilldata("Data %s:\n" % tag, attrs) assert attrs == [] if inherited: attrs = inherited thisclass = attrs[0][2] attrs, inherited = _split_class_attrs(attrs, lambda t: t[2] is thisclass) contents = '\n'.join(contents) if not contents: return title + '\n'
def makename(c, m=object.__module__): return classname(c, m)
def docother(self, object, name=None, mod=None, maxlen=None):
def docother(self, object, name=None, mod=None, maxlen=None, doc=None):
def docother(self, object, name=None, mod=None, maxlen=None): """Produce text documentation for a data object.""" repr = self.repr(object) if maxlen: line = (name and name + ' = ' or '') + repr chop = maxlen - len(line) if chop < 0: repr = repr[:chop] + '...' line = (name and self.bold(name) + ' = ' or '') + repr return line
return ExpatParser()
return xml.sax.make_parser()
def _getParser(): return ExpatParser()
def pickle_complex(c): return complex, (c.real, c.imag)
try: complex except NameError: pass else:
def pickle_complex(c): return complex, (c.real, c.imag)
pickle(type(1j), pickle_complex, complex)
def pickle_complex(c): return complex, (c.real, c.imag) pickle(complex, pickle_complex, complex)
def pickle_complex(c): return complex, (c.real, c.imag)
print "testing complex args"
if verbose: print "testing complex args"
exec 'def f(a): global a; a = 1'
def __init__(self, name, mode=RTLD_LOCAL, handle=None):
def __init__(self, name, mode=DEFAULT_MODE, handle=None):
def __init__(self, name, mode=RTLD_LOCAL, handle=None): self._name = name if handle is None: self._handle = _dlopen(self._name, mode) else: self._handle = handle
streamservers = [UnixStreamServer, ThreadingUnixStreamServer, ForkingUnixStreamServer]
streamservers = [UnixStreamServer, ThreadingUnixStreamServer] if hasattr(os, 'fork') and os.name not in ('os2',): streamservers.append(ForkingUnixStreamServer)
def testloop(proto, servers, hdlrcls, testfunc): for svrcls in servers: addr = pickaddr(proto) if verbose: print "ADDR =", addr print "CLASS =", svrcls t = ServerThread(addr, svrcls, hdlrcls) if verbose: print "server created" t.start() if verbose: print "server running" for i in range(NREQ): time.sleep(DELAY) if verbose: print "test client", i testfunc(proto, addr) if verbose: print "waiting for server" t.join() if verbose: print "done"
dgramservers = [UnixDatagramServer, ThreadingUnixDatagramServer, ForkingUnixDatagramServer]
dgramservers = [UnixDatagramServer, ThreadingUnixDatagramServer] if hasattr(os, 'fork') and os.name not in ('os2',): dgramservers.append(ForkingUnixDatagramServer)
def testloop(proto, servers, hdlrcls, testfunc): for svrcls in servers: addr = pickaddr(proto) if verbose: print "ADDR =", addr print "CLASS =", svrcls t = ServerThread(addr, svrcls, hdlrcls) if verbose: print "server created" t.start() if verbose: print "server running" for i in range(NREQ): time.sleep(DELAY) if verbose: print "test client", i testfunc(proto, addr) if verbose: print "waiting for server" t.join() if verbose: print "done"
except ImportError:
gzip.GzipFile except (ImportError, AttributeError):
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'"
db_incs = find_file('db_185.h', inc_dirs, []) if (db_incs is not None and self.compiler.find_library_file(lib_dirs, 'db') ):
dblib = [] if self.compiler.find_library_file(lib_dirs, 'db'): dblib = ['db'] db185_incs = find_file('db_185.h', inc_dirs, ['/usr/include/db3', '/usr/include/db2']) db_inc = find_file('db.h', inc_dirs, ['/usr/include/db1']) if db185_incs is not None:
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
include_dirs = db_incs, libraries = ['db'] ) ) else: db_incs = find_file('db.h', inc_dirs, []) if db_incs is not None: exts.append( Extension('bsddb', ['bsddbmodule.c'], include_dirs = db_incs) )
include_dirs = db185_incs, define_macros=[('HAVE_DB_185_H',1)], libraries = dblib ) ) elif db_inc is not None: exts.append( Extension('bsddb', ['bsddbmodule.c'], include_dirs = db_inc, libraries = dblib) )
def detect_modules(self): # Ensure that /usr/local is always used if '/usr/local/lib' not in self.compiler.library_dirs: self.compiler.library_dirs.append('/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.append( '/usr/local/include' )
return Carbon.Files.ResolveAliasFile(fss, chain)
return Carbon.File.ResolveAliasFile(fss, chain)
def ResolveAliasFile(fss, chain=1): return Carbon.Files.ResolveAliasFile(fss, chain)
codestring = open(pathname, 'r').read()
codestring = open(pathname, 'rU').read()
def _compile(pathname, timestamp): """Compile (and cache) a Python source file. The file specified by <pathname> is compiled to a code object and returned. Presuming the appropriate privileges exist, the bytecodes will be saved back to the filesystem for future imports. The source file's modification timestamp must be provided as a Long value. """ codestring = open(pathname, 'r').read() if codestring and codestring[-1] != '\n': codestring = codestring + '\n' code = __builtin__.compile(codestring, pathname, 'exec') # try to cache the compiled code try: f = open(pathname + _suffix_char, 'wb') except IOError: pass else: f.write('\0\0\0\0') f.write(struct.pack('<I', timestamp)) marshal.dump(code, f) f.flush() f.seek(0, 0) f.write(imp.get_magic()) f.close() return code
i = i - len(argstr)
i = i - len(argstr) - 2
def send(self, buffer): self.unfinished = self.unfinished + buffer i = 0 n = len(self.unfinished) while i < n: c = self.unfinished[i] i = i+1 if c != ESC: self.add_char(c) continue if i >= n: i = i-1 break c = self.unfinished[i] i = i+1 if c == 'c': self.reset() continue if c <> '[': self.msg('unrecognized: ESC %s', `c`) continue argstr = '' while i < n: c = self.unfinished[i] i = i+1 if c not in '0123456789;': break argstr = argstr + c else: i = i - len(argstr) break
if brightness <= 0.5:
if brightness <= 128:
def __trackarrow(self, chip, rgbtuple): # invert the last chip if self.__lastchip is not None: color = self.__canvas.itemcget(self.__lastchip, 'fill') self.__canvas.itemconfigure(self.__lastchip, outline=color) self.__lastchip = chip
_notfound = None
def execvpe(file, args, env): """execv(file, args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env , replacing the current process. args may be a list or tuple of strings. """ _execvpe(file, args, env)
global _notfound
def _execvpe(file, args, env=None): if env is not None: func = execve argrest = (args, env) else: func = execv argrest = (args,) env = environ global _notfound head, tail = path.split(file) if head: apply(func, (file,) + argrest) return if 'PATH' in env: envpath = env['PATH'] else: envpath = defpath PATH = envpath.split(pathsep) if not _notfound: if sys.platform[:4] == 'beos': # Process handling (fork, wait) under BeOS (up to 5.0) # doesn't interoperate reliably with the thread interlocking # that happens during an import. The actual error we need # is the same on BeOS for posix.open() et al., ENOENT. try: unlink('/_#.# ## #.#') except error, _notfound: pass else: import tempfile t = tempfile.mktemp() # Exec a file that is guaranteed not to exist try: execv(t, ('blah',)) except error, _notfound: pass exc, arg = error, _notfound for dir in PATH: fullname = path.join(dir, file) try: apply(func, (fullname,) + argrest) except error, (errno, msg): if errno != arg[0]: exc, arg = error, (errno, msg) raise exc, arg
if not _notfound: if sys.platform[:4] == 'beos': try: unlink('/_ except error, _notfound: pass else: import tempfile t = tempfile.mktemp() try: execv(t, ('blah',)) except error, _notfound: pass exc, arg = error, _notfound
def _execvpe(file, args, env=None): if env is not None: func = execve argrest = (args, env) else: func = execv argrest = (args,) env = environ global _notfound head, tail = path.split(file) if head: apply(func, (file,) + argrest) return if 'PATH' in env: envpath = env['PATH'] else: envpath = defpath PATH = envpath.split(pathsep) if not _notfound: if sys.platform[:4] == 'beos': # Process handling (fork, wait) under BeOS (up to 5.0) # doesn't interoperate reliably with the thread interlocking # that happens during an import. The actual error we need # is the same on BeOS for posix.open() et al., ENOENT. try: unlink('/_#.# ## #.#') except error, _notfound: pass else: import tempfile t = tempfile.mktemp() # Exec a file that is guaranteed not to exist try: execv(t, ('blah',)) except error, _notfound: pass exc, arg = error, _notfound for dir in PATH: fullname = path.join(dir, file) try: apply(func, (fullname,) + argrest) except error, (errno, msg): if errno != arg[0]: exc, arg = error, (errno, msg) raise exc, arg
if errno != arg[0]: exc, arg = error, (errno, msg) raise exc, arg
if errno != ENOENT and errno != ENOTDIR: raise raise error, (errno, msg)
def _execvpe(file, args, env=None): if env is not None: func = execve argrest = (args, env) else: func = execv argrest = (args,) env = environ global _notfound head, tail = path.split(file) if head: apply(func, (file,) + argrest) return if 'PATH' in env: envpath = env['PATH'] else: envpath = defpath PATH = envpath.split(pathsep) if not _notfound: if sys.platform[:4] == 'beos': # Process handling (fork, wait) under BeOS (up to 5.0) # doesn't interoperate reliably with the thread interlocking # that happens during an import. The actual error we need # is the same on BeOS for posix.open() et al., ENOENT. try: unlink('/_#.# ## #.#') except error, _notfound: pass else: import tempfile t = tempfile.mktemp() # Exec a file that is guaranteed not to exist try: execv(t, ('blah',)) except error, _notfound: pass exc, arg = error, _notfound for dir in PATH: fullname = path.join(dir, file) try: apply(func, (fullname,) + argrest) except error, (errno, msg): if errno != arg[0]: exc, arg = error, (errno, msg) raise exc, arg
info = metadata.long_description or '' + '\n'
info = (metadata.long_description or '') + '\n'
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
prog = open(filename).read()
prog = open(filename, "rU").read()
def find_executable_linenos(filename): """Return dict where keys are line numbers in the line number table.""" assert filename.endswith('.py') try: prog = open(filename).read() except IOError, err: print >> sys.stderr, ("Not printing coverage data for %r: %s" % (filename, err)) return {} code = compile(prog, filename, "exec") strs = find_strings(filename) return find_lines(code, strs)
import sys
def __init__(self, indent=1, width=80, depth=None, stream=None): """Handle pretty printing operations onto a stream using a set of configured parameters.
if not (typ in (DictType, ListType, TupleType) and object):
if not (typ in (DictType, ListType, TupleType, StringType) and object):
def _safe_repr(object, context, maxlevels=None, level=0): level += 1 typ = type(object) if not (typ in (DictType, ListType, TupleType) and object): rep = `object` return rep, (rep and (rep[0] != '<')), 0 if context.has_key(id(object)): return `_Recursion(object)`, 0, 1 objid = id(object) context[objid] = 1 readable = 1 recursive = 0 startchar, endchar = {ListType: "[]", TupleType: "()", DictType: "{}"}[typ] if maxlevels and level > maxlevels: with_commas = "..." readable = 0 elif typ is DictType: components = [] for k, v in object.iteritems(): krepr, kreadable, krecur = _safe_repr(k, context, maxlevels, level) vrepr, vreadable, vrecur = _safe_repr(v, context, maxlevels, level) components.append("%s: %s" % (krepr, vrepr)) readable = readable and kreadable and vreadable recursive = recursive or krecur or vrecur with_commas = ", ".join(components) else: # list or tuple assert typ in (ListType, TupleType) components = [] for element in object: subrepr, subreadable, subrecur = _safe_repr( element, context, maxlevels, level) components.append(subrepr) readable = readable and subreadable recursive = recursive or subrecur if len(components) == 1 and typ is TupleType: components[0] += "," with_commas = ", ".join(components) s = "%s%s%s" % (startchar, with_commas, endchar) del context[objid] return s, readable and not recursive, recursive
def test_varsized_array(self): array = (c_int * 20)(20, 21, 22, 23, 24, 25, 26, 27, 28, 29) varsize_array = (c_int * 1).from_address(addressof(array)) self.failUnlessEqual(varsize_array[0], 20) self.failUnlessEqual(varsize_array[1], 21) self.failUnlessEqual(varsize_array[2], 22) self.failUnlessEqual(varsize_array[3], 23) self.failUnlessEqual(varsize_array[4], 24) self.failUnlessEqual(varsize_array[5], 25) self.failUnlessEqual(varsize_array[6], 26) self.failUnlessEqual(varsize_array[7], 27) self.failUnlessEqual(varsize_array[8], 28) self.failUnlessEqual(varsize_array[9], 29) self.failUnlessEqual(varsize_array[-1], 20) self.failUnlessRaises(IndexError, lambda: varsize_array[-2]) self.failUnlessRaises(MemoryError, lambda: varsize_array[:]) varsize_array[0] = 100 varsize_array[1] = 101 varsize_array[2] = 102 varsize_array[3] = 103 varsize_array[4] = 104 varsize_array[5] = 105 varsize_array[6] = 106 varsize_array[7] = 107 varsize_array[8] = 108 varsize_array[9] = 109 for i in range(10): self.failUnlessEqual(varsize_array[i], i + 100) self.failUnlessEqual(array[i], i + 100) self.failUnlessEqual(varsize_array[0:10], range(100, 110)) self.failUnlessEqual(varsize_array[1:9], range(101, 109)) self.failUnlessEqual(varsize_array[1:-1], []) varsize_array[0:10] = range(1000, 1010) self.failUnlessEqual(varsize_array[0:10], range(1000, 1010)) varsize_array[1:9] = range(1001, 1009) self.failUnlessEqual(varsize_array[1:9], range(1001, 1009)) def test_vararray_is_sane(self): array = (c_int * 15)(20, 21, 22, 23, 24, 25, 26, 27, 28, 29) varsize_array = (c_int * 1).from_address(addressof(array)) varsize_array[:] = [1, 2, 3, 4, 5] self.failUnlessEqual(array[:], [1, 2, 3, 4, 5, 25, 26, 27, 28, 29, 0, 0, 0, 0, 0]) self.failUnlessEqual(varsize_array[0:10], [1, 2, 3, 4, 5, 25, 26, 27, 28, 29]) array[:5] = [10, 11, 12, 13, 14] self.failUnlessEqual(array[:], [10, 11, 12, 13, 14, 25, 26, 27, 28, 29, 0, 0, 0, 0, 0]) self.failUnlessEqual(varsize_array[0:10], [10, 11, 12, 13, 14, 25, 26, 27, 28, 29])
def test_varsized_array(self): array = (c_int * 20)(20, 21, 22, 23, 24, 25, 26, 27, 28, 29)