rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
elif op1.sign == -1: result.sign = -1 op1.sign, op2.sign = (1, 1)
elif op1.sign == 1: result.sign = 1 op1.sign, op2.sign = (0, 0)
def __add__(self, other, context=None): """Returns self + other.
if op2.sign == 1:
if op2.sign == 0:
def __add__(self, other, context=None): """Returns self + other.
if sign: sign = -1 else: sign = 1 adjust = 0
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
if isinstance(value, Decimal): if value._sign: self.sign = -1 else: self.sign = 1
elif isinstance(value, Decimal): self.sign = value._sign
def __init__(self, value=None): if value is None: self.sign = None self.int = 0 self.exp = None if isinstance(value, Decimal): if value._sign: self.sign = -1 else: self.sign = 1 cum = 0 for digit in value._int: cum = cum * 10 + digit self.int = cum self.exp = value._exp if isinstance(value, tuple): self.sign = value[0] self.int = value[1] self.exp = value[2]
if isinstance(value, tuple):
else:
def __init__(self, value=None): if value is None: self.sign = None self.int = 0 self.exp = None if isinstance(value, Decimal): if value._sign: self.sign = -1 else: self.sign = 1 cum = 0 for digit in value._int: cum = cum * 10 + digit self.int = cum self.exp = value._exp if isinstance(value, tuple): self.sign = value[0] self.int = value[1] self.exp = value[2]
def __neg__(self): if self.sign == 1: return _WorkRep( (-1, self.int, self.exp) ) else: return _WorkRep( (1, self.int, self.exp) ) def __abs__(self): if self.sign == -1: return -self else: return self def __cmp__(self, other): if self.exp != other.exp: raise ValueError("Operands not normalized: %r, %r" % (self, other)) if self.sign != other.sign: if self.sign == -1: return -1 else: return 1 if self.sign == -1: direction = -1 else: direction = 1 int1 = self.int int2 = other.int if int1 > int2: return direction * 1 if int1 < int2: return direction * -1 return 0
def __repr__(self): return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
self._parser.ProcessingInstructionHandler = \ self._cont_handler.processingInstruction self._parser.CharacterDataHandler = self._cont_handler.characters
self._reset_cont_handler()
def reset(self): if self._namespaces: self._parser = expat.ParserCreate(None, " ") self._parser.StartElementHandler = self.start_element_ns self._parser.EndElementHandler = self.end_element_ns else: self._parser = expat.ParserCreate() self._parser.StartElementHandler = self.start_element self._parser.EndElementHandler = self.end_element
self._parser.CommentHandler = self._lex_handler_prop.comment self._parser.StartCdataSectionHandler = self._lex_handler_prop.startCDATA self._parser.EndCdataSectionHandler = self._lex_handler_prop.endCDATA
self._reset_lex_handler_prop()
def reset(self): if self._namespaces: self._parser = expat.ParserCreate(None, " ") self._parser.StartElementHandler = self.start_element_ns self._parser.EndElementHandler = self.end_element_ns else: self._parser = expat.ParserCreate() self._parser.StartElementHandler = self.start_element self._parser.EndElementHandler = self.end_element
if string.lower(filename[-3:]) == '.py' and os.path.exists(filename):
for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: return None if os.path.exists(filename):
def getsourcefile(object): """Return the Python source file an object was defined in, if it exists.""" filename = getfile(object) if string.lower(filename[-4:]) in ['.pyc', '.pyo']: filename = filename[:-4] + '.py' if string.lower(filename[-3:]) == '.py' and os.path.exists(filename): return filename
try:
if hasattr(main, object.__name__):
def getmodule(object): """Try to guess which module an object was defined in.""" if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] for module in sys.modules.values(): if hasattr(module, '__file__'): modulesbyfile[getabsfile(module)] = module.__name__ if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] main = sys.modules['__main__'] try: mainobject = getattr(main, object.__name__) if mainobject is object: return main except AttributeError: pass builtin = sys.modules['__builtin__'] try: builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin except AttributeError: pass
if mainobject is object: return main except AttributeError: pass
if mainobject is object: return main
def getmodule(object): """Try to guess which module an object was defined in.""" if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] for module in sys.modules.values(): if hasattr(module, '__file__'): modulesbyfile[getabsfile(module)] = module.__name__ if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] main = sys.modules['__main__'] try: mainobject = getattr(main, object.__name__) if mainobject is object: return main except AttributeError: pass builtin = sys.modules['__builtin__'] try: builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin except AttributeError: pass
try:
if hasattr(builtin, object.__name__):
def getmodule(object): """Try to guess which module an object was defined in.""" if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] for module in sys.modules.values(): if hasattr(module, '__file__'): modulesbyfile[getabsfile(module)] = module.__name__ if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] main = sys.modules['__main__'] try: mainobject = getattr(main, object.__name__) if mainobject is object: return main except AttributeError: pass builtin = sys.modules['__builtin__'] try: builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin except AttributeError: pass
if builtinobject is object: return builtin except AttributeError: pass
if builtinobject is object: return builtin
def getmodule(object): """Try to guess which module an object was defined in.""" if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] for module in sys.modules.values(): if hasattr(module, '__file__'): modulesbyfile[getabsfile(module)] = module.__name__ if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] main = sys.modules['__main__'] try: mainobject = getattr(main, object.__name__) if mainobject is object: return main except AttributeError: pass builtin = sys.modules['__builtin__'] try: builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin except AttributeError: pass
lines = file.readlines() file.close()
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) lines = file.readlines() file.close() except (TypeError, IOError): raise IOError, 'could not get source code' if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ matches = (['class', name], ['class', name + ':']) for i in range(len(lines)): if string.split(lines[i])[:2] in matches: return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): try: lnum = object.co_firstlineno - 1 except AttributeError: raise IOError, 'could not find function definition' else: while lnum > 0: if string.split(lines[lnum])[:1] == ['def']: break lnum = lnum - 1 return lines, lnum
try: lnum = object.co_firstlineno - 1 except AttributeError:
if not hasattr(object, 'co_firstlineno'):
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) lines = file.readlines() file.close() except (TypeError, IOError): raise IOError, 'could not get source code' if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ matches = (['class', name], ['class', name + ':']) for i in range(len(lines)): if string.split(lines[i])[:2] in matches: return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): try: lnum = object.co_firstlineno - 1 except AttributeError: raise IOError, 'could not find function definition' else: while lnum > 0: if string.split(lines[lnum])[:1] == ['def']: break lnum = lnum - 1 return lines, lnum
else: while lnum > 0: if string.split(lines[lnum])[:1] == ['def']: break lnum = lnum - 1 return lines, lnum
lnum = object.co_firstlineno - 1 while lnum > 0: if string.split(lines[lnum])[:1] == ['def']: break lnum = lnum - 1 return lines, lnum
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) lines = file.readlines() file.close() except (TypeError, IOError): raise IOError, 'could not get source code' if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ matches = (['class', name], ['class', name + ':']) for i in range(len(lines)): if string.split(lines[i])[:2] in matches: return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): try: lnum = object.co_firstlineno - 1 except AttributeError: raise IOError, 'could not find function definition' else: while lnum > 0: if string.split(lines[lnum])[:1] == ['def']: break lnum = lnum - 1 return lines, lnum
except: return None
except IOError: return None
def getcomments(object): """Get lines of comments immediately preceding an object's source code.""" try: lines, lnum = findsource(object) except: return None if ismodule(object): # Look for a comment block at the top of the file. start = 0 if lines[0][:2] == '#!': start = 1 while start < len(lines) and string.strip(lines[start]) in ['', '#']: start = start + 1 if lines[start][:1] == '#': comments = [] end = start while end < len(lines) and lines[end][:1] == '#': comments.append(string.expandtabs(lines[end])) end = end + 1 return string.join(comments, '') # Look for a preceding block of comments at the same indentation. elif lnum > 0: indent = indentsize(lines[lnum]) end = lnum - 1 if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \ indentsize(lines[end]) == indent: comments = [string.lstrip(string.expandtabs(lines[end]))] if end > 0: end = end - 1 comment = string.lstrip(string.expandtabs(lines[end])) while comment[:1] == '#' and indentsize(lines[end]) == indent: comments[:0] = [comment] end = end - 1 if end < 0: break comment = string.lstrip(string.expandtabs(lines[end])) while comments and string.strip(comments[0]) == '#': comments[:1] = [] while comments and string.strip(comments[-1]) == '#': comments[-1:] = [] return string.join(comments, '')
except IOError: lines = index = None
def getframeinfo(frame, context=1): """Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line.""" if istraceback(frame): frame = frame.tb_frame if not isframe(frame): raise TypeError, 'arg is not a frame or traceback object' filename = getsourcefile(frame) lineno = getlineno(frame) if context > 0: start = lineno - 1 - context/2 try: lines, lnum = findsource(frame) start = max(start, 1) start = min(start, len(lines) - context) lines = lines[start:start+context] index = lineno - 1 - start except IOError: lines = index = None else: lines = index = None return (filename, lineno, frame.f_code.co_name, lines, index)
bytes = "" while 1: line = self.rfile.readline() bytes = bytes + line if line == '\r\n' or line == '\n' or line == '': break
def parse_request(self): """Parse a request (internal).
hfile = cStringIO.StringIO(bytes) self.headers = self.MessageClass(hfile)
self.headers = self.MessageClass(self.rfile, 0)
def parse_request(self): """Parse a request (internal).
MIN_SQLITE_VERSION_NUMBER = 3000008 MIN_SQLITE_VERSION = "3.0.8"
MIN_SQLITE_VERSION_NUMBER = (3, 0, 8) MIN_SQLITE_VERSION = ".".join([str(x) for x in MIN_SQLITE_VERSION_NUMBER])
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
f = open(f).read() m = re.search(r"
incf = open(f).read() m = re.search( r'\s*.*
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
sqlite_version = int(m.group(1)) if sqlite_version >= MIN_SQLITE_VERSION_NUMBER:
sqlite_version = m.group(1) sqlite_version_tuple = tuple([int(x) for x in sqlite_version.split(".")]) if sqlite_version_tuple >= MIN_SQLITE_VERSION_NUMBER:
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
elif sqlite_version == 3000000: if sqlite_setup_debug: print "found buggy SQLITE_VERSION_NUMBER, checking" m = re.search(r' f) if m: sqlite_version = m.group(1) if sqlite_version >= MIN_SQLITE_VERSION: print "%s/sqlite3.h: version %s"%(d, sqlite_version) sqlite_incdir = d break
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
elif sqlite_setup_debug: print "sqlite: %s had no SQLITE_VERSION"%(f,)
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
def walktree(name, change): if os.path.isfile(name): for ext, cr, tp in list: if name[-len(ext):] == ext: fs = macfs.FSSpec(name) curcrtp = fs.GetCreatorType() if curcrtp <> (cr, tp): if change: fs.SetCreatorType(cr, tp) print 'Fixed ', name else: print 'Wrong', curcrtp, name elif os.path.isdir(name): print '->', name files = os.listdir(name) for f in files: walktree(os.path.join(name, f), change)
def mkalias(src, dst): """Create a finder alias""" srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) alias = srcfss.NewAlias() srcfinfo = srcfss.GetFInfo() Res.FSpCreateResFile(dstfss, srcfinfo.Creator, srcfinfo.Type, -1) h = Res.FSpOpenResFile(dstfss, 3) resource = Res.Resource(alias.data) resource.AddResource('alis', 0, '') Res.CloseResFile(h) dstfinfo = dstfss.GetFInfo() dstfinfo.Flags = dstfinfo.Flags|0x8000 dstfss.SetFInfo(dstfinfo) def main(): dir, ok = macfs.GetDirectory() if not ok: sys.exit(0) os.chdir(dir.as_pathname()) if EasyDialogs.AskYesNoCancel('Proceed with removing old aliases?') <= 0: sys.exit(0) LibFiles = [] allfiles = os.listdir(':') for f in allfiles: if f[-4:] == '.slb': finfo = macfs.FSSpec(f).GetFInfo() if finfo.Flags & 0x8000: os.unlink(f) else: LibFiles.append(f) print LibFiles if EasyDialogs.AskYesNoCancel('Proceed with creating new ones?') <= 0: sys.exit(0) for dst, src in goals: if src in LibFiles: mkalias(src, dst) else: EasyDialogs.Message(dst+' not created: '+src+' not found')
def walktree(name, change): if os.path.isfile(name): for ext, cr, tp in list: if name[-len(ext):] == ext: fs = macfs.FSSpec(name) curcrtp = fs.GetCreatorType() if curcrtp <> (cr, tp): if change: fs.SetCreatorType(cr, tp) print 'Fixed ', name else: print 'Wrong', curcrtp, name elif os.path.isdir(name): print '->', name files = os.listdir(name) for f in files: walktree(os.path.join(name, f), change)
def run(change): fss, ok = macfs.GetDirectory() if not ok: sys.exit(0) walktree(fss.as_pathname(), change)
EasyDialogs.Message('All done!')
def run(change): fss, ok = macfs.GetDirectory() if not ok: sys.exit(0) walktree(fss.as_pathname(), change)
run(1)
main()
def run(change): fss, ok = macfs.GetDirectory() if not ok: sys.exit(0) walktree(fss.as_pathname(), change)
InteractiveInterpreter.__init__(self)
locals = sys.modules['__main__'].__dict__ InteractiveInterpreter.__init__(self, locals=locals)
def __init__(self, tkconsole): self.tkconsole = tkconsole InteractiveInterpreter.__init__(self)
filename = self.stuffsource(source) self.more = 0 return InteractiveInterpreter.runsource(self, source, filename) def stuffsource(self, source):
def runsource(self, source): # Extend base class to stuff the source in the line cache filename = "<pyshell#%d>" % self.gid self.gid = self.gid + 1 lines = string.split(source, "\n") linecache.cache[filename] = len(source)+1, 0, lines, filename self.more = 0 return InteractiveInterpreter.runsource(self, source, filename)
self.more = 0 return InteractiveInterpreter.runsource(self, source, filename)
return filename
def runsource(self, source): # Extend base class to stuff the source in the line cache filename = "<pyshell#%d>" % self.gid self.gid = self.gid + 1 lines = string.split(source, "\n") linecache.cache[filename] = len(source)+1, 0, lines, filename self.more = 0 return InteractiveInterpreter.runsource(self, source, filename)
if char in string.letters + string.digits + "_":
if char and char in string.letters + string.digits + "_":
def showsyntaxerror(self, filename=None): # Extend base class to color the offending position # (instead of printing it and pointing at it with a caret) text = self.tkconsole.text stuff = self.unpackerror() if not stuff: self.tkconsole.resetoutput() InteractiveInterpreter.showsyntaxerror(self, filename) return msg, lineno, offset, line = stuff if lineno == 1: pos = "iomark + %d chars" % (offset-1) else: pos = "iomark linestart + %d lines + %d chars" % (lineno-1, offset-1) text.tag_add("ERROR", pos) text.see(pos) char = text.get(pos) if char in string.letters + string.digits + "_": text.tag_add("ERROR", pos + " wordstart", pos) self.tkconsole.resetoutput() self.write("SyntaxError: %s\n" % str(msg))
ok = type == SyntaxError
ok = type is SyntaxError
def unpackerror(self): type, value, tb = sys.exc_info() ok = type == SyntaxError if ok: try: msg, (dummy_filename, lineno, offset, line) = value except: ok = 0 if ok: return msg, lineno, offset, line else: return None
sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.stdin = sys.__stdin__
sys.stdout = self.save_stdout sys.stderr = self.save_stderr sys.stdin = self.save_stdin
def close(self): # Extend base class method if self.executing: # XXX Need to ask a question here if not tkMessageBox.askokcancel( "Kill?", "The program is still running; do you want to kill it?", default="ok", master=self.text): return "cancel" self.canceled = 1 if self.reading: self.top.quit() return "cancel" reply = PyShellEditorWindow.close(self) if reply != "cancel": self.flist.pyshell = None # Restore std streams sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.stdin = sys.__stdin__ # Break cycles self.interp = None self.console = None return reply
return "Python Shell"
return self.shell_title
def short_title(self): return "Python Shell"
opts, args = getopt.getopt(sys.argv[1:], "d")
opts, args = getopt.getopt(sys.argv[1:], "c:deist:")
def main(): debug = 0 try: opts, args = getopt.getopt(sys.argv[1:], "d") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.exit(2) for o, a in opts: if o == "-d": debug = 1 global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) if args: for filename in sys.argv[1:]: flist.open(filename) aPath = os.path.abspath(os.path.dirname(filename)) if not aPath in sys.path: sys.path.insert(0, aPath) else: aPath = os.getcwd() if not aPath in sys.path: sys.path.insert(0, aPath) t = PyShell(flist) flist.pyshell = t t.begin() if debug: t.open_debugger() root.mainloop()
if o == "-d":
if o == '-c': cmd = a if o == '-d':
def main(): debug = 0 try: opts, args = getopt.getopt(sys.argv[1:], "d") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.exit(2) for o, a in opts: if o == "-d": debug = 1 global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) if args: for filename in sys.argv[1:]: flist.open(filename) aPath = os.path.abspath(os.path.dirname(filename)) if not aPath in sys.path: sys.path.insert(0, aPath) else: aPath = os.getcwd() if not aPath in sys.path: sys.path.insert(0, aPath) t = PyShell(flist) flist.pyshell = t t.begin() if debug: t.open_debugger() root.mainloop()
if args: for filename in sys.argv[1:]:
if edit: for filename in args:
def main(): debug = 0 try: opts, args = getopt.getopt(sys.argv[1:], "d") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.exit(2) for o, a in opts: if o == "-d": debug = 1 global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) if args: for filename in sys.argv[1:]: flist.open(filename) aPath = os.path.abspath(os.path.dirname(filename)) if not aPath in sys.path: sys.path.insert(0, aPath) else: aPath = os.getcwd() if not aPath in sys.path: sys.path.insert(0, aPath) t = PyShell(flist) flist.pyshell = t t.begin() if debug: t.open_debugger() root.mainloop()
aPath = os.path.abspath(os.path.dirname(filename)) if not aPath in sys.path: sys.path.insert(0, aPath) else: aPath = os.getcwd() if not aPath in sys.path: sys.path.insert(0, aPath) t = PyShell(flist) flist.pyshell = t t.begin()
shell = PyShell(flist) interp = shell.interp flist.pyshell = shell if startup: filename = os.environ.get("IDLESTARTUP") or \ os.environ.get("PYTHONSTARTUP") if filename and os.path.isfile(filename): interp.execfile(filename)
def main(): debug = 0 try: opts, args = getopt.getopt(sys.argv[1:], "d") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.exit(2) for o, a in opts: if o == "-d": debug = 1 global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) if args: for filename in sys.argv[1:]: flist.open(filename) aPath = os.path.abspath(os.path.dirname(filename)) if not aPath in sys.path: sys.path.insert(0, aPath) else: aPath = os.getcwd() if not aPath in sys.path: sys.path.insert(0, aPath) t = PyShell(flist) flist.pyshell = t t.begin() if debug: t.open_debugger() root.mainloop()
t.open_debugger()
shell.open_debugger() if cmd: interp.execsource(cmd) elif not edit and args and args[0] != "-": interp.execfile(args[0]) shell.begin()
def main(): debug = 0 try: opts, args = getopt.getopt(sys.argv[1:], "d") except getopt.error, msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.exit(2) for o, a in opts: if o == "-d": debug = 1 global flist, root root = Tk() fixwordbreaks(root) root.withdraw() flist = PyShellFileList(root) if args: for filename in sys.argv[1:]: flist.open(filename) aPath = os.path.abspath(os.path.dirname(filename)) if not aPath in sys.path: sys.path.insert(0, aPath) else: aPath = os.getcwd() if not aPath in sys.path: sys.path.insert(0, aPath) t = PyShell(flist) flist.pyshell = t t.begin() if debug: t.open_debugger() root.mainloop()
self.apply() self.cancel()
try: self.apply() finally: self.cancel()
def ok(self, event=None):
if debuginfo: self.move_file(debuginfo[0], self.dist_dir)
def run (self):
if platform not in ['cygwin']: exts.append( Extension('resource', ['resource.c']) )
exts.append( Extension('resource', ['resource.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.insert(0, '/usr/local/lib') if '/usr/local/include' not in self.compiler.include_dirs: self.compiler.include_dirs.insert(0, '/usr/local/include' )
if short_first: self.format_option_strings = self.format_option_strings_short_first else: self.format_option_strings = self.format_option_strings_long_first
self.short_first = short_first
def __init__ (self, indent_increment, max_help_position, width, short_first): self.indent_increment = indent_increment self.help_position = self.max_help_position = max_help_position self.width = width self.current_indent = 0 self.level = 0 self.help_width = width - max_help_position if short_first: self.format_option_strings = self.format_option_strings_short_first else: self.format_option_strings = self.format_option_strings_long_first
raise NotImplementedError( "abstract method: use format_option_strings_short_first or " "format_option_strings_long_first instead.") def format_option_strings_short_first (self, option): opts = [] takes_value = option.takes_value() if takes_value:
if option.takes_value():
def format_option_strings (self, option): """Return a comma-separated list of option strings & metavariables.""" raise NotImplementedError( "abstract method: use format_option_strings_short_first or " "format_option_strings_long_first instead.")
for sopt in option._short_opts: opts.append(sopt + metavar) for lopt in option._long_opts: opts.append(lopt + "=" + metavar) else: for opt in option._short_opts + option._long_opts: opts.append(opt)
short_opts = [sopt + metavar for sopt in option._short_opts] long_opts = [lopt + "=" + metavar for lopt in option._long_opts] else: short_opts = option._short_opts long_opts = option._long_opts if self.short_first: opts = short_opts + long_opts else: opts = long_opts + short_opts
def format_option_strings_short_first (self, option): opts = [] # list of "-a" or "--foo=FILE" strings takes_value = option.takes_value() if takes_value: metavar = option.metavar or option.dest.upper() for sopt in option._short_opts: opts.append(sopt + metavar) for lopt in option._long_opts: opts.append(lopt + "=" + metavar) else: for opt in option._short_opts + option._long_opts: opts.append(opt) return ", ".join(opts)
def format_option_strings_long_first (self, option): opts = [] takes_value = option.takes_value() if takes_value: metavar = option.metavar or option.dest.upper() for lopt in option._long_opts: opts.append(lopt + "=" + metavar) for sopt in option._short_opts: opts.append(sopt + metavar) else: for opt in option._long_opts + option._short_opts: opts.append(opt) return ", ".join(opts)
def format_option_strings_short_first (self, option): opts = [] # list of "-a" or "--foo=FILE" strings takes_value = option.takes_value() if takes_value: metavar = option.metavar or option.dest.upper() for sopt in option._short_opts: opts.append(sopt + metavar) for lopt in option._long_opts: opts.append(lopt + "=" + metavar) else: for opt in option._short_opts + option._long_opts: opts.append(opt) return ", ".join(opts)
self._short_opts = [] self._long_opts = []
def __init__ (self, *opts, **attrs): # Set _short_opts, _long_opts attrs from 'opts' tuple opts = self._check_opt_strings(opts) self._set_opt_strings(opts)
raise OptionError("at least one option string must be supplied", self)
raise TypeError("at least one option string must be supplied")
def _check_opt_strings (self, opts): # Filter out None because early versions of Optik had exactly # one short option and one long option, either of which # could be None. opts = filter(None, opts) if not opts: raise OptionError("at least one option string must be supplied", self) return opts
self._short_opts = [] self._long_opts = []
def _set_opt_strings (self, opts): self._short_opts = [] self._long_opts = [] for opt in opts: if len(opt) < 2: raise OptionError( "invalid option string %r: " "must be at least two characters long" % opt, self) elif len(opt) == 2: if not (opt[0] == "-" and opt[1] != "-"): raise OptionError( "invalid short option string %r: " "must be of the form -x, (x any non-dash char)" % opt, self) self._short_opts.append(opt) else: if not (opt[0:2] == "--" and opt[2] != "-"): raise OptionError( "invalid long option string %r: " "must start with --, followed by non-dash" % opt, self) self._long_opts.append(opt)
if self._short_opts or self._long_opts: return "/".join(self._short_opts + self._long_opts) else: raise RuntimeError, "short_opts and long_opts both empty!"
return "/".join(self._short_opts + self._long_opts)
def __str__ (self): if self._short_opts or self._long_opts: return "/".join(self._short_opts + self._long_opts) else: raise RuntimeError, "short_opts and long_opts both empty!"
setattr(values, dest, 1)
setattr(values, dest, True)
def take_action (self, action, dest, opt, value, values, parser): if action == "store": setattr(values, dest, value) elif action == "store_const": setattr(values, dest, self.const) elif action == "store_true": setattr(values, dest, 1) elif action == "store_false": setattr(values, dest, 0) elif action == "append": values.ensure_value(dest, []).append(value) elif action == "count": setattr(values, dest, values.ensure_value(dest, 0) + 1) elif action == "callback": args = self.callback_args or () kwargs = self.callback_kwargs or {} self.callback(self, opt, value, parser, *args, **kwargs) elif action == "help": parser.print_help() sys.exit(0) elif action == "version": parser.print_version() sys.exit(0) else: raise RuntimeError, "unknown action %r" % self.action
setattr(values, dest, 0)
setattr(values, dest, False)
def take_action (self, action, dest, opt, value, values, parser): if action == "store": setattr(values, dest, value) elif action == "store_const": setattr(values, dest, self.const) elif action == "store_true": setattr(values, dest, 1) elif action == "store_false": setattr(values, dest, 0) elif action == "append": values.ensure_value(dest, []).append(value) elif action == "count": setattr(values, dest, values.ensure_value(dest, 0) + 1) elif action == "callback": args = self.callback_args or () kwargs = self.callback_kwargs or {} self.callback(self, opt, value, parser, *args, **kwargs) elif action == "help": parser.print_help() sys.exit(0) elif action == "version": parser.print_version() sys.exit(0) else: raise RuntimeError, "unknown action %r" % self.action
your program (os.path.basename(sys.argv[0])).
your program (self.prog or os.path.basename(sys.argv[0])). prog : string the name of the current program (to override os.path.basename(sys.argv[0])).
def format_help (self, formatter): result = formatter.format_heading(self.title) formatter.indent() result += OptionContainer.format_help(self, formatter) formatter.dedent() return result
add_help_option=1):
add_help_option=1, prog=None):
def __init__ (self, usage=None, option_list=None, option_class=Option, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=1): OptionContainer.__init__( self, option_class, conflict_handler, description) self.set_usage(usage) self.version = version self.allow_interspersed_args = 1 if formatter is None: formatter = IndentedHelpFormatter() self.formatter = formatter
spawn(("gpg", "--detach-sign", "-a", filename),
gpg_args = ["gpg", "--detach-sign", "-a", filename] if self.identity: gpg_args[2:2] = ["--local-user", self.identity] spawn(gpg_args,
def upload_file(self, command, pyversion, filename): # Sign if requested if self.sign: spawn(("gpg", "--detach-sign", "-a", filename), dry_run=self.dry_run)
... self.close = self.generator.close
... def __init__(self, name):
>>> for s in sets: s.close()
... def __str__(self):
... self.close = g.close
... def __init__(self, g):
>>> m235.close()
>>> def m235():
>>> fib.close()
... def tail(g):
exclude=0, single=0, randomize=0, leakdebug=0,
exclude=0, single=0, randomize=0, findleaks=0,
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, leakdebug=0, use_large_resources=0): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other seven default arguments (verbose, quiet, generate, exclude, single, randomize, and leakdebug) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ try: opts, args = getopt.getopt(sys.argv[1:], 'vgqxsrl', ['have-resources']) except getopt.error, msg: print msg print __doc__ return 2 for o, a in opts: if o == '-v': verbose = verbose+1 if o == '-q': quiet = 1; verbose = 0 if o == '-g': generate = 1 if o == '-x': exclude = 1 if o == '-s': single = 1 if o == '-r': randomize = 1 if o == '-l': leakdebug = 1 if o == '--have-resources': use_large_resources = 1 if generate and verbose: print "-g and -v don't go together!" return 2 good = [] bad = [] skipped = [] if leakdebug: try: import gc except ImportError: print 'cycle garbage collection not available' else: gc.set_debug(gc.DEBUG_LEAK) if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = string.strip(fp.read()) tests = [next] fp.close() except IOError: pass for i in range(len(args)): # Strip trailing ".py" from arguments if args[i][-3:] == '.py': args[i] = args[i][:-3] stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_large_resources = use_large_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if bad: print count(len(bad), "test"), "failed:", print string.join(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:", print string.join(skipped) if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) return len(bad) > 0
single, randomize, and leakdebug) allow programmers calling main()
single, randomize, and findleaks) allow programmers calling main()
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, leakdebug=0, use_large_resources=0): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other seven default arguments (verbose, quiet, generate, exclude, single, randomize, and leakdebug) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ try: opts, args = getopt.getopt(sys.argv[1:], 'vgqxsrl', ['have-resources']) except getopt.error, msg: print msg print __doc__ return 2 for o, a in opts: if o == '-v': verbose = verbose+1 if o == '-q': quiet = 1; verbose = 0 if o == '-g': generate = 1 if o == '-x': exclude = 1 if o == '-s': single = 1 if o == '-r': randomize = 1 if o == '-l': leakdebug = 1 if o == '--have-resources': use_large_resources = 1 if generate and verbose: print "-g and -v don't go together!" return 2 good = [] bad = [] skipped = [] if leakdebug: try: import gc except ImportError: print 'cycle garbage collection not available' else: gc.set_debug(gc.DEBUG_LEAK) if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = string.strip(fp.read()) tests = [next] fp.close() except IOError: pass for i in range(len(args)): # Strip trailing ".py" from arguments if args[i][-3:] == '.py': args[i] = args[i][:-3] stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_large_resources = use_large_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if bad: print count(len(bad), "test"), "failed:", print string.join(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:", print string.join(skipped) if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) return len(bad) > 0
if o == '-l': leakdebug = 1
if o == '-l': findleaks = 1
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, leakdebug=0, use_large_resources=0): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other seven default arguments (verbose, quiet, generate, exclude, single, randomize, and leakdebug) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ try: opts, args = getopt.getopt(sys.argv[1:], 'vgqxsrl', ['have-resources']) except getopt.error, msg: print msg print __doc__ return 2 for o, a in opts: if o == '-v': verbose = verbose+1 if o == '-q': quiet = 1; verbose = 0 if o == '-g': generate = 1 if o == '-x': exclude = 1 if o == '-s': single = 1 if o == '-r': randomize = 1 if o == '-l': leakdebug = 1 if o == '--have-resources': use_large_resources = 1 if generate and verbose: print "-g and -v don't go together!" return 2 good = [] bad = [] skipped = [] if leakdebug: try: import gc except ImportError: print 'cycle garbage collection not available' else: gc.set_debug(gc.DEBUG_LEAK) if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = string.strip(fp.read()) tests = [next] fp.close() except IOError: pass for i in range(len(args)): # Strip trailing ".py" from arguments if args[i][-3:] == '.py': args[i] = args[i][:-3] stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_large_resources = use_large_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if bad: print count(len(bad), "test"), "failed:", print string.join(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:", print string.join(skipped) if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) return len(bad) > 0
if leakdebug:
if findleaks:
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, leakdebug=0, use_large_resources=0): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other seven default arguments (verbose, quiet, generate, exclude, single, randomize, and leakdebug) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ try: opts, args = getopt.getopt(sys.argv[1:], 'vgqxsrl', ['have-resources']) except getopt.error, msg: print msg print __doc__ return 2 for o, a in opts: if o == '-v': verbose = verbose+1 if o == '-q': quiet = 1; verbose = 0 if o == '-g': generate = 1 if o == '-x': exclude = 1 if o == '-s': single = 1 if o == '-r': randomize = 1 if o == '-l': leakdebug = 1 if o == '--have-resources': use_large_resources = 1 if generate and verbose: print "-g and -v don't go together!" return 2 good = [] bad = [] skipped = [] if leakdebug: try: import gc except ImportError: print 'cycle garbage collection not available' else: gc.set_debug(gc.DEBUG_LEAK) if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = string.strip(fp.read()) tests = [next] fp.close() except IOError: pass for i in range(len(args)): # Strip trailing ".py" from arguments if args[i][-3:] == '.py': args[i] = args[i][:-3] stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_large_resources = use_large_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if bad: print count(len(bad), "test"), "failed:", print string.join(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:", print string.join(skipped) if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) return len(bad) > 0
gc.set_debug(gc.DEBUG_LEAK)
gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = []
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, leakdebug=0, use_large_resources=0): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other seven default arguments (verbose, quiet, generate, exclude, single, randomize, and leakdebug) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ try: opts, args = getopt.getopt(sys.argv[1:], 'vgqxsrl', ['have-resources']) except getopt.error, msg: print msg print __doc__ return 2 for o, a in opts: if o == '-v': verbose = verbose+1 if o == '-q': quiet = 1; verbose = 0 if o == '-g': generate = 1 if o == '-x': exclude = 1 if o == '-s': single = 1 if o == '-r': randomize = 1 if o == '-l': leakdebug = 1 if o == '--have-resources': use_large_resources = 1 if generate and verbose: print "-g and -v don't go together!" return 2 good = [] bad = [] skipped = [] if leakdebug: try: import gc except ImportError: print 'cycle garbage collection not available' else: gc.set_debug(gc.DEBUG_LEAK) if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = string.strip(fp.read()) tests = [next] fp.close() except IOError: pass for i in range(len(args)): # Strip trailing ".py" from arguments if args[i][-3:] == '.py': args[i] = args[i][:-3] stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_large_resources = use_large_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if bad: print count(len(bad), "test"), "failed:", print string.join(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:", print string.join(skipped) if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) return len(bad) > 0
fullname = '.'.join(path)+'.'+name
fullname = string.join(path, '.')+'.'+name
def find_module(self, name, path): if path: fullname = '.'.join(path)+'.'+name else: fullname = name if fullname in self.excludes: self.msgout(3, "find_module -> Excluded", fullname) raise ImportError, name
self.buf = self.buf + string.joinfields(self.buflist, '')
self.buf += EMPTYSTRING.join(self.buflist)
def seek(self, pos, mode = 0): if self.closed: raise ValueError, "I/O operation on closed file" if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] if mode == 1: pos = pos + self.pos elif mode == 2: pos = pos + self.len self.pos = max(0, pos)
pos = pos + self.pos
pos += self.pos
def seek(self, pos, mode = 0): if self.closed: raise ValueError, "I/O operation on closed file" if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] if mode == 1: pos = pos + self.pos elif mode == 2: pos = pos + self.len self.pos = max(0, pos)
pos = pos + self.len
pos += self.len
def seek(self, pos, mode = 0): if self.closed: raise ValueError, "I/O operation on closed file" if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] if mode == 1: pos = pos + self.pos elif mode == 2: pos = pos + self.len self.pos = max(0, pos)
self.buf = self.buf + string.joinfields(self.buflist, '')
self.buf += EMPTYSTRING.join(self.buflist)
def read(self, n = -1): if self.closed: raise ValueError, "I/O operation on closed file" if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] if n < 0: newpos = self.len else: newpos = min(self.pos+n, self.len) r = self.buf[self.pos:newpos] self.pos = newpos return r
self.buf = self.buf + string.joinfields(self.buflist, '')
self.buf += EMPTYSTRING.join(self.buflist)
def readline(self, length=None): if self.closed: raise ValueError, "I/O operation on closed file" if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] i = string.find(self.buf, '\n', self.pos) if i < 0: newpos = self.len else: newpos = i+1 if length is not None: if self.pos + length < newpos: newpos = self.pos + length r = self.buf[self.pos:newpos] self.pos = newpos return r
i = string.find(self.buf, '\n', self.pos)
i = self.buf.find('\n', self.pos)
def readline(self, length=None): if self.closed: raise ValueError, "I/O operation on closed file" if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] i = string.find(self.buf, '\n', self.pos) if i < 0: newpos = self.len else: newpos = i+1 if length is not None: if self.pos + length < newpos: newpos = self.pos + length r = self.buf[self.pos:newpos] self.pos = newpos return r
raise IOError(errno.EINVAL, "Negative size not allowed")
raise IOError(EINVAL, "Negative size not allowed")
def truncate(self, size=None): if self.closed: raise ValueError, "I/O operation on closed file" if size is None: size = self.pos elif size < 0: raise IOError(errno.EINVAL, "Negative size not allowed") elif size < self.pos: self.pos = size self.buf = self.getvalue()[:size]
self.buf = self.buf + string.joinfields(self.buflist, '')
self.buf += EMPTYSTRING.join(self.buflist)
def write(self, s): if self.closed: raise ValueError, "I/O operation on closed file" if not s: return if self.pos > self.len: self.buflist.append('\0'*(self.pos - self.len)) self.len = self.pos newpos = self.pos + len(s) if self.pos < self.len: if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] self.buflist = [self.buf[:self.pos], s, self.buf[newpos:]] self.buf = '' if newpos > self.len: self.len = newpos else: self.buflist.append(s) self.len = newpos self.pos = newpos
self.write(string.joinfields(list, ''))
self.write(EMPTYSTRING.join(list))
def writelines(self, list): self.write(string.joinfields(list, ''))
self.buf = self.buf + string.joinfields(self.buflist, '')
self.buf += EMPTYSTRING.join(self.buflist)
def getvalue(self): if self.buflist: self.buf = self.buf + string.joinfields(self.buflist, '') self.buflist = [] return self.buf
print 'Skip', path,'- Up-to-date'
print 'Skip', dstfile,'- Up-to-date'
def hexbincwprojects(creator): """Compact and hexbin all files remembered with a given creator""" print 'Please start project mgr with signature', creator,'-' sys.stdin.readline() try: mgr = MwShell(creator) except 'foo': print 'Not handled:', creator return for fss in project_files[creator]: srcfile = fss.as_pathname() dstfile = srcfile + '.hqx' if os.path.exists(dstfile) and \ os.stat(dstfile)[8] > os.stat(srcfile)[8]: print 'Skip', path,'- Up-to-date' continue print 'Compacting', dstfile mgr.open(fss) mgr.Reset_File_Paths() mgr.Remove_Binaries() mgr.Close_Project() print 'Binhexing', dstfile binhex.binhex(srcfile, dstfile) mgr.quit()
self.botframe = frame
self.botframe = frame.f_back
def dispatch_call(self, frame, arg): # XXX 'arg' is no longer used if self.botframe is None: # First call of dispatch since reset() self.botframe = frame return self.trace_dispatch if not (self.stop_here(frame) or self.break_anywhere(frame)): # No need to trace this function return # None self.user_call(frame, arg) if self.quitting: raise BdbQuit return self.trace_dispatch
if self.stopframe is None: return True
def stop_here(self, frame): if self.stopframe is None: return True if frame is self.stopframe: return True while frame is not None and frame is not self.stopframe: if frame is self.botframe: return True frame = frame.f_back return False
try: raise Exception except: frame = sys.exc_info()[2].tb_frame.f_back
frame = sys._getframe().f_back
def set_trace(self): """Start debugging from here.""" try: raise Exception except: frame = sys.exc_info()[2].tb_frame.f_back self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back self.set_step() sys.settrace(self.trace_dispatch)
try: raise Exception except: frame = sys.exc_info()[2].tb_frame.f_back
frame = sys._getframe().f_back
def set_continue(self): # Don't stop except at breakpoints or when finished self.stopframe = self.botframe self.returnframe = None self.quitting = 0 if not self.breaks: # no breakpoints; run without debugger overhead sys.settrace(None) try: raise Exception except: frame = sys.exc_info()[2].tb_frame.f_back while frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back
(1, Complex(0,10), 'TypeError'),
(1, Complex(0,10), 1),
def test(): testsuite = { 'a+b': [ (1, 10, 11), (1, Complex(0,10), Complex(1,10)), (Complex(0,10), 1, Complex(1,10)), (Complex(0,10), Complex(1), Complex(1,10)), (Complex(1), Complex(0,10), Complex(1,10)), ], 'a-b': [ (1, 10, -9), (1, Complex(0,10), Complex(1,-10)), (Complex(0,10), 1, Complex(-1,10)), (Complex(0,10), Complex(1), Complex(-1,10)), (Complex(1), Complex(0,10), Complex(1,-10)), ], 'a*b': [ (1, 10, 10), (1, Complex(0,10), Complex(0, 10)), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), Complex(0,10)), ], 'a/b': [ (1., 10, 0.1), (1, Complex(0,10), Complex(0, -0.1)), (Complex(0, 10), 1, Complex(0, 10)), (Complex(0, 10), Complex(1), Complex(0, 10)), (Complex(1), Complex(0,10), Complex(0, -0.1)), ], 'pow(a,b)': [ (1, 10, 1), (1, Complex(0,10), 'TypeError'), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), 'TypeError'), (2, Complex(4,0), 16), ], 'cmp(a,b)': [ (1, 10, -1), (1, Complex(0,10), 1), (Complex(0,10), 1, -1), (Complex(0,10), Complex(1), -1), (Complex(1), Complex(0,10), 1), ], } exprs = testsuite.keys() exprs.sort() for expr in exprs: print expr + ':' t = (expr,) for item in testsuite[expr]: apply(checkop, t+item)
(Complex(1), Complex(0,10), 'TypeError'),
(Complex(1), Complex(0,10), 1),
def test(): testsuite = { 'a+b': [ (1, 10, 11), (1, Complex(0,10), Complex(1,10)), (Complex(0,10), 1, Complex(1,10)), (Complex(0,10), Complex(1), Complex(1,10)), (Complex(1), Complex(0,10), Complex(1,10)), ], 'a-b': [ (1, 10, -9), (1, Complex(0,10), Complex(1,-10)), (Complex(0,10), 1, Complex(-1,10)), (Complex(0,10), Complex(1), Complex(-1,10)), (Complex(1), Complex(0,10), Complex(1,-10)), ], 'a*b': [ (1, 10, 10), (1, Complex(0,10), Complex(0, 10)), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), Complex(0,10)), ], 'a/b': [ (1., 10, 0.1), (1, Complex(0,10), Complex(0, -0.1)), (Complex(0, 10), 1, Complex(0, 10)), (Complex(0, 10), Complex(1), Complex(0, 10)), (Complex(1), Complex(0,10), Complex(0, -0.1)), ], 'pow(a,b)': [ (1, 10, 1), (1, Complex(0,10), 'TypeError'), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), 'TypeError'), (2, Complex(4,0), 16), ], 'cmp(a,b)': [ (1, 10, -1), (1, Complex(0,10), 1), (Complex(0,10), 1, -1), (Complex(0,10), Complex(1), -1), (Complex(1), Complex(0,10), 1), ], } exprs = testsuite.keys() exprs.sort() for expr in exprs: print expr + ':' t = (expr,) for item in testsuite[expr]: apply(checkop, t+item)
self.file = self.sock.makefile('r')
self.file = self.sock.makefile('rb')
def open(self, host, port): """Setup connection to remote server on "host:port". This connection will be used by the routines: read, readline, send, shutdown. """ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host, self.port)) self.file = self.sock.makefile('r')
host = user + ':' + passwd + '@' + host
host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
def retry_http_basic_auth(self, url, realm, data=None): host, selector = splithost(url) i = host.find('@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = 'http://' + host + selector if data is None: return self.open(newurl) else: return self.open(newurl, data)
host = user + ':' + passwd + '@' + host
host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
def retry_https_basic_auth(self, url, realm, data=None): host, selector = splithost(url) i = host.find('@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = '//' + host + selector return self.open_https(newurl)
return self.open_https(newurl)
return self.open_https(newurl, data)
def retry_https_basic_auth(self, url, realm, data=None): host, selector = splithost(url) i = host.find('@') + 1 host = host[i:] user, passwd = self.get_user_passwd(host, realm, i) if not (user or passwd): return None host = user + ':' + passwd + '@' + host newurl = '//' + host + selector return self.open_https(newurl)
sf = StringIO('Content-Length: %d\n' % retrlen) headers = mimetools.Message(sf) else: headers = noheaders()
headers += "Content-Length: %d\n" % retrlen sf = StringIO(headers) headers = mimetools.Message(sf)
def ftp_open(self, req): host = req.get_host() if not host: raise IOError, ('ftp error', 'no host given') # XXX handle custom username & password try: host = socket.gethostbyname(host) except socket.error, msg: raise URLError(msg) host, port = splitport(host) if port is None: port = ftplib.FTP_PORT path, attrs = splitattr(req.get_selector()) path = unquote(path) dirs = path.split('/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] user = passwd = '' # XXX try: fw = self.connect_ftp(user, passwd, host, port, dirs) type = file and 'I' or 'D' for attr in attrs: attr, value = splitattr(attr) if attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() fp, retrlen = fw.retrfile(file, type) if retrlen is not None and retrlen >= 0: sf = StringIO('Content-Length: %d\n' % retrlen) headers = mimetools.Message(sf) else: headers = noheaders() return addinfourl(fp, headers, req.get_full_url()) except ftplib.all_errors, msg: raise IOError, ('ftp error', msg), sys.exc_info()[2]
host = 'www.cwi.nl:80' selector = '/index.html'
host = 'www.python.org' selector = '/'
def test(): import sys import getopt opts, args = getopt.getopt(sys.argv[1:], 'd') dl = 0 for o, a in opts: if o == '-d': dl = dl + 1 host = 'www.cwi.nl:80' selector = '/index.html' if args[0:]: host = args[0] if args[1:]: selector = args[1] h = HTTP() h.set_debuglevel(dl) h.connect(host) h.putrequest('GET', selector) errcode, errmsg, headers = h.getreply() print 'errcode =', errcode print 'headers =', headers print 'errmsg =', errmsg if headers: for header in headers.headers: print string.strip(header) print h.getfile().read()
print 'headers =', headers
def test(): import sys import getopt opts, args = getopt.getopt(sys.argv[1:], 'd') dl = 0 for o, a in opts: if o == '-d': dl = dl + 1 host = 'www.cwi.nl:80' selector = '/index.html' if args[0:]: host = args[0] if args[1:]: selector = args[1] h = HTTP() h.set_debuglevel(dl) h.connect(host) h.putrequest('GET', selector) errcode, errmsg, headers = h.getreply() print 'errcode =', errcode print 'headers =', headers print 'errmsg =', errmsg if headers: for header in headers.headers: print string.strip(header) print h.getfile().read()
if not os.path.isfile(makefile):
if not os.path.isfile(makefile) or os.path.getsize(makefile)==0:
def main(): build_all = "-a" in sys.argv if sys.argv[1] == "Release": arch = "x86" debug = False configure = "VC-WIN32" do_script = "ms\\do_masm" makefile = "ms\\nt.mak" elif sys.argv[1] == "Debug": arch = "x86" debug = True configure = "VC-WIN32" do_script = "ms\\do_masm" makefile="ms\\d32.mak" elif sys.argv[1] == "ReleaseItanium": arch = "ia64" debug = False configure = "VC-WIN64I" do_script = "ms\\do_win64i" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_ITANIUM" elif sys.argv[1] == "ReleaseAMD64": arch="amd64" debug=False configure = "VC-WIN64A" do_script = "ms\\do_win64a" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON" make_flags = "" if build_all: make_flags = "-a" # perl should be on the path, but we also look in "\perl" and "c:\\perl" # as "well known" locations perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) perl = find_working_perl(perls) if perl is None: sys.exit(1) print "Found a working perl at '%s'" % (perl,) sys.stdout.flush() # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live. ssl_dir = find_best_ssl_dir(("..\\..",)) if ssl_dir is None: sys.exit(1) old_cd = os.getcwd() try: os.chdir(ssl_dir) # If the ssl makefiles do not exist, we invoke Perl to generate them. if not os.path.isfile(makefile): print "Creating the makefiles..." sys.stdout.flush() # Put our working Perl at the front of our path os.environ["PATH"] = os.path.dirname(perl) + \ os.pathsep + \ os.environ["PATH"] if arch=="x86" and debug: # the do_masm script in openssl doesn't generate a debug # build makefile so we generate it here: os.system("perl util\mk1mf.pl debug "+configure+" >"+makefile) run_configure(configure, do_script) # Now run make. print "Executing nmake over the ssl makefiles..." sys.stdout.flush() rc = os.system("nmake /nologo PERL=\"%s\" -f \"%s\"" %(perl, makefile)) if rc: print "Executing "+makefile+" failed" print rc sys.exit(rc) finally: os.chdir(old_cd) # And finally, we can build the _ssl module itself for Python. defs = "SSL_DIR=\"%s\"" % (ssl_dir,) if debug: defs = defs + " " + "DEBUG=1" makeCommand = 'nmake /nologo -f _ssl.mak ' + defs + " " + make_flags print "Executing:", makeCommand sys.stdout.flush() rc = os.system(makeCommand) sys.exit(rc)
run_configure(configure, do_script)
def main(): build_all = "-a" in sys.argv if sys.argv[1] == "Release": arch = "x86" debug = False configure = "VC-WIN32" do_script = "ms\\do_masm" makefile = "ms\\nt.mak" elif sys.argv[1] == "Debug": arch = "x86" debug = True configure = "VC-WIN32" do_script = "ms\\do_masm" makefile="ms\\d32.mak" elif sys.argv[1] == "ReleaseItanium": arch = "ia64" debug = False configure = "VC-WIN64I" do_script = "ms\\do_win64i" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_ITANIUM" elif sys.argv[1] == "ReleaseAMD64": arch="amd64" debug=False configure = "VC-WIN64A" do_script = "ms\\do_win64a" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON" make_flags = "" if build_all: make_flags = "-a" # perl should be on the path, but we also look in "\perl" and "c:\\perl" # as "well known" locations perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) perl = find_working_perl(perls) if perl is None: sys.exit(1) print "Found a working perl at '%s'" % (perl,) sys.stdout.flush() # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live. ssl_dir = find_best_ssl_dir(("..\\..",)) if ssl_dir is None: sys.exit(1) old_cd = os.getcwd() try: os.chdir(ssl_dir) # If the ssl makefiles do not exist, we invoke Perl to generate them. if not os.path.isfile(makefile): print "Creating the makefiles..." sys.stdout.flush() # Put our working Perl at the front of our path os.environ["PATH"] = os.path.dirname(perl) + \ os.pathsep + \ os.environ["PATH"] if arch=="x86" and debug: # the do_masm script in openssl doesn't generate a debug # build makefile so we generate it here: os.system("perl util\mk1mf.pl debug "+configure+" >"+makefile) run_configure(configure, do_script) # Now run make. print "Executing nmake over the ssl makefiles..." sys.stdout.flush() rc = os.system("nmake /nologo PERL=\"%s\" -f \"%s\"" %(perl, makefile)) if rc: print "Executing "+makefile+" failed" print rc sys.exit(rc) finally: os.chdir(old_cd) # And finally, we can build the _ssl module itself for Python. defs = "SSL_DIR=\"%s\"" % (ssl_dir,) if debug: defs = defs + " " + "DEBUG=1" makeCommand = 'nmake /nologo -f _ssl.mak ' + defs + " " + make_flags print "Executing:", makeCommand sys.stdout.flush() rc = os.system(makeCommand) sys.exit(rc)
print "Executing nmake over the ssl makefiles..."
makeCommand = "nmake /nologo PERL=\"%s\" -f \"%s\"" %(perl, makefile) print "Executing ssl makefiles:", makeCommand
def main(): build_all = "-a" in sys.argv if sys.argv[1] == "Release": arch = "x86" debug = False configure = "VC-WIN32" do_script = "ms\\do_masm" makefile = "ms\\nt.mak" elif sys.argv[1] == "Debug": arch = "x86" debug = True configure = "VC-WIN32" do_script = "ms\\do_masm" makefile="ms\\d32.mak" elif sys.argv[1] == "ReleaseItanium": arch = "ia64" debug = False configure = "VC-WIN64I" do_script = "ms\\do_win64i" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_ITANIUM" elif sys.argv[1] == "ReleaseAMD64": arch="amd64" debug=False configure = "VC-WIN64A" do_script = "ms\\do_win64a" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON" make_flags = "" if build_all: make_flags = "-a" # perl should be on the path, but we also look in "\perl" and "c:\\perl" # as "well known" locations perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) perl = find_working_perl(perls) if perl is None: sys.exit(1) print "Found a working perl at '%s'" % (perl,) sys.stdout.flush() # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live. ssl_dir = find_best_ssl_dir(("..\\..",)) if ssl_dir is None: sys.exit(1) old_cd = os.getcwd() try: os.chdir(ssl_dir) # If the ssl makefiles do not exist, we invoke Perl to generate them. if not os.path.isfile(makefile): print "Creating the makefiles..." sys.stdout.flush() # Put our working Perl at the front of our path os.environ["PATH"] = os.path.dirname(perl) + \ os.pathsep + \ os.environ["PATH"] if arch=="x86" and debug: # the do_masm script in openssl doesn't generate a debug # build makefile so we generate it here: os.system("perl util\mk1mf.pl debug "+configure+" >"+makefile) run_configure(configure, do_script) # Now run make. print "Executing nmake over the ssl makefiles..." sys.stdout.flush() rc = os.system("nmake /nologo PERL=\"%s\" -f \"%s\"" %(perl, makefile)) if rc: print "Executing "+makefile+" failed" print rc sys.exit(rc) finally: os.chdir(old_cd) # And finally, we can build the _ssl module itself for Python. defs = "SSL_DIR=\"%s\"" % (ssl_dir,) if debug: defs = defs + " " + "DEBUG=1" makeCommand = 'nmake /nologo -f _ssl.mak ' + defs + " " + make_flags print "Executing:", makeCommand sys.stdout.flush() rc = os.system(makeCommand) sys.exit(rc)
rc = os.system("nmake /nologo PERL=\"%s\" -f \"%s\"" %(perl, makefile))
rc = os.system(makeCommand)
def main(): build_all = "-a" in sys.argv if sys.argv[1] == "Release": arch = "x86" debug = False configure = "VC-WIN32" do_script = "ms\\do_masm" makefile = "ms\\nt.mak" elif sys.argv[1] == "Debug": arch = "x86" debug = True configure = "VC-WIN32" do_script = "ms\\do_masm" makefile="ms\\d32.mak" elif sys.argv[1] == "ReleaseItanium": arch = "ia64" debug = False configure = "VC-WIN64I" do_script = "ms\\do_win64i" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_ITANIUM" elif sys.argv[1] == "ReleaseAMD64": arch="amd64" debug=False configure = "VC-WIN64A" do_script = "ms\\do_win64a" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON" make_flags = "" if build_all: make_flags = "-a" # perl should be on the path, but we also look in "\perl" and "c:\\perl" # as "well known" locations perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) perl = find_working_perl(perls) if perl is None: sys.exit(1) print "Found a working perl at '%s'" % (perl,) sys.stdout.flush() # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live. ssl_dir = find_best_ssl_dir(("..\\..",)) if ssl_dir is None: sys.exit(1) old_cd = os.getcwd() try: os.chdir(ssl_dir) # If the ssl makefiles do not exist, we invoke Perl to generate them. if not os.path.isfile(makefile): print "Creating the makefiles..." sys.stdout.flush() # Put our working Perl at the front of our path os.environ["PATH"] = os.path.dirname(perl) + \ os.pathsep + \ os.environ["PATH"] if arch=="x86" and debug: # the do_masm script in openssl doesn't generate a debug # build makefile so we generate it here: os.system("perl util\mk1mf.pl debug "+configure+" >"+makefile) run_configure(configure, do_script) # Now run make. print "Executing nmake over the ssl makefiles..." sys.stdout.flush() rc = os.system("nmake /nologo PERL=\"%s\" -f \"%s\"" %(perl, makefile)) if rc: print "Executing "+makefile+" failed" print rc sys.exit(rc) finally: os.chdir(old_cd) # And finally, we can build the _ssl module itself for Python. defs = "SSL_DIR=\"%s\"" % (ssl_dir,) if debug: defs = defs + " " + "DEBUG=1" makeCommand = 'nmake /nologo -f _ssl.mak ' + defs + " " + make_flags print "Executing:", makeCommand sys.stdout.flush() rc = os.system(makeCommand) sys.exit(rc)
if not uthread2:
if uthread2:
def execstring(pytext, globals, locals, filename="<string>", debugging=0, modname="__main__", profiling=0): if debugging: import PyDebugger, bdb BdbQuit = bdb.BdbQuit else: BdbQuit = 'BdbQuitDummyException' pytext = string.split(pytext, '\r') pytext = string.join(pytext, '\n') + '\n' W.SetCursor("watch") globals['__name__'] = modname globals['__file__'] = filename sys.argv = [filename] try: code = compile(pytext, filename, "exec") except: # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError # special. That's wrong because THIS case is special (could be literal # overflow!) and SyntaxError could mean we need a traceback (syntax error # in imported module!!! tracebackwindow.traceback(1, filename) return try: if debugging: if uthread2: uthread2.globalLock() PyDebugger.startfromhere() uthread2.globalUnlock() else: PyDebugger.startfromhere() elif not uthread2: MacOS.EnableAppswitch(0) try: if profiling: import profile, ProfileBrowser p = profile.Profile() p.set_cmd(filename) try: p.runctx(code, globals, locals) finally: import pstats stats = pstats.Stats(p) ProfileBrowser.ProfileBrowser(stats) else: exec code in globals, locals finally: if not uthread2: MacOS.EnableAppswitch(-1) except W.AlertError, detail: raise W.AlertError, detail except (KeyboardInterrupt, BdbQuit): pass except: if uthread2: uthread2.globalLock() if debugging: sys.settrace(None) PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback) return else: tracebackwindow.traceback(1, filename) if not uthread2: uthread2.globalUnlock() if debugging: sys.settrace(None) PyDebugger.stop()
scheme = urllib.splittype(url)
scheme, path = urllib.splittype(url)
def getpage(self, url_pair): # Incoming argument name is a (URL, fragment) pair. # The page may have been cached in the name_table variable. url, fragment = url_pair if self.name_table.has_key(url): return self.name_table[url]
self.draw['xscroll'] = self.draw.scrollX.set self.draw['yscroll'] = self.draw.scrollY.set
self.draw['xscrollcommand'] = self.draw.scrollX.set self.draw['yscrollcommand'] = self.draw.scrollY.set
def createWidgets(self):
def __init__(self, host, port=None, **x509): keys = x509.keys() try: keys.remove('key_file') except ValueError: pass try: keys.remove('cert_file') except ValueError: pass if keys: raise IllegalKeywordArgument()
def __init__(self, host, port=None, key_file=None, cert_file=None):
def __init__(self, host, port=None, **x509): keys = x509.keys() try: keys.remove('key_file') except ValueError: pass try: keys.remove('cert_file') except ValueError: pass if keys: raise IllegalKeywordArgument() HTTPConnection.__init__(self, host, port) self.key_file = x509.get('key_file') self.cert_file = x509.get('cert_file')
self.key_file = x509.get('key_file') self.cert_file = x509.get('cert_file')
self.key_file = key_file self.cert_file = cert_file
def __init__(self, host, port=None, **x509): keys = x509.keys() try: keys.remove('key_file') except ValueError: pass try: keys.remove('cert_file') except ValueError: pass if keys: raise IllegalKeywordArgument() HTTPConnection.__init__(self, host, port) self.key_file = x509.get('key_file') self.cert_file = x509.get('cert_file')