diff options
Diffstat (limited to 'Lib')
183 files changed, 518 insertions, 502 deletions
diff --git a/Lib/CGIHTTPServer.py b/Lib/CGIHTTPServer.py index c119c9a..ce942ef 100644 --- a/Lib/CGIHTTPServer.py +++ b/Lib/CGIHTTPServer.py @@ -320,7 +320,7 @@ class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): sys.stdout = save_stdout sys.stderr = save_stderr os.chdir(save_cwd) - except SystemExit, sts: + except SystemExit as sts: self.log_error("CGI script exit status %s", str(sts)) else: self.log_message("CGI script exited OK") diff --git a/Lib/ConfigParser.py b/Lib/ConfigParser.py index 65c8ce5..bdc88cf 100644 --- a/Lib/ConfigParser.py +++ b/Lib/ConfigParser.py @@ -567,7 +567,7 @@ class ConfigParser(RawConfigParser): value = self._KEYCRE.sub(self._interpolation_replace, value) try: value = value % vars - except KeyError, e: + except KeyError as e: raise InterpolationMissingOptionError( option, section, rawval, e[0]) else: diff --git a/Lib/SimpleXMLRPCServer.py b/Lib/SimpleXMLRPCServer.py index c6f6958..0a62b47 100644 --- a/Lib/SimpleXMLRPCServer.py +++ b/Lib/SimpleXMLRPCServer.py @@ -259,7 +259,7 @@ class SimpleXMLRPCDispatcher: response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) - except Fault, fault: + except Fault as fault: response = xmlrpclib.dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except: @@ -359,7 +359,7 @@ class SimpleXMLRPCDispatcher: # XXX A marshalling error in any response will fail the entire # multicall. If someone cares they should fix this. results.append([self._dispatch(method_name, params)]) - except Fault, fault: + except Fault as fault: results.append( {'faultCode' : fault.faultCode, 'faultString' : fault.faultString} diff --git a/Lib/_strptime.py b/Lib/_strptime.py index 3fb5602..2d9be36 100644 --- a/Lib/_strptime.py +++ b/Lib/_strptime.py @@ -291,7 +291,7 @@ def strptime(data_string, format="%a %b %d %H:%M:%S %Y"): format_regex = time_re.compile(format) # KeyError raised when a bad format is found; can be specified as # \\, in which case it was a stray % but with a space after it - except KeyError, err: + except KeyError as err: bad_directive = err.args[0] if bad_directive == "\\": bad_directive = "%" diff --git a/Lib/asynchat.py b/Lib/asynchat.py index 6f99ba1..1ad3161 100644 --- a/Lib/asynchat.py +++ b/Lib/asynchat.py @@ -87,7 +87,7 @@ class async_chat (asyncore.dispatcher): try: data = self.recv (self.ac_in_buffer_size) - except socket.error, why: + except socket.error as why: self.handle_error() return @@ -220,7 +220,7 @@ class async_chat (asyncore.dispatcher): if num_sent: self.ac_out_buffer = self.ac_out_buffer[num_sent:] - except socket.error, why: + except socket.error as why: self.handle_error() return diff --git a/Lib/asyncore.py b/Lib/asyncore.py index 7b2f301..9eb6d7f 100644 --- a/Lib/asyncore.py +++ b/Lib/asyncore.py @@ -119,7 +119,7 @@ def poll(timeout=0.0, map=None): else: try: r, w, e = select.select(r, w, e, timeout) - except select.error, err: + except select.error as err: if err[0] != EINTR: raise else: @@ -165,7 +165,7 @@ def poll2(timeout=0.0, map=None): pollster.register(fd, flags) try: r = pollster.poll(timeout) - except select.error, err: + except select.error as err: if err[0] != EINTR: raise r = [] @@ -320,7 +320,7 @@ class dispatcher: try: conn, addr = self.socket.accept() return conn, addr - except socket.error, why: + except socket.error as why: if why[0] == EWOULDBLOCK: pass else: @@ -330,7 +330,7 @@ class dispatcher: try: result = self.socket.send(data) return result - except socket.error, why: + except socket.error as why: if why[0] == EWOULDBLOCK: return 0 else: @@ -347,7 +347,7 @@ class dispatcher: return '' else: return data - except socket.error, why: + except socket.error as why: # winsock sometimes throws ENOTCONN if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]: self.handle_close() diff --git a/Lib/base64.py b/Lib/base64.py index 41a5e14..009f9f6 100755 --- a/Lib/base64.py +++ b/Lib/base64.py @@ -71,7 +71,7 @@ def b64decode(s, altchars=None): s = _translate(s, {altchars[0]: '+', altchars[1]: '/'}) try: return binascii.a2b_base64(s) - except binascii.Error, msg: + except binascii.Error as msg: # Transform this exception for consistency raise TypeError(msg) @@ -328,7 +328,7 @@ def test(): import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'deut') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print """usage: %s [-d|-e|-u|-t] [file|-] diff --git a/Lib/bsddb/dbtables.py b/Lib/bsddb/dbtables.py index 7f862d7..704c4d2 100644 --- a/Lib/bsddb/dbtables.py +++ b/Lib/bsddb/dbtables.py @@ -260,7 +260,7 @@ class bsdTableDB : txn.commit() txn = None - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise TableDBError, dberror[1] @@ -338,7 +338,7 @@ class bsdTableDB : txn = None self.__load_column_info(table) - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise TableDBError, dberror[1] @@ -407,7 +407,7 @@ class bsdTableDB : txn.commit() txn = None - except DBError, dberror: + except DBError as dberror: # WIBNI we could just abort the txn and re-raise the exception? # But no, because TableDBError is not related to DBError via # inheritance, so it would be backwards incompatible. Do the next @@ -466,7 +466,7 @@ class bsdTableDB : txn.abort() raise - except DBError, dberror: + except DBError as dberror: raise TableDBError, dberror[1] def Delete(self, table, conditions={}): @@ -502,11 +502,11 @@ class bsdTableDB : pass txn.commit() txn = None - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise - except DBError, dberror: + except DBError as dberror: raise TableDBError, dberror[1] @@ -526,7 +526,7 @@ class bsdTableDB : if columns is None: columns = self.__tablecolumns[table] matching_rowids = self.__Select(table, columns, conditions) - except DBError, dberror: + except DBError as dberror: raise TableDBError, dberror[1] # return the matches as a list of dictionaries return matching_rowids.values() @@ -616,7 +616,7 @@ class bsdTableDB : key, data = cur.next() - except DBError, dberror: + except DBError as dberror: if dberror[0] != DB_NOTFOUND: raise continue @@ -636,7 +636,7 @@ class bsdTableDB : try: rowdata[column] = self.db.get( _data_key(table, column, rowid)) - except DBError, dberror: + except DBError as dberror: if dberror[0] != DB_NOTFOUND: raise rowdata[column] = None @@ -700,7 +700,7 @@ class bsdTableDB : if table in self.__tablecolumns: del self.__tablecolumns[table] - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise TableDBError, dberror[1] diff --git a/Lib/bsddb/test/test_basics.py b/Lib/bsddb/test/test_basics.py index 48ecdb9..281e942 100644 --- a/Lib/bsddb/test/test_basics.py +++ b/Lib/bsddb/test/test_basics.py @@ -58,7 +58,7 @@ class BasicTestCase(unittest.TestCase): self.homeDir = homeDir try: shutil.rmtree(homeDir) - except OSError, e: + except OSError as e: # unix returns ENOENT, windows returns ESRCH if e.errno not in (errno.ENOENT, errno.ESRCH): raise os.mkdir(homeDir) @@ -162,7 +162,7 @@ class BasicTestCase(unittest.TestCase): # set_get_returns_none() to change it. try: d.delete('abcd') - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND if verbose: print val else: @@ -181,7 +181,7 @@ class BasicTestCase(unittest.TestCase): try: d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE) - except db.DBKeyExistError, val: + except db.DBKeyExistError as val: assert val[0] == db.DB_KEYEXIST if verbose: print val else: @@ -313,7 +313,7 @@ class BasicTestCase(unittest.TestCase): print rec try: rec = c.next() - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND if verbose: print val @@ -333,7 +333,7 @@ class BasicTestCase(unittest.TestCase): print rec try: rec = c.prev() - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND if verbose: print val @@ -357,7 +357,7 @@ class BasicTestCase(unittest.TestCase): try: n = c.set('bad key') - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND if verbose: print val else: @@ -371,7 +371,7 @@ class BasicTestCase(unittest.TestCase): try: n = c.get_both('0404', 'bad data') - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND if verbose: print val else: @@ -399,7 +399,7 @@ class BasicTestCase(unittest.TestCase): c.delete() try: rec = c.current() - except db.DBKeyEmptyError, val: + except db.DBKeyEmptyError as val: if get_raises_error: assert val[0] == db.DB_KEYEMPTY if verbose: print val @@ -445,7 +445,7 @@ class BasicTestCase(unittest.TestCase): method # a bug may cause a NULL pointer dereference... getattr(c, method)(*args) - except db.DBError, val: + except db.DBError as val: assert val[0] == 0 if verbose: print val else: @@ -730,7 +730,7 @@ class BasicTransactionTestCase(BasicTestCase): txn.abort() try: txn.abort() - except db.DBError, e: + except db.DBError as e: pass else: raise RuntimeError, "DBTxn.abort() called after DB_TXN no longer valid w/o an exception" @@ -739,7 +739,7 @@ class BasicTransactionTestCase(BasicTestCase): txn.commit() try: txn.commit() - except db.DBError, e: + except db.DBError as e: pass else: raise RuntimeError, "DBTxn.commit() called after DB_TXN no longer valid w/o an exception" diff --git a/Lib/bsddb/test/test_compare.py b/Lib/bsddb/test/test_compare.py index ccf8b83..b3eaf3a 100644 --- a/Lib/bsddb/test/test_compare.py +++ b/Lib/bsddb/test/test_compare.py @@ -234,7 +234,7 @@ class BtreeExceptionsTestCase (AbstractBtreeKeyCompareTestCase): self.db.set_bt_compare (my_compare) assert False, "this set should fail" - except RuntimeError, msg: + except RuntimeError as msg: pass def test_suite (): diff --git a/Lib/bsddb/test/test_pickle.py b/Lib/bsddb/test/test_pickle.py index 3916e5c..4683ec6 100644 --- a/Lib/bsddb/test/test_pickle.py +++ b/Lib/bsddb/test/test_pickle.py @@ -11,7 +11,7 @@ import glob try: # For Pythons w/distutils pybsddb from bsddb3 import db -except ImportError, e: +except ImportError as e: # For Python 2.3 from bsddb import db @@ -47,7 +47,7 @@ class pickleTestCase(unittest.TestCase): assert self.db['spam'] == 'eggs' try: self.db.put('spam', 'ham', flags=db.DB_NOOVERWRITE) - except db.DBError, egg: + except db.DBError as egg: pickledEgg = pickle.dumps(egg) #print repr(pickledEgg) rottenEgg = pickle.loads(pickledEgg) diff --git a/Lib/bsddb/test/test_recno.py b/Lib/bsddb/test/test_recno.py index 35399b5..7bf3695 100644 --- a/Lib/bsddb/test/test_recno.py +++ b/Lib/bsddb/test/test_recno.py @@ -29,7 +29,7 @@ class SimpleRecnoTestCase(unittest.TestCase): def tearDown(self): try: os.remove(self.filename) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise def test01_basic(self): @@ -63,7 +63,7 @@ class SimpleRecnoTestCase(unittest.TestCase): try: data = d[0] # This should raise a KeyError!?!?! - except db.DBInvalidArgError, val: + except db.DBInvalidArgError as val: assert val[0] == db.EINVAL if verbose: print val else: @@ -72,7 +72,7 @@ class SimpleRecnoTestCase(unittest.TestCase): # test that has_key raises DB exceptions (fixed in pybsddb 4.3.2) try: d.has_key(0) - except db.DBError, val: + except db.DBError as val: pass else: self.fail("has_key did not raise a proper exception") @@ -86,7 +86,7 @@ class SimpleRecnoTestCase(unittest.TestCase): try: data = d.get(100) - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: if get_returns_none: self.fail("unexpected exception") else: @@ -177,7 +177,7 @@ class SimpleRecnoTestCase(unittest.TestCase): try: d.get(99) - except db.DBKeyEmptyError, val: + except db.DBKeyEmptyError as val: if get_returns_none: self.fail("unexpected DBKeyEmptyError exception") else: @@ -267,7 +267,7 @@ class SimpleRecnoTestCase(unittest.TestCase): try: # this one will fail d.append('bad' * 20) - except db.DBInvalidArgError, val: + except db.DBInvalidArgError as val: assert val[0] == db.EINVAL if verbose: print val else: diff --git a/Lib/bsddb/test/test_thread.py b/Lib/bsddb/test/test_thread.py index bf19d21..b3d7ef9 100644 --- a/Lib/bsddb/test/test_thread.py +++ b/Lib/bsddb/test/test_thread.py @@ -57,7 +57,7 @@ class BaseThreadedTestCase(unittest.TestCase): self.homeDir = homeDir try: os.mkdir(homeDir) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise self.env = db.DBEnv() self.setEnvOpts() @@ -247,7 +247,7 @@ class SimpleThreadedBase(BaseThreadedTestCase): # flush them try: dbutils.DeadlockWrap(d.sync, max_retries=12) - except db.DBIncompleteError, val: + except db.DBIncompleteError as val: if verbose: print "could not complete sync()..." @@ -360,7 +360,7 @@ class ThreadedTransactionsBase(BaseThreadedTestCase): print "%s: records %d - %d finished" % (name, start, x) txn.commit() finished = True - except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: + except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) txn.abort() @@ -398,7 +398,7 @@ class ThreadedTransactionsBase(BaseThreadedTestCase): finished = True if verbose: print "%s: deleted records %s" % (name, recs) - except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: + except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) txn.abort() @@ -428,7 +428,7 @@ class ThreadedTransactionsBase(BaseThreadedTestCase): c.close() txn.commit() finished = True - except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: + except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) c.close() @@ -982,7 +982,7 @@ def print_directory(): print "<H3>Current Working Directory:</H3>" try: pwd = os.getcwd() - except os.error, msg: + except os.error as msg: print "os.error:", escape(str(msg)) else: print escape(pwd) diff --git a/Lib/codecs.py b/Lib/codecs.py index f834b8d..e4e14cf 100644 --- a/Lib/codecs.py +++ b/Lib/codecs.py @@ -13,7 +13,7 @@ import __builtin__, sys try: from _codecs import * -except ImportError, why: +except ImportError as why: raise SystemError('Failed to load the builtin codecs: %s' % why) __all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE", @@ -422,7 +422,7 @@ class StreamReader(Codec): data = self.bytebuffer + newdata try: newchars, decodedbytes = self.decode(data, self.errors) - except UnicodeDecodeError, exc: + except UnicodeDecodeError as exc: if firstline: newchars, decodedbytes = self.decode(data[:exc.start], self.errors) lines = newchars.splitlines(True) diff --git a/Lib/codeop.py b/Lib/codeop.py index 5616d92..6abde2e 100644 --- a/Lib/codeop.py +++ b/Lib/codeop.py @@ -80,18 +80,18 @@ def _maybe_compile(compiler, source, filename, symbol): try: code = compiler(source, filename, symbol) - except SyntaxError, err: + except SyntaxError as err: pass try: code1 = compiler(source + "\n", filename, symbol) - except SyntaxError, err1: - pass + except SyntaxError as e: + err1 = e try: code2 = compiler(source + "\n\n", filename, symbol) - except SyntaxError, err2: - pass + except SyntaxError as e: + err2 = e if code: return code diff --git a/Lib/compileall.py b/Lib/compileall.py index b21d95f..1e5c6a6 100644 --- a/Lib/compileall.py +++ b/Lib/compileall.py @@ -65,12 +65,12 @@ def compile_dir(dir, maxlevels=10, ddir=None, ok = py_compile.compile(fullname, None, dfile, True) except KeyboardInterrupt: raise KeyboardInterrupt - except py_compile.PyCompileError,err: + except py_compile.PyCompileError as err: if quiet: print 'Compiling', fullname, '...' print err.msg success = 0 - except IOError, e: + except IOError as e: print "Sorry", e success = 0 else: @@ -109,7 +109,7 @@ def main(): import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:') - except getopt.error, msg: + except getopt.error as msg: print msg print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ "[-x regexp] [directory ...]" diff --git a/Lib/compiler/pycodegen.py b/Lib/compiler/pycodegen.py index 325ca06..55d2617 100644 --- a/Lib/compiler/pycodegen.py +++ b/Lib/compiler/pycodegen.py @@ -227,7 +227,7 @@ class CodeGenerator: assert getattr(self, 'NameFinder') assert getattr(self, 'FunctionGen') assert getattr(self, 'ClassGen') - except AssertionError, msg: + except AssertionError as msg: intro = "Bad class construction for %s" % self.__class__.__name__ raise AssertionError, intro diff --git a/Lib/contextlib.py b/Lib/contextlib.py index a807c42..731bf8f 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -28,7 +28,7 @@ class GeneratorContextManager(object): try: self.gen.throw(type, value, traceback) raise RuntimeError("generator didn't stop after throw()") - except StopIteration, exc: + except StopIteration as exc: # Suppress the exception *unless* it's the same exception that # was passed to throw(). This prevents a StopIteration # raised inside the "with" statement from being suppressed @@ -48,7 +48,7 @@ class Dialect: def _validate(self): try: _Dialect(self) - except TypeError, e: + except TypeError as e: # We do this for compatibility with py2.3 raise Error(str(e)) diff --git a/Lib/ctypes/macholib/dyld.py b/Lib/ctypes/macholib/dyld.py index 376f65d..011a371 100644 --- a/Lib/ctypes/macholib/dyld.py +++ b/Lib/ctypes/macholib/dyld.py @@ -148,7 +148,7 @@ def framework_find(fn, executable_path=None, env=None): """ try: return dyld_find(fn, executable_path=executable_path, env=env) - except ValueError, e: + except ValueError as e: pass fmwk_index = fn.rfind('.framework') if fmwk_index == -1: diff --git a/Lib/ctypes/test/__init__.py b/Lib/ctypes/test/__init__.py index 2b745c2..245dda6 100644 --- a/Lib/ctypes/test/__init__.py +++ b/Lib/ctypes/test/__init__.py @@ -57,12 +57,12 @@ def get_tests(package, mask, verbosity): for modname in find_package_modules(package, mask): try: mod = __import__(modname, globals(), locals(), ['*']) - except ResourceDenied, detail: + except ResourceDenied as detail: skipped.append(modname) if verbosity > 1: print >> sys.stderr, "Skipped %s: %s" % (modname, detail) continue - except Exception, detail: + except Exception as detail: print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail) continue for name in dir(mod): diff --git a/Lib/ctypes/test/test_bitfields.py b/Lib/ctypes/test/test_bitfields.py index 2867cbf..c17ba3c 100644 --- a/Lib/ctypes/test/test_bitfields.py +++ b/Lib/ctypes/test/test_bitfields.py @@ -191,7 +191,7 @@ class BitFieldTest(unittest.TestCase): def get_except(self, func, *args, **kw): try: func(*args, **kw) - except Exception, detail: + except Exception as detail: return detail.__class__, str(detail) def test_mixed_1(self): diff --git a/Lib/ctypes/test/test_structures.py b/Lib/ctypes/test/test_structures.py index 613163d..097e1da 100644 --- a/Lib/ctypes/test/test_structures.py +++ b/Lib/ctypes/test/test_structures.py @@ -313,7 +313,7 @@ class StructureTestCase(unittest.TestCase): def get_except(self, func, *args): try: func(*args) - except Exception, detail: + except Exception as detail: return detail.__class__, str(detail) @@ -388,7 +388,7 @@ class TestRecursiveStructure(unittest.TestCase): try: Recursive._fields_ = [("next", Recursive)] - except AttributeError, details: + except AttributeError as details: self.failUnless("Structure or union cannot contain itself" in str(details)) else: @@ -405,7 +405,7 @@ class TestRecursiveStructure(unittest.TestCase): try: Second._fields_ = [("first", First)] - except AttributeError, details: + except AttributeError as details: self.failUnless("_fields_ is final" in str(details)) else: diff --git a/Lib/ctypes/util.py b/Lib/ctypes/util.py index 2ee2968..e65646a 100644 --- a/Lib/ctypes/util.py +++ b/Lib/ctypes/util.py @@ -60,12 +60,12 @@ elif os.name == "posix": finally: try: os.unlink(outfile) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise try: os.unlink(ccout) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise res = re.search(expr, trace) @@ -33,7 +33,7 @@ def dis(x=None): print "Disassembly of %s:" % name try: dis(x1) - except TypeError, msg: + except TypeError as msg: print "Sorry:", msg print elif hasattr(x, 'co_code'): diff --git a/Lib/distutils/bcppcompiler.py b/Lib/distutils/bcppcompiler.py index ca524a5..6968cb8 100644 --- a/Lib/distutils/bcppcompiler.py +++ b/Lib/distutils/bcppcompiler.py @@ -115,7 +115,7 @@ class BCPPCompiler(CCompiler) : # This needs to be compiled to a .res file -- do it now. try: self.spawn (["brcc32", "-fo", obj, src]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg continue # the 'for' loop @@ -139,7 +139,7 @@ class BCPPCompiler(CCompiler) : self.spawn ([self.cc] + compile_opts + pp_opts + [input_opt, output_opt] + extra_postargs + [src]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg return objects @@ -164,7 +164,7 @@ class BCPPCompiler(CCompiler) : pass # XXX what goes here? try: self.spawn ([self.lib] + lib_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LibError, msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -298,7 +298,7 @@ class BCPPCompiler(CCompiler) : self.mkpath (os.path.dirname (output_filename)) try: self.spawn ([self.linker] + ld_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LinkError, msg else: @@ -391,7 +391,7 @@ class BCPPCompiler(CCompiler) : self.mkpath(os.path.dirname(output_file)) try: self.spawn(pp_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: print msg raise CompileError, msg diff --git a/Lib/distutils/command/register.py b/Lib/distutils/command/register.py index 3177476..cb9525a 100644 --- a/Lib/distutils/command/register.py +++ b/Lib/distutils/command/register.py @@ -284,11 +284,11 @@ Your selection [default 1]: ''', data = '' try: result = opener.open(req) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if self.show_response: data = e.fp.read() result = e.code, e.msg - except urllib2.URLError, e: + except urllib2.URLError as e: result = 500, str(e) else: if self.show_response: diff --git a/Lib/distutils/command/sdist.py b/Lib/distutils/command/sdist.py index 3dfe6f2..eb2db50 100644 --- a/Lib/distutils/command/sdist.py +++ b/Lib/distutils/command/sdist.py @@ -333,7 +333,7 @@ class sdist (Command): try: self.filelist.process_template_line(line) - except DistutilsTemplateError, msg: + except DistutilsTemplateError as msg: self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg)) diff --git a/Lib/distutils/command/upload.py b/Lib/distutils/command/upload.py index 67ba080..7f96a47 100644 --- a/Lib/distutils/command/upload.py +++ b/Lib/distutils/command/upload.py @@ -184,7 +184,7 @@ class upload(Command): http.putheader('Authorization', auth) http.endheaders() http.send(body) - except socket.error, e: + except socket.error as e: self.announce(str(e), log.ERROR) return diff --git a/Lib/distutils/core.py b/Lib/distutils/core.py index 85a28fe..4dc8eb0 100644 --- a/Lib/distutils/core.py +++ b/Lib/distutils/core.py @@ -110,7 +110,7 @@ def setup (**attrs): # (ie. everything except distclass) to initialize it try: _setup_distribution = dist = klass(attrs) - except DistutilsSetupError, msg: + except DistutilsSetupError as msg: if 'name' not in attrs: raise SystemExit, "error in %s setup command: %s" % \ (attrs['name'], msg) @@ -135,7 +135,7 @@ def setup (**attrs): # fault, so turn them into SystemExit to suppress tracebacks. try: ok = dist.parse_command_line() - except DistutilsArgError, msg: + except DistutilsArgError as msg: raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg if DEBUG: @@ -151,7 +151,7 @@ def setup (**attrs): dist.run_commands() except KeyboardInterrupt: raise SystemExit, "interrupted" - except (IOError, os.error), exc: + except (IOError, os.error) as exc: error = grok_environment_error(exc) if DEBUG: @@ -161,7 +161,7 @@ def setup (**attrs): raise SystemExit, error except (DistutilsError, - CCompilerError), msg: + CCompilerError) as msg: if DEBUG: raise else: diff --git a/Lib/distutils/cygwinccompiler.py b/Lib/distutils/cygwinccompiler.py index 4fd23e6..44b5850 100644 --- a/Lib/distutils/cygwinccompiler.py +++ b/Lib/distutils/cygwinccompiler.py @@ -142,13 +142,13 @@ class CygwinCCompiler (UnixCCompiler): # gcc needs '.res' and '.rc' compiled to object files !!! try: self.spawn(["windres", "-i", src, "-o", obj]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg else: # for other files use the C-compiler try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def link (self, @@ -379,7 +379,7 @@ def check_config_h(): s = f.read() f.close() - except IOError, exc: + except IOError as exc: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing return (CONFIG_H_UNCERTAIN, diff --git a/Lib/distutils/dir_util.py b/Lib/distutils/dir_util.py index 92f4934..398f242 100644 --- a/Lib/distutils/dir_util.py +++ b/Lib/distutils/dir_util.py @@ -75,7 +75,7 @@ def mkpath (name, mode=0777, verbose=0, dry_run=0): try: os.mkdir(head) created_dirs.append(head) - except OSError, exc: + except OSError as exc: raise DistutilsFileError, \ "could not create '%s': %s" % (head, exc[-1]) @@ -142,7 +142,8 @@ def copy_tree (src, dst, "cannot copy tree '%s': not a directory" % src try: names = os.listdir(src) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e if dry_run: names = [] else: @@ -209,7 +210,7 @@ def remove_tree (directory, verbose=0, dry_run=0): abspath = os.path.abspath(cmd[1]) if abspath in _path_created: del _path_created[abspath] - except (IOError, OSError), exc: + except (IOError, OSError) as exc: log.warn(grok_environment_error( exc, "error removing %s: " % directory)) diff --git a/Lib/distutils/dist.py b/Lib/distutils/dist.py index d098cb9..d21c5e2 100644 --- a/Lib/distutils/dist.py +++ b/Lib/distutils/dist.py @@ -398,7 +398,7 @@ Common commands: (see '--help-commands' for more) setattr(self, opt, strtobool(val)) else: setattr(self, opt, val) - except ValueError, msg: + except ValueError as msg: raise DistutilsOptionError, msg # parse_config_files () @@ -515,7 +515,7 @@ Common commands: (see '--help-commands' for more) # it takes. try: cmd_class = self.get_command_class(command) - except DistutilsModuleError, msg: + except DistutilsModuleError as msg: raise DistutilsArgError, msg # Require that the command class be derived from Command -- want @@ -917,7 +917,7 @@ Common commands: (see '--help-commands' for more) raise DistutilsOptionError, \ ("error in %s: command '%s' has no such option '%s'" % (source, command_name, option)) - except ValueError, msg: + except ValueError as msg: raise DistutilsOptionError, msg def reinitialize_command (self, command, reinit_subcommands=0): diff --git a/Lib/distutils/emxccompiler.py b/Lib/distutils/emxccompiler.py index f52e632..8aef2b7 100644 --- a/Lib/distutils/emxccompiler.py +++ b/Lib/distutils/emxccompiler.py @@ -79,13 +79,13 @@ class EMXCCompiler (UnixCCompiler): # gcc requires '.rc' compiled to binary ('.res') files !!! try: self.spawn(["rc", "-r", src]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg else: # for other files use the C-compiler try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def link (self, @@ -275,7 +275,7 @@ def check_config_h(): s = f.read() f.close() - except IOError, exc: + except IOError as exc: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing return (CONFIG_H_UNCERTAIN, diff --git a/Lib/distutils/fancy_getopt.py b/Lib/distutils/fancy_getopt.py index 31cf0c5..62a24e8 100644 --- a/Lib/distutils/fancy_getopt.py +++ b/Lib/distutils/fancy_getopt.py @@ -256,7 +256,7 @@ class FancyGetopt: short_opts = string.join(self.short_opts) try: opts, args = getopt.getopt(args, short_opts, self.long_opts) - except getopt.error, msg: + except getopt.error as msg: raise DistutilsArgError, msg for opt, val in opts: diff --git a/Lib/distutils/file_util.py b/Lib/distutils/file_util.py index 37b152e..c225ad3 100644 --- a/Lib/distutils/file_util.py +++ b/Lib/distutils/file_util.py @@ -32,27 +32,31 @@ def _copy_file_contents (src, dst, buffer_size=16*1024): try: try: fsrc = open(src, 'rb') - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not open '%s': %s" % (src, errstr) if os.path.exists(dst): try: os.unlink(dst) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not delete '%s': %s" % (dst, errstr) try: fdst = open(dst, 'wb') - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not create '%s': %s" % (dst, errstr) while 1: try: buf = fsrc.read(buffer_size) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not read from '%s': %s" % (src, errstr) @@ -61,7 +65,8 @@ def _copy_file_contents (src, dst, buffer_size=16*1024): try: fdst.write(buf) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not write to '%s': %s" % (dst, errstr) @@ -146,7 +151,7 @@ def copy_file (src, dst, import macostools try: macostools.copy(src, dst, 0, preserve_times) - except os.error, exc: + except os.error as exc: raise DistutilsFileError, \ "could not copy '%s' to '%s': %s" % (src, dst, exc[-1]) @@ -217,7 +222,8 @@ def move_file (src, dst, copy_it = 0 try: os.rename(src, dst) - except os.error, (num, msg): + except os.error as e: + (num, msg) = e if num == errno.EXDEV: copy_it = 1 else: @@ -228,7 +234,8 @@ def move_file (src, dst, copy_file(src, dst) try: os.unlink(src) - except os.error, (num, msg): + except os.error as e: + (num, msg) = e try: os.unlink(dst) except os.error: diff --git a/Lib/distutils/msvccompiler.py b/Lib/distutils/msvccompiler.py index 9ec3508..968a4ff 100644 --- a/Lib/distutils/msvccompiler.py +++ b/Lib/distutils/msvccompiler.py @@ -129,7 +129,7 @@ class MacroExpander: self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") - except KeyError, exc: # + except KeyError as exc: # raise DistutilsPlatformError, \ ("""Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. @@ -371,7 +371,7 @@ class MSVCCompiler (CCompiler) : try: self.spawn ([self.rc] + pp_opts + [output_opt] + [input_opt]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg continue elif ext in self._mc_extensions: @@ -400,7 +400,7 @@ class MSVCCompiler (CCompiler) : self.spawn ([self.rc] + ["/fo" + obj] + [rc_file]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg continue else: @@ -414,7 +414,7 @@ class MSVCCompiler (CCompiler) : self.spawn ([self.cc] + compile_opts + pp_opts + [input_opt, output_opt] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg return objects @@ -440,7 +440,7 @@ class MSVCCompiler (CCompiler) : pass # XXX what goes here? try: self.spawn ([self.lib] + lib_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LibError, msg else: @@ -519,7 +519,7 @@ class MSVCCompiler (CCompiler) : self.mkpath (os.path.dirname (output_filename)) try: self.spawn ([self.linker] + ld_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LinkError, msg else: diff --git a/Lib/distutils/spawn.py b/Lib/distutils/spawn.py index e5654ff..6b07f52 100644 --- a/Lib/distutils/spawn.py +++ b/Lib/distutils/spawn.py @@ -78,7 +78,7 @@ def _spawn_nt (cmd, # spawn for NT requires a full path to the .exe try: rc = os.spawnv(os.P_WAIT, executable, cmd) - except OSError, exc: + except OSError as exc: # this seems to happen when the command isn't found raise DistutilsExecError, \ "command '%s' failed: %s" % (cmd[0], exc[-1]) @@ -103,7 +103,7 @@ def _spawn_os2 (cmd, # spawnv for OS/2 EMX requires a full path to the .exe try: rc = os.spawnv(os.P_WAIT, executable, cmd) - except OSError, exc: + except OSError as exc: # this seems to happen when the command isn't found raise DistutilsExecError, \ "command '%s' failed: %s" % (cmd[0], exc[-1]) @@ -131,7 +131,7 @@ def _spawn_posix (cmd, #print "cmd[0] =", cmd[0] #print "cmd =", cmd exec_fn(cmd[0], cmd) - except OSError, e: + except OSError as e: sys.stderr.write("unable to execute %s: %s\n" % (cmd[0], e.strerror)) os._exit(1) @@ -146,7 +146,7 @@ def _spawn_posix (cmd, while 1: try: (pid, status) = os.waitpid(pid, 0) - except OSError, exc: + except OSError as exc: import errno if exc.errno == errno.EINTR: continue diff --git a/Lib/distutils/sysconfig.py b/Lib/distutils/sysconfig.py index 8989d92..9de7234 100644 --- a/Lib/distutils/sysconfig.py +++ b/Lib/distutils/sysconfig.py @@ -344,7 +344,7 @@ def _init_posix(): try: filename = get_makefile_filename() parse_makefile(filename, g) - except IOError, msg: + except IOError as msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror @@ -355,7 +355,7 @@ def _init_posix(): try: filename = get_config_h_filename() parse_config_h(open(filename), g) - except IOError, msg: + except IOError as msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror diff --git a/Lib/distutils/unixccompiler.py b/Lib/distutils/unixccompiler.py index 75e8a53..0795f12 100644 --- a/Lib/distutils/unixccompiler.py +++ b/Lib/distutils/unixccompiler.py @@ -162,7 +162,7 @@ class UnixCCompiler(CCompiler): self.mkpath(os.path.dirname(output_file)) try: self.spawn(pp_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): @@ -172,7 +172,7 @@ class UnixCCompiler(CCompiler): try: self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def create_static_lib(self, objects, output_libname, @@ -196,7 +196,7 @@ class UnixCCompiler(CCompiler): if self.ranlib: try: self.spawn(self.ranlib + [output_filename]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LibError, msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -250,7 +250,7 @@ class UnixCCompiler(CCompiler): linker = _darwin_compiler_fixup(linker, ld_args) self.spawn(linker + ld_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LinkError, msg else: log.debug("skipping %s (up-to-date)", output_filename) diff --git a/Lib/distutils/util.py b/Lib/distutils/util.py index 1bcda93..16d8bcb 100644 --- a/Lib/distutils/util.py +++ b/Lib/distutils/util.py @@ -229,7 +229,7 @@ def subst_vars (s, local_vars): try: return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s) - except KeyError, var: + except KeyError as var: raise ValueError, "invalid variable '$%s'" % var # subst_vars () diff --git a/Lib/doctest.py b/Lib/doctest.py index 435e13b..d120a01 100644 --- a/Lib/doctest.py +++ b/Lib/doctest.py @@ -1604,8 +1604,8 @@ class DebugRunner(DocTestRunner): ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) - ... except UnexpectedException, failure: - ... pass + ... except UnexpectedException as f: + ... failure = f >>> failure.test is test True @@ -1632,8 +1632,8 @@ class DebugRunner(DocTestRunner): >>> try: ... runner.run(test) - ... except DocTestFailure, failure: - ... pass + ... except DocTestFailure as f: + ... failure = f DocTestFailure objects provide access to the test: @@ -2141,8 +2141,8 @@ class DocTestCase(unittest.TestCase): >>> case = DocTestCase(test) >>> try: ... case.debug() - ... except UnexpectedException, failure: - ... pass + ... except UnexpectedException as f: + ... failure = f The UnexpectedException contains the test, the example, and the original exception: @@ -2170,8 +2170,8 @@ class DocTestCase(unittest.TestCase): >>> try: ... case.debug() - ... except DocTestFailure, failure: - ... pass + ... except DocTestFailure as f: + ... failure = f DocTestFailure objects provide access to the test: diff --git a/Lib/encodings/uu_codec.py b/Lib/encodings/uu_codec.py index 43fb93c..3baf779 100644 --- a/Lib/encodings/uu_codec.py +++ b/Lib/encodings/uu_codec.py @@ -81,7 +81,7 @@ def uu_decode(input,errors='strict'): break try: data = a2b_uu(s) - except binascii.Error, v: + except binascii.Error as v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = a2b_uu(s[:nbytes]) diff --git a/Lib/filecmp.py b/Lib/filecmp.py index 9885765..51a97a5 100644 --- a/Lib/filecmp.py +++ b/Lib/filecmp.py @@ -148,12 +148,12 @@ class dircmp: ok = 1 try: a_stat = os.stat(a_path) - except os.error, why: + except os.error as why: # print 'Can\'t stat', a_path, ':', why[1] ok = 0 try: b_stat = os.stat(b_path) - except os.error, why: + except os.error as why: # print 'Can\'t stat', b_path, ':', why[1] ok = 0 diff --git a/Lib/ftplib.py b/Lib/ftplib.py index 9cb67dd..72f5c89 100644 --- a/Lib/ftplib.py +++ b/Lib/ftplib.py @@ -119,7 +119,7 @@ class FTP: try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None @@ -277,7 +277,7 @@ class FTP: try: sock = socket.socket(af, socktype, proto) sock.bind(sa) - except socket.error, msg: + except socket.error as msg: if sock: sock.close() sock = None @@ -496,7 +496,7 @@ class FTP: if dirname == '..': try: return self.voidcmd('CDUP') - except error_perm, msg: + except error_perm as msg: if msg.args[0][:3] != '500': raise elif dirname == '': diff --git a/Lib/hotshot/stones.py b/Lib/hotshot/stones.py index cd4c51d..7f88606 100644 --- a/Lib/hotshot/stones.py +++ b/Lib/hotshot/stones.py @@ -19,7 +19,7 @@ def main(logfile): stats.sort_stats('time', 'calls') try: stats.print_stats(20) - except IOError, e: + except IOError as e: if e.errno != errno.EPIPE: raise diff --git a/Lib/htmllib.py b/Lib/htmllib.py index 24a2e2f..652519f 100644 --- a/Lib/htmllib.py +++ b/Lib/htmllib.py @@ -463,7 +463,7 @@ def test(args = None): else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) diff --git a/Lib/httplib.py b/Lib/httplib.py index 1e0037f..93c081a 100644 --- a/Lib/httplib.py +++ b/Lib/httplib.py @@ -667,7 +667,7 @@ class HTTPConnection: if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: @@ -713,7 +713,7 @@ class HTTPConnection: data=str.read(blocksize) else: self.sock.sendall(str) - except socket.error, v: + except socket.error as v: if v[0] == 32: # Broken pipe self.close() raise @@ -868,7 +868,7 @@ class HTTPConnection: try: self._send_request(method, url, body, headers) - except socket.error, v: + except socket.error as v: # trap 'Broken pipe' if we're allowed to automatically reconnect if v[0] != 32 or not self.auto_open: raise @@ -890,7 +890,7 @@ class HTTPConnection: thelen=None try: thelen=str(len(body)) - except TypeError, te: + except TypeError as te: # If this is a file-like object, try to # fstat its file descriptor import os @@ -1019,7 +1019,7 @@ class SSLFile(SharedSocketClient): while True: try: buf = self._ssl.read(self._bufsize) - except socket.sslerror, err: + except socket.sslerror as err: if (err[0] == socket.SSL_ERROR_WANT_READ or err[0] == socket.SSL_ERROR_WANT_WRITE): continue @@ -1027,7 +1027,7 @@ class SSLFile(SharedSocketClient): or err[0] == socket.SSL_ERROR_EOF): break raise - except socket.error, err: + except socket.error as err: if err[0] == errno.EINTR: continue if err[0] == errno.EBADF: @@ -1215,7 +1215,7 @@ class HTTP: """ try: response = self._conn.getresponse() - except BadStatusLine, e: + except BadStatusLine as e: ### hmm. if getresponse() ever closes the socket on a bad request, ### then we are going to have problems with self.sock diff --git a/Lib/idlelib/ClassBrowser.py b/Lib/idlelib/ClassBrowser.py index e5a60a5..d3f9048 100644 --- a/Lib/idlelib/ClassBrowser.py +++ b/Lib/idlelib/ClassBrowser.py @@ -94,7 +94,7 @@ class ModuleBrowserTreeItem(TreeItem): return [] try: dict = pyclbr.readmodule_ex(name, [dir] + sys.path) - except ImportError, msg: + except ImportError as msg: return [] items = [] self.classes = {} diff --git a/Lib/idlelib/EditorWindow.py b/Lib/idlelib/EditorWindow.py index 1841b1c..400c31c 100644 --- a/Lib/idlelib/EditorWindow.py +++ b/Lib/idlelib/EditorWindow.py @@ -505,7 +505,7 @@ class EditorWindow(object): # XXX Ought to insert current file's directory in front of path try: (f, file, (suffix, mode, type)) = _find_module(name) - except (NameError, ImportError), msg: + except (NameError, ImportError) as msg: tkMessageBox.showerror("Import error", str(msg), parent=self.text) return if type != imp.PY_SOURCE: diff --git a/Lib/idlelib/GrepDialog.py b/Lib/idlelib/GrepDialog.py index ab136bc..99d2e4d 100644 --- a/Lib/idlelib/GrepDialog.py +++ b/Lib/idlelib/GrepDialog.py @@ -82,7 +82,7 @@ class GrepDialog(SearchDialogBase): for fn in list: try: f = open(fn) - except IOError, msg: + except IOError as msg: print msg continue lineno = 0 @@ -110,7 +110,7 @@ class GrepDialog(SearchDialogBase): def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) - except os.error, msg: + except os.error as msg: print msg return [] list = [] diff --git a/Lib/idlelib/IOBinding.py b/Lib/idlelib/IOBinding.py index deeb5c5..e23b40c 100644 --- a/Lib/idlelib/IOBinding.py +++ b/Lib/idlelib/IOBinding.py @@ -246,7 +246,7 @@ class IOBinding: f = open(filename,'rb') chars = f.read() f.close() - except IOError, msg: + except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False @@ -289,7 +289,7 @@ class IOBinding: # Next look for coding specification try: enc = coding_spec(chars) - except LookupError, name: + except LookupError as name: tkMessageBox.showerror( title="Error loading the file", message="The encoding '%s' is not known to this Python "\ @@ -380,7 +380,7 @@ class IOBinding: f.flush() f.close() return True - except IOError, msg: + except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False @@ -400,7 +400,7 @@ class IOBinding: try: enc = coding_spec(chars) failed = None - except LookupError, msg: + except LookupError as msg: failed = msg enc = None if enc: diff --git a/Lib/idlelib/PyShell.py b/Lib/idlelib/PyShell.py index 20d00be..46ef211 100644 --- a/Lib/idlelib/PyShell.py +++ b/Lib/idlelib/PyShell.py @@ -380,7 +380,7 @@ class ModifiedInterpreter(InteractiveInterpreter): try: self.rpcclt = MyRPCClient(addr) break - except socket.error, err: + except socket.error as err: pass else: self.display_port_binding_error() @@ -389,7 +389,7 @@ class ModifiedInterpreter(InteractiveInterpreter): self.rpcclt.listening_sock.settimeout(10) try: self.rpcclt.accept() - except socket.timeout, err: + except socket.timeout as err: self.display_no_subprocess_error() return None self.rpcclt.register("stdin", self.tkconsole) @@ -423,7 +423,7 @@ class ModifiedInterpreter(InteractiveInterpreter): self.spawn_subprocess() try: self.rpcclt.accept() - except socket.timeout, err: + except socket.timeout as err: self.display_no_subprocess_error() return None self.transfer_path() @@ -1324,7 +1324,7 @@ def main(): startup = False try: opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:") - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) diff --git a/Lib/idlelib/ScriptBinding.py b/Lib/idlelib/ScriptBinding.py index 3746eb8..a83f715 100644 --- a/Lib/idlelib/ScriptBinding.py +++ b/Lib/idlelib/ScriptBinding.py @@ -66,13 +66,13 @@ class ScriptBinding: f = open(filename, 'r') try: tabnanny.process_tokens(tokenize.generate_tokens(f.readline)) - except tokenize.TokenError, msg: + except tokenize.TokenError as msg: msgtxt, (lineno, start) = msg self.editwin.gotoline(lineno) self.errorbox("Tabnanny Tokenizing Error", "Token Error: %s" % msgtxt) return False - except tabnanny.NannyNag, nag: + except tabnanny.NannyNag as nag: # The error messages from tabnanny are too confusing... self.editwin.gotoline(nag.get_lineno()) self.errorbox("Tab/space error", indent_message) @@ -97,7 +97,7 @@ class ScriptBinding: try: # If successful, return the compiled code return compile(source, filename, "exec") - except (SyntaxError, OverflowError), err: + except (SyntaxError, OverflowError) as err: try: msg, (errorfilename, lineno, offset, line) = err if not errorfilename: diff --git a/Lib/idlelib/SearchEngine.py b/Lib/idlelib/SearchEngine.py index cc40a00..6745faf 100644 --- a/Lib/idlelib/SearchEngine.py +++ b/Lib/idlelib/SearchEngine.py @@ -66,7 +66,7 @@ class SearchEngine: flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) - except re.error, what: + except re.error as what: try: msg, col = what except: diff --git a/Lib/idlelib/run.py b/Lib/idlelib/run.py index 61364a5..6b29003 100644 --- a/Lib/idlelib/run.py +++ b/Lib/idlelib/run.py @@ -114,7 +114,7 @@ def manage_socket(address): try: server = MyRPCServer(address, MyHandler) break - except socket.error, err: + except socket.error as err: print>>sys.__stderr__,"IDLE Subprocess: socket error: "\ + err[1] + ", retrying...." else: diff --git a/Lib/imaplib.py b/Lib/imaplib.py index 08e1520..11e262e 100644 --- a/Lib/imaplib.py +++ b/Lib/imaplib.py @@ -845,7 +845,7 @@ class IMAP4: try: self.send('%s%s' % (data, CRLF)) - except (socket.error, OSError), val: + except (socket.error, OSError) as val: raise self.abort('socket error: %s' % val) if literal is None: @@ -870,7 +870,7 @@ class IMAP4: try: self.send(literal) self.send(CRLF) - except (socket.error, OSError), val: + except (socket.error, OSError) as val: raise self.abort('socket error: %s' % val) if not literator: @@ -883,9 +883,9 @@ class IMAP4: self._check_bye() try: typ, data = self._get_tagged_response(tag) - except self.abort, val: + except self.abort as val: raise self.abort('command: %s => %s' % (name, val)) - except self.error, val: + except self.error as val: raise self.error('command: %s => %s' % (name, val)) self._check_bye() if typ == 'BAD': @@ -984,7 +984,7 @@ class IMAP4: try: self._get_response() - except self.abort, val: + except self.abort as val: if __debug__: if self.debug >= 1: self.print_log() @@ -1402,7 +1402,7 @@ if __name__ == '__main__': try: optlist, args = getopt.getopt(sys.argv[1:], 'd:s:') - except getopt.error, val: + except getopt.error as val: optlist, args = (), () stream_command = None diff --git a/Lib/lib-tk/Tkinter.py b/Lib/lib-tk/Tkinter.py index f8538ed..157b066 100644 --- a/Lib/lib-tk/Tkinter.py +++ b/Lib/lib-tk/Tkinter.py @@ -85,7 +85,7 @@ def _cnfmerge(cnfs): for c in _flatten(cnfs): try: cnf.update(c) - except (AttributeError, TypeError), msg: + except (AttributeError, TypeError) as msg: print "_cnfmerge: fallback due to:", msg for k, v in c.items(): cnf[k] = v @@ -1401,7 +1401,7 @@ class CallWrapper: if self.subst: args = self.subst(*args) return self.func(*args) - except SystemExit, msg: + except SystemExit as msg: raise SystemExit, msg except: self.widget._report_exception() diff --git a/Lib/linecache.py b/Lib/linecache.py index 4838625..89383ea 100644 --- a/Lib/linecache.py +++ b/Lib/linecache.py @@ -78,7 +78,7 @@ def updatecache(filename, module_globals=None): fullname = filename try: stat = os.stat(fullname) - except os.error, msg: + except os.error as msg: basename = os.path.split(filename)[1] # Try for a __loader__, if available @@ -128,7 +128,7 @@ def updatecache(filename, module_globals=None): fp = open(fullname, 'rU') lines = fp.readlines() fp.close() - except IOError, msg: + except IOError as msg: ## print '*** Cannot open', fullname, ':', msg return [] size, mtime = stat.st_size, stat.st_mtime diff --git a/Lib/logging/config.py b/Lib/logging/config.py index a9970d0..41d577f 100644 --- a/Lib/logging/config.py +++ b/Lib/logging/config.py @@ -288,7 +288,7 @@ def listen(port=DEFAULT_LOGGING_CONFIG_PORT): except: traceback.print_exc() os.remove(file) - except socket.error, e: + except socket.error as e: if type(e.args) != types.TupleType: raise else: diff --git a/Lib/mailbox.py b/Lib/mailbox.py index 8d1df4b..2293a6c 100755 --- a/Lib/mailbox.py +++ b/Lib/mailbox.py @@ -258,7 +258,7 @@ class Maildir(Mailbox): os.remove(tmp_file.name) else: os.rename(tmp_file.name, dest) - except OSError, e: + except OSError as e: os.remove(tmp_file.name) if e.errno == errno.EEXIST: raise ExternalClashError('Name clash with existing message: %s' @@ -280,7 +280,7 @@ class Maildir(Mailbox): self.remove(key) except KeyError: pass - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise @@ -437,12 +437,12 @@ class Maildir(Mailbox): path = os.path.join(self._path, 'tmp', uniq) try: os.stat(path) - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: Maildir._count += 1 try: return _create_carefully(path) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise else: @@ -495,7 +495,7 @@ class _singlefileMailbox(Mailbox): Mailbox.__init__(self, path, factory, create) try: f = open(self._path, 'rb+') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: if create: f = open(self._path, 'wb+') @@ -605,7 +605,7 @@ class _singlefileMailbox(Mailbox): self._file.close() try: os.rename(new_file.name, self._path) - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(self._path) @@ -837,7 +837,7 @@ class MH(Mailbox): path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -859,7 +859,7 @@ class MH(Mailbox): path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -885,7 +885,7 @@ class MH(Mailbox): f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -912,7 +912,7 @@ class MH(Mailbox): f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -932,7 +932,7 @@ class MH(Mailbox): """Return a file-like representation or raise a KeyError.""" try: f = open(os.path.join(self._path, str(key)), 'rb') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -1843,7 +1843,7 @@ def _lock_file(f, dotlock=True): if fcntl: try: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) - except IOError, e: + except IOError as e: if e.errno in (errno.EAGAIN, errno.EACCES): raise ExternalClashError('lockf: lock unavailable: %s' % f.name) @@ -1853,7 +1853,7 @@ def _lock_file(f, dotlock=True): try: pre_lock = _create_temporary(f.name + '.lock') pre_lock.close() - except IOError, e: + except IOError as e: if e.errno == errno.EACCES: return # Without write access, just skip dotlocking. else: @@ -1866,7 +1866,7 @@ def _lock_file(f, dotlock=True): else: os.rename(pre_lock.name, f.name + '.lock') dotlock_done = True - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(pre_lock.name) diff --git a/Lib/mhlib.py b/Lib/mhlib.py index 1a90375..8ae6bad 100644 --- a/Lib/mhlib.py +++ b/Lib/mhlib.py @@ -370,7 +370,7 @@ class Folder: count = len(all) try: anchor = self._parseindex(head, all) - except Error, msg: + except Error as msg: seqs = self.getsequences() if not head in seqs: if not msg: @@ -407,7 +407,7 @@ class Folder: # Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence try: n = self._parseindex(seq, all) - except Error, msg: + except Error as msg: seqs = self.getsequences() if not seq in seqs: if not msg: @@ -471,7 +471,7 @@ class Folder: pass try: os.rename(path, commapath) - except os.error, msg: + except os.error as msg: errors.append(msg) else: deleted.append(n) @@ -499,7 +499,7 @@ class Folder: try: shutil.copy2(path, topath) os.unlink(path) - except (IOError, os.error), msg: + except (IOError, os.error) as msg: errors.append(msg) try: os.unlink(topath) @@ -989,7 +989,7 @@ def test(): 'all'): try: do('f.parsesequence(%r)' % (seq,)) - except Error, msg: + except Error as msg: print "Error:", msg stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read() list = map(int, stuff.split()) diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index b0d2f18..83071d4 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -510,7 +510,7 @@ More than one type argument may be given. try: opts, args = getopt.getopt(sys.argv[1:], 'hle', ['help', 'lenient', 'extension']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) strict = 1 diff --git a/Lib/modulefinder.py b/Lib/modulefinder.py index 9c90d8d..04c9abf 100644 --- a/Lib/modulefinder.py +++ b/Lib/modulefinder.py @@ -317,7 +317,7 @@ class ModuleFinder: return try: self.import_hook(name, caller, level=level) - except ImportError, msg: + except ImportError as msg: self.msg(2, "ImportError:", str(msg)) self._add_badmodule(name, caller) else: @@ -328,7 +328,7 @@ class ModuleFinder: continue try: self.import_hook(name, caller, [sub], level=level) - except ImportError, msg: + except ImportError as msg: self.msg(2, "ImportError:", str(msg)) fullname = name + "." + sub self._add_badmodule(fullname, caller) @@ -602,7 +602,7 @@ def test(): import getopt try: opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") - except getopt.error, msg: + except getopt.error as msg: print msg return diff --git a/Lib/msilib/__init__.py b/Lib/msilib/__init__.py index 9efef91..b14bc32 100644 --- a/Lib/msilib/__init__.py +++ b/Lib/msilib/__init__.py @@ -111,7 +111,7 @@ def add_data(db, table, values): raise TypeError, "Unsupported type %s" % field.__class__.__name__ try: v.Modify(MSIMODIFY_INSERT, r) - except Exception, e: + except Exception as e: raise MSIError("Could not insert "+repr(values)+" into "+table) r.ClearData() diff --git a/Lib/nntplib.py b/Lib/nntplib.py index cc51d1d..6e6a2b6 100644 --- a/Lib/nntplib.py +++ b/Lib/nntplib.py @@ -127,7 +127,7 @@ class NNTP: except NNTPPermanentError: # error 500, probably 'not implemented' pass - except NNTPTemporaryError, e: + except NNTPTemporaryError as e: if user and e.response[:3] == '480': # Need authorization before 'mode reader' readermode_afterauth = 1 diff --git a/Lib/optparse.py b/Lib/optparse.py index f8f643d..e1c675a 100644 --- a/Lib/optparse.py +++ b/Lib/optparse.py @@ -1376,7 +1376,7 @@ class OptionParser (OptionContainer): try: stop = self._process_args(largs, rargs, values) - except (BadOptionError, OptionValueError), err: + except (BadOptionError, OptionValueError) as err: self.error(str(err)) args = largs + rargs @@ -163,7 +163,7 @@ def makedirs(name, mode=0777): if head and tail and not path.exists(head): try: makedirs(head, mode) - except OSError, e: + except OSError as e: # be happy if someone already created the path if e.errno != EEXIST: raise @@ -284,7 +284,7 @@ def walk(top, topdown=True, onerror=None): # Note that listdir and error are globals in this module due # to earlier import-*. names = listdir(top) - except error, err: + except error as err: if onerror is not None: onerror(err) return @@ -390,7 +390,7 @@ def _execvpe(file, args, env=None): fullname = path.join(dir, file) try: func(fullname, *argrest) - except error, e: + except error as e: tb = sys.exc_info()[2] if (e.errno != ENOENT and e.errno != ENOTDIR and saved_exc is None): @@ -330,7 +330,7 @@ class Pdb(bdb.Bdb, cmd.Cmd): arg = arg[colon+1:].lstrip() try: lineno = int(arg) - except ValueError, msg: + except ValueError as msg: print >>self.stdout, '*** Bad lineno:', arg return else: @@ -618,7 +618,7 @@ class Pdb(bdb.Bdb, cmd.Cmd): self.curframe.f_lineno = arg self.stack[self.curindex] = self.stack[self.curindex][0], arg self.print_stack_entry(self.stack[self.curindex]) - except ValueError, e: + except ValueError as e: print >>self.stdout, '*** Jump failed:', e do_j = do_jump diff --git a/Lib/pickle.py b/Lib/pickle.py index b0b3aa1..b32ee83 100644 --- a/Lib/pickle.py +++ b/Lib/pickle.py @@ -816,7 +816,7 @@ class Unpickler: while 1: key = read(1) dispatch[key](self) - except _Stop, stopinst: + except _Stop as stopinst: return stopinst.value # Return largest index k such that self.stack[k] is self.mark. @@ -1018,7 +1018,7 @@ class Unpickler: if not instantiated: try: value = klass(*args) - except TypeError, err: + except TypeError as err: raise TypeError, "in constructor for %s: %s" % ( klass.__name__, str(err)), sys.exc_info()[2] self.append(value) diff --git a/Lib/pkgutil.py b/Lib/pkgutil.py index 37738e4..5b6b169 100644 --- a/Lib/pkgutil.py +++ b/Lib/pkgutil.py @@ -532,7 +532,7 @@ def extend_path(path, name): if os.path.isfile(pkgfile): try: f = open(pkgfile) - except IOError, msg: + except IOError as msg: sys.stderr.write("Can't open %s: %s\n" % (pkgfile, msg)) else: diff --git a/Lib/plat-irix5/torgb.py b/Lib/plat-irix5/torgb.py index 54c86c4..02bcb53 100755 --- a/Lib/plat-irix5/torgb.py +++ b/Lib/plat-irix5/torgb.py @@ -80,7 +80,7 @@ def _torgb(filename, temps): fname = filename try: ftype = imghdr.what(fname) - except IOError, msg: + except IOError as msg: if type(msg) == type(()) and len(msg) == 2 and \ type(msg[0]) == type(0) and type(msg[1]) == type(''): msg = msg[1] diff --git a/Lib/plat-irix6/torgb.py b/Lib/plat-irix6/torgb.py index 54c86c4..02bcb53 100644 --- a/Lib/plat-irix6/torgb.py +++ b/Lib/plat-irix6/torgb.py @@ -80,7 +80,7 @@ def _torgb(filename, temps): fname = filename try: ftype = imghdr.what(fname) - except IOError, msg: + except IOError as msg: if type(msg) == type(()) and len(msg) == 2 and \ type(msg[0]) == type(0) and type(msg[1]) == type(''): msg = msg[1] diff --git a/Lib/plat-mac/EasyDialogs.py b/Lib/plat-mac/EasyDialogs.py index 1bd46a8..340e3ed 100644 --- a/Lib/plat-mac/EasyDialogs.py +++ b/Lib/plat-mac/EasyDialogs.py @@ -651,7 +651,7 @@ def AskFileForOpen( try: rr = Nav.NavChooseFile(args) good = 1 - except Nav.error, arg: + except Nav.error as arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None @@ -704,7 +704,7 @@ def AskFileForSave( try: rr = Nav.NavPutFile(args) good = 1 - except Nav.error, arg: + except Nav.error as arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None @@ -764,7 +764,7 @@ def AskFolder( try: rr = Nav.NavChooseFolder(args) good = 1 - except Nav.error, arg: + except Nav.error as arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None diff --git a/Lib/plat-mac/MiniAEFrame.py b/Lib/plat-mac/MiniAEFrame.py index 569cd7b..1d990af 100644 --- a/Lib/plat-mac/MiniAEFrame.py +++ b/Lib/plat-mac/MiniAEFrame.py @@ -70,7 +70,7 @@ class MiniApplication: msg = "High Level Event: %r %r" % (code(message), code(h | (v<<16))) try: AE.AEProcessAppleEvent(event) - except AE.Error, err: + except AE.Error as err: print 'AE error: ', err print 'in', msg traceback.print_exc() diff --git a/Lib/plat-mac/aetools.py b/Lib/plat-mac/aetools.py index 55288bf..7a52eb9a 100644 --- a/Lib/plat-mac/aetools.py +++ b/Lib/plat-mac/aetools.py @@ -57,7 +57,7 @@ aekeywords = [ def missed(ae): try: desc = ae.AEGetAttributeDesc('miss', 'keyw') - except AE.Error, msg: + except AE.Error as msg: return None return desc.data @@ -86,7 +86,7 @@ def unpackevent(ae, formodulename=""): for key in aekeywords: try: desc = ae.AEGetAttributeDesc(key, '****') - except (AE.Error, MacOS.Error), msg: + except (AE.Error, MacOS.Error) as msg: if msg[0] != -1701 and msg[0] != -1704: raise continue diff --git a/Lib/plat-mac/applesingle.py b/Lib/plat-mac/applesingle.py index 76bdb06..fdd163d 100644 --- a/Lib/plat-mac/applesingle.py +++ b/Lib/plat-mac/applesingle.py @@ -48,7 +48,7 @@ class AppleSingle(object): header = fileobj.read(AS_HEADER_LENGTH) try: magic, version, ig, nentry = struct.unpack(AS_HEADER_FORMAT, header) - except ValueError, arg: + except ValueError as arg: raise Error, "Unpack header error: %s" % (arg,) if verbose: print 'Magic: 0x%8.8x' % (magic,) @@ -65,7 +65,7 @@ class AppleSingle(object): for hdr in headers: try: restype, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) - except ValueError, arg: + except ValueError as arg: raise Error, "Unpack entry error: %s" % (arg,) if verbose: print "Fork %d, offset %d, length %d" % (restype, offset, length) diff --git a/Lib/plat-mac/argvemulator.py b/Lib/plat-mac/argvemulator.py index 2d66f1c..fe9e8f8 100644 --- a/Lib/plat-mac/argvemulator.py +++ b/Lib/plat-mac/argvemulator.py @@ -52,7 +52,7 @@ class ArgvCollector: if what == kHighLevelEvent: try: AE.AEProcessAppleEvent(event) - except AE.Error, err: + except AE.Error as err: msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16))) print 'AE error: ', err print 'in', msg @@ -77,7 +77,7 @@ class ArgvCollector: fsref = alias.FSResolveAlias(None)[0] pathname = fsref.as_pathname() sys.argv.append(pathname) - except Exception, e: + except Exception as e: print "argvemulator.py warning: can't unpack an open document event" import traceback traceback.print_exc() diff --git a/Lib/plat-mac/buildtools.py b/Lib/plat-mac/buildtools.py index 7c5d0f4..4a0efbf 100644 --- a/Lib/plat-mac/buildtools.py +++ b/Lib/plat-mac/buildtools.py @@ -78,7 +78,7 @@ def process(template, filename, destname, copy_codefragment=0, fp.close() try: code = compile(text + '\n', filename, "exec") - except SyntaxError, arg: + except SyntaxError as arg: raise BuildError, "Syntax error in script %s: %s" % (filename, arg) except EOFError: raise BuildError, "End-of-file in script %s" % (filename,) diff --git a/Lib/plat-mac/bundlebuilder.py b/Lib/plat-mac/bundlebuilder.py index d21fc3e..d58adf2 100755 --- a/Lib/plat-mac/bundlebuilder.py +++ b/Lib/plat-mac/bundlebuilder.py @@ -764,7 +764,7 @@ def makedirs(dir): directory. Don't moan if any path element already exists.""" try: os.makedirs(dir) - except OSError, why: + except OSError as why: if why.errno != errno.EEXIST: raise diff --git a/Lib/plat-mac/gensuitemodule.py b/Lib/plat-mac/gensuitemodule.py index 53c0a52..7d03d8f 100644 --- a/Lib/plat-mac/gensuitemodule.py +++ b/Lib/plat-mac/gensuitemodule.py @@ -114,7 +114,7 @@ def main_interactive(interact=0, basepkgname='StdSuites'): try: processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) - except MacOS.Error, arg: + except MacOS.Error as arg: print "Error getting terminology:", arg print "Retry, manually parsing resources" processfile_fromresource(filename, edit_modnames=edit_modnames, @@ -190,7 +190,7 @@ def processfile(fullname, output=None, basepkgname=None, print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname) try: aedescobj, launched = OSATerminology.GetAppTerminology(fullname) - except MacOS.Error, arg: + except MacOS.Error as arg: if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound if verbose: print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually" @@ -244,7 +244,7 @@ def getappterminology(fullname, verbose=None): talker = aetools.TalkTo(cr) try: talker._start() - except (MacOS.Error, aetools.Error), arg: + except (MacOS.Error, aetools.Error) as arg: if verbose: print >>verbose, 'Warning: start() failed, continuing anyway:', arg reply = talker.send("ascr", "gdte") diff --git a/Lib/plat-mac/macresource.py b/Lib/plat-mac/macresource.py index d5839a1..91dfffa 100644 --- a/Lib/plat-mac/macresource.py +++ b/Lib/plat-mac/macresource.py @@ -76,14 +76,14 @@ def open_pathname(pathname, verbose=0): AppleSingle file""" try: refno = Res.FSpOpenResFile(pathname, 1) - except Res.Error, arg: + except Res.Error as arg: if arg[0] in (-37, -39): # No resource fork. We may be on OSX, and this may be either # a data-fork based resource file or a AppleSingle file # from the CVS repository. try: refno = Res.FSOpenResourceFile(pathname, u'', 1) - except Res.Error, arg: + except Res.Error as arg: if arg[0] != -199: # -199 is "bad resource map" raise @@ -103,14 +103,14 @@ def resource_pathname(pathname, verbose=0): try: refno = Res.FSpOpenResFile(pathname, 1) Res.CloseResFile(refno) - except Res.Error, arg: + except Res.Error as arg: if arg[0] in (-37, -39): # No resource fork. We may be on OSX, and this may be either # a data-fork based resource file or a AppleSingle file # from the CVS repository. try: refno = Res.FSOpenResourceFile(pathname, u'', 1) - except Res.Error, arg: + except Res.Error as arg: if arg[0] != -199: # -199 is "bad resource map" raise diff --git a/Lib/plat-mac/pimp.py b/Lib/plat-mac/pimp.py index ff696b1..6927ad7 100644 --- a/Lib/plat-mac/pimp.py +++ b/Lib/plat-mac/pimp.py @@ -76,7 +76,7 @@ def getDefaultDatabase(experimental=False): url = DEFAULT_PIMPDATABASE_FMT % (PIMP_VERSION, status, pyvers, osname, rel, machine) try: urllib2.urlopen(url) - except urllib2.HTTPError, arg: + except urllib2.HTTPError as arg: pass else: break @@ -589,13 +589,13 @@ class PimpPackage: installTest = self._dict['Install-test'].strip() + '\n' try: exec(installTest, namespace) - except ImportError, arg: + except ImportError as arg: return "no", str(arg) - except _scriptExc_NotInstalled, arg: + except _scriptExc_NotInstalled as arg: return "no", str(arg) - except _scriptExc_OldInstalled, arg: + except _scriptExc_OldInstalled as arg: return "old", str(arg) - except _scriptExc_BadInstalled, arg: + except _scriptExc_BadInstalled as arg: return "bad", str(arg) except: sys.stderr.write("-------------------------------------\n") diff --git a/Lib/plat-mac/terminalcommand.py b/Lib/plat-mac/terminalcommand.py index 292f09c..a2f008c 100644 --- a/Lib/plat-mac/terminalcommand.py +++ b/Lib/plat-mac/terminalcommand.py @@ -35,7 +35,7 @@ def run(command): try: theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout) - except AE.Error, why: + except AE.Error as why: if why[0] != -600: # Terminal.app not yet running raise os.system(START_TERMINAL) diff --git a/Lib/platform.py b/Lib/platform.py index 5fd13a3..cf58819 100755 --- a/Lib/platform.py +++ b/Lib/platform.py @@ -404,10 +404,10 @@ def _syscmd_ver(system='',release='',version='', raise os.error,'command failed' # XXX How can I supress shell errors from being written # to stderr ? - except os.error,why: + except os.error as why: #print 'Command %s failed: %s' % (cmd,why) continue - except IOError,why: + except IOError as why: #print 'Command %s failed: %s' % (cmd,why) continue else: diff --git a/Lib/poplib.py b/Lib/poplib.py index 1cf114a..b7a7a8a 100644 --- a/Lib/poplib.py +++ b/Lib/poplib.py @@ -86,7 +86,7 @@ class POP3: try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None @@ -262,7 +262,7 @@ class POP3: """Signoff: commit changes on server, unlock mailbox, close connection.""" try: resp = self._shortcmd('QUIT') - except error_proto, val: + except error_proto as val: resp = val self.file.close() self.sock.close() @@ -347,7 +347,7 @@ class POP3_SSL(POP3): try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None @@ -399,7 +399,7 @@ class POP3_SSL(POP3): """Signoff: commit changes on server, unlock mailbox, close connection.""" try: resp = self._shortcmd('QUIT') - except error_proto, val: + except error_proto as val: resp = val self.sock.close() del self.sslobj, self.sock diff --git a/Lib/pstats.py b/Lib/pstats.py index ba0b804..2b152c3 100644 --- a/Lib/pstats.py +++ b/Lib/pstats.py @@ -618,7 +618,7 @@ if __name__ == '__main__': if line: try: self.stats = Stats(line) - except IOError, args: + except IOError as args: print >> self.stream, args[1] return self.prompt = line + "% " @@ -56,7 +56,7 @@ def _open_terminal(): else: try: tty_name, master_fd = sgi._getpty(os.O_RDWR, 0666, 0) - except IOError, msg: + except IOError as msg: raise os.error, msg return master_fd, tty_name for x in 'pqrstuvwxyzPQRST': diff --git a/Lib/py_compile.py b/Lib/py_compile.py index 1cb41f1..23c5d18 100644 --- a/Lib/py_compile.py +++ b/Lib/py_compile.py @@ -123,7 +123,7 @@ def compile(file, cfile=None, dfile=None, doraise=False): codestring = codestring + '\n' try: codeobject = __builtin__.compile(codestring, dfile or file,'exec') - except Exception,err: + except Exception as err: py_exc = PyCompileError(err.__class__,err.args,dfile or file) if doraise: raise py_exc @@ -157,7 +157,7 @@ def main(args=None): for filename in args: try: compile(filename, doraise=True) - except PyCompileError,err: + except PyCompileError as err: sys.stderr.write(err.msg) if __name__ == "__main__": diff --git a/Lib/pydoc.py b/Lib/pydoc.py index d1ab01c..892e278 100755 --- a/Lib/pydoc.py +++ b/Lib/pydoc.py @@ -1479,7 +1479,7 @@ def doc(thing, title='Python Library Documentation: %s', forceload=0): object = type(object) desc += ' object' pager(title % desc + '\n\n' + text.document(object, name)) - except (ImportError, ErrorDuringImport), value: + except (ImportError, ErrorDuringImport) as value: print value def writedoc(thing, forceload=0): @@ -1491,7 +1491,7 @@ def writedoc(thing, forceload=0): file.write(page) file.close() print 'wrote', name + '.html' - except (ImportError, ErrorDuringImport), value: + except (ImportError, ErrorDuringImport) as value: print value def writedocs(dir, pkgpath='', done=None): @@ -1920,7 +1920,7 @@ def serve(port, callback=None, completer=None): if path and path != '.': try: obj = locate(path, forceload=1) - except ErrorDuringImport, value: + except ErrorDuringImport as value: self.send_document(path, html.escape(str(value))) return if obj: @@ -2223,7 +2223,7 @@ def cli(): writedoc(arg) else: help.help(arg) - except ErrorDuringImport, value: + except ErrorDuringImport as value: print value except (getopt.error, BadUsage): diff --git a/Lib/quopri.py b/Lib/quopri.py index 8788afc..171a59e 100755 --- a/Lib/quopri.py +++ b/Lib/quopri.py @@ -194,7 +194,7 @@ def main(): import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'td') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print "usage: quopri [-t | -d] [file] ..." @@ -218,7 +218,7 @@ def main(): else: try: fp = open(file) - except IOError, msg: + except IOError as msg: sys.stderr.write("%s: can't open (%s)\n" % (file, msg)) sts = 1 continue @@ -229,7 +229,7 @@ def _compile(*key): raise TypeError, "first argument must be string or compiled pattern" try: p = sre_compile.compile(pattern, flags) - except error, v: + except error as v: raise error, v # invalid expression if len(_cache) >= _MAXCACHE: _cache.clear() @@ -244,7 +244,7 @@ def _compile_repl(*key): repl, pattern = key try: p = sre_parse.parse_template(repl, pattern) - except error, v: + except error as v: raise error, v # invalid expression if len(_cache_repl) >= _MAXCACHE: _cache_repl.clear() diff --git a/Lib/rexec.py b/Lib/rexec.py index 37dff62..665f294 100644 --- a/Lib/rexec.py +++ b/Lib/rexec.py @@ -551,7 +551,7 @@ def test(): if args and args[0] != '-': try: fp = open(args[0]) - except IOError, msg: + except IOError as msg: print "%s: can't open file %r" % (sys.argv[0], args[0]) return 1 if fp.isatty(): @@ -566,7 +566,7 @@ def test(): r.s_apply(code.InteractiveConsole.runcode, (self, co)) try: RestrictedConsole(r.modules['__main__'].__dict__).interact() - except SystemExit, n: + except SystemExit as n: return n else: text = fp.read() @@ -574,7 +574,7 @@ def test(): c = compile(text, fp.name, 'exec') try: r.s_exec(c) - except SystemExit, n: + except SystemExit as n: return n except: traceback.print_exc() diff --git a/Lib/sgmllib.py b/Lib/sgmllib.py index 3ab57c2..1574f44 100644 --- a/Lib/sgmllib.py +++ b/Lib/sgmllib.py @@ -530,7 +530,7 @@ def test(args = None): else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) diff --git a/Lib/shutil.py b/Lib/shutil.py index c3ff687..7da5cac 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -121,18 +121,18 @@ def copytree(src, dst, symlinks=False): else: copy2(srcname, dstname) # XXX What about devices, sockets etc.? - except (IOError, os.error), why: + except (IOError, os.error) as why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files - except Error, err: + except Error as err: errors.extend(err.args[0]) try: copystat(src, dst) except WindowsError: # can't copy file access times on Windows pass - except OSError, why: + except OSError as why: errors.extend((src, dst, str(why))) if errors: raise Error, errors @@ -157,7 +157,7 @@ def rmtree(path, ignore_errors=False, onerror=None): names = [] try: names = os.listdir(path) - except os.error, err: + except os.error as err: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) @@ -170,7 +170,7 @@ def rmtree(path, ignore_errors=False, onerror=None): else: try: os.remove(fullname) - except os.error, err: + except os.error as err: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) diff --git a/Lib/site.py b/Lib/site.py index 1513818..5b03b5e 100644 --- a/Lib/site.py +++ b/Lib/site.py @@ -391,7 +391,7 @@ def execsitecustomize(): import sitecustomize except ImportError: pass - except Exception, err: + except Exception as err: if os.environ.get("PYTHONVERBOSE"): raise sys.stderr.write( diff --git a/Lib/smtpd.py b/Lib/smtpd.py index c656ec7..3b81856 100755 --- a/Lib/smtpd.py +++ b/Lib/smtpd.py @@ -357,10 +357,10 @@ class PureProxy(SMTPServer): refused = s.sendmail(mailfrom, rcpttos, data) finally: s.quit() - except smtplib.SMTPRecipientsRefused, e: + except smtplib.SMTPRecipientsRefused as e: print >> DEBUGSTREAM, 'got SMTPRecipientsRefused' refused = e.recipients - except (socket.error, smtplib.SMTPException), e: + except (socket.error, smtplib.SMTPException) as e: print >> DEBUGSTREAM, 'got', e.__class__ # All recipients were refused. If the exception had an associated # error code, use it. Otherwise,fake it with a non-triggering @@ -464,7 +464,7 @@ def parseargs(): opts, args = getopt.getopt( sys.argv[1:], 'nVhc:d', ['class=', 'nosetuid', 'version', 'help', 'debug']) - except getopt.error, e: + except getopt.error as e: usage(1, e) options = Options() @@ -528,7 +528,7 @@ if __name__ == '__main__': nobody = pwd.getpwnam('nobody')[2] try: os.setuid(nobody) - except OSError, e: + except OSError as e: if e.errno != errno.EPERM: raise print >> sys.stderr, \ 'Cannot setuid "nobody"; try running with -n option.' diff --git a/Lib/smtplib.py b/Lib/smtplib.py index a7305ce..a96082a 100755 --- a/Lib/smtplib.py +++ b/Lib/smtplib.py @@ -306,7 +306,7 @@ class SMTP: af, socktype, proto, canonname, sa = res try: self._get_socket(af,socktype,proto,sa) - except socket.error, msg: + except socket.error as msg: if self.debuglevel > 0: print>>stderr, 'connect fail:', msg if self.sock: self.sock.close() diff --git a/Lib/sqlite3/test/dbapi.py b/Lib/sqlite3/test/dbapi.py index b08da9c..6fe93ab 100644 --- a/Lib/sqlite3/test/dbapi.py +++ b/Lib/sqlite3/test/dbapi.py @@ -326,7 +326,7 @@ class CursorTests(unittest.TestCase): self.fail("should have raised a TypeError") except TypeError: return - except Exception, e: + except Exception as e: print "raised", e.__class__ self.fail("raised wrong exception.") diff --git a/Lib/sqlite3/test/hooks.py b/Lib/sqlite3/test/hooks.py index 761bdaa..d67028f 100644 --- a/Lib/sqlite3/test/hooks.py +++ b/Lib/sqlite3/test/hooks.py @@ -36,7 +36,7 @@ class CollationTests(unittest.TestCase): try: con.create_collation("X", 42) self.fail("should have raised a TypeError") - except TypeError, e: + except TypeError as e: self.failUnlessEqual(e.args[0], "parameter must be callable") def CheckCreateCollationNotAscii(self): @@ -44,7 +44,7 @@ class CollationTests(unittest.TestCase): try: con.create_collation("collä", cmp) self.fail("should have raised a ProgrammingError") - except sqlite.ProgrammingError, e: + except sqlite.ProgrammingError as e: pass def CheckCollationIsUsed(self): @@ -73,7 +73,7 @@ class CollationTests(unittest.TestCase): try: result = con.execute(sql).fetchall() self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0].lower(), "no such collation sequence: mycoll") def CheckCollationRegisterTwice(self): @@ -101,7 +101,7 @@ class CollationTests(unittest.TestCase): try: con.execute("select 'a' as x union select 'b' as x order by x collate mycoll") self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: if not e.args[0].startswith("no such collation sequence"): self.fail("wrong OperationalError raised") diff --git a/Lib/sqlite3/test/userfunctions.py b/Lib/sqlite3/test/userfunctions.py index e455fb6..a7cdcae 100644 --- a/Lib/sqlite3/test/userfunctions.py +++ b/Lib/sqlite3/test/userfunctions.py @@ -205,7 +205,7 @@ class FunctionTests(unittest.TestCase): cur.execute("select raiseexception()") cur.fetchone() self.fail("should have raised OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], 'user-defined function raised exception') def CheckParamString(self): @@ -279,7 +279,7 @@ class AggregateTests(unittest.TestCase): try: cur.execute("select nostep(t) from test") self.fail("should have raised an AttributeError") - except AttributeError, e: + except AttributeError as e: self.failUnlessEqual(e.args[0], "'AggrNoStep' object has no attribute 'step'") def CheckAggrNoFinalize(self): @@ -288,7 +288,7 @@ class AggregateTests(unittest.TestCase): cur.execute("select nofinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrExceptionInInit(self): @@ -297,7 +297,7 @@ class AggregateTests(unittest.TestCase): cur.execute("select excInit(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's '__init__' method raised error") def CheckAggrExceptionInStep(self): @@ -306,7 +306,7 @@ class AggregateTests(unittest.TestCase): cur.execute("select excStep(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'step' method raised error") def CheckAggrExceptionInFinalize(self): @@ -315,7 +315,7 @@ class AggregateTests(unittest.TestCase): cur.execute("select excFinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrCheckParamStr(self): @@ -384,7 +384,7 @@ class AuthorizerTests(unittest.TestCase): def CheckTableAccess(self): try: self.con.execute("select * from t2") - except sqlite.DatabaseError, e: + except sqlite.DatabaseError as e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return @@ -393,7 +393,7 @@ class AuthorizerTests(unittest.TestCase): def CheckColumnAccess(self): try: self.con.execute("select c2 from t1") - except sqlite.DatabaseError, e: + except sqlite.DatabaseError as e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return diff --git a/Lib/subprocess.py b/Lib/subprocess.py index 62b70ba..f5800fb 100644 --- a/Lib/subprocess.py +++ b/Lib/subprocess.py @@ -792,7 +792,7 @@ class Popen(object): env, cwd, startupinfo) - except pywintypes.error, e: + except pywintypes.error as e: # Translate pywintypes.error to WindowsError, which is # a subclass of OSError. FIXME: We should really # translate errno using _sys_errlist (or simliar), but @@ -1190,7 +1190,7 @@ def _demo_posix(): print "Trying a weird file..." try: print Popen(["/this/path/does/not/exist"]).communicate() - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: print "The file didn't exist. I thought so..." print "Child traceback:" diff --git a/Lib/tabnanny.py b/Lib/tabnanny.py index 76665ac..1d2c6db 100755 --- a/Lib/tabnanny.py +++ b/Lib/tabnanny.py @@ -43,7 +43,7 @@ def main(): global verbose, filename_only try: opts, args = getopt.getopt(sys.argv[1:], "qv") - except getopt.error, msg: + except getopt.error as msg: errprint(msg) return for o, a in opts: @@ -95,7 +95,7 @@ def check(file): try: f = open(file) - except IOError, msg: + except IOError as msg: errprint("%r: I/O Error: %s" % (file, msg)) return @@ -105,15 +105,15 @@ def check(file): try: process_tokens(tokenize.generate_tokens(f.readline)) - except tokenize.TokenError, msg: + except tokenize.TokenError as msg: errprint("%r: Token Error: %s" % (file, msg)) return - except IndentationError, msg: + except IndentationError as msg: errprint("%r: Indentation Error: %s" % (file, msg)) return - except NannyNag, nag: + except NannyNag as nag: badline = nag.get_lineno() line = nag.get_line() if verbose: diff --git a/Lib/tarfile.py b/Lib/tarfile.py index 3ffdff3..2088e5c 100644 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -1540,7 +1540,7 @@ class TarFile(object): self.chown(tarinfo, path) self.utime(tarinfo, path) self.chmod(tarinfo, path) - except ExtractError, e: + except ExtractError as e: if self.errorlevel > 1: raise else: @@ -1565,7 +1565,7 @@ class TarFile(object): try: self._extract_member(tarinfo, os.path.join(path, tarinfo.name)) - except EnvironmentError, e: + except EnvironmentError as e: if self.errorlevel > 0: raise else: @@ -1573,7 +1573,7 @@ class TarFile(object): self._dbg(1, "tarfile: %s" % e.strerror) else: self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) - except ExtractError, e: + except ExtractError as e: if self.errorlevel > 1: raise else: @@ -1681,7 +1681,7 @@ class TarFile(object): """ try: os.mkdir(targetpath) - except EnvironmentError, e: + except EnvironmentError as e: if e.errno != errno.EEXIST: raise @@ -1745,11 +1745,11 @@ class TarFile(object): try: self._extract_member(self.getmember(linkpath), targetpath) - except (EnvironmentError, KeyError), e: + except (EnvironmentError, KeyError) as e: linkpath = os.path.normpath(linkpath) try: shutil.copy2(linkpath, targetpath) - except EnvironmentError, e: + except EnvironmentError as e: raise IOError("link could not be created") def chown(self, tarinfo, targetpath): @@ -1777,7 +1777,7 @@ class TarFile(object): else: if sys.platform != "os2emx": os.chown(targetpath, u, g) - except EnvironmentError, e: + except EnvironmentError as e: raise ExtractError("could not change owner") def chmod(self, tarinfo, targetpath): @@ -1786,7 +1786,7 @@ class TarFile(object): if hasattr(os, 'chmod'): try: os.chmod(targetpath, tarinfo.mode) - except EnvironmentError, e: + except EnvironmentError as e: raise ExtractError("could not change mode") def utime(self, tarinfo, targetpath): @@ -1800,7 +1800,7 @@ class TarFile(object): return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) - except EnvironmentError, e: + except EnvironmentError as e: raise ExtractError("could not change modification time") #-------------------------------------------------------------------------- @@ -1833,7 +1833,7 @@ class TarFile(object): tarinfo = self.proc_member(tarinfo) - except HeaderError, e: + except HeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE diff --git a/Lib/telnetlib.py b/Lib/telnetlib.py index a13e85c..4964d59 100644 --- a/Lib/telnetlib.py +++ b/Lib/telnetlib.py @@ -227,7 +227,7 @@ class Telnet: try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None diff --git a/Lib/tempfile.py b/Lib/tempfile.py index 2e8cd6d..f4f1058 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -201,7 +201,7 @@ def _get_default_tempdir(): _os.unlink(filename) del fp, fd return dir - except (OSError, IOError), e: + except (OSError, IOError) as e: if e[0] != _errno.EEXIST: break # no point trying more names in this directory pass @@ -236,7 +236,7 @@ def _mkstemp_inner(dir, pre, suf, flags): fd = _os.open(file, flags, 0600) _set_cloexec(fd) return (fd, _os.path.abspath(file)) - except OSError, e: + except OSError as e: if e.errno == _errno.EEXIST: continue # try again raise @@ -327,7 +327,7 @@ def mkdtemp(suffix="", prefix=template, dir=None): try: _os.mkdir(file, 0700) return file - except OSError, e: + except OSError as e: if e.errno == _errno.EEXIST: continue # try again raise diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py index 30c1e7c..0f1386e 100644 --- a/Lib/test/pickletester.py +++ b/Lib/test/pickletester.py @@ -585,7 +585,7 @@ class AbstractPickleTests(unittest.TestCase): badpickle = pickle.PROTO + chr(oob) + build_none try: self.loads(badpickle) - except ValueError, detail: + except ValueError as detail: self.failUnless(str(detail).startswith( "unsupported pickle protocol")) else: diff --git a/Lib/test/regrtest.py b/Lib/test/regrtest.py index 8c0f2e4..ce39649 100755 --- a/Lib/test/regrtest.py +++ b/Lib/test/regrtest.py @@ -211,7 +211,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False, 'coverdir=', 'nocoverdir', 'runleaks', 'huntrleaks=', 'verbose2', 'memlimit=', ]) - except getopt.error, msg: + except getopt.error as msg: usage(2, msg) # Defaults @@ -556,19 +556,19 @@ def runtest_inner(test, generate, verbose, quiet, dash_R(the_module, test, indirect_test, huntrleaks) finally: sys.stdout = save_stdout - except test_support.ResourceDenied, msg: + except test_support.ResourceDenied as msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() return -2 - except (ImportError, test_support.TestSkipped), msg: + except (ImportError, test_support.TestSkipped) as msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() return -1 except KeyboardInterrupt: raise - except test_support.TestFailed, msg: + except test_support.TestFailed as msg: print "test", test, "failed --", msg sys.stdout.flush() return 0 @@ -640,7 +640,7 @@ def cleanup_test_droppings(testname, verbose): print "%r left behind %s %r" % (testname, kind, name) try: nuker(name) - except Exception, msg: + except Exception as msg: print >> sys.stderr, ("%r left behind %s %r and it couldn't be " "removed: %s" % (testname, kind, name, msg)) diff --git a/Lib/test/sortperf.py b/Lib/test/sortperf.py index cc83ee4..3c95b89 100644 --- a/Lib/test/sortperf.py +++ b/Lib/test/sortperf.py @@ -37,7 +37,7 @@ def randfloats(n): os.unlink(fn) except os.error: pass - except IOError, msg: + except IOError as msg: print "can't write", fn, ":", msg else: result = marshal.load(fp) diff --git a/Lib/test/string_tests.py b/Lib/test/string_tests.py index 1aa68de..2116ea4 100644 --- a/Lib/test/string_tests.py +++ b/Lib/test/string_tests.py @@ -970,7 +970,7 @@ class MixinStrUnicodeUserStringTest: def f(): yield 4 + "" self.fixtype(' ').join(f()) - except TypeError, e: + except TypeError as e: if '+' not in str(e): self.fail('join() ate exception message') else: diff --git a/Lib/test/test_bool.py b/Lib/test/test_bool.py index 8121e03..954423f 100644 --- a/Lib/test/test_bool.py +++ b/Lib/test/test_bool.py @@ -373,13 +373,11 @@ class BoolTest(unittest.TestCase): return badval try: bool(A()) - except (Exception), e_bool: - pass - try: - len(A()) - except (Exception), e_len: - pass - self.assertEqual(str(e_bool), str(e_len)) + except (Exception) as e_bool: + try: + len(A()) + except (Exception) as e_len: + self.assertEqual(str(e_bool), str(e_len)) def test_main(): test_support.run_unittest(BoolTest) diff --git a/Lib/test/test_cfgparser.py b/Lib/test/test_cfgparser.py index 3979f15..1b288b4 100644 --- a/Lib/test/test_cfgparser.py +++ b/Lib/test/test_cfgparser.py @@ -181,7 +181,7 @@ class TestCaseBase(unittest.TestCase): def get_error(self, exc, section, option): try: self.cf.get(section, option) - except exc, e: + except exc as e: return e else: self.fail("expected exception type %s.%s" diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py index 52e5e91..9cf6a12 100644 --- a/Lib/test/test_cgi.py +++ b/Lib/test/test_cgi.py @@ -50,7 +50,7 @@ def do_test(buf, method): raise ValueError, "unknown method: %s" % method try: return cgi.parse(fp, env, strict_parsing=1) - except StandardError, err: + except StandardError as err: return ComparableException(err) # A list of test cases. Each test case is a a two-tuple that contains diff --git a/Lib/test/test_class.py b/Lib/test/test_class.py index 3201dd8..1758fd4 100644 --- a/Lib/test/test_class.py +++ b/Lib/test/test_class.py @@ -372,7 +372,7 @@ class A: a = property(booh) try: A().a # Raised AttributeError: A instance has no attribute 'a' -except AttributeError, x: +except AttributeError as x: if str(x) != "booh": print "attribute error for A().a got masked:", str(x) @@ -384,7 +384,7 @@ class I: __init__ = property(booh) try: I() # In debug mode, printed XXX undetected error and raises AttributeError -except AttributeError, x: +except AttributeError as x: pass else: print "attribute error for I.__init__ got masked" diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py index 3c800f8..0711923 100644 --- a/Lib/test/test_codecs.py +++ b/Lib/test/test_codecs.py @@ -595,7 +595,7 @@ class UnicodeInternalTest(unittest.TestCase): if sys.maxunicode > 0xffff: try: "\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal") - except UnicodeDecodeError, ex: + except UnicodeDecodeError as ex: self.assertEquals("unicode_internal", ex.encoding) self.assertEquals("\x00\x00\x00\x00\x00\x11\x11\x00", ex.object) self.assertEquals(4, ex.start) @@ -782,7 +782,7 @@ class NameprepTest(unittest.TestCase): prepped = unicode(prepped, "utf-8") try: self.assertEquals(nameprep(orig), prepped) - except Exception,e: + except Exception as e: raise test_support.TestFailed("Test 3.%d: %s" % (pos+1, str(e))) class IDNACodecTest(unittest.TestCase): diff --git a/Lib/test/test_compiler.py b/Lib/test/test_compiler.py index 2ecd093..ebccb36 100644 --- a/Lib/test/test_compiler.py +++ b/Lib/test/test_compiler.py @@ -44,7 +44,7 @@ class CompilerTest(unittest.TestCase): else: try: compiler.compile(buf, basename, "exec") - except Exception, e: + except Exception as e: args = list(e.args) args[0] += "[in file %s]" % basename e.args = tuple(args) diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py index 747785d..9142428 100644 --- a/Lib/test/test_contextlib.py +++ b/Lib/test/test_contextlib.py @@ -76,7 +76,7 @@ class ContextManagerTestCase(unittest.TestCase): state.append(1) try: yield 42 - except ZeroDivisionError, e: + except ZeroDivisionError as e: state.append(e.args[0]) self.assertEqual(state, [1, 42, 999]) with woohoo() as x: diff --git a/Lib/test/test_cookielib.py b/Lib/test/test_cookielib.py index 544f29f..9b06869 100644 --- a/Lib/test/test_cookielib.py +++ b/Lib/test/test_cookielib.py @@ -257,7 +257,7 @@ class FileCookieJarTests(TestCase): try: c.load(filename="for this test to work, a file with this " "filename should not exist") - except IOError, exc: + except IOError as exc: # exactly IOError, not LoadError self.assertEqual(exc.__class__, IOError) else: diff --git a/Lib/test/test_dbm.py b/Lib/test/test_dbm.py index ed92bfe..0a9db4e 100755 --- a/Lib/test/test_dbm.py +++ b/Lib/test/test_dbm.py @@ -16,7 +16,8 @@ def cleanup(): for suffix in ['', '.pag', '.dir', '.db']: try: os.unlink(filename + suffix) - except OSError, (errno, strerror): + except OSError as e: + (errno, strerror) = e # if we can't delete the file because of permissions, # nothing will work, so skip the test if errno == 1: diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index 50df93d..f9a9e82 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -146,7 +146,7 @@ class DecimalTest(unittest.TestCase): print 'Error in test cases:' print line continue - except DecimalException, exception: + except DecimalException as exception: #Exception raised where there shoudn't have been one. self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line) @@ -238,7 +238,7 @@ class DecimalTest(unittest.TestCase): funct(self.context.create_decimal(v)) except error: pass - except Signals, e: + except Signals as e: self.fail("Raised %s in %s when %s disabled" % \ (e, s, error)) else: @@ -258,7 +258,7 @@ class DecimalTest(unittest.TestCase): funct(*vals) except error: pass - except Signals, e: + except Signals as e: self.fail("Raised %s in %s when %s disabled" % \ (e, s, error)) else: @@ -268,7 +268,7 @@ class DecimalTest(unittest.TestCase): result = str(funct(*vals)) if fname == 'same_quantum': result = str(int(eval(result))) # 'True', 'False' -> '1', '0' - except Signals, error: + except Signals as error: self.fail("Raised %s in %s" % (error, s)) except: #Catch any error long enough to state the test case. print "ERROR:", s diff --git a/Lib/test/test_defaultdict.py b/Lib/test/test_defaultdict.py index 134b5a8..602e0d9 100644 --- a/Lib/test/test_defaultdict.py +++ b/Lib/test/test_defaultdict.py @@ -43,7 +43,7 @@ class TestDefaultDict(unittest.TestCase): self.assertEqual(d2.default_factory, None) try: d2[15] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (15,)) else: self.fail("d2[15] didn't raise KeyError") diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index 2968e3d..96ff9f3 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -945,7 +945,7 @@ def mro_disagreement(): def raises(exc, expected, callable, *args): try: callable(*args) - except exc, msg: + except exc as msg: if not str(msg).startswith(expected): raise TestFailed, "Message %r, expected %r" % (str(msg), expected) @@ -1813,7 +1813,7 @@ def weakrefs(): no = NoWeak() try: weakref.ref(no) - except TypeError, msg: + except TypeError as msg: verify(str(msg).find("weak reference") >= 0) else: verify(0, "weakref.ref(no) should be illegal") @@ -1866,7 +1866,7 @@ def properties(): for attr in "__doc__", "fget", "fset", "fdel": try: setattr(raw, attr, 42) - except TypeError, msg: + except TypeError as msg: if str(msg).find('readonly') < 0: raise TestFailed("when setting readonly attr %r on a " "property, got unexpected TypeError " @@ -2416,7 +2416,7 @@ f = t(%r, 'w') # rexec can't catch this by itself for code in code1, code2, code3: try: sandbox.r_exec(code) - except IOError, msg: + except IOError as msg: if str(msg).find("restricted") >= 0: outcome = "OK" else: @@ -3523,7 +3523,7 @@ def test_mutable_bases(): try: D.__bases__ = () - except TypeError, msg: + except TypeError as msg: if str(msg) == "a new-style class can't have only classic bases": raise TestFailed, "wrong error message for .__bases__ = ()" else: diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py index ff6ccde..c7fa15d 100644 --- a/Lib/test/test_dict.py +++ b/Lib/test/test_dict.py @@ -414,7 +414,7 @@ class DictTest(unittest.TestCase): e = E() try: e[42] - except RuntimeError, err: + except RuntimeError as err: self.assertEqual(err.args, (42,)) else: self.fail_("e[42] didn't raise RuntimeError") @@ -425,7 +425,7 @@ class DictTest(unittest.TestCase): f = F() try: f[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("f[42] didn't raise KeyError") @@ -434,7 +434,7 @@ class DictTest(unittest.TestCase): g = G() try: g[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("g[42] didn't raise KeyError") @@ -444,7 +444,7 @@ class DictTest(unittest.TestCase): d = {} try: d[(1,)] - except KeyError, e: + except KeyError as e: self.assertEqual(e.args, ((1,),)) else: self.fail("missing KeyError") diff --git a/Lib/test/test_dl.py b/Lib/test/test_dl.py index b70a4cf..9c70427 100755 --- a/Lib/test/test_dl.py +++ b/Lib/test/test_dl.py @@ -18,7 +18,7 @@ for s, func in sharedlibs: if verbose: print 'trying to open:', s, l = dl.open(s) - except dl.error, err: + except dl.error as err: if verbose: print 'failed', repr(str(err)) pass diff --git a/Lib/test/test_eof.py b/Lib/test/test_eof.py index aae3518..1187d07 100644 --- a/Lib/test/test_eof.py +++ b/Lib/test/test_eof.py @@ -11,7 +11,7 @@ class EOFTestCase(unittest.TestCase): try: eval("""'this is a test\ """) - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(str(msg), expect) else: raise test_support.TestFailed @@ -20,7 +20,7 @@ class EOFTestCase(unittest.TestCase): expect = "EOF while scanning triple-quoted string (<string>, line 1)" try: eval("""'''this is a test""") - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(str(msg), expect) else: raise test_support.TestFailed diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py index 7619aae..4a6b8c5 100644 --- a/Lib/test/test_exceptions.py +++ b/Lib/test/test_exceptions.py @@ -21,17 +21,17 @@ class ExceptionTests(unittest.TestCase): try: import exceptions reload(exceptions) - except ImportError, e: + except ImportError as e: self.fail("reloading exceptions: %s" % e) def raise_catch(self, exc, excname): try: raise exc, "spam" - except exc, err: + except exc as err: buf1 = str(err) try: raise exc("spam") - except exc, err: + except exc as err: buf2 = str(err) self.assertEquals(buf1, buf2) self.assertEquals(exc.__name__, excname) @@ -115,7 +115,7 @@ class ExceptionTests(unittest.TestCase): self.raise_catch(Exception, "Exception") try: x = 1/0 - except Exception, e: pass + except Exception as e: pass def testSyntaxErrorMessage(self): # make sure the right exception message is raised for each of @@ -124,7 +124,7 @@ class ExceptionTests(unittest.TestCase): def ckmsg(src, msg): try: compile(src, '<fragment>', 'exec') - except SyntaxError, e: + except SyntaxError as e: if e.msg != msg: self.fail("expected %s, got %s" % (msg, e.msg)) else: @@ -163,7 +163,7 @@ class ExceptionTests(unittest.TestCase): import _testcapi try: _testcapi.raise_exception(BadException, 1) - except TypeError, err: + except TypeError as err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEquals(co.co_name, "test_capi1") @@ -175,7 +175,7 @@ class ExceptionTests(unittest.TestCase): import _testcapi try: _testcapi.raise_exception(BadException, 0) - except RuntimeError, err: + except RuntimeError as err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEquals(co.co_name, "__init__") @@ -285,7 +285,7 @@ class ExceptionTests(unittest.TestCase): for exc, args, expected in exceptionList: try: raise exc(*args) - except BaseException, e: + except BaseException as e: if type(e) is not exc: raise # Verify module name @@ -344,6 +344,16 @@ class ExceptionTests(unittest.TestCase): self.failUnless(str(Exception('a'))) self.failUnless(unicode(Exception(u'a'))) + def testExceptionCleanup(self): + # Make sure "except V as N" exceptions are cleaned up properly + + try: + raise Exception() + except Exception as e: + self.failUnless(e) + del e + self.failIf('e' in locals()) + def test_main(): run_unittest(ExceptionTests) diff --git a/Lib/test/test_extcall.py b/Lib/test/test_extcall.py index 284dbb2..11cf43a 100644 --- a/Lib/test/test_extcall.py +++ b/Lib/test/test_extcall.py @@ -35,21 +35,21 @@ else: try: g() -except TypeError, err: +except TypeError as err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" try: g(*()) -except TypeError, err: +except TypeError as err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" try: g(*(), **{}) -except TypeError, err: +except TypeError as err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" @@ -61,7 +61,7 @@ g(1, 2, 3, *(4, 5)) class Nothing: pass try: g(*Nothing()) -except TypeError, attr: +except TypeError as attr: pass else: print "should raise TypeError" @@ -71,7 +71,7 @@ class Nothing: return 5 try: g(*Nothing()) -except TypeError, attr: +except TypeError as attr: pass else: print "should raise TypeError" @@ -93,7 +93,7 @@ class Nothing: return self try: g(*Nothing()) -except TypeError, attr: +except TypeError as attr: pass else: print "should raise TypeError" @@ -132,77 +132,77 @@ del kw['x'] try: g(1, 2, 3, **{'x':4, 'y':5}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: keyword parameter redefined" try: g(1, 2, 3, a=4, b=5, *(6, 7), **{'a':8, 'b':9}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: keyword parameter redefined" try: f(**{1:2}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: keywords must be strings" try: h(**{'e': 2}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: unexpected keyword argument: e" try: h(*h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: * argument must be a tuple" try: dir(*h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: * argument must be a tuple" try: None(*h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: * argument must be a tuple" try: h(**h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: ** argument must be a dictionary" try: dir(**h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: ** argument must be a dictionary" try: None(**h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: ** argument must be a dictionary" try: dir(b=1,**{'b':1}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: dir() got multiple values for keyword argument 'b'" @@ -226,13 +226,13 @@ print Foo.method(*(x, 1, 2)) print Foo.method(x, *(1, 2)) try: print Foo.method(*(1, 2, 3)) -except TypeError, err: +except TypeError as err: pass else: print 'expected a TypeError for unbound method call' try: print Foo.method(1, *(2, 3)) -except TypeError, err: +except TypeError as err: pass else: print 'expected a TypeError for unbound method call' @@ -276,4 +276,4 @@ for name in ['za', 'zade', 'zabk', 'zabdv', 'zabdevk']: for k in kwargs: kwdict[k] = k + k print func.func_name, args, sortdict(kwdict), '->', try: func(*args, **kwdict) - except TypeError, err: print err + except TypeError as err: print err diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py index 234920d..52c4a02 100644 --- a/Lib/test/test_file.py +++ b/Lib/test/test_file.py @@ -159,7 +159,7 @@ class OtherFileTests(unittest.TestCase): bad_mode = "qwerty" try: f = open(TESTFN, bad_mode) - except ValueError, msg: + except ValueError as msg: if msg[0] != 0: s = str(msg) if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: @@ -183,7 +183,7 @@ class OtherFileTests(unittest.TestCase): d = int(f.read()) f.close() f.close() - except IOError, msg: + except IOError as msg: self.fail('error setting buffer size %d: %s' % (s, str(msg))) self.assertEquals(d, s) diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py index 8bf5d6e..ace3bc9 100644 --- a/Lib/test/test_format.py +++ b/Lib/test/test_format.py @@ -199,7 +199,7 @@ if verbose: def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) - except exception, exc: + except exception as exc: if str(exc) == excmsg: if verbose: print "yes" diff --git a/Lib/test/test_frozen.py b/Lib/test/test_frozen.py index 673799d..678b9a8 100644 --- a/Lib/test/test_frozen.py +++ b/Lib/test/test_frozen.py @@ -12,17 +12,17 @@ import sys, os try: import __hello__ -except ImportError, x: +except ImportError as x: raise TestFailed, "import __hello__ failed:" + str(x) try: import __phello__ -except ImportError, x: +except ImportError as x: raise TestFailed, "import __phello__ failed:" + str(x) try: import __phello__.spam -except ImportError, x: +except ImportError as x: raise TestFailed, "import __phello__.spam failed:" + str(x) if sys.platform != "mac": # On the Mac this import does succeed. diff --git a/Lib/test/test_future.py b/Lib/test/test_future.py index 9a5f829..1437489 100644 --- a/Lib/test/test_future.py +++ b/Lib/test/test_future.py @@ -29,7 +29,7 @@ class FutureTest(unittest.TestCase): def test_badfuture3(self): try: from test import badsyntax_future3 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future3", '3')) else: self.fail("expected exception didn't occur") @@ -37,7 +37,7 @@ class FutureTest(unittest.TestCase): def test_badfuture4(self): try: from test import badsyntax_future4 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future4", '3')) else: self.fail("expected exception didn't occur") @@ -45,7 +45,7 @@ class FutureTest(unittest.TestCase): def test_badfuture5(self): try: from test import badsyntax_future5 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future5", '4')) else: self.fail("expected exception didn't occur") @@ -53,7 +53,7 @@ class FutureTest(unittest.TestCase): def test_badfuture6(self): try: from test import badsyntax_future6 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future6", '3')) else: self.fail("expected exception didn't occur") @@ -61,7 +61,7 @@ class FutureTest(unittest.TestCase): def test_badfuture7(self): try: from test import badsyntax_future7 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future7", '3')) else: self.fail("expected exception didn't occur") @@ -69,7 +69,7 @@ class FutureTest(unittest.TestCase): def test_badfuture8(self): try: from test import badsyntax_future8 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future8", '3')) else: self.fail("expected exception didn't occur") @@ -77,7 +77,7 @@ class FutureTest(unittest.TestCase): def test_badfuture9(self): try: from test import badsyntax_future9 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future9", '3')) else: self.fail("expected exception didn't occur") diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py index 2ffd2f8..30df034 100644 --- a/Lib/test/test_generators.py +++ b/Lib/test/test_generators.py @@ -1554,7 +1554,7 @@ Now check some throw() conditions: ... while True: ... try: ... print (yield) -... except ValueError,v: +... except ValueError as v: ... print "caught ValueError (%s)" % (v), >>> import sys >>> g = f() diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py index 34c550e..0d36a62 100644 --- a/Lib/test/test_grammar.py +++ b/Lib/test/test_grammar.py @@ -554,7 +554,7 @@ hello world assert 1, lambda x:x+1 try: assert 0, "msg" - except AssertionError, e: + except AssertionError as e: self.assertEquals(e.args[0], "msg") else: if __debug__: @@ -612,7 +612,7 @@ hello world def testTry(self): ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] ### | 'try' ':' suite 'finally' ':' suite - ### except_clause: 'except' [expr [',' expr]] + ### except_clause: 'except' [expr ['as' expr]] try: 1/0 except ZeroDivisionError: @@ -621,14 +621,14 @@ hello world pass try: 1/0 except EOFError: pass - except TypeError, msg: pass - except RuntimeError, msg: pass + except TypeError as msg: pass + except RuntimeError as msg: pass except: pass else: pass try: 1/0 except (EOFError, TypeError, ZeroDivisionError): pass try: 1/0 - except (EOFError, TypeError, ZeroDivisionError), msg: pass + except (EOFError, TypeError, ZeroDivisionError) as msg: pass try: pass finally: pass diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py index 58de944..f3d1d49 100644 --- a/Lib/test/test_import.py +++ b/Lib/test/test_import.py @@ -55,7 +55,7 @@ class ImportTest(unittest.TestCase): try: try: mod = __import__(TESTFN) - except ImportError, err: + except ImportError as err: self.fail("import from %s failed: %s" % (ext, err)) self.assertEquals(mod.a, a, @@ -68,7 +68,7 @@ class ImportTest(unittest.TestCase): try: try: reload(mod) - except ImportError, err: + except ImportError as err: self.fail("import from .pyc/.pyo failed: %s" % err) finally: try: diff --git a/Lib/test/test_linuxaudiodev.py b/Lib/test/test_linuxaudiodev.py index fe902b5..05e4041 100644 --- a/Lib/test/test_linuxaudiodev.py +++ b/Lib/test/test_linuxaudiodev.py @@ -27,7 +27,7 @@ def play_sound_file(path): try: a = linuxaudiodev.open('w') - except linuxaudiodev.error, msg: + except linuxaudiodev.error as msg: if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise TestSkipped, msg raise TestFailed, msg @@ -62,27 +62,27 @@ def test_errors(): nchannels = 1 try: a.setparameters(-1, size, nchannels, fmt) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, -2, nchannels, fmt) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, size, 3, fmt) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, size, nchannels, 177) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, 16, nchannels, fmt) - except ValueError, msg: + except ValueError as msg: print msg def test(): diff --git a/Lib/test/test_nis.py b/Lib/test/test_nis.py index 590868f..55dd32c 100644 --- a/Lib/test/test_nis.py +++ b/Lib/test/test_nis.py @@ -6,7 +6,7 @@ class NisTests(unittest.TestCase): def test_maps(self): try: maps = nis.maps() - except nis.error, msg: + except nis.error as msg: # NIS is probably not active, so this test isn't useful if verbose: self.fail("(failing because of verbose mode) %s" % msg) diff --git a/Lib/test/test_opcodes.py b/Lib/test/test_opcodes.py index 1a2f5d6..0ee51a8 100644 --- a/Lib/test/test_opcodes.py +++ b/Lib/test/test_opcodes.py @@ -47,12 +47,12 @@ class OpcodeTest(unittest.TestCase): b = BClass() try: raise AClass, b - except BClass, v: + except BClass as v: if v != b: self.fail("v!=b") else: self.fail("no exception") try: raise b - except AClass, v: + except AClass as v: if v != b: self.fail("v!=b AClass") else: self.fail("no exception") @@ -63,7 +63,7 @@ class OpcodeTest(unittest.TestCase): ##else: self.fail("no exception") try: raise DClass, a - except DClass, v: + except DClass as v: self.assert_(isinstance(v, DClass)) else: self.fail("no exception") diff --git a/Lib/test/test_optparse.py b/Lib/test/test_optparse.py index 4582fa7..1c4970f 100644 --- a/Lib/test/test_optparse.py +++ b/Lib/test/test_optparse.py @@ -114,7 +114,7 @@ Args were %(args)s.""" % locals ()) try: func(*args, **kwargs) - except expected_exception, err: + except expected_exception as err: actual_message = str(err) if isinstance(expected_message, retype): self.assert_(expected_message.search(actual_message), @@ -152,7 +152,7 @@ and kwargs %(kwargs)r """ try: self.parser.parse_args(cmdline_args) - except InterceptedError, err: + except InterceptedError as err: self.assertEqual(err.error_message, expected_output) else: self.assertFalse("expected parse failure") @@ -175,7 +175,7 @@ and kwargs %(kwargs)r output = sys.stdout.getvalue() sys.stdout = save_stdout - except InterceptedError, err: + except InterceptedError as err: self.assert_( type(output) is types.StringType, "expected output to be an ordinary string, not %r" @@ -460,7 +460,7 @@ def _check_duration(option, opt, value): return int(value) else: return int(value[:-1]) * _time_units[value[-1]] - except ValueError, IndexError: + except ValueError as IndexError: raise OptionValueError( 'option %s: invalid duration: %r' % (opt, value)) diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py index 1c87d06..93e530c 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -179,7 +179,7 @@ class StatAttributeTests(unittest.TestCase): import statvfs try: result = os.statvfs(self.fname) - except OSError, e: + except OSError as e: # On AtheOS, glibc always returns ENOSYS import errno if e.errno == errno.ENOSYS: diff --git a/Lib/test/test_ossaudiodev.py b/Lib/test/test_ossaudiodev.py index 5868ea7..0377e9c 100644 --- a/Lib/test/test_ossaudiodev.py +++ b/Lib/test/test_ossaudiodev.py @@ -48,7 +48,7 @@ def _assert(expr, message=None): def play_sound_file(data, rate, ssize, nchannels): try: dsp = ossaudiodev.open('w') - except IOError, msg: + except IOError as msg: if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise TestSkipped, msg raise TestFailed, msg @@ -142,7 +142,7 @@ def test_bad_setparameters(dsp): try: result = dsp.setparameters(fmt, channels, rate, True) raise AssertionError("setparameters: expected OSSAudioError") - except ossaudiodev.OSSAudioError, err: + except ossaudiodev.OSSAudioError as err: print "setparameters: got OSSAudioError as expected" def test(): diff --git a/Lib/test/test_parser.py b/Lib/test/test_parser.py index 0bf1218..36bc4e3 100644 --- a/Lib/test/test_parser.py +++ b/Lib/test/test_parser.py @@ -15,7 +15,7 @@ class RoundtripLegalSyntaxTestCase(unittest.TestCase): t = st1.totuple() try: st2 = parser.sequence2st(t) - except parser.ParserError, why: + except parser.ParserError as why: self.fail("could not roundtrip %r: %s" % (s, why)) self.assertEquals(t, st2.totuple(), diff --git a/Lib/test/test_pep277.py b/Lib/test/test_pep277.py index f307089..ff71bf2 100644 --- a/Lib/test/test_pep277.py +++ b/Lib/test/test_pep277.py @@ -50,7 +50,7 @@ class UnicodeFileTests(unittest.TestCase): fn(filename) raise test_support.TestFailed("Expected to fail calling '%s(%r)'" % (fn.__name__, filename)) - except expected_exception, details: + except expected_exception as details: if check_fn_in_exception and details.filename != filename: raise test_support.TestFailed("Function '%s(%r) failed with " "bad filename in the exception: %r" diff --git a/Lib/test/test_pyexpat.py b/Lib/test/test_pyexpat.py index 0698818..73092c1 100644 --- a/Lib/test/test_pyexpat.py +++ b/Lib/test/test_pyexpat.py @@ -177,7 +177,7 @@ expat.ParserCreate(namespace_separator=' ') print "Legal values tested o.k." try: expat.ParserCreate(namespace_separator=42) -except TypeError, e: +except TypeError as e: print "Caught expected TypeError:" print e else: @@ -185,7 +185,7 @@ else: try: expat.ParserCreate(namespace_separator='too long') -except ValueError, e: +except ValueError as e: print "Caught expected ValueError:" print e else: @@ -321,7 +321,7 @@ parser.StartElementHandler = StartElementHandler try: parser.Parse("<a><b><c/></b></a>", 1) -except RuntimeError, e: +except RuntimeError as e: if e.args[0] != "a": print "Expected RuntimeError for element 'a'; found %r" % e.args[0] else: diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index 02f4dca..dafd82e 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -633,7 +633,7 @@ def run_re_tests(): else: try: result = obj.search(s) - except re.error, msg: + except re.error as msg: print '=== Unexpected exception', t, repr(msg) if outcome == SYNTAX_ERROR: # This should have been a syntax error; forget it. diff --git a/Lib/test/test_runpy.py b/Lib/test/test_runpy.py index 88e9900..a37ee7b 100644 --- a/Lib/test/test_runpy.py +++ b/Lib/test/test_runpy.py @@ -117,7 +117,7 @@ class RunModuleTest(unittest.TestCase): entry = parts[0] try: del sys.modules[entry] - except KeyError, ex: + except KeyError as ex: if verbose: print ex # Persist with cleaning up if verbose: print " Removed sys.modules entries" del sys.path[0] @@ -126,18 +126,18 @@ class RunModuleTest(unittest.TestCase): for name in files: try: os.remove(os.path.join(root, name)) - except OSError, ex: + except OSError as ex: if verbose: print ex # Persist with cleaning up for name in dirs: fullname = os.path.join(root, name) try: os.rmdir(fullname) - except OSError, ex: + except OSError as ex: if verbose: print ex # Persist with cleaning up try: os.rmdir(top) if verbose: print " Removed package tree" - except OSError, ex: + except OSError as ex: if verbose: print ex # Persist with cleaning up def _check_module(self, depth): diff --git a/Lib/test/test_sax.py b/Lib/test/test_sax.py index 83ffcf1..d3939c0 100644 --- a/Lib/test/test_sax.py +++ b/Lib/test/test_sax.py @@ -479,7 +479,7 @@ def test_expat_inpsource_location(): source.setSystemId(name) try: parser.parse(source) - except SAXException, e: + except SAXException as e: return e.getSystemId() == name def test_expat_incomplete(): diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py index 9bd0d43..0d08b79 100644 --- a/Lib/test/test_set.py +++ b/Lib/test/test_set.py @@ -332,7 +332,7 @@ class TestSet(TestJointOps): for v1 in ['Q', (1,)]: try: self.s.remove(v1) - except KeyError, e: + except KeyError as e: v2 = e.args[0] self.assertEqual(v1, v2) else: diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py index df37f73..e141257 100644 --- a/Lib/test/test_socket.py +++ b/Lib/test/test_socket.py @@ -129,7 +129,7 @@ class ThreadableTest: raise TypeError, "test_func must be a callable function" try: test_func() - except Exception, strerror: + except Exception as strerror: self.queue.put(strerror) self.clientTearDown() diff --git a/Lib/test/test_socket_ssl.py b/Lib/test/test_socket_ssl.py index 3c9c9f0..5d308c5 100644 --- a/Lib/test/test_socket_ssl.py +++ b/Lib/test/test_socket_ssl.py @@ -58,7 +58,7 @@ def test_timeout(): except socket.timeout: error_msg('timed out') return - except socket.error, exc: # In case connection is refused. + except socket.error as exc: # In case connection is refused. if exc.args[0] == errno.ECONNREFUSED: error_msg('was refused') return diff --git a/Lib/test/test_socketserver.py b/Lib/test/test_socketserver.py index e4cbb2b..202f2da 100644 --- a/Lib/test/test_socketserver.py +++ b/Lib/test/test_socketserver.py @@ -155,7 +155,8 @@ class ForgivingTCPServer(TCPServer): self.server_address = host, port TCPServer.server_bind(self) break - except socket.error, (err, msg): + except socket.error as e: + (err, msg) = e if err != errno.EADDRINUSE: raise print >>sys.__stderr__, \ diff --git a/Lib/test/test_strftime.py b/Lib/test/test_strftime.py index e9d3826..00fa227 100755 --- a/Lib/test/test_strftime.py +++ b/Lib/test/test_strftime.py @@ -119,7 +119,7 @@ def strftest(now): for e in expectations: try: result = time.strftime(e[0], now) - except ValueError, error: + except ValueError as error: print "Standard '%s' format gave error:" % e[0], error continue if re.match(escapestr(e[1], ampm), result): continue @@ -132,7 +132,7 @@ def strftest(now): for e in nonstandard_expectations: try: result = time.strftime(e[0], now) - except ValueError, result: + except ValueError as result: if verbose: print "Error for nonstandard '%s' format (%s): %s" % \ (e[0], e[2], str(result)) diff --git a/Lib/test/test_string.py b/Lib/test/test_string.py index fdd431d..6d5e8e4 100644 --- a/Lib/test/test_string.py +++ b/Lib/test/test_string.py @@ -55,7 +55,7 @@ class StringTest( def f(): yield 4 + "" self.fixtype(' ').join(f()) - except TypeError, e: + except TypeError as e: if '+' not in str(e): self.fail('join() ate exception message') else: diff --git a/Lib/test/test_strptime.py b/Lib/test/test_strptime.py index ba65649..df94f7b 100644 --- a/Lib/test/test_strptime.py +++ b/Lib/test/test_strptime.py @@ -206,7 +206,7 @@ class StrptimeTests(unittest.TestCase): _strptime.strptime("2005", bad_format) except ValueError: continue - except Exception, err: + except Exception as err: self.fail("'%s' raised %s, not ValueError" % (bad_format, err.__class__.__name__)) else: diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py index 64f8d40..fcc0f45 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -67,7 +67,7 @@ class ProcessTestCase(unittest.TestCase): try: subprocess.check_call([sys.executable, "-c", "import sys; sys.exit(47)"]) - except subprocess.CalledProcessError, e: + except subprocess.CalledProcessError as e: self.assertEqual(e.returncode, 47) else: self.fail("Expected CalledProcessError") @@ -475,7 +475,7 @@ class ProcessTestCase(unittest.TestCase): try: p = subprocess.Popen([sys.executable, "-c", ""], cwd="/this/path/does/not/exist") - except OSError, e: + except OSError as e: # The attribute child_traceback should contain "os.chdir" # somewhere. self.assertNotEqual(e.child_traceback.find("os.chdir"), -1) diff --git a/Lib/test/test_sunaudiodev.py b/Lib/test/test_sunaudiodev.py index f203d9a..0427db5 100644 --- a/Lib/test/test_sunaudiodev.py +++ b/Lib/test/test_sunaudiodev.py @@ -16,7 +16,7 @@ def play_sound_file(path): fp.close() try: a = sunaudiodev.open('w') - except sunaudiodev.error, msg: + except sunaudiodev.error as msg: raise TestFailed, msg else: a.write(data) diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py index 2c19698..6115800 100644 --- a/Lib/test/test_support.py +++ b/Lib/test/test_support.py @@ -102,7 +102,8 @@ def bind_port(sock, host='', preferred_port=54321): try: sock.bind((host, port)) return port - except socket.error, (err, msg): + except socket.error as e: + (err, msg) = e if err != errno.EADDRINUSE: raise print >>sys.__stderr__, \ diff --git a/Lib/test/test_syntax.py b/Lib/test/test_syntax.py index a0eaac6..2c7315d 100644 --- a/Lib/test/test_syntax.py +++ b/Lib/test/test_syntax.py @@ -387,7 +387,7 @@ class SyntaxTestCase(unittest.TestCase): """ try: compile(code, filename, mode) - except SyntaxError, err: + except SyntaxError as err: if subclass and not isinstance(err, subclass): self.fail("SyntaxError is not a %s" % subclass.__name__) mo = re.search(errtext, str(err)) diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py index fdeb500..897c6b0 100644 --- a/Lib/test/test_sys.py +++ b/Lib/test/test_sys.py @@ -54,7 +54,7 @@ class SysModuleTest(unittest.TestCase): self.assertRaises(TypeError, eh) try: raise ValueError(42) - except ValueError, exc: + except ValueError as exc: eh(*sys.exc_info()) sys.stderr = savestderr @@ -84,7 +84,7 @@ class SysModuleTest(unittest.TestCase): def clear(): try: raise ValueError, 42 - except ValueError, exc: + except ValueError as exc: clear_check(exc) # Raise an exception and check that it can be cleared @@ -94,7 +94,7 @@ class SysModuleTest(unittest.TestCase): # unaffected by calling exc_clear in a nested frame. try: raise ValueError, 13 - except ValueError, exc: + except ValueError as exc: typ1, value1, traceback1 = sys.exc_info() clear() typ2, value2, traceback2 = sys.exc_info() @@ -104,16 +104,13 @@ class SysModuleTest(unittest.TestCase): self.assert_(value1 is value2) self.assert_(traceback1 is traceback2) - # Check that an exception can be cleared outside of an except block - clear_check(exc) - def test_exit(self): self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument try: sys.exit(0) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, 0) except: self.fail("wrong exception") @@ -124,7 +121,7 @@ class SysModuleTest(unittest.TestCase): # entry will be unpacked try: sys.exit(42) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, 42) except: self.fail("wrong exception") @@ -134,7 +131,7 @@ class SysModuleTest(unittest.TestCase): # call with integer argument try: sys.exit((42,)) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, 42) except: self.fail("wrong exception") @@ -144,7 +141,7 @@ class SysModuleTest(unittest.TestCase): # call with string argument try: sys.exit("exit") - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, "exit") except: self.fail("wrong exception") @@ -154,7 +151,7 @@ class SysModuleTest(unittest.TestCase): # call with tuple argument with two entries try: sys.exit((17, 23)) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, (17, 23)) except: self.fail("wrong exception") diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py index 2b39715..9ae913d 100644 --- a/Lib/test/test_tarfile.py +++ b/Lib/test/test_tarfile.py @@ -545,7 +545,7 @@ class ExtractHardlinkTest(BaseTest): try: # Extract 1-LNKTYPE which is a hardlink to 0-REGTYPE self.tar.extract("1-LNKTYPE", dirname()) - except EnvironmentError, e: + except EnvironmentError as e: import errno if e.errno == errno.ENOENT: self.fail("hardlink not extracted properly") diff --git a/Lib/test/test_tcl.py b/Lib/test/test_tcl.py index fa170ef..4255d8a 100644 --- a/Lib/test/test_tcl.py +++ b/Lib/test/test_tcl.py @@ -107,7 +107,7 @@ class TclTest(unittest.TestCase): filename = "doesnotexists" try: os.remove(filename) - except Exception,e: + except Exception as e: pass self.assertRaises(TclError,tcl.evalfile,filename) diff --git a/Lib/test/test_trace.py b/Lib/test/test_trace.py index 08aec8e..42d1a4a 100644 --- a/Lib/test/test_trace.py +++ b/Lib/test/test_trace.py @@ -97,7 +97,7 @@ def raises(): def test_raise(): try: raises() - except Exception, exc: + except Exception as exc: x = 1 test_raise.events = [(0, 'call'), @@ -127,7 +127,7 @@ def _settrace_and_raise(tracefunc): def settrace_and_raise(tracefunc): try: _settrace_and_raise(tracefunc) - except RuntimeError, exc: + except RuntimeError as exc: pass settrace_and_raise.events = [(2, 'exception'), @@ -432,7 +432,7 @@ def no_jump_too_far_forwards(output): try: output.append(2) output.append(3) - except ValueError, e: + except ValueError as e: output.append('after' in str(e)) no_jump_too_far_forwards.jump = (3, 6) @@ -442,7 +442,7 @@ def no_jump_too_far_backwards(output): try: output.append(2) output.append(3) - except ValueError, e: + except ValueError as e: output.append('before' in str(e)) no_jump_too_far_backwards.jump = (3, -1) @@ -472,7 +472,7 @@ no_jump_to_except_2.output = [True] def no_jump_to_except_3(output): try: output.append(2) - except ValueError, e: + except ValueError as e: output.append('except' in str(e)) no_jump_to_except_3.jump = (2, 3) @@ -481,7 +481,7 @@ no_jump_to_except_3.output = [True] def no_jump_to_except_4(output): try: output.append(2) - except (ValueError, RuntimeError), e: + except (ValueError, RuntimeError) as e: output.append('except' in str(e)) no_jump_to_except_4.jump = (2, 3) @@ -492,7 +492,7 @@ def no_jump_forwards_into_block(output): output.append(2) for i in 1, 2: output.append(4) - except ValueError, e: + except ValueError as e: output.append('into' in str(e)) no_jump_forwards_into_block.jump = (2, 4) @@ -503,7 +503,7 @@ def no_jump_backwards_into_block(output): for i in 1, 2: output.append(3) output.append(4) - except ValueError, e: + except ValueError as e: output.append('into' in str(e)) no_jump_backwards_into_block.jump = (4, 3) @@ -516,7 +516,7 @@ def no_jump_into_finally_block(output): x = 1 finally: output.append(6) - except ValueError, e: + except ValueError as e: output.append('finally' in str(e)) no_jump_into_finally_block.jump = (4, 6) @@ -529,7 +529,7 @@ def no_jump_out_of_finally_block(output): finally: output.append(5) output.append(6) - except ValueError, e: + except ValueError as e: output.append('finally' in str(e)) no_jump_out_of_finally_block.jump = (5, 1) @@ -539,7 +539,7 @@ no_jump_out_of_finally_block.output = [3, True] def no_jump_to_non_integers(output): try: output.append(2) - except ValueError, e: + except ValueError as e: output.append('integer' in str(e)) no_jump_to_non_integers.jump = (2, "Spam") @@ -551,7 +551,7 @@ def no_jump_without_trace_function(): try: previous_frame = sys._getframe().f_back previous_frame.f_lineno = previous_frame.f_lineno - except ValueError, e: + except ValueError as e: # This is the exception we wanted; make sure the error message # talks about trace functions. if 'trace' not in str(e): diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index 48c5d19..5c8a4e4 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -12,7 +12,7 @@ class TracebackCases(unittest.TestCase): def get_exception_format(self, func, exc): try: func() - except exc, value: + except exc as value: return traceback.format_exception_only(exc, value) else: raise ValueError, "call did not raise exception" diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py index 00cf202..50acff8 100644 --- a/Lib/test/test_urllib2net.py +++ b/Lib/test/test_urllib2net.py @@ -236,7 +236,7 @@ class OtherNetworkTests(unittest.TestCase): debug(url) try: f = urllib2.urlopen(url, req) - except (IOError, socket.error, OSError), err: + except (IOError, socket.error, OSError) as err: debug(err) if expected_err: msg = ("Didn't get expected error(s) %s for %s %s, got %s" % diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py index 447f434..25aa307 100644 --- a/Lib/test/test_userdict.py +++ b/Lib/test/test_userdict.py @@ -168,7 +168,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): e = E() try: e[42] - except RuntimeError, err: + except RuntimeError as err: self.assertEqual(err.args, (42,)) else: self.fail_("e[42] didn't raise RuntimeError") @@ -180,7 +180,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): f = F() try: f[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("f[42] didn't raise KeyError") @@ -189,7 +189,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol): g = G() try: g[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("g[42] didn't raise KeyError") diff --git a/Lib/test/test_uu.py b/Lib/test/test_uu.py index 16a55e4..7128148 100644 --- a/Lib/test/test_uu.py +++ b/Lib/test/test_uu.py @@ -50,7 +50,7 @@ class UUTest(unittest.TestCase): try: uu.decode(inp, out) self.fail("No exception thrown") - except uu.Error, e: + except uu.Error as e: self.assertEqual(str(e), "Truncated input file") def test_missingbegin(self): @@ -59,7 +59,7 @@ class UUTest(unittest.TestCase): try: uu.decode(inp, out) self.fail("No exception thrown") - except uu.Error, e: + except uu.Error as e: self.assertEqual(str(e), "No valid begin line found in input file") class UUStdIOTest(unittest.TestCase): diff --git a/Lib/test/test_winreg.py b/Lib/test/test_winreg.py index 5830fd6..81bd760 100644 --- a/Lib/test/test_winreg.py +++ b/Lib/test/test_winreg.py @@ -142,7 +142,7 @@ except (IndexError, ValueError): if remote_name is not None: try: remote_key = ConnectRegistry(remote_name, HKEY_CURRENT_USER) - except EnvironmentError, exc: + except EnvironmentError as exc: print "Could not connect to the remote machine -", exc.strerror remote_key = None if remote_key is not None: diff --git a/Lib/timeit.py b/Lib/timeit.py index 190b8c5..5dd3ca9 100644 --- a/Lib/timeit.py +++ b/Lib/timeit.py @@ -209,7 +209,7 @@ def main(args=None): opts, args = getopt.getopt(args, "n:s:r:tcvh", ["number=", "setup=", "repeat=", "time", "clock", "verbose", "help"]) - except getopt.error, err: + except getopt.error as err: print err print "use -h/--help for command line help" return 2 diff --git a/Lib/toaiff.py b/Lib/toaiff.py index 3c8a02b..438d225 100644 --- a/Lib/toaiff.py +++ b/Lib/toaiff.py @@ -87,7 +87,7 @@ def _toaiff(filename, temps): ftype = sndhdr.whathdr(fname) if ftype: ftype = ftype[0] # All we're interested in - except IOError, msg: + except IOError as msg: if type(msg) == type(()) and len(msg) == 2 and \ type(msg[0]) == type(0) and type(msg[1]) == type(''): msg = msg[1] diff --git a/Lib/token.py b/Lib/token.py index 2770cfd..477827ac 100755 --- a/Lib/token.py +++ b/Lib/token.py @@ -93,7 +93,7 @@ def main(): outFileName = args[1] try: fp = open(inFileName) - except IOError, err: + except IOError as err: sys.stdout.write("I/O error: %s\n" % str(err)) sys.exit(1) lines = fp.read().split("\n") @@ -113,7 +113,7 @@ def main(): # load the output skeleton from the target: try: fp = open(outFileName) - except IOError, err: + except IOError as err: sys.stderr.write("I/O error: %s\n" % str(err)) sys.exit(2) format = fp.read().split("\n") @@ -130,7 +130,7 @@ def main(): format[start:end] = lines try: fp = open(outFileName, 'w') - except IOError, err: + except IOError as err: sys.stderr.write("I/O error: %s\n" % str(err)) sys.exit(4) fp.write("\n".join(format)) diff --git a/Lib/trace.py b/Lib/trace.py index c7ed0a5..ca44eae 100644 --- a/Lib/trace.py +++ b/Lib/trace.py @@ -220,7 +220,7 @@ class CoverageResults: counts, calledfuncs, callers = \ pickle.load(open(self.infile, 'rb')) self.update(self.__class__(counts, calledfuncs, callers)) - except (IOError, EOFError, ValueError), err: + except (IOError, EOFError, ValueError) as err: print >> sys.stderr, ("Skipping counts file %r: %s" % (self.infile, err)) @@ -328,7 +328,7 @@ class CoverageResults: try: pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1) - except IOError, err: + except IOError as err: print >> sys.stderr, "Can't save counts files because %s" % err def write_results_file(self, path, lines, lnotab, lines_hit): @@ -336,7 +336,7 @@ class CoverageResults: try: outfile = open(path, "w") - except IOError, err: + except IOError as err: print >> sys.stderr, ("trace: Could not open %r for writing: %s" "- skipping" % (path, err)) return 0, 0 @@ -422,7 +422,7 @@ def find_executable_linenos(filename): """Return dict where keys are line numbers in the line number table.""" try: prog = open(filename, "rU").read() - except IOError, err: + except IOError as err: print >> sys.stderr, ("Not printing coverage data for %r: %s" % (filename, err)) return {} @@ -658,7 +658,7 @@ def main(argv=None): "coverdir=", "listfuncs", "trackcalls"]) - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0]) @@ -778,7 +778,7 @@ def main(argv=None): outfile=counts_file) try: t.run('execfile(%r)' % (progname,)) - except IOError, err: + except IOError as err: _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err)) except SystemExit: pass diff --git a/Lib/unittest.py b/Lib/unittest.py index b34b389..9163e84 100644 --- a/Lib/unittest.py +++ b/Lib/unittest.py @@ -783,7 +783,7 @@ Examples: else: self.testNames = (self.defaultTest,) self.createTests() - except getopt.error, msg: + except getopt.error as msg: self.usageExit(msg) def createTests(self): diff --git a/Lib/urllib.py b/Lib/urllib.py index 27ec2c9..aacc373 100644 --- a/Lib/urllib.py +++ b/Lib/urllib.py @@ -190,7 +190,7 @@ class URLopener: return getattr(self, name)(url) else: return getattr(self, name)(url, data) - except socket.error, msg: + except socket.error as msg: raise IOError, ('socket error', msg), sys.exc_info()[2] def open_unknown(self, fullurl, data=None): @@ -217,7 +217,7 @@ class URLopener: hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs - except IOError, msg: + except IOError as msg: pass fp = self.open(url, data) headers = fp.info() @@ -461,7 +461,7 @@ class URLopener: localname = url2pathname(file) try: stats = os.stat(localname) - except OSError, e: + except OSError as e: raise IOError(e.errno, e.strerror, e.filename) size = stats.st_size modified = email.Utils.formatdate(stats.st_mtime, usegmt=True) @@ -544,7 +544,7 @@ class URLopener: headers += "Content-Length: %d\n" % retrlen headers = mimetools.Message(StringIO(headers)) return addinfourl(fp, headers, "ftp:" + url) - except ftperrors(), msg: + except ftperrors() as msg: raise IOError, ('ftp error', msg), sys.exc_info()[2] def open_data(self, url, data=None): @@ -861,7 +861,7 @@ class ftpwrapper: try: cmd = 'RETR ' + file conn = self.ftp.ntransfercmd(cmd) - except ftplib.error_perm, reason: + except ftplib.error_perm as reason: if str(reason)[:3] != '550': raise IOError, ('ftp error', reason), sys.exc_info()[2] if not conn: @@ -1503,7 +1503,7 @@ def main(): import getopt, sys try: opts, args = getopt.getopt(sys.argv[1:], "th") - except getopt.error, msg: + except getopt.error as msg: print msg print "Use -h for help" return diff --git a/Lib/urllib2.py b/Lib/urllib2.py index a880e64..d14996d 100644 --- a/Lib/urllib2.py +++ b/Lib/urllib2.py @@ -1072,7 +1072,7 @@ class AbstractHTTPHandler(BaseHandler): try: h.request(req.get_method(), req.get_selector(), req.data, headers) r = h.getresponse() - except socket.error, err: # XXX what error? + except socket.error as err: # XXX what error? raise URLError(err) # Pick apart the HTTPResponse object to get the addinfourl @@ -1254,7 +1254,7 @@ class FTPHandler(BaseHandler): try: host = socket.gethostbyname(host) - except socket.error, msg: + except socket.error as msg: raise URLError(msg) path, attrs = splitattr(req.get_selector()) dirs = path.split('/') @@ -1280,7 +1280,7 @@ class FTPHandler(BaseHandler): sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) - except ftplib.all_errors, msg: + except ftplib.all_errors as msg: raise IOError, ('ftp error', msg), sys.exc_info()[2] def connect_ftp(self, user, passwd, host, port, dirs): @@ -132,7 +132,7 @@ def decode(in_file, out_file=None, mode=None, quiet=0): while s and s.strip() != 'end': try: data = binascii.a2b_uu(s) - except binascii.Error, v: + except binascii.Error as v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3 data = binascii.a2b_uu(s[:nbytes]) diff --git a/Lib/warnings.py b/Lib/warnings.py index b7fac69..c0a96d6 100644 --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -192,7 +192,7 @@ def _processoptions(args): for arg in args: try: _setoption(arg) - except _OptionError, msg: + except _OptionError as msg: print >>sys.stderr, "Invalid -W option ignored:", msg # Helper for _processoptions() diff --git a/Lib/webbrowser.py b/Lib/webbrowser.py index 0d5f44f..28e6bde 100644 --- a/Lib/webbrowser.py +++ b/Lib/webbrowser.py @@ -625,7 +625,7 @@ def main(): -t: open new tab""" % sys.argv[0] try: opts, args = getopt.getopt(sys.argv[1:], 'ntd') - except getopt.error, msg: + except getopt.error as msg: print >>sys.stderr, msg print >>sys.stderr, usage sys.exit(1) diff --git a/Lib/xdrlib.py b/Lib/xdrlib.py index 796dfaf..23e1ff2 100644 --- a/Lib/xdrlib.py +++ b/Lib/xdrlib.py @@ -68,12 +68,12 @@ class Packer: def pack_float(self, x): try: self.__buf.write(struct.pack('>f', x)) - except struct.error, msg: + except struct.error as msg: raise ConversionError, msg def pack_double(self, x): try: self.__buf.write(struct.pack('>d', x)) - except struct.error, msg: + except struct.error as msg: raise ConversionError, msg def pack_fstring(self, n, s): diff --git a/Lib/xml/sax/__init__.py b/Lib/xml/sax/__init__.py index d55ffb7..242c689 100644 --- a/Lib/xml/sax/__init__.py +++ b/Lib/xml/sax/__init__.py @@ -79,7 +79,7 @@ def make_parser(parser_list = []): for parser_name in parser_list + default_parser_list: try: return _create_parser(parser_name) - except ImportError,e: + except ImportError as e: import sys if parser_name in sys.modules: # The parser module was found, but importing it diff --git a/Lib/xml/sax/expatreader.py b/Lib/xml/sax/expatreader.py index bb9c294..c4fb930 100644 --- a/Lib/xml/sax/expatreader.py +++ b/Lib/xml/sax/expatreader.py @@ -205,7 +205,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): # document. When feeding chunks, they are not normally final - # except when invoked from close. self._parser.Parse(data, isFinal) - except expat.error, e: + except expat.error as e: exc = SAXParseException(expat.ErrorString(e.code), e, self) # FIXME: when to invoke error()? self._err_handler.fatalError(exc) diff --git a/Lib/xmllib.py b/Lib/xmllib.py index 2a189cd..59fbcd1 100644 --- a/Lib/xmllib.py +++ b/Lib/xmllib.py @@ -896,7 +896,7 @@ def test(args = None): else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) @@ -914,7 +914,7 @@ def test(args = None): for c in data: x.feed(c) x.close() - except Error, msg: + except Error as msg: t1 = time() print msg if do_time: diff --git a/Lib/xmlrpclib.py b/Lib/xmlrpclib.py index da3d396..f584ad7 100644 --- a/Lib/xmlrpclib.py +++ b/Lib/xmlrpclib.py @@ -1454,7 +1454,7 @@ if __name__ == "__main__": try: print server.currentTime.getCurrentTime() - except Error, v: + except Error as v: print "ERROR", v multi = MultiCall(server) @@ -1463,5 +1463,5 @@ if __name__ == "__main__": try: for response in multi(): print response - except Error, v: + except Error as v: print "ERROR", v diff --git a/Lib/zipfile.py b/Lib/zipfile.py index 5c3fff3..0f3bccc 100644 --- a/Lib/zipfile.py +++ b/Lib/zipfile.py @@ -812,7 +812,7 @@ class PyZipFile(ZipFile): print "Compiling", file_py try: py_compile.compile(file_py, file_pyc, None, True) - except py_compile.PyCompileError,err: + except py_compile.PyCompileError as err: print err.msg fname = file_pyc else: |