SF patch 1631942 by Collin Winter:

(a) "except E, V" -> "except E as V"
(b) V is now limited to a simple name (local variable)
(c) V is now deleted at the end of the except block
This commit is contained in:
Guido van Rossum 2007-01-10 16:19:56 +00:00
parent 893523e80a
commit b940e113bf
295 changed files with 817 additions and 743 deletions

View File

@ -119,5 +119,5 @@ class WikiPage:
f.write('\n')
f.close()
return ""
except IOError, err:
except IOError as err:
return "IOError: %s" % str(err)

View File

@ -28,7 +28,7 @@ def main():
for file in sys.argv[1:]:
try:
fp = open(file, 'r')
except IOError, msg:
except IOError as msg:
print "%s: %s" % (file, msg)
continue
lineno = 0

View File

@ -41,7 +41,7 @@ def main():
def reportboguslinks(prefix):
try:
names = os.listdir('.')
except os.error, msg:
except os.error as msg:
print "%s%s: can't list: %s" % (prefix, '.', msg)
return
names.sort()
@ -62,7 +62,7 @@ def reportboguslinks(prefix):
elif S_ISDIR(mode):
try:
os.chdir(name)
except os.error, msg:
except os.error as msg:
print "%s%s: can't chdir: %s" % \
(prefix, name, msg)
continue

View File

@ -17,7 +17,7 @@ def testChunk(t, fileName):
# against a large source file like Tkinter.py.
ast = None
new = parser.tuple2ast(tup)
except parser.ParserError, err:
except parser.ParserError as err:
print
print 'parser module raised exception on input file', fileName + ':'
traceback.print_exc()

View File

@ -492,7 +492,7 @@ def testdir(a):
print 'Testing %s' % fullname
try:
roundtrip(fullname, output)
except Exception, e:
except Exception as e:
print ' Failed to compile, exception is %s' % repr(e)
elif os.path.isdir(fullname):
testdir(fullname)

View File

@ -87,7 +87,7 @@ class FSProxyLocal:
fs = macfs.FSSpec(name)
c, t = fs.GetCreatorType()
if t != 'TEXT': return 0
except macfs.error, msg:
except macfs.error as msg:
print "***", name, msg
return 0
else:

View File

@ -42,7 +42,7 @@ class CommandFrameWork:
if args is None: args = sys.argv[1:]
try:
opts, args = getopt.getopt(args, self.GlobalFlags)
except getopt.error, msg:
except getopt.error as msg:
return self.usage(msg)
self.options(opts)
if not args:
@ -62,7 +62,7 @@ class CommandFrameWork:
flags = ''
try:
opts, args = getopt.getopt(args[1:], flags)
except getopt.error, msg:
except getopt.error as msg:
return self.usage(
"subcommand %s: " % cmd + str(msg))
self.ready()

View File

@ -135,7 +135,7 @@ def compare(local, remote, mode):
def sendfile(local, remote, name):
try:
remote.create(name)
except (IOError, os.error), msg:
except (IOError, os.error) as msg:
print "cannot create:", msg
return
@ -171,7 +171,7 @@ def recvfile(local, remote, name):
def recvfile_real(local, remote, name):
try:
local.create(name)
except (IOError, os.error), msg:
except (IOError, os.error) as msg:
print "cannot create:", msg
return

View File

@ -129,7 +129,7 @@ class Lock:
self.lockdir = self.cvslck
os.mkdir(self.cvslck, 0777)
return
except os.error, msg:
except os.error as msg:
self.lockdir = None
if msg[0] == EEXIST:
try:
@ -234,7 +234,7 @@ def MultipleWriteLock(repositories, delay = DELAY):
for r in repositories:
try:
locks.append(WriteLock(r, 0))
except Locked, instance:
except Locked as instance:
del locks
break
else:

View File

@ -22,7 +22,7 @@ def main():
raise getopt.error, "unknown command"
coptset, func = commands[cmd]
copts, files = getopt.getopt(rest, coptset)
except getopt.error, msg:
except getopt.error as msg:
print msg
print "usage: rrcs [options] command [options] [file] ..."
print "where command can be:"
@ -41,7 +41,7 @@ def main():
for fn in files:
try:
func(x, copts, fn)
except (IOError, os.error), msg:
except (IOError, os.error) as msg:
print "%s: %s" % (fn, msg)
def checkin(x, copts, fn):

View File

@ -21,14 +21,14 @@ def main():
opts, args = getopt.getopt(sys.argv[1:], "")
if len(args) > 1:
raise getopt.error, "Too many arguments."
except getopt.error, msg:
except getopt.error as msg:
usage(msg)
for o, a in opts:
pass
if args:
try:
port = string.atoi(args[0])
except ValueError, msg:
except ValueError as msg:
usage(msg)
else:
port = PORT
@ -83,7 +83,7 @@ def run_interpreter(stdin, stdout):
source = source + line
try:
code = compile_command(source)
except SyntaxError, err:
except SyntaxError as err:
source = ""
traceback.print_exception(SyntaxError, err, None, file=stdout)
continue
@ -92,7 +92,7 @@ def run_interpreter(stdin, stdout):
source = ""
try:
run_command(code, stdin, stdout, globals)
except SystemExit, how:
except SystemExit as how:
if how:
try:
how = str(how)
@ -109,7 +109,7 @@ def run_command(code, stdin, stdout, globals):
sys.stdin = stdin
try:
exec(code, globals)
except SystemExit, how:
except SystemExit as how:
raise SystemExit, how, sys.exc_info()[2]
except:
type, value, tb = sys.exc_info()

View File

@ -194,8 +194,7 @@ def test():
fh = sf[1]
if fh:
ncl = NFSClient(host)
as = ncl.Getattr(fh)
print as
print ncl.Getattr(fh)
list = ncl.Listdir(fh)
for item in list: print item
mcl.Umnt(filesys)

View File

@ -330,7 +330,8 @@ def bindresvport(sock, host):
try:
sock.bind((host, i))
return last_resv_port_tried
except socket.error, (errno, msg):
except socket.error as e:
(errno, msg) = e
if errno != 114:
raise socket.error, (errno, msg)
raise RuntimeError, 'can\'t assign reserved port'
@ -765,7 +766,7 @@ class TCPServer(Server):
call = recvrecord(sock)
except EOFError:
break
except socket.error, msg:
except socket.error as msg:
print 'socket error:', msg
break
reply = self.handle(call)
@ -866,7 +867,7 @@ def testsvr():
s = S('', 0x20000000, 1, 0)
try:
s.unregister()
except RuntimeError, msg:
except RuntimeError as msg:
print 'RuntimeError:', msg, '(ignored)'
s.register()
print 'Service started...'

View File

@ -62,7 +62,7 @@ def recursedown(dirname):
bad = 0
try:
names = os.listdir(dirname)
except os.error, msg:
except os.error as msg:
err('%s: cannot list directory: %r\n' % (dirname, msg))
return 1
names.sort()
@ -83,7 +83,7 @@ def fix(filename):
## dbg('fix(%r)\n' % (dirname,))
try:
f = open(filename, 'r')
except IOError, msg:
except IOError as msg:
err('%s: cannot open: %r\n' % (filename, msg))
return 1
head, tail = os.path.split(filename)
@ -120,7 +120,7 @@ def fix(filename):
if g is None:
try:
g = open(tempname, 'w')
except IOError, msg:
except IOError as msg:
f.close()
err('%s: cannot create: %r\n' % (tempname, msg))
return 1
@ -144,17 +144,17 @@ def fix(filename):
try:
statbuf = os.stat(filename)
os.chmod(tempname, statbuf[ST_MODE] & 07777)
except os.error, msg:
except os.error as msg:
err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
# Then make a backup of the original file as filename~
try:
os.rename(filename, filename + '~')
except os.error, msg:
except os.error as msg:
err('%s: warning: backup failed (%r)\n' % (filename, msg))
# Now move the temp file to the original file
try:
os.rename(tempname, filename)
except os.error, msg:
except os.error as msg:
err('%s: rename failed (%r)\n' % (filename, msg))
return 1
# Return succes

View File

@ -25,7 +25,7 @@ def main():
search = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'm:s:')
except getopt.error, msg:
except getopt.error as msg:
print msg
print 'usage: ftpstats [-m maxitems] [file]'
sys.exit(2)
@ -41,7 +41,7 @@ def main():
else:
try:
f = open(file, 'r')
except IOError, msg:
except IOError as msg:
print file, ':', msg
sys.exit(1)
bydate = {}

View File

@ -16,7 +16,7 @@ def main():
dofile = mmdf
try:
opts, args = getopt.getopt(sys.argv[1:], 'f')
except getopt.error, msg:
except getopt.error as msg:
sys.stderr.write('%s\n' % msg)
sys.exit(2)
for o, a in opts:
@ -33,7 +33,7 @@ def main():
elif os.path.isfile(arg):
try:
f = open(arg)
except IOError, msg:
except IOError as msg:
sys.stderr.write('%s: %s\n' % (arg, msg))
sts = 1
continue
@ -56,7 +56,7 @@ def mh(dir):
fn = os.path.join(dir, msg)
try:
f = open(fn)
except IOError, msg:
except IOError as msg:
sys.stderr.write('%s: %s\n' % (fn, msg))
sts = 1
continue

View File

@ -330,7 +330,7 @@ def main():
else:
s = NNTP(newshost)
connected = 1
except (nntplib.error_temp, nntplib.error_perm), x:
except (nntplib.error_temp, nntplib.error_perm) as x:
print 'Error connecting to host:', x
print 'I\'ll try to use just the local list.'
connected = 0

View File

@ -35,7 +35,7 @@ PFLAG = 0
try:
optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np')
except getopt.error, msg:
except getopt.error as msg:
sys.stderr.write(sys.argv[0] + ': ' + msg + '\n')
sys.exit(2)

View File

@ -19,7 +19,7 @@ class FileObj:
self.changed = 0
try:
self.lines = open(filename, 'r').readlines()
except IOError, msg:
except IOError as msg:
print '*** Can\'t open "%s":' % filename, msg
self.lines = None
return
@ -32,7 +32,7 @@ class FileObj:
try:
os.rename(self.filename, self.filename + '~')
fp = open(self.filename, 'w')
except (os.error, IOError), msg:
except (os.error, IOError) as msg:
print '*** Can\'t rewrite "%s":' % self.filename, msg
return
print 'writing', self.filename
@ -67,7 +67,7 @@ def main():
if sys.argv[1:]:
try:
fp = open(sys.argv[1], 'r')
except IOError, msg:
except IOError as msg:
print 'Can\'t open "%s":' % sys.argv[1], msg
sys.exit(1)
else:

View File

@ -142,7 +142,7 @@ def browser(*args):
raise RuntimeError, 'too many args'
try:
browse_menu(selector, host, port)
except socket.error, msg:
except socket.error as msg:
print 'Socket error:', msg
sys.exit(1)
except KeyboardInterrupt:
@ -202,7 +202,7 @@ def browse_textfile(selector, host, port):
p = os.popen('${PAGER-more}', 'w')
x = SaveLines(p)
get_alt_textfile(selector, host, port, x.writeln)
except IOError, msg:
except IOError as msg:
print 'IOError:', msg
if x:
x.close()
@ -213,7 +213,7 @@ def browse_textfile(selector, host, port):
try:
get_alt_textfile(selector, host, port, x.writeln)
print 'Done.'
except IOError, msg:
except IOError as msg:
print 'IOError:', msg
x.close()
@ -311,7 +311,7 @@ def open_savefile():
cmd = savefile[1:].strip()
try:
p = os.popen(cmd, 'w')
except IOError, msg:
except IOError as msg:
print repr(cmd), ':', msg
return None
print 'Piping through', repr(cmd), '...'
@ -320,7 +320,7 @@ def open_savefile():
savefile = os.path.expanduser(savefile)
try:
f = open(savefile, 'w')
except IOError, msg:
except IOError as msg:
print repr(savefile), ':', msg
return None
print 'Saving to', repr(savefile), '...'

View File

@ -52,7 +52,7 @@ def main():
#
try:
s.connect((host, port))
except error, msg:
except error as msg:
sys.stderr.write('connect failed: ' + repr(msg) + '\n')
sys.exit(1)
#

View File

@ -131,7 +131,7 @@ def selector(dir, name, fullname, stat):
def find(dir, pred, wq):
try:
names = os.listdir(dir)
except os.error, msg:
except os.error as msg:
print repr(dir), ':', msg
return
for name in names:
@ -139,7 +139,7 @@ def find(dir, pred, wq):
fullname = os.path.join(dir, name)
try:
stat = os.lstat(fullname)
except os.error, msg:
except os.error as msg:
print repr(fullname), ':', msg
continue
if pred(dir, name, fullname, stat):

View File

@ -56,7 +56,7 @@ def main():
#
try:
s.connect((host, port))
except error, msg:
except error as msg:
sys.stderr.write('connect failed: %r\n' % (msg,))
sys.exit(1)
#

View File

@ -156,7 +156,7 @@ class PackDialog(Dialog):
self.current = self.var.get()
try:
self.dialog.widget.pack(**{self.option: self.current})
except TclError, msg:
except TclError as msg:
print msg
self.refresh()
@ -212,7 +212,7 @@ class RemotePackDialog(PackDialog):
'pack',
'info',
self.widget))
except TclError, msg:
except TclError as msg:
print msg
return
dict = {}
@ -239,7 +239,7 @@ class RemotePackDialog(PackDialog):
'-'+self.option,
self.dialog.master.tk.merge(
self.current))
except TclError, msg:
except TclError as msg:
print msg
self.refresh()
@ -285,7 +285,7 @@ class WidgetDialog(Dialog):
self.current = self.var.get()
try:
self.dialog.widget[self.option] = self.current
except TclError, msg:
except TclError as msg:
print msg
self.refresh()
@ -374,7 +374,7 @@ class RemoteWidgetDialog(WidgetDialog):
self.master.send(self.app,
self.widget,
'config'))
except TclError, msg:
except TclError as msg:
print msg
return
dict = {}
@ -398,7 +398,7 @@ class RemoteWidgetDialog(WidgetDialog):
'config',
'-'+self.option,
self.current)
except TclError, msg:
except TclError as msg:
print msg
self.refresh()
@ -445,7 +445,7 @@ def opendialogs(e):
if widget == '.': continue
try:
RemotePackDialog(list, list.app, widget)
except TclError, msg:
except TclError as msg:
print msg
test()

View File

@ -95,7 +95,7 @@ class EditableManPage(ScrolledText):
self._parseline('')
try:
self.tk.deletefilehandler(self.fp)
except TclError, msg:
except TclError as msg:
pass
self.fp.close()
self.fp = None

View File

@ -27,7 +27,7 @@ def main():
seq = 'all'
try:
opts, args = getopt.getopt(sys.argv[1:], '')
except getopt.error, msg:
except getopt.error as msg:
print msg
sys.exit(2)
for arg in args:

View File

@ -216,7 +216,7 @@ class SelectionBox:
prog = re.compile(search, map)
else:
prog = re.compile(search)
except re.error, msg:
except re.error as msg:
self.frame.bell()
print 'Regex error:', msg
return

View File

@ -23,7 +23,7 @@ while 1:
tk.record(line)
try:
result = tk.call('eval', cmd)
except _tkinter.TclError, msg:
except _tkinter.TclError as msg:
print 'TclError:', msg
else:
if result: print result

View File

@ -214,7 +214,7 @@ e.g. ::
>>> req = urllib2.Request('http://www.pretend_server.org')
>>> try: urllib2.urlopen(req)
>>> except URLError, e:
>>> except URLError as e:
>>> print e.reason
>>>
(4, 'getaddrinfo failed')
@ -326,7 +326,7 @@ attribute, it also has read, geturl, and info, methods. ::
>>> req = urllib2.Request('http://www.python.org/fish.html')
>>> try:
>>> urllib2.urlopen(req)
>>> except URLError, e:
>>> except URLError as e:
>>> print e.code
>>> print e.read()
>>>
@ -354,10 +354,10 @@ Number 1
req = Request(someurl)
try:
response = urlopen(req)
except HTTPError, e:
except HTTPError as e:
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
except URLError, e:
except URLError as e:
print 'We failed to reach a server.'
print 'Reason: ', e.reason
else:
@ -378,7 +378,7 @@ Number 2
req = Request(someurl)
try:
response = urlopen(req)
except URLError, e:
except URLError as e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason

View File

@ -35,7 +35,7 @@ Usage: %prog [options] msgfile
try:
os.mkdir(opts.directory)
except OSError, e:
except OSError as e:
# Ignore directory exists error
if e.errno != errno.EEXIST:
raise

View File

@ -426,7 +426,7 @@ reader = csv.reader(open(filename, "rb"))
try:
for row in reader:
print row
except csv.Error, e:
except csv.Error as e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
\end{verbatim}

View File

@ -126,7 +126,7 @@ import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError, err:
except getopt.GetoptError as err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()

View File

@ -144,6 +144,6 @@ def copytree(src, dst, symlinks=0):
copytree(srcname, dstname, symlinks)
else:
copy2(srcname, dstname)
except (IOError, os.error), why:
except (IOError, os.error) as why:
print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why))
\end{verbatim}

View File

@ -813,13 +813,13 @@ for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM,
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error, msg:
except socket.error as msg:
s = None
continue
try:
s.bind(sa)
s.listen(1)
except socket.error, msg:
except socket.error as msg:
s.close()
s = None
continue
@ -848,12 +848,12 @@ for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error, msg:
except socket.error as msg:
s = None
continue
try:
s.connect(sa)
except socket.error, msg:
except socket.error as msg:
s.close()
s = None
continue

View File

@ -284,7 +284,7 @@ try:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
except OSError as e:
print >>sys.stderr, "Execution failed:", e
\end{verbatim}

View File

@ -246,6 +246,6 @@ import xdrlib
p = xdrlib.Packer()
try:
p.pack_double(8.01)
except xdrlib.ConversionError, instance:
except xdrlib.ConversionError as instance:
print 'packing the double failed:', instance.msg
\end{verbatim}

View File

@ -358,7 +358,7 @@ print server
try:
print server.examples.getStateName(41)
except Error, v:
except Error as v:
print "ERROR", v
\end{verbatim}

View File

@ -23,7 +23,7 @@ while True:
if buffer.lstrip().upper().startswith("SELECT"):
print cur.fetchall()
except sqlite3.Error, e:
except sqlite3.Error as e:
print "An error occurred:", e.args[0]
buffer = ""

View File

@ -127,7 +127,7 @@ def main():
print_list(undocumented, "Undocumented symbols")
else:
print_list(L)
except IOError, e:
except IOError as e:
if e.errno != errno.EPIPE:
raise

View File

@ -53,7 +53,7 @@ def main():
opts, args = getopt.getopt(
args, "abchi:",
["annotate", "built-in", "categorize", "help", "ignore-from="])
except getopt.error, msg:
except getopt.error as msg:
sys.stdout = sys.stderr
print msg
print

View File

@ -599,7 +599,7 @@ def main():
options = Options()
try:
args = options.parse(sys.argv[1:])
except getopt.error, msg:
except getopt.error as msg:
error(options, msg)
if not args:
# attempt to locate single .tex file in current directory:

View File

@ -45,7 +45,7 @@ def main():
opts, args = getopt.getopt(sys.argv[1:], "Aabgtzq",
["all", "bzip2", "gzip", "tools", "zip",
"quiet", "anonymous"])
except getopt.error, e:
except getopt.error as e:
usage(warning=str(e))
sys.exit(2)
if len(args) not in (1, 2):

View File

@ -448,7 +448,7 @@ def do_project(library, output, arch, version):
def openfile(file):
try:
p = open(file, "w")
except IOError, msg:
except IOError as msg:
print file, ":", msg
sys.exit(1)
return p
@ -466,7 +466,7 @@ def do_it(args = None):
try:
optlist, args = getopt.getopt(args, 'ckpv:')
except getopt.error, msg:
except getopt.error as msg:
print msg
usage()

View File

@ -1039,7 +1039,8 @@ def convert(ifp, ofp):
#
try:
write_esis(fragment, ofp, knownempty)
except IOError, (err, msg):
except IOError as e:
(err, msg) = e
# Ignore EPIPE; it just means that whoever we're writing to stopped
# reading. The rest of the output would be ignored. All other errors
# should still be reported,

View File

@ -255,7 +255,8 @@ def main():
if xml and xmldecl:
opf.write('<?xml version="1.0" encoding="iso8859-1"?>\n')
convert(ifp, ofp, xml=xml, autoclose=autoclose, verbatims=verbatims)
except IOError, (err, msg):
except IOError as e:
(err, msg) = e
if err != errno.EPIPE:
raise

View File

@ -139,7 +139,7 @@ class ESISReader(xml.sax.xmlreader.XMLReader):
def _get_token(self, fp):
try:
line = fp.readline()
except IOError, e:
except IOError as e:
e = SAXException("I/O error reading input stream", e)
self.getErrorHandler().fatalError(e)
return

View File

@ -397,7 +397,8 @@ def convert(ifp, ofp, table):
c = Conversion(ifp, ofp, table)
try:
c.convert()
except IOError, (err, msg):
except IOError as e:
(err, msg) = e
if err != errno.EPIPE:
raise

View File

@ -3480,8 +3480,9 @@ try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
except IOError as e:
(errno, strerror) = e
print "I/O error(%s): %s" % (e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
@ -3530,7 +3531,7 @@ as desired.
\begin{verbatim}
>>> try:
... raise Exception('spam', 'eggs')
... except Exception, inst:
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
@ -3559,7 +3560,7 @@ For example:
...
>>> try:
... this_fails()
... except ZeroDivisionError, detail:
... except ZeroDivisionError as detail:
... print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo by zero
@ -3619,7 +3620,7 @@ example:
...
>>> try:
... raise MyError(2*2)
... except MyError, e:
... except MyError as e:
... print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4

View File

@ -79,7 +79,7 @@ try_stmt: ('try' ':' suite
with_stmt: 'with' test [ with_var ] ':' suite
with_var: 'as' expr
# NB compile.c makes sure that the default except clause is last
except_clause: 'except' [test [',' test]]
except_clause: 'except' [test ['as' test]]
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
# Backward compatibility cruft to support:

View File

@ -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")

View File

@ -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:

View File

@ -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}

View File

@ -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 = "%"

View File

@ -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

View File

@ -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()

View File

@ -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|-]

View File

@ -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]

View File

@ -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"

View File

@ -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 ():

View File

@ -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)

View File

@ -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:

View File

@ -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()

View File

@ -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)

View File

@ -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)

View File

@ -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

View File

@ -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 ...]"

View File

@ -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

View File

@ -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

View File

@ -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))

View File

@ -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:

View File

@ -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):

View File

@ -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):

View File

@ -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:

View File

@ -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)

View File

@ -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'):

View File

@ -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

View File

@ -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:

View File

@ -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))

View File

@ -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

View File

@ -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:

View File

@ -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,

View File

@ -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))

View File

@ -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):

View File

@ -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,

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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 ()

View File

@ -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:

View File

@ -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])

View File

@ -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

View File

@ -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 == '':

View File

@ -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

View File

@ -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)

View File

@ -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

View File

@ -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 = {}

View File

@ -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:

Some files were not shown because too many files have changed in this diff Show More