[PATCH 1 of 2] global: mass rewrite to use modern exception syntax

Gregory Szorc gregory.szorc at gmail.com
Wed Jun 24 00:22:15 CDT 2015


# HG changeset patch
# User Gregory Szorc <gregory.szorc at gmail.com>
# Date 1435123208 25200
#      Tue Jun 23 22:20:08 2015 -0700
# Node ID e465446d585fc9c5a67ef925f6dd6de1c932d8c8
# Parent  7fdd1782fc4ee9da87d8af13e806dc9055db2c38
global: mass rewrite to use modern exception syntax

Python 2.6 introduced the "except type as instance" syntax, replacing
the "except type, instance" syntax that came before. Python 3 dropped
support for the latter syntax. Since we no longer support Python 2.4 or
2.5, we have no need to continue supporting the "except type, instance".

This patch mass rewrites the exception syntax to be Python 2.6+ and
Python 3 compatible.

This patch was produced by running `2to3 -f except -w -n .`.

diff --git a/contrib/check-code.py b/contrib/check-code.py
--- a/contrib/check-code.py
+++ b/contrib/check-code.py
@@ -453,9 +453,9 @@ def checkfile(f, logfunc=_defaultlogger.
     result = True
 
     try:
         fp = open(f)
-    except IOError, e:
+    except IOError as e:
         print "Skipping %s, %s" % (f, str(e).split(':', 1)[0])
         return result
     pre = post = fp.read()
     fp.close()
diff --git a/contrib/import-checker.py b/contrib/import-checker.py
--- a/contrib/import-checker.py
+++ b/contrib/import-checker.py
@@ -327,9 +327,9 @@ def find_cycles(imports):
     cycles = set()
     for mod in sorted(imports.iterkeys()):
         try:
             checkmod(mod, imports)
-        except CircularImport, e:
+        except CircularImport as e:
             cycle = e.args[0]
             cycles.add(" -> ".join(rotatecycle(cycle)))
     return cycles
 
diff --git a/contrib/revsetbenchmarks.py b/contrib/revsetbenchmarks.py
--- a/contrib/revsetbenchmarks.py
+++ b/contrib/revsetbenchmarks.py
@@ -32,9 +32,9 @@ def check_output(*args, **kwargs):
 def update(rev):
     """update the repo to a revision"""
     try:
         check_call(['hg', 'update', '--quiet', '--check', str(rev)])
-    except CalledProcessError, exc:
+    except CalledProcessError as exc:
         print >> sys.stderr, 'update to revision %s failed, aborting' % rev
         sys.exit(exc.returncode)
 
 
@@ -55,9 +55,9 @@ def perf(revset, target=None):
     """run benchmark for this very revset"""
     try:
         output = hg(['perfrevset', revset], repo=target)
         return parseoutput(output)
-    except CalledProcessError, exc:
+    except CalledProcessError as exc:
         print >> sys.stderr, 'abort: cannot run revset benchmark: %s' % exc.cmd
         if exc.output is None:
             print >> sys.stderr, '(no ouput)'
         else:
@@ -195,9 +195,9 @@ def printheader(variants, maxidx, verbos
 def getrevs(spec):
     """get the list of rev matched by a revset"""
     try:
         out = check_output(['hg', 'log', '--template={rev}\n', '--rev', spec])
-    except CalledProcessError, exc:
+    except CalledProcessError as exc:
         print >> sys.stderr, "abort, can't get revision from %s" % spec
         sys.exit(exc.returncode)
     return [r for r in out.split() if r]
 
diff --git a/contrib/synthrepo.py b/contrib/synthrepo.py
--- a/contrib/synthrepo.py
+++ b/contrib/synthrepo.py
@@ -252,9 +252,9 @@ def synthesize(ui, repo, descpath, **opt
     path to an alternate dictionary to use.
     '''
     try:
         fp = hg.openpath(ui, descpath)
-    except Exception, err:
+    except Exception as err:
         raise util.Abort('%s: %s' % (descpath, err[0].strerror))
     desc = json.load(fp)
     fp.close()
 
@@ -284,9 +284,9 @@ def synthesize(ui, repo, descpath, **opt
 
     dictfile = opts.get('dict') or '/usr/share/dict/words'
     try:
         fp = open(dictfile, 'rU')
-    except IOError, err:
+    except IOError as err:
         raise util.Abort('%s: %s' % (dictfile, err.strerror))
     words = fp.read().splitlines()
     fp.close()
 
diff --git a/hgext/blackbox.py b/hgext/blackbox.py
--- a/hgext/blackbox.py
+++ b/hgext/blackbox.py
@@ -51,16 +51,16 @@ def wrapui(ui):
         def _openlogfile(self):
             def rotate(oldpath, newpath):
                 try:
                     os.unlink(newpath)
-                except OSError, err:
+                except OSError as err:
                     if err.errno != errno.ENOENT:
                         self.debug("warning: cannot remove '%s': %s\n" %
                                    (newpath, err.strerror))
                 try:
                     if newpath:
                         os.rename(oldpath, newpath)
-                except OSError, err:
+                except OSError as err:
                     if err.errno != errno.ENOENT:
                         self.debug("warning: cannot rename '%s' to '%s': %s\n" %
                                    (newpath, oldpath, err.strerror))
 
@@ -91,9 +91,9 @@ def wrapui(ui):
                 blackbox = self._blackbox
             elif util.safehasattr(self, '_bbopener'):
                 try:
                     self._blackbox = self._openlogfile()
-                except (IOError, OSError), err:
+                except (IOError, OSError) as err:
                     self.debug('warning: cannot write to blackbox.log: %s\n' %
                                err.strerror)
                     del self._bbopener
                     self._blackbox = None
@@ -109,9 +109,9 @@ def wrapui(ui):
                 user = util.getuser()
                 formattedmsg = msg[0] % msg[1:]
                 try:
                     blackbox.write('%s %s> %s' % (date, user, formattedmsg))
-                except IOError, err:
+                except IOError as err:
                     self.debug('warning: cannot write to blackbox.log: %s\n' %
                                err.strerror)
                 lastblackbox = blackbox
 
diff --git a/hgext/bugzilla.py b/hgext/bugzilla.py
--- a/hgext/bugzilla.py
+++ b/hgext/bugzilla.py
@@ -356,9 +356,9 @@ class bzmysql(bzaccess):
     def __init__(self, ui):
         try:
             import MySQLdb as mysql
             bzmysql._MySQLdb = mysql
-        except ImportError, err:
+        except ImportError as err:
             raise util.Abort(_('python mysql support not available: %s') % err)
 
         bzaccess.__init__(self, ui)
 
@@ -909,6 +909,6 @@ def hook(ui, repo, hooktype, node=None, 
         if bugs:
             for bug in bugs:
                 bz.update(bug, bugs[bug], ctx)
             bz.notify(bugs, util.email(ctx.user()))
-    except Exception, e:
+    except Exception as e:
         raise util.Abort(_('Bugzilla error: %s') % e)
diff --git a/hgext/censor.py b/hgext/censor.py
--- a/hgext/censor.py
+++ b/hgext/censor.py
@@ -146,9 +146,9 @@ def censor(ui, repo, path, rev='', tombs
         if crev in flog.parentrevs(srev):
             # Immediate children of censored node must be re-added as fulltext.
             try:
                 revdata = flog.revision(srev)
-            except error.CensoredNodeError, e:
+            except error.CensoredNodeError as e:
                 revdata = e.tombstone
             dlen = rewrite(srev, offset, revdata)
         else:
             # Copy any other revision data verbatim after fixing up the offset.
diff --git a/hgext/churn.py b/hgext/churn.py
--- a/hgext/churn.py
+++ b/hgext/churn.py
@@ -25,9 +25,9 @@ testedwith = 'internal'
 def maketemplater(ui, repo, tmpl):
     try:
         t = cmdutil.changeset_templater(ui, repo, False, None, tmpl,
                                         None, False)
-    except SyntaxError, inst:
+    except SyntaxError as inst:
         raise util.Abort(inst.args[0])
     return t
 
 def changedlines(ui, repo, ctx1, ctx2, fns):
diff --git a/hgext/color.py b/hgext/color.py
--- a/hgext/color.py
+++ b/hgext/color.py
@@ -193,9 +193,9 @@ def _terminfosetup(ui, mode):
         if key.startswith('color.'))
 
     try:
         curses.setupterm()
-    except curses.error, e:
+    except curses.error as e:
         _terminfo_params = {}
         return
 
     for key, (b, e) in _terminfo_params.items():
diff --git a/hgext/convert/common.py b/hgext/convert/common.py
--- a/hgext/convert/common.py
+++ b/hgext/convert/common.py
@@ -426,9 +426,9 @@ class mapfile(dict):
         if not self.path:
             return
         try:
             fp = open(self.path, 'r')
-        except IOError, err:
+        except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
             return
         for i, line in enumerate(fp):
@@ -450,9 +450,9 @@ class mapfile(dict):
     def __setitem__(self, key, value):
         if self.fp is None:
             try:
                 self.fp = open(self.path, 'a')
-            except IOError, err:
+            except IOError as err:
                 raise util.Abort(_('could not open map file %r: %s') %
                                  (self.path, err.strerror))
         self.fp.write('%s %s\n' % (key, value))
         self.fp.flush()
diff --git a/hgext/convert/convcmd.py b/hgext/convert/convcmd.py
--- a/hgext/convert/convcmd.py
+++ b/hgext/convert/convcmd.py
@@ -53,9 +53,9 @@ def convertsource(ui, path, type, rev):
     for name, source, sortmode in source_converters:
         try:
             if not type or name == type:
                 return source(ui, path, rev), sortmode
-        except (NoRepo, MissingTool), inst:
+        except (NoRepo, MissingTool) as inst:
             exceptions.append(inst)
     if not ui.quiet:
         for inst in exceptions:
             ui.write("%s\n" % inst)
@@ -67,11 +67,11 @@ def convertsink(ui, path, type):
     for name, sink in sink_converters:
         try:
             if not type or name == type:
                 return sink(ui, path)
-        except NoRepo, inst:
+        except NoRepo as inst:
             ui.note(_("convert: %s\n") % inst)
-        except MissingTool, inst:
+        except MissingTool as inst:
             raise util.Abort('%s\n' % inst)
     raise util.Abort(_('%s: unknown repository type') % path)
 
 class progresssource(object):
diff --git a/hgext/convert/cvs.py b/hgext/convert/cvs.py
--- a/hgext/convert/cvs.py
+++ b/hgext/convert/cvs.py
@@ -135,9 +135,9 @@ class convert_cvs(converter_source):
                             if part1 == format:
                                 passw = part2
                                 break
                         pf.close()
-                    except IOError, inst:
+                    except IOError as inst:
                         if inst.errno != errno.ENOENT:
                             if not getattr(inst, 'filename', None):
                                 inst.filename = cvspass
                             raise
diff --git a/hgext/convert/cvsps.py b/hgext/convert/cvsps.py
--- a/hgext/convert/cvsps.py
+++ b/hgext/convert/cvsps.py
@@ -178,9 +178,9 @@ def createlog(ui, directory=None, root="
                     oldlog = []
                     break
 
             ui.note(_('cache has %d log entries\n') % len(oldlog))
-        except Exception, e:
+        except Exception as e:
             ui.note(_('error reading cache: %r\n') % e)
 
         if oldlog:
             date = oldlog[-1].date    # last commit date as a (time,tz) tuple
@@ -823,9 +823,9 @@ def debugcvsps(ui, *args, **opts):
             for d in args:
                 log += createlog(ui, d, root=opts["root"], cache=cache)
         else:
             log = createlog(ui, root=opts["root"], cache=cache)
-    except logerror, e:
+    except logerror as e:
         ui.write("%r\n"%e)
         return
 
     changesets = createchangeset(ui, log, opts["fuzz"])
diff --git a/hgext/convert/darcs.py b/hgext/convert/darcs.py
--- a/hgext/convert/darcs.py
+++ b/hgext/convert/darcs.py
@@ -196,9 +196,9 @@ class darcs_source(converter_source, com
         path = os.path.join(self.tmppath, name)
         try:
             data = util.readfile(path)
             mode = os.lstat(path).st_mode
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno == errno.ENOENT:
                 return None, None
             raise
         mode = (mode & 0111) and 'x' or ''
diff --git a/hgext/convert/hg.py b/hgext/convert/hg.py
--- a/hgext/convert/hg.py
+++ b/hgext/convert/hg.py
@@ -41,9 +41,9 @@ class mercurial_sink(converter_sink):
                 self.repo = hg.repository(self.ui, path)
                 if not self.repo.local():
                     raise NoRepo(_('%s is not a local Mercurial repository')
                                  % path)
-            except error.RepoError, err:
+            except error.RepoError as err:
                 ui.traceback()
                 raise NoRepo(err.args[0])
         else:
             try:
@@ -486,9 +486,9 @@ class mercurial_source(converter_source)
                     continue
                 copies[name] = copysource
             except TypeError:
                 pass
-            except error.LookupError, e:
+            except error.LookupError as e:
                 if not self.ignoreerrors:
                     raise
                 self.ignored.add(name)
                 self.ui.warn(_('ignoring: %s\n') % e)
diff --git a/hgext/convert/subversion.py b/hgext/convert/subversion.py
--- a/hgext/convert/subversion.py
+++ b/hgext/convert/subversion.py
@@ -125,9 +125,9 @@ def get_log_child(fp, url, paths, start,
                        receiver)
     except IOError:
         # Caller may interrupt the iteration
         pickle.dump(None, fp, protocol)
-    except Exception, inst:
+    except Exception as inst:
         pickle.dump(str(inst), fp, protocol)
     else:
         pickle.dump(None, fp, protocol)
     fp.close()
@@ -215,9 +215,9 @@ def httpcheck(ui, path, proto):
     try:
         opener = urllib2.build_opener()
         rsp = opener.open('%s://%s/!svn/ver/0/.svn' % (proto, path))
         data = rsp.read()
-    except urllib2.HTTPError, inst:
+    except urllib2.HTTPError as inst:
         if inst.code != 404:
             # Except for 404 we cannot know for sure this is not an svn repo
             ui.warn(_('svn: cannot probe remote repository, assume it could '
                       'be a subversion repository. Use --source-type if you '
@@ -943,9 +943,10 @@ class svn_source(converter_source):
                         if latest:
                             firstcset.parents.append(latest)
                 except SvnPathNotFound:
                     pass
-        except SubversionException, (inst, num):
+        except SubversionException as xxx_todo_changeme:
+            (inst, num) = xxx_todo_changeme.args
             if num == svn.core.SVN_ERR_FS_NO_SUCH_REVISION:
                 raise util.Abort(_('svn: branch has no revision %s')
                                  % to_revnum)
             raise
@@ -969,9 +970,9 @@ class svn_source(converter_source):
             if isinstance(info, list):
                 info = info[-1]
             mode = ("svn:executable" in info) and 'x' or ''
             mode = ("svn:special" in info) and 'l' or mode
-        except SubversionException, e:
+        except SubversionException as e:
             notfound = (svn.core.SVN_ERR_FS_NOT_FOUND,
                 svn.core.SVN_ERR_RA_DAV_PATH_NOT_FOUND)
             if e.apr_err in notfound: # File not found
                 return None, None
diff --git a/hgext/convert/transport.py b/hgext/convert/transport.py
--- a/hgext/convert/transport.py
+++ b/hgext/convert/transport.py
@@ -86,9 +86,10 @@ class SvnRaTransport(object):
             try:
                 self.ra = svn.client.open_ra_session(
                     self.svn_url,
                     self.client, self.pool)
-            except SubversionException, (inst, num):
+            except SubversionException as xxx_todo_changeme:
+                (inst, num) = xxx_todo_changeme.args
                 if num in (svn.core.SVN_ERR_RA_ILLEGAL_URL,
                            svn.core.SVN_ERR_RA_LOCAL_REPOS_OPEN_FAILED,
                            svn.core.SVN_ERR_BAD_URL):
                     raise NotBranchError(url)
diff --git a/hgext/eol.py b/hgext/eol.py
--- a/hgext/eol.py
+++ b/hgext/eol.py
@@ -217,9 +217,9 @@ def parseeol(ui, repo, nodes):
                     data = repo[node]['.hgeol'].data()
                 return eolfile(ui, repo.root, data)
             except (IOError, LookupError):
                 pass
-    except error.ParseError, inst:
+    except error.ParseError as inst:
         ui.warn(_("warning: ignoring .hgeol file due to parse error "
                   "at %s: %s\n") % (inst.args[1], inst.args[0]))
     return None
 
diff --git a/hgext/gpg.py b/hgext/gpg.py
--- a/hgext/gpg.py
+++ b/hgext/gpg.py
@@ -282,9 +282,9 @@ def sign(ui, repo, *revs, **opts):
     try:
         editor = cmdutil.getcommiteditor(editform='gpg.sign', **opts)
         repo.commit(message, opts['user'], opts['date'], match=msigs,
                     editor=editor)
-    except ValueError, inst:
+    except ValueError as inst:
         raise util.Abort(str(inst))
 
 def shortkey(ui, key):
     if len(key) != 16:
diff --git a/hgext/histedit.py b/hgext/histedit.py
--- a/hgext/histedit.py
+++ b/hgext/histedit.py
@@ -221,9 +221,9 @@ class histeditstate(object):
     def read(self):
         """Load histedit state from disk and set fields appropriately."""
         try:
             fp = self.repo.vfs('histedit-state', 'r')
-        except IOError, err:
+        except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
             raise util.Abort(_('no histedit in progress'))
 
diff --git a/hgext/largefiles/basestore.py b/hgext/largefiles/basestore.py
--- a/hgext/largefiles/basestore.py
+++ b/hgext/largefiles/basestore.py
@@ -95,9 +95,9 @@ class basestore(object):
                                       createmode=self.repo.store.createmode)
 
         try:
             gothash = self._getfile(tmpfile, filename, hash)
-        except StoreError, err:
+        except StoreError as err:
             self.ui.warn(err.longmessage())
             gothash = ""
         tmpfile.close()
 
diff --git a/hgext/largefiles/lfcommands.py b/hgext/largefiles/lfcommands.py
--- a/hgext/largefiles/lfcommands.py
+++ b/hgext/largefiles/lfcommands.py
@@ -390,9 +390,9 @@ def cachelfiles(ui, repo, node, filelist
 
     for lfile in lfiles:
         try:
             expectedhash = repo[node][lfutil.standin(lfile)].data().strip()
-        except IOError, err:
+        except IOError as err:
             if err.errno == errno.ENOENT:
                 continue # node must be None and standin wasn't found in wctx
             raise
         if not lfutil.findfile(repo, expectedhash):
diff --git a/hgext/largefiles/overrides.py b/hgext/largefiles/overrides.py
--- a/hgext/largefiles/overrides.py
+++ b/hgext/largefiles/overrides.py
@@ -579,9 +579,9 @@ def overridecopy(orig, ui, repo, pats, o
     nolfiles = False
     installnormalfilesmatchfn(repo[None].manifest())
     try:
         result = orig(ui, repo, pats, opts, rename)
-    except util.Abort, e:
+    except util.Abort as e:
         if str(e) != _('no files to copy'):
             raise e
         else:
             nonormalfiles = True
@@ -681,9 +681,9 @@ def overridecopy(orig, ui, repo, pats, o
                                   repo.wjoin(destlfile))
 
                 lfdirstate.add(destlfile)
         lfdirstate.write()
-    except util.Abort, e:
+    except util.Abort as e:
         if str(e) != _('no files to copy'):
             raise e
         else:
             nolfiles = True
diff --git a/hgext/largefiles/proto.py b/hgext/largefiles/proto.py
--- a/hgext/largefiles/proto.py
+++ b/hgext/largefiles/proto.py
@@ -36,9 +36,9 @@ def putlfile(repo, proto, sha):
         if sha != lfutil.hexsha1(tmpfp._fp):
             raise IOError(0, _('largefile contents do not match hash'))
         tmpfp.close()
         lfutil.linktousercache(repo, sha)
-    except IOError, e:
+    except IOError as e:
         repo.ui.warn(_('largefiles: failed to put %s into store: %s\n') %
                      (sha, e.strerror))
         return wireproto.pushres(1)
     finally:
diff --git a/hgext/largefiles/remotestore.py b/hgext/largefiles/remotestore.py
--- a/hgext/largefiles/remotestore.py
+++ b/hgext/largefiles/remotestore.py
@@ -37,9 +37,9 @@ class remotestore(basestore.basestore):
         fd = None
         try:
             fd = lfutil.httpsendfile(self.ui, filename)
             return self._put(hash, fd)
-        except IOError, e:
+        except IOError as e:
             raise util.Abort(
                 _('remotestore: could not open file %s: %s')
                 % (filename, str(e)))
         finally:
@@ -48,19 +48,19 @@ class remotestore(basestore.basestore):
 
     def _getfile(self, tmpfile, filename, hash):
         try:
             chunks = self._get(hash)
-        except urllib2.HTTPError, e:
+        except urllib2.HTTPError as e:
             # 401s get converted to util.Aborts; everything else is fine being
             # turned into a StoreError
             raise basestore.StoreError(filename, hash, self.url, str(e))
-        except urllib2.URLError, e:
+        except urllib2.URLError as e:
             # This usually indicates a connection problem, so don't
             # keep trying with the other files... they will probably
             # all fail too.
             raise util.Abort('%s: %s' %
                              (util.hidepassword(self.url), e.reason))
-        except IOError, e:
+        except IOError as e:
             raise basestore.StoreError(filename, hash, self.url, str(e))
 
         return lfutil.copyandhash(chunks, tmpfile)
 
diff --git a/hgext/mq.py b/hgext/mq.py
--- a/hgext/mq.py
+++ b/hgext/mq.py
@@ -447,18 +447,18 @@ class queue(object):
                 # else we ignore empty lines
         try:
             lines = self.opener.read(self.statuspath).splitlines()
             return list(parselines(lines))
-        except IOError, e:
+        except IOError as e:
             if e.errno == errno.ENOENT:
                 return []
             raise
 
     @util.propertycache
     def fullseries(self):
         try:
             return self.opener.read(self.seriespath).splitlines()
-        except IOError, e:
+        except IOError as e:
             if e.errno == errno.ENOENT:
                 return []
             raise
 
@@ -573,9 +573,9 @@ class queue(object):
         if self.activeguards is None:
             self.activeguards = []
             try:
                 guards = self.opener.read(self.guardspath).split()
-            except IOError, err:
+            except IOError as err:
                 if err.errno != errno.ENOENT:
                     raise
                 guards = []
             for i, guard in enumerate(guards):
@@ -674,9 +674,9 @@ class queue(object):
         if not os.path.exists(undo):
             return
         try:
             os.unlink(undo)
-        except OSError, inst:
+        except OSError as inst:
             self.ui.warn(_('error removing undo: %s\n') % str(inst))
 
     def backup(self, repo, files, copy=False):
         # backup local changes in --force case
@@ -803,9 +803,9 @@ class queue(object):
         try:
             fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
                                   files=files, eolmode=None)
             return (True, list(files), fuzz)
-        except Exception, inst:
+        except Exception as inst:
             self.ui.note(str(inst) + '\n')
             if not self.ui.verbose:
                 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
             self.ui.traceback()
@@ -958,9 +958,9 @@ class queue(object):
                 r[None].forget(patches)
             for p in patches:
                 try:
                     os.unlink(self.join(p))
-                except OSError, inst:
+                except OSError as inst:
                     if inst.errno != errno.ENOENT:
                         raise
 
         qfinished = []
@@ -1158,9 +1158,9 @@ class queue(object):
         try:
             try:
                 # if patch file write fails, abort early
                 p = self.opener(patchfn, "w")
-            except IOError, e:
+            except IOError as e:
                 raise util.Abort(_('cannot write patch "%s": %s')
                                  % (patchfn, e.strerror))
             try:
                 defaultmsg = "[mq]: %s" % patchfn
@@ -1815,9 +1815,9 @@ class queue(object):
         if not create and os.path.isdir(self.path):
             raise util.Abort(_("patch queue directory already exists"))
         try:
             os.mkdir(self.path)
-        except OSError, inst:
+        except OSError as inst:
             if inst.errno != errno.EEXIST or not create:
                 raise
         if create:
             return self.qrepo(create=True)
diff --git a/hgext/notify.py b/hgext/notify.py
--- a/hgext/notify.py
+++ b/hgext/notify.py
@@ -275,9 +275,9 @@ class notifier(object):
 
         p = email.Parser.Parser()
         try:
             msg = p.parsestr(data)
-        except email.Errors.MessageParseError, inst:
+        except email.Errors.MessageParseError as inst:
             raise util.Abort(inst)
 
         # store sender and subject
         sender, subject = msg['From'], msg['Subject']
diff --git a/hgext/patchbomb.py b/hgext/patchbomb.py
--- a/hgext/patchbomb.py
+++ b/hgext/patchbomb.py
@@ -627,9 +627,9 @@ def patchbomb(ui, repo, *revs, **opts):
             generator = email.Generator.Generator(fp, mangle_from_=False)
             try:
                 generator.flatten(m, 0)
                 fp.write('\n')
-            except IOError, inst:
+            except IOError as inst:
                 if inst.errno != errno.EPIPE:
                     raise
             if fp is not ui:
                 fp.close()
diff --git a/hgext/rebase.py b/hgext/rebase.py
--- a/hgext/rebase.py
+++ b/hgext/rebase.py
@@ -837,9 +837,9 @@ def restorestatus(repo):
         repo.ui.debug('rebase status resumed\n')
         _setrebasesetvisibility(repo, state.keys())
         return (originalwd, target, state, skipped,
                 collapse, keep, keepbranches, external, activebookmark)
-    except IOError, err:
+    except IOError as err:
         if err.errno != errno.ENOENT:
             raise
         raise util.Abort(_('no rebase in progress'))
 
diff --git a/hgext/relink.py b/hgext/relink.py
--- a/hgext/relink.py
+++ b/hgext/relink.py
@@ -177,9 +177,9 @@ def do_relink(src, dst, files, ui):
             relinkfile(source, tgt)
             ui.progress(_('relinking'), pos, f, _('files'), total)
             relinked += 1
             savedbytes += sz
-        except OSError, inst:
+        except OSError as inst:
             ui.warn('%s: %s\n' % (tgt, str(inst)))
 
     ui.progress(_('relinking'), None)
 
diff --git a/hgext/share.py b/hgext/share.py
--- a/hgext/share.py
+++ b/hgext/share.py
@@ -83,9 +83,9 @@ def extsetup(ui):
 def _hassharedbookmarks(repo):
     """Returns whether this repo has shared bookmarks"""
     try:
         shared = repo.vfs.read('shared').splitlines()
-    except IOError, inst:
+    except IOError as inst:
         if inst.errno != errno.ENOENT:
             raise
         return False
     return 'bookmarks' in shared
diff --git a/hgext/shelve.py b/hgext/shelve.py
--- a/hgext/shelve.py
+++ b/hgext/shelve.py
@@ -68,9 +68,9 @@ class shelvedfile(object):
 
     def opener(self, mode='rb'):
         try:
             return self.vfs(self.fname, mode)
-        except IOError, err:
+        except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
             raise util.Abort(_("shelved change '%s' not found") % self.name)
 
@@ -293,9 +293,9 @@ def deletecmd(ui, repo, pats):
     try:
         for name in pats:
             for suffix in 'hg patch'.split():
                 shelvedfile(repo, name, suffix).unlink()
-    except OSError, err:
+    except OSError as err:
         if err.errno != errno.ENOENT:
             raise
         raise util.Abort(_("shelved change '%s' not found") % name)
     finally:
@@ -304,9 +304,9 @@ def deletecmd(ui, repo, pats):
 def listshelves(repo):
     """return all shelves in repo as list of (time, filename)"""
     try:
         names = repo.vfs.readdir('shelved')
-    except OSError, err:
+    except OSError as err:
         if err.errno != errno.ENOENT:
             raise
         return []
     info = []
@@ -531,9 +531,9 @@ def unshelve(ui, repo, *shelved, **opts)
                                'naming a shelved change'))
 
         try:
             state = shelvedstate.load(repo)
-        except IOError, err:
+        except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
             raise util.Abort(_('no unshelve operation underway'))
 
diff --git a/hgext/transplant.py b/hgext/transplant.py
--- a/hgext/transplant.py
+++ b/hgext/transplant.py
@@ -271,9 +271,9 @@ class transplanter(object):
             try:
                 files = set()
                 patch.patch(self.ui, repo, patchfile, files=files, eolmode=None)
                 files = list(files)
-            except Exception, inst:
+            except Exception as inst:
                 seriespath = os.path.join(self.path, 'series')
                 if os.path.exists(seriespath):
                     os.unlink(seriespath)
                 p1 = repo.dirstate.p1()
diff --git a/i18n/polib.py b/i18n/polib.py
--- a/i18n/polib.py
+++ b/i18n/polib.py
@@ -1275,9 +1275,9 @@ class _POFileParser(object):
         try:
             (action, state) = self.transitions[(symbol, self.current_state)]
             if action():
                 self.current_state = state
-        except Exception, exc:
+        except Exception as exc:
             raise IOError('Syntax error in po file (line %s)' % linenum)
 
     # state handlers
 
diff --git a/mercurial/bookmarks.py b/mercurial/bookmarks.py
--- a/mercurial/bookmarks.py
+++ b/mercurial/bookmarks.py
@@ -44,18 +44,18 @@ class bmstore(dict):
                 try:
                     self[refspec] = repo.changelog.lookup(sha)
                 except LookupError:
                     pass
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
 
     def getbkfile(self, repo):
         bkfile = None
         if 'HG_PENDING' in os.environ:
             try:
                 bkfile = repo.vfs('bookmarks.pending')
-            except IOError, inst:
+            except IOError as inst:
                 if inst.errno != errno.ENOENT:
                     raise
         if bkfile is None:
             bkfile = repo.vfs('bookmarks')
@@ -115,9 +115,9 @@ def readactive(repo):
     """
     mark = None
     try:
         file = repo.vfs('bookmarks.current')
-    except IOError, inst:
+    except IOError as inst:
         if inst.errno != errno.ENOENT:
             raise
         return None
     try:
@@ -158,9 +158,9 @@ def deactivate(repo):
     wlock = repo.wlock()
     try:
         repo.vfs.unlink('bookmarks.current')
         repo._activebookmark = None
-    except OSError, inst:
+    except OSError as inst:
         if inst.errno != errno.ENOENT:
             raise
     finally:
         wlock.release()
diff --git a/mercurial/branchmap.py b/mercurial/branchmap.py
--- a/mercurial/branchmap.py
+++ b/mercurial/branchmap.py
@@ -54,9 +54,9 @@ def read(repo):
             if state == 'c':
                 partial._closednodes.add(node)
     except KeyboardInterrupt:
         raise
-    except Exception, inst:
+    except Exception as inst:
         if repo.ui.debugflag:
             msg = 'invalid branchheads cache'
             if repo.filtername is not None:
                 msg += ' (%s)' % repo.filtername
@@ -202,9 +202,9 @@ class branchcache(dict):
             f.close()
             repo.ui.log('branchcache',
                         'wrote %s branch cache with %d labels and %d nodes\n',
                         repo.filtername, len(self), nodecount)
-        except (IOError, OSError, util.Abort), inst:
+        except (IOError, OSError, util.Abort) as inst:
             repo.ui.debug("couldn't write branch cache: %s\n" % inst)
             # Abort may be raise by read only opener
             pass
 
@@ -314,18 +314,18 @@ class revbranchcache(object):
         try:
             bndata = repo.vfs.read(_rbcnames)
             self._rbcsnameslen = len(bndata) # for verification before writing
             self._names = [encoding.tolocal(bn) for bn in bndata.split('\0')]
-        except (IOError, OSError), inst:
+        except (IOError, OSError) as inst:
             if readonly:
                 # don't try to use cache - fall back to the slow path
                 self.branchinfo = self._branchinfo
 
         if self._names:
             try:
                 data = repo.vfs.read(_rbcrevs)
                 self._rbcrevs.fromstring(data)
-            except (IOError, OSError), inst:
+            except (IOError, OSError) as inst:
                 repo.ui.debug("couldn't read revision branch cache: %s\n" %
                               inst)
         # remember number of good records on disk
         self._rbcrevslen = min(len(self._rbcrevs) // _rbcrecsize,
@@ -417,9 +417,9 @@ class revbranchcache(object):
                 f.write('\0'.join(encoding.fromlocal(b)
                                   for b in self._names[self._rbcnamescount:]))
                 self._rbcsnameslen = f.tell()
                 f.close()
-            except (IOError, OSError, util.Abort), inst:
+            except (IOError, OSError, util.Abort) as inst:
                 repo.ui.debug("couldn't write revision branch cache names: "
                               "%s\n" % inst)
                 return
             self._rbcnamescount = len(self._names)
@@ -435,9 +435,9 @@ class revbranchcache(object):
                     f.truncate()
                 end = revs * _rbcrecsize
                 f.write(self._rbcrevs[start:end])
                 f.close()
-            except (IOError, OSError, util.Abort), inst:
+            except (IOError, OSError, util.Abort) as inst:
                 repo.ui.debug("couldn't write revision branch cache: %s\n" %
                               inst)
                 return
             self._rbcrevslen = revs
diff --git a/mercurial/bundle2.py b/mercurial/bundle2.py
--- a/mercurial/bundle2.py
+++ b/mercurial/bundle2.py
@@ -335,9 +335,9 @@ def processbundle(repo, unbundler, trans
     nbpart = 0
     try:
         for nbpart, part in iterparts:
             _processpart(op, part)
-    except BaseException, exc:
+    except BaseException as exc:
         for nbpart, part in iterparts:
             # consume the bundle content
             part.seek(0, 2)
         # Small hack to let caller code distinguish exceptions from bundle2
@@ -379,9 +379,9 @@ def _processpart(op, part):
                 status = 'unsupported-params (%s)' % unknownparams
                 raise error.UnsupportedPartError(parttype=part.type,
                                                params=unknownparams)
             status = 'supported'
-        except error.UnsupportedPartError, exc:
+        except error.UnsupportedPartError as exc:
             if part.mandatory: # mandatory parts
                 raise
             indebug(op.ui, 'ignoring unsupported advisory part %s' % exc)
             return # skip to part processing
@@ -584,9 +584,9 @@ class unpackermixin(object):
         """return the file offset, or None if file is not seekable"""
         if self._seekable:
             try:
                 return self._fp.tell()
-            except IOError, e:
+            except IOError as e:
                 if e.errno == errno.ESPIPE:
                     self._seekable = False
                 else:
                     raise
@@ -840,9 +840,9 @@ class bundlepart(object):
             for chunk in self._payloadchunks():
                 outdebug(ui, 'payload chunk size: %i' % len(chunk))
                 yield _pack(_fpayloadsize, len(chunk))
                 yield chunk
-        except BaseException, exc:
+        except BaseException as exc:
             # backup exception data for later
             ui.debug('bundle2-input-stream-interrupt: encoding exception %s'
                      % exc)
             exc_info = sys.exc_info()
@@ -1247,9 +1247,9 @@ def handleremotechangegroup(op, inpart):
         part.addparam('in-reply-to', str(inpart.id), mandatory=False)
         part.addparam('return', '%i' % ret, mandatory=False)
     try:
         real_part.validate()
-    except util.Abort, e:
+    except util.Abort as e:
         raise util.Abort(_('bundle at %s is corrupted:\n%s') %
             (util.hidepassword(raw_url), str(e)))
     assert not inpart.read()
 
diff --git a/mercurial/byterange.py b/mercurial/byterange.py
--- a/mercurial/byterange.py
+++ b/mercurial/byterange.py
@@ -263,9 +263,9 @@ class FTPRangeHandler(urllib2.FTPHandler
         passwd = unquote(passwd or '')
 
         try:
             host = socket.gethostbyname(host)
-        except socket.error, msg:
+        except socket.error as msg:
             raise urllib2.URLError(msg)
         path, attrs = splitattr(req.get_selector())
         dirs = path.split('/')
         dirs = map(unquote, dirs)
@@ -321,9 +321,9 @@ class FTPRangeHandler(urllib2.FTPHandler
             if retrlen is not None and retrlen >= 0:
                 headers += "Content-Length: %d\n" % retrlen
             headers = email.message_from_string(headers)
             return addinfourl(fp, headers, req.get_full_url())
-        except ftplib.all_errors, msg:
+        except ftplib.all_errors as msg:
             raise IOError('ftp error', msg)
 
     def connect_ftp(self, user, passwd, host, port, dirs):
         fw = ftpwrapper(user, passwd, host, port, dirs)
@@ -351,17 +351,17 @@ class ftpwrapper(urllib.ftpwrapper):
         if file and not isdir:
             # Use nlst to see if the file exists at all
             try:
                 self.ftp.nlst(file)
-            except ftplib.error_perm, reason:
+            except ftplib.error_perm as reason:
                 raise IOError('ftp error', reason)
             # Restore the transfer mode!
             self.ftp.voidcmd(cmd)
             # Try to retrieve as a file
             try:
                 cmd = 'RETR ' + file
                 conn = self.ftp.ntransfercmd(cmd, rest)
-            except ftplib.error_perm, reason:
+            except ftplib.error_perm as reason:
                 if str(reason).startswith('501'):
                     # workaround for REST not supported error
                     fp, retrlen = self.retrfile(file, type)
                     fp = RangeableFileObject(fp, (rest,''))
diff --git a/mercurial/changegroup.py b/mercurial/changegroup.py
--- a/mercurial/changegroup.py
+++ b/mercurial/changegroup.py
@@ -490,9 +490,9 @@ class cg1packer(object):
         prefix = ''
         if revlog.iscensored(base) or revlog.iscensored(rev):
             try:
                 delta = revlog.revision(node)
-            except error.CensoredNodeError, e:
+            except error.CensoredNodeError as e:
                 delta = e.tombstone
             if base == nullrev:
                 prefix = mdiff.trivialdiffheader(len(delta))
             else:
@@ -664,9 +664,9 @@ def addchangegroupfiles(repo, source, re
         o = len(fl)
         try:
             if not fl.addgroup(source, revmap, trp):
                 raise util.Abort(_("received file revlog group is empty"))
-        except error.CensoredBaseError, e:
+        except error.CensoredBaseError as e:
             raise util.Abort(_("received delta base is censored: %s") % e)
         revisions += len(fl) - o
         files += 1
         if f in needfiles:
diff --git a/mercurial/cmdutil.py b/mercurial/cmdutil.py
--- a/mercurial/cmdutil.py
+++ b/mercurial/cmdutil.py
@@ -118,9 +118,9 @@ def dorecord(ui, repo, commitfunc, cmdsu
 
         # 1. filter patch, so we have intending-to apply subset of it
         try:
             chunks = filterfn(ui, originalchunks)
-        except patch.PatchError, err:
+        except patch.PatchError as err:
             raise util.Abort(_('error parsing patch: %s') % err)
 
         # We need to keep a backup of files that have been newly added and
         # modified during the recording process because there is a previous
@@ -152,9 +152,9 @@ def dorecord(ui, repo, commitfunc, cmdsu
         if tobackup:
             backupdir = repo.join('record-backups')
             try:
                 os.mkdir(backupdir)
-            except OSError, err:
+            except OSError as err:
                 if err.errno != errno.EEXIST:
                     raise
         try:
             # backup continues
@@ -188,9 +188,9 @@ def dorecord(ui, repo, commitfunc, cmdsu
                 try:
                     ui.debug('applying patch\n')
                     ui.debug(fp.getvalue())
                     patch.internalpatch(ui, repo, fp, 1, eolmode=None)
-                except patch.PatchError, err:
+                except patch.PatchError as err:
                     raise util.Abort(str(err))
             del fp
 
             # 4. We prepared working directory according to filtered
@@ -308,9 +308,9 @@ def logmessage(ui, opts):
             if logfile == '-':
                 message = ui.fin.read()
             else:
                 message = '\n'.join(util.readfile(logfile).splitlines())
-        except IOError, inst:
+        except IOError as inst:
             raise util.Abort(_("can't read commit message '%s': %s") %
                              (logfile, inst.strerror))
     return message
 
@@ -417,9 +417,9 @@ def makefilename(repo, pat, node, desc=N
                 c = expander[c]()
             newname.append(c)
             i += 1
         return ''.join(newname)
-    except KeyError, inst:
+    except KeyError as inst:
         raise util.Abort(_("invalid format spec '%%%s' in output filename") %
                          inst.args[0])
 
 def makefileobj(repo, pat, node=None, desc=None, total=None,
@@ -604,9 +604,9 @@ def copy(ui, repo, pats, opts, rename=Fa
                     os.rename(tmp, target)
                 else:
                     util.copyfile(src, target)
                 srcexists = True
-            except IOError, inst:
+            except IOError as inst:
                 if inst.errno == errno.ENOENT:
                     ui.warn(_('%s: deleted in working directory\n') % relsrc)
                     srcexists = False
                 else:
@@ -772,9 +772,9 @@ def service(opts, parentfn=None, initfn=
             writepid(pid)
         finally:
             try:
                 os.unlink(lockpath)
-            except OSError, e:
+            except OSError as e:
                 if e.errno != errno.ENOENT:
                     raise
         if parentfn:
             return parentfn(pid)
@@ -897,9 +897,9 @@ def tryimportone(ui, repo, hunk, parents
             files = set()
             try:
                 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
                             files=files, eolmode=None, similarity=sim / 100.0)
-            except patch.PatchError, e:
+            except patch.PatchError as e:
                 if not partial:
                     raise util.Abort(str(e))
                 if partial:
                     rejects = True
@@ -941,9 +941,9 @@ def tryimportone(ui, repo, hunk, parents
                 files = set()
                 try:
                     patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
                                     files, eolmode=None)
-                except patch.PatchError, e:
+                except patch.PatchError as e:
                     raise util.Abort(str(e))
                 if opts.get('exact'):
                     editor = None
                 else:
@@ -1458,12 +1458,12 @@ class changeset_templater(changeset_prin
                 if not self.footer:
                     self.footer = templater.stringify(self.t(types['footer'],
                                                       **props))
 
-        except KeyError, inst:
+        except KeyError as inst:
             msg = _("%s: no key named '%s'")
             raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
-        except SyntaxError, inst:
+        except SyntaxError as inst:
             raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
 
 def gettemplate(ui, tmpl, style):
     """
@@ -1522,9 +1522,9 @@ def show_changeset(ui, repo, opts, buffe
 
     try:
         t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
                                 buffered)
-    except SyntaxError, inst:
+    except SyntaxError as inst:
         raise util.Abort(inst.args[0])
     return t
 
 def showmarker(ui, marker):
@@ -2681,9 +2681,9 @@ def buildcommittemplate(repo, ctx, subs,
     tmpl, mapfile = gettemplate(ui, tmpl, None)
 
     try:
         t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
-    except SyntaxError, inst:
+    except SyntaxError as inst:
         raise util.Abort(inst.args[0])
 
     for k, v in repo.ui.configitems('committemplate'):
         if k != 'changeset':
@@ -3114,9 +3114,9 @@ def _performrevert(repo, parents, ctx, a
             chunks = recordfilter(repo.ui, originalchunks)
             if reversehunks:
                 chunks = patch.reversehunks(chunks)
 
-        except patch.PatchError, err:
+        except patch.PatchError as err:
             raise util.Abort(_('error parsing patch: %s') % err)
 
         newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
         # Apply changes
@@ -3127,9 +3127,9 @@ def _performrevert(repo, parents, ctx, a
         fp.seek(0)
         if dopatch:
             try:
                 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
-            except patch.PatchError, err:
+            except patch.PatchError as err:
                 raise util.Abort(str(err))
         del fp
     else:
         for f in actions['revert'][0]:
diff --git a/mercurial/commands.py b/mercurial/commands.py
--- a/mercurial/commands.py
+++ b/mercurial/commands.py
@@ -2339,9 +2339,9 @@ def debuginstall(ui):
     # encoding
     ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
     try:
         encoding.fromlocal("test")
-    except util.Abort, inst:
+    except util.Abort as inst:
         ui.write(" %s\n" % inst)
         ui.write(_(" (check that your locale is properly set)\n"))
         problems += 1
 
@@ -2357,9 +2357,9 @@ def debuginstall(ui):
               % os.path.dirname(__file__))
     try:
         import bdiff, mpatch, base85, osutil
         dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
-    except Exception, inst:
+    except Exception as inst:
         ui.write(" %s\n" % inst)
         ui.write(_(" One or more extensions could not be found"))
         ui.write(_(" (check that you compiled the extensions)\n"))
         problems += 1
@@ -2373,9 +2373,9 @@ def debuginstall(ui):
         if m:
             # template found, check if it is working
             try:
                 templater.templater(m)
-            except Exception, inst:
+            except Exception as inst:
                 ui.write(" %s\n" % inst)
                 p = None
         else:
             ui.write(_(" template 'default' not found\n"))
@@ -2405,9 +2405,9 @@ def debuginstall(ui):
     # check username
     ui.status(_("checking username...\n"))
     try:
         ui.username()
-    except util.Abort, e:
+    except util.Abort as e:
         ui.write(" %s\n" % e)
         ui.write(_(" (specify a username in your configuration file)\n"))
         problems += 1
 
@@ -2516,9 +2516,9 @@ def debuglocks(ui, repo, **opts):
                         locker = 'user %s, process %s, host %s' \
                                  % (user, pid, host)
                 ui.write("%-6s %s (%ds)\n" % (name + ":", locker, age))
                 return 1
-            except OSError, e:
+            except OSError as e:
                 if e.errno != errno.ENOENT:
                     raise
 
         ui.write("%-6s free\n" % (name + ":"))
@@ -2580,9 +2580,9 @@ def debugobsolete(ui, repo, precursor=No
                 repo.obsstore.create(tr, prec, succs, opts['flags'],
                                      parents=parents, date=date,
                                      metadata=metadata)
                 tr.close()
-            except ValueError, exc:
+            except ValueError as exc:
                 raise util.Abort(_('bad obsmarker input: %s') % exc)
             finally:
                 tr.release()
         finally:
@@ -3464,9 +3464,9 @@ def graft(ui, repo, *revs, **opts):
         # read in unfinished revisions
         try:
             nodes = repo.vfs.read('graftstate').splitlines()
             revs = [repo[node].rev() for node in nodes]
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
             raise util.Abort(_("no graft state found, can't continue"))
     else:
@@ -3658,9 +3658,9 @@ def grep(ui, repo, pattern, *pats, **opt
     if opts.get('ignore_case'):
         reflags |= re.I
     try:
         regexp = util.re.compile(pattern, reflags)
-    except re.error, inst:
+    except re.error as inst:
         ui.warn(_("grep: invalid match pattern: %s\n") % inst)
         return 1
     sep, eol = ':', '\n'
     if opts.get('print0'):
@@ -5062,9 +5062,9 @@ def postincoming(ui, repo, modheads, opt
     if optupdate:
         checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
         try:
             ret = hg.update(repo, checkout)
-        except util.Abort, inst:
+        except util.Abort as inst:
             ui.warn(_("not updating: %s\n") % str(inst))
             if inst.hint:
                 ui.warn(_("(%s)\n") % inst.hint)
             return 0
diff --git a/mercurial/commandserver.py b/mercurial/commandserver.py
--- a/mercurial/commandserver.py
+++ b/mercurial/commandserver.py
@@ -299,11 +299,11 @@ class _requesthandler(SocketServer.Strea
             try:
                 sv.serve()
             # handle exceptions that may be raised by command server. most of
             # known exceptions are caught by dispatch.
-            except util.Abort, inst:
+            except util.Abort as inst:
                 ui.warn(_('abort: %s\n') % inst)
-            except IOError, inst:
+            except IOError as inst:
                 if inst.errno != errno.EPIPE:
                     raise
             except KeyboardInterrupt:
                 pass
diff --git a/mercurial/config.py b/mercurial/config.py
--- a/mercurial/config.py
+++ b/mercurial/config.py
@@ -121,9 +121,9 @@ class config(object):
 
                     try:
                         include(inc, remap=remap, sections=sections)
                         break
-                    except IOError, inst:
+                    except IOError as inst:
                         if inst.errno != errno.ENOENT:
                             raise error.ParseError(_("cannot include %s (%s)")
                                                    % (inc, inst.strerror),
                                                    "%s:%s" % (src, line))
diff --git a/mercurial/context.py b/mercurial/context.py
--- a/mercurial/context.py
+++ b/mercurial/context.py
@@ -1437,9 +1437,9 @@ class workingctx(committablectx):
 
     def copy(self, source, dest):
         try:
             st = self._repo.wvfs.lstat(dest)
-        except OSError, err:
+        except OSError as err:
             if err.errno != errno.ENOENT:
                 raise
             self._repo.ui.warn(_("%s does not exist!\n") % dest)
             return
@@ -1683,9 +1683,9 @@ class workingfilectx(committablefilectx)
     def date(self):
         t, tz = self._changectx.date()
         try:
             return (int(self._repo.wvfs.lstat(self._path).st_mtime), tz)
-        except OSError, err:
+        except OSError as err:
             if err.errno != errno.ENOENT:
                 raise
             return (t, tz)
 
diff --git a/mercurial/dirstate.py b/mercurial/dirstate.py
--- a/mercurial/dirstate.py
+++ b/mercurial/dirstate.py
@@ -114,9 +114,9 @@ class dirstate(object):
     @repocache('branch')
     def _branch(self):
         try:
             return self._opener.read("branch").strip() or "default"
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
             return "default"
 
@@ -130,9 +130,9 @@ class dirstate(object):
             if l == 40:
                 return st[:20], st[20:40]
             elif l > 0 and l < 40:
                 raise util.Abort(_('working directory state appears damaged!'))
-        except IOError, err:
+        except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
         return [nullid, nullid]
 
@@ -330,9 +330,9 @@ class dirstate(object):
             try:
                 st = fp.read()
             finally:
                 fp.close()
-        except IOError, err:
+        except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
             return
         if not st:
@@ -716,9 +716,9 @@ class dirstate(object):
                 else:
                     badfn(ff, badtype(kind))
                     if nf in dmap:
                         results[nf] = None
-            except OSError, inst: # nf not found on disk - it is dirstate only
+            except OSError as inst: # nf not found on disk - it is dirstate only
                 if nf in dmap: # does it exactly match a missing file?
                     results[nf] = None
                 else: # does it match a missing directory?
                     if alldirs is None:
@@ -801,9 +801,9 @@ class dirstate(object):
                 else:
                     skip = '.hg'
                 try:
                     entries = listdir(join(nd), stat=True, skip=skip)
-                except OSError, inst:
+                except OSError as inst:
                     if inst.errno in (errno.EACCES, errno.ENOENT):
                         match.bad(self.pathto(nd), inst.strerror)
                         continue
                     raise
diff --git a/mercurial/dispatch.py b/mercurial/dispatch.py
--- a/mercurial/dispatch.py
+++ b/mercurial/dispatch.py
@@ -75,14 +75,14 @@ def dispatch(req):
         if req.fout:
             req.ui.fout = req.fout
         if req.ferr:
             req.ui.ferr = req.ferr
-    except util.Abort, inst:
+    except util.Abort as inst:
         ferr.write(_("abort: %s\n") % inst)
         if inst.hint:
             ferr.write(_("(%s)\n") % inst.hint)
         return -1
-    except error.ParseError, inst:
+    except error.ParseError as inst:
         _formatparse(ferr.write, inst)
         return -1
 
     msg = ' '.join(' ' in a and repr(a) or a for a in req.args)
@@ -171,31 +171,31 @@ def _runcatch(req):
             raise
 
     # Global exception handling, alphabetically
     # Mercurial-specific first, followed by built-in and library exceptions
-    except error.AmbiguousCommand, inst:
+    except error.AmbiguousCommand as inst:
         ui.warn(_("hg: command '%s' is ambiguous:\n    %s\n") %
                 (inst.args[0], " ".join(inst.args[1])))
-    except error.ParseError, inst:
+    except error.ParseError as inst:
         _formatparse(ui.warn, inst)
         return -1
-    except error.LockHeld, inst:
+    except error.LockHeld as inst:
         if inst.errno == errno.ETIMEDOUT:
             reason = _('timed out waiting for lock held by %s') % inst.locker
         else:
             reason = _('lock held by %s') % inst.locker
         ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
-    except error.LockUnavailable, inst:
+    except error.LockUnavailable as inst:
         ui.warn(_("abort: could not lock %s: %s\n") %
                (inst.desc or inst.filename, inst.strerror))
-    except error.CommandError, inst:
+    except error.CommandError as inst:
         if inst.args[0]:
             ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
             commands.help_(ui, inst.args[0], full=False, command=True)
         else:
             ui.warn(_("hg: %s\n") % inst.args[1])
             commands.help_(ui, 'shortlist')
-    except error.OutOfBandError, inst:
+    except error.OutOfBandError as inst:
         if inst.args:
             msg = _("abort: remote error:\n")
         else:
             msg = _("abort: remote error\n")
@@ -203,27 +203,27 @@ def _runcatch(req):
         if inst.args:
             ui.warn(''.join(inst.args))
         if inst.hint:
             ui.warn('(%s)\n' % inst.hint)
-    except error.RepoError, inst:
+    except error.RepoError as inst:
         ui.warn(_("abort: %s!\n") % inst)
         if inst.hint:
             ui.warn(_("(%s)\n") % inst.hint)
-    except error.ResponseError, inst:
+    except error.ResponseError as inst:
         ui.warn(_("abort: %s") % inst.args[0])
         if not isinstance(inst.args[1], basestring):
             ui.warn(" %r\n" % (inst.args[1],))
         elif not inst.args[1]:
             ui.warn(_(" empty string\n"))
         else:
             ui.warn("\n%r\n" % util.ellipsis(inst.args[1]))
-    except error.CensoredNodeError, inst:
+    except error.CensoredNodeError as inst:
         ui.warn(_("abort: file censored %s!\n") % inst)
-    except error.RevlogError, inst:
+    except error.RevlogError as inst:
         ui.warn(_("abort: %s!\n") % inst)
     except error.SignalInterrupt:
         ui.warn(_("killed!\n"))
-    except error.UnknownCommand, inst:
+    except error.UnknownCommand as inst:
         ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
         try:
             # check if the command is in a disabled extension
             # (but don't check for extensions themselves)
@@ -237,23 +237,23 @@ def _runcatch(req):
                             ', '.join(sorted(sim)))
                     suggested = True
             if not suggested:
                 commands.help_(ui, 'shortlist')
-    except error.InterventionRequired, inst:
+    except error.InterventionRequired as inst:
         ui.warn("%s\n" % inst)
         return 1
-    except util.Abort, inst:
+    except util.Abort as inst:
         ui.warn(_("abort: %s\n") % inst)
         if inst.hint:
             ui.warn(_("(%s)\n") % inst.hint)
-    except ImportError, inst:
+    except ImportError as inst:
         ui.warn(_("abort: %s!\n") % inst)
         m = str(inst).split()[-1]
         if m in "mpatch bdiff".split():
             ui.warn(_("(did you forget to compile extensions?)\n"))
         elif m in "zlib".split():
             ui.warn(_("(is your Python install correct?)\n"))
-    except IOError, inst:
+    except IOError as inst:
         if util.safehasattr(inst, "code"):
             ui.warn(_("abort: %s\n") % inst)
         elif util.safehasattr(inst, "reason"):
             try: # usually it is in the form (errno, strerror)
@@ -275,29 +275,29 @@ def _runcatch(req):
             else:
                 ui.warn(_("abort: %s\n") % inst.strerror)
         else:
             raise
-    except OSError, inst:
+    except OSError as inst:
         if getattr(inst, "filename", None) is not None:
             ui.warn(_("abort: %s: '%s'\n") % (inst.strerror, inst.filename))
         else:
             ui.warn(_("abort: %s\n") % inst.strerror)
     except KeyboardInterrupt:
         try:
             ui.warn(_("interrupted!\n"))
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno == errno.EPIPE:
                 if ui.debugflag:
                     ui.warn(_("\nbroken pipe\n"))
             else:
                 raise
     except MemoryError:
         ui.warn(_("abort: out of memory\n"))
-    except SystemExit, inst:
+    except SystemExit as inst:
         # Commands shouldn't sys.exit directly, but give a return code.
         # Just in case catch this and and pass exit code to caller.
         return inst.code
-    except socket.error, inst:
+    except socket.error as inst:
         ui.warn(_("abort: %s\n") % inst.args[-1])
     except: # re-raises
         myver = util.version()
         # For compatibility checking, we discard the portion of the hg
@@ -451,9 +451,9 @@ class cmdalias(object):
             return
 
         try:
             args = shlex.split(self.definition)
-        except ValueError, inst:
+        except ValueError as inst:
             self.badalias = (_("error in definition for alias '%s': %s")
                              % (self.name, inst))
             return
         self.cmdname = cmd = args.pop(0)
@@ -542,9 +542,9 @@ def _parse(ui, args):
     cmdoptions = {}
 
     try:
         args = fancyopts.fancyopts(args, commands.globalopts, options)
-    except fancyopts.getopt.GetoptError, inst:
+    except fancyopts.getopt.GetoptError as inst:
         raise error.CommandError(None, inst)
 
     if args:
         cmd, args = args[0], args[1:]
@@ -565,9 +565,9 @@ def _parse(ui, args):
         c.append((o[0], o[1], options[o[1]], o[3]))
 
     try:
         args = fancyopts.fancyopts(args, c, cmdoptions, True)
-    except fancyopts.getopt.GetoptError, inst:
+    except fancyopts.getopt.GetoptError as inst:
         raise error.CommandError(cmd, inst)
 
     # separate global options back out
     for o in commands.globalopts:
@@ -664,9 +664,9 @@ def _getlocal(ui, rpath):
     Takes paths in [cwd]/.hg/hgrc into account."
     """
     try:
         wd = os.getcwd()
-    except OSError, e:
+    except OSError as e:
         raise util.Abort(_("error getting current working directory: %s") %
                          e.strerror)
     path = cmdutil.findrepo(wd) or ""
     if not path:
diff --git a/mercurial/encoding.py b/mercurial/encoding.py
--- a/mercurial/encoding.py
+++ b/mercurial/encoding.py
@@ -137,9 +137,9 @@ def tolocal(s):
                 return localstr(u.encode('UTF-8'), r)
             except UnicodeDecodeError:
                 u = s.decode("utf-8", "replace") # last ditch
                 return u.encode(encoding, "replace") # can't round-trip
-    except LookupError, k:
+    except LookupError as k:
         raise error.Abort(k, hint="please check your locale settings")
 
 def fromlocal(s):
     """
@@ -157,12 +157,12 @@ def fromlocal(s):
         return s._utf8
 
     try:
         return s.decode(encoding, encodingmode).encode("utf-8")
-    except UnicodeDecodeError, inst:
+    except UnicodeDecodeError as inst:
         sub = s[max(0, inst.start - 10):inst.start + 10]
         raise error.Abort("decoding near '%s': %s!" % (sub, inst))
-    except LookupError, k:
+    except LookupError as k:
         raise error.Abort(k, hint="please check your locale settings")
 
 # How to treat ambiguous-width characters. Set to 'wide' to treat as wide.
 wide = (os.environ.get("HGENCODINGAMBIGUOUS", "narrow") == "wide"
@@ -329,9 +329,9 @@ def lower(s):
             return s # preserve localstring
         return lu.encode(encoding)
     except UnicodeError:
         return s.lower() # we don't know how to fold this except in ASCII
-    except LookupError, k:
+    except LookupError as k:
         raise error.Abort(k, hint="please check your locale settings")
 
 def upper(s):
     "best-effort encoding-aware case-folding of local string s"
@@ -352,9 +352,9 @@ def upperfallback(s):
             return s # preserve localstring
         return uu.encode(encoding)
     except UnicodeError:
         return s.upper() # we don't know how to fold this except in ASCII
-    except LookupError, k:
+    except LookupError as k:
         raise error.Abort(k, hint="please check your locale settings")
 
 class normcasespecs(object):
     '''what a platform's normcase does to ASCII strings
diff --git a/mercurial/exchange.py b/mercurial/exchange.py
--- a/mercurial/exchange.py
+++ b/mercurial/exchange.py
@@ -214,9 +214,9 @@ def push(repo, remote, force=False, revs
         if _canusebundle2(pushop) and maypushback:
             localwlock = pushop.repo.wlock()
         locallock = pushop.repo.lock()
         pushop.locallocked = True
-    except IOError, err:
+    except IOError as err:
         pushop.locallocked = False
         if err.errno != errno.EACCES:
             raise
         # source repo cannot be locked.
@@ -645,18 +645,18 @@ def _pushbundle2(pushop):
     stream = util.chunkbuffer(bundler.getchunks())
     try:
         try:
             reply = pushop.remote.unbundle(stream, ['force'], 'push')
-        except error.BundleValueError, exc:
+        except error.BundleValueError as exc:
             raise util.Abort('missing support for %s' % exc)
         try:
             trgetter = None
             if pushback:
                 trgetter = pushop.trmanager.transaction
             op = bundle2.processbundle(pushop.repo, reply, trgetter)
-        except error.BundleValueError, exc:
+        except error.BundleValueError as exc:
             raise util.Abort('missing support for %s' % exc)
-    except error.PushkeyFailed, exc:
+    except error.PushkeyFailed as exc:
         partid = int(exc.partid)
         if partid not in pushop.pkfailcb:
             raise
         pushop.pkfailcb[partid](pushop, exc)
@@ -1060,9 +1060,9 @@ def _pullbundle2(pullop):
     _pullbundle2extraprepare(pullop, kwargs)
     bundle = pullop.remote.getbundle('pull', **kwargs)
     try:
         op = bundle2.processbundle(pullop.repo, bundle, pullop.gettransaction)
-    except error.BundleValueError, exc:
+    except error.BundleValueError as exc:
         raise util.Abort('missing support for %s' % exc)
 
     if pullop.fetch:
         results = [cg['return'] for cg in op.records['changegroup']]
@@ -1424,9 +1424,9 @@ def unbundle(repo, cg, heads, source, ur
                         repo.ui.pushbuffer(error=True, subproc=True)
                         def recordout(output):
                             r.newpart('output', data=output, mandatory=False)
                 tr.close()
-            except BaseException, exc:
+            except BaseException as exc:
                 exc.duringunbundle2 = True
                 if captureoutput and r is not None:
                     parts = exc._bundle2salvagedoutput = r.salvageoutput()
                     def recordout(output):
diff --git a/mercurial/extensions.py b/mercurial/extensions.py
--- a/mercurial/extensions.py
+++ b/mercurial/extensions.py
@@ -52,9 +52,9 @@ def loadpath(path, module_name):
         return imp.load_module(module_name, fd, fpath, desc)
     else:
         try:
             return imp.load_source(module_name, path)
-        except IOError, exc:
+        except IOError as exc:
             if not exc.filename:
                 exc.filename = path # python does not fill this
             raise
 
@@ -81,9 +81,9 @@ def load(ui, name, path):
                 mod = getattr(mod, comp)
             return mod
         try:
             mod = importh("hgext.%s" % name)
-        except ImportError, err:
+        except ImportError as err:
             ui.debug('could not import hgext.%s (%s): trying %s\n'
                      % (name, err, name))
             if ui.debugflag:
                 ui.traceback()
@@ -104,9 +104,9 @@ def loadall(ui):
         try:
             load(ui, name, path)
         except KeyboardInterrupt:
             raise
-        except Exception, inst:
+        except Exception as inst:
             if path:
                 ui.warn(_("*** failed to import extension %s from %s: %s\n")
                         % (name, path, inst))
             else:
diff --git a/mercurial/fileset.py b/mercurial/fileset.py
--- a/mercurial/fileset.py
+++ b/mercurial/fileset.py
@@ -279,9 +279,9 @@ def grep(mctx, x):
     """
     try:
         # i18n: "grep" is a keyword
         r = re.compile(getstring(x, _("grep requires a pattern")))
-    except re.error, e:
+    except re.error as e:
         raise error.ParseError(_('invalid match pattern: %s') % e)
     return [f for f in mctx.existing() if r.search(mctx.ctx[f].data())]
 
 def _sizetomax(s):
diff --git a/mercurial/help.py b/mercurial/help.py
--- a/mercurial/help.py
+++ b/mercurial/help.py
@@ -227,9 +227,9 @@ def help_(ui, name, unknowncmd=False, fu
     def helpcmd(name):
         try:
             aliases, entry = cmdutil.findcmd(name, commands.table,
                                              strict=unknowncmd)
-        except error.AmbiguousCommand, inst:
+        except error.AmbiguousCommand as inst:
             # py3k fix: except vars can't be used outside the scope of the
             # except block, nor can be used inside a lambda. python issue4617
             prefix = inst.args[0]
             select = lambda c: c.lstrip('^').startswith(prefix)
diff --git a/mercurial/hg.py b/mercurial/hg.py
--- a/mercurial/hg.py
+++ b/mercurial/hg.py
@@ -201,9 +201,9 @@ def share(ui, source, dest=None, update=
 
     requirements = ''
     try:
         requirements = srcrepo.vfs.read('requires')
-    except IOError, inst:
+    except IOError as inst:
         if inst.errno != errno.ENOENT:
             raise
 
     requirements += 'shared\n'
@@ -387,9 +387,9 @@ def clone(ui, peeropts, source, dest=Non
                 cleandir = hgdir
             try:
                 destpath = hgdir
                 util.makedir(destpath, notindexed=True)
-            except OSError, inst:
+            except OSError as inst:
                 if inst.errno == errno.EEXIST:
                     cleandir = None
                     raise util.Abort(_("destination '%s' already exists")
                                      % dest)
@@ -427,9 +427,9 @@ def clone(ui, peeropts, source, dest=Non
         else:
             try:
                 destpeer = peer(srcrepo or ui, peeropts, dest, create=True)
                                 # only pass ui when no srcrepo
-            except OSError, inst:
+            except OSError as inst:
                 if inst.errno == errno.EEXIST:
                     cleandir = None
                     raise util.Abort(_("destination '%s' already exists")
                                      % dest)
diff --git a/mercurial/hgweb/common.py b/mercurial/hgweb/common.py
--- a/mercurial/hgweb/common.py
+++ b/mercurial/hgweb/common.py
@@ -152,9 +152,9 @@ def staticfile(directory, fname, req):
         fp.close()
         req.respond(HTTP_OK, ct, body=data)
     except TypeError:
         raise ErrorResponse(HTTP_SERVER_ERROR, 'illegal filename')
-    except OSError, err:
+    except OSError as err:
         if err.errno == errno.ENOENT:
             raise ErrorResponse(HTTP_NOT_FOUND)
         else:
             raise ErrorResponse(HTTP_SERVER_ERROR, err.strerror)
diff --git a/mercurial/hgweb/hgweb_mod.py b/mercurial/hgweb/hgweb_mod.py
--- a/mercurial/hgweb/hgweb_mod.py
+++ b/mercurial/hgweb/hgweb_mod.py
@@ -189,9 +189,9 @@ class hgweb(object):
                     raise ErrorResponse(HTTP_NOT_FOUND)
                 if cmd in perms:
                     self.check_perm(req, perms[cmd])
                 return protocol.call(self.repo, req, cmd)
-            except ErrorResponse, inst:
+            except ErrorResponse as inst:
                 # A client that sends unbundle without 100-continue will
                 # break if we respond early.
                 if (cmd == 'unbundle' and
                     (req.env.get('HTTP_EXPECT',
@@ -268,19 +268,19 @@ class hgweb(object):
                 req.respond(HTTP_OK, ctype)
 
             return content
 
-        except (error.LookupError, error.RepoLookupError), err:
+        except (error.LookupError, error.RepoLookupError) as err:
             req.respond(HTTP_NOT_FOUND, ctype)
             msg = str(err)
             if (util.safehasattr(err, 'name') and
                 not isinstance(err,  error.ManifestLookupError)):
                 msg = 'revision not found: %s' % err.name
             return tmpl('error', error=msg)
-        except (error.RepoError, error.RevlogError), inst:
+        except (error.RepoError, error.RevlogError) as inst:
             req.respond(HTTP_SERVER_ERROR, ctype)
             return tmpl('error', error=str(inst))
-        except ErrorResponse, inst:
+        except ErrorResponse as inst:
             req.respond(inst, ctype)
             if inst.code == HTTP_NOT_MODIFIED:
                 # Not allowed to return a body on a 304
                 return ['']
diff --git a/mercurial/hgweb/hgwebdir_mod.py b/mercurial/hgweb/hgwebdir_mod.py
--- a/mercurial/hgweb/hgwebdir_mod.py
+++ b/mercurial/hgweb/hgwebdir_mod.py
@@ -218,12 +218,12 @@ class hgwebdir(object):
                     try:
                         # ensure caller gets private copy of ui
                         repo = hg.repository(self.ui.copy(), real)
                         return hgweb(repo).run_wsgi(req)
-                    except IOError, inst:
+                    except IOError as inst:
                         msg = inst.strerror
                         raise ErrorResponse(HTTP_SERVER_ERROR, msg)
-                    except error.RepoError, inst:
+                    except error.RepoError as inst:
                         raise ErrorResponse(HTTP_SERVER_ERROR, str(inst))
 
                 up = virtualrepo.rfind('/')
                 if up < 0:
@@ -239,9 +239,9 @@ class hgwebdir(object):
             # prefixes not found
             req.respond(HTTP_NOT_FOUND, ctype)
             return tmpl("notfound", repo=virtual)
 
-        except ErrorResponse, err:
+        except ErrorResponse as err:
             req.respond(err, ctype)
             return tmpl('error', error=err.message or '')
         finally:
             tmpl = None
@@ -335,9 +335,9 @@ class hgwebdir(object):
 
                 u = self.ui.copy()
                 try:
                     u.readconfig(os.path.join(path, '.hg', 'hgrc'))
-                except Exception, e:
+                except Exception as e:
                     u.warn(_('error reading %s/.hg/hgrc: %s\n') % (path, e))
                     continue
                 def get(section, name, default=None):
                     return u.config(section, name, default, untrusted=True)
diff --git a/mercurial/hgweb/request.py b/mercurial/hgweb/request.py
--- a/mercurial/hgweb/request.py
+++ b/mercurial/hgweb/request.py
@@ -110,9 +110,9 @@ class wsgirequest(object):
     def write(self, thing):
         if thing:
             try:
                 self.server_write(thing)
-            except socket.error, inst:
+            except socket.error as inst:
                 if inst[0] != errno.ECONNRESET:
                     raise
 
     def writelines(self, lines):
diff --git a/mercurial/hgweb/server.py b/mercurial/hgweb/server.py
--- a/mercurial/hgweb/server.py
+++ b/mercurial/hgweb/server.py
@@ -70,9 +70,9 @@ class _httprequesthandler(BaseHTTPServer
 
     def do_write(self):
         try:
             self.do_hgweb()
-        except socket.error, inst:
+        except socket.error as inst:
             if inst[0] != errno.EPIPE:
                 raise
 
     def do_POST(self):
@@ -225,9 +225,9 @@ class _httprequesthandleropenssl(_httpre
     def do_write(self):
         import OpenSSL
         try:
             _httprequesthandler.do_write(self)
-        except OpenSSL.SSL.SysCallError, inst:
+        except OpenSSL.SSL.SysCallError as inst:
             if inst.args[0] != errno.EPIPE:
                 raise
 
     def handle_one_request(self):
@@ -343,7 +343,7 @@ def create_server(ui, app):
     address = ui.config('web', 'address', '')
     port = util.getport(ui.config('web', 'port', 8000))
     try:
         return cls(ui, app, (address, port), handler)
-    except socket.error, inst:
+    except socket.error as inst:
         raise util.Abort(_("cannot start server at '%s:%d': %s")
                          % (address, port, inst.args[1]))
diff --git a/mercurial/hgweb/webcommands.py b/mercurial/hgweb/webcommands.py
--- a/mercurial/hgweb/webcommands.py
+++ b/mercurial/hgweb/webcommands.py
@@ -75,9 +75,9 @@ def rawfile(web, req, tmpl):
         return content
 
     try:
         fctx = webutil.filectx(web.repo, req)
-    except error.LookupError, inst:
+    except error.LookupError as inst:
         try:
             content = manifest(web, req, tmpl)
             req.respond(HTTP_OK, web.ctype)
             return content
@@ -159,9 +159,9 @@ def file(web, req, tmpl):
     if not path:
         return manifest(web, req, tmpl)
     try:
         return _filerevision(web, req, tmpl, webutil.filectx(web.repo, req))
-    except error.LookupError, inst:
+    except error.LookupError as inst:
         try:
             return manifest(web, req, tmpl)
         except ErrorResponse:
             raise inst
diff --git a/mercurial/hook.py b/mercurial/hook.py
--- a/mercurial/hook.py
+++ b/mercurial/hook.py
@@ -79,9 +79,9 @@ def _pythonhook(ui, repo, name, hname, f
         old = sys.stdout, sys.stderr, sys.stdin
         sys.stdout, sys.stderr, sys.stdin = ui.fout, ui.ferr, ui.fin
 
         r = obj(ui=ui, repo=repo, hooktype=name, **args)
-    except Exception, exc:
+    except Exception as exc:
         if isinstance(exc, util.Abort):
             ui.warn(_('error: %s hook failed: %s\n') %
                          (hname, exc.args[0]))
         else:
diff --git a/mercurial/httpclient/__init__.py b/mercurial/httpclient/__init__.py
--- a/mercurial/httpclient/__init__.py
+++ b/mercurial/httpclient/__init__.py
@@ -165,9 +165,9 @@ class HTTPResponse(object):
                 logger.info('timed out with timeout of %s', self._timeout)
                 raise HTTPTimeoutException('timeout reading data')
         try:
             data = self.sock.recv(INCOMING_BUFFER_SIZE)
-        except socket.sslerror, e:
+        except socket.sslerror as e:
             if e.args[0] != socket.SSL_ERROR_WANT_READ:
                 raise
             logger.debug('SSL_ERROR_WANT_READ in _select, should retry later')
             return True
@@ -554,9 +554,9 @@ class HTTPConnection(object):
             if r:
                 try:
                     try:
                         data = r[0].recv(INCOMING_BUFFER_SIZE)
-                    except socket.sslerror, e:
+                    except socket.sslerror as e:
                         if e.args[0] != socket.SSL_ERROR_WANT_READ:
                             raise
                         logger.debug('SSL_ERROR_WANT_READ while sending '
                                      'data, retrying...')
@@ -609,9 +609,9 @@ class HTTPConnection(object):
                     response._load_response(data)
                     # Jump to the next select() call so we load more
                     # data if the server is still sending us content.
                     continue
-                except socket.error, e:
+                except socket.error as e:
                     if e[0] != errno.EPIPE and not was_first:
                         raise
 
             # outgoing data
@@ -632,9 +632,9 @@ class HTTPConnection(object):
                             out = hex(len(data))[2:] + EOL + data + EOL
                         else:
                             out = data
                     amt = w[0].send(out)
-                except socket.error, e:
+                except socket.error as e:
                     if e[0] == socket.SSL_ERROR_WANT_WRITE and self.ssl:
                         # This means that SSL hasn't flushed its buffer into
                         # the socket yet.
                         # TODO: find a way to block on ssl flushing its buffer
diff --git a/mercurial/httpclient/socketutil.py b/mercurial/httpclient/socketutil.py
--- a/mercurial/httpclient/socketutil.py
+++ b/mercurial/httpclient/socketutil.py
@@ -63,9 +63,9 @@ except AttributeError:
             try:
                 sock = socket.socket(af, socktype, proto)
                 logger.info("connect: (%s, %s)", host, port)
                 sock.connect(sa)
-            except socket.error, msg:
+            except socket.error as msg:
                 logger.info('connect fail: %s %s', host, port)
                 if sock:
                     sock.close()
                 sock = None
@@ -99,9 +99,9 @@ else:
                     self.__class__)
             while True:
                 try:
                     return self._ssl.read(buflen)
-                except socket.sslerror, x:
+                except socket.sslerror as x:
                     if x.args[0] == socket.SSL_ERROR_WANT_READ:
                         continue
                     else:
                         raise x
diff --git a/mercurial/httpconnection.py b/mercurial/httpconnection.py
--- a/mercurial/httpconnection.py
+++ b/mercurial/httpconnection.py
@@ -210,9 +210,9 @@ class http2handler(urllib2.HTTPHandler, 
             if path[0] != '/':
                 path = '/' + path
             h.request(req.get_method(), path, req.data, headers)
             r = h.getresponse()
-        except socket.error, err: # XXX what error?
+        except socket.error as err: # XXX what error?
             raise urllib2.URLError(err)
 
         # Pick apart the HTTPResponse object to get the addinfourl
         # object initialized properly.
diff --git a/mercurial/httppeer.py b/mercurial/httppeer.py
--- a/mercurial/httppeer.py
+++ b/mercurial/httppeer.py
@@ -118,13 +118,13 @@ class httppeer(wireproto.wirepeer):
             self.ui.debug("sending %s bytes\n" % size)
             req.add_unredirected_header('Content-Length', '%d' % size)
         try:
             resp = self.urlopener.open(req)
-        except urllib2.HTTPError, inst:
+        except urllib2.HTTPError as inst:
             if inst.code == 401:
                 raise util.Abort(_('authorization failed'))
             raise
-        except httplib.HTTPException, inst:
+        except httplib.HTTPException as inst:
             self.ui.debug('http error while sending %s command\n' % cmd)
             self.ui.traceback()
             raise IOError(None, inst)
         except IndexError:
@@ -204,9 +204,9 @@ class httppeer(wireproto.wirepeer):
             vals = r.split('\n', 1)
             if len(vals) < 2:
                 raise error.ResponseError(_("unexpected response:"), r)
             return vals
-        except socket.error, err:
+        except socket.error as err:
             if err.args[0] in (errno.ECONNRESET, errno.EPIPE):
                 raise util.Abort(_('push failed: %s') % err.args[1])
             raise util.Abort(err.args[1])
         finally:
@@ -266,9 +266,9 @@ def instance(ui, path, create):
         except error.RepoError:
             # No luck, try older compatibility check.
             inst.between([(nullid, nullid)])
         return inst
-    except error.RepoError, httpexception:
+    except error.RepoError as httpexception:
         try:
             r = statichttprepo.instance(ui, "static-" + path, create)
             ui.note('(falling back to static-http)\n')
             return r
diff --git a/mercurial/keepalive.py b/mercurial/keepalive.py
--- a/mercurial/keepalive.py
+++ b/mercurial/keepalive.py
@@ -250,9 +250,9 @@ class KeepAliveHandler(object):
                                host, id(h))
                 self._cm.add(host, h, 0)
                 self._start_transaction(h, req)
                 r = h.getresponse()
-        except (socket.error, httplib.HTTPException), err:
+        except (socket.error, httplib.HTTPException) as err:
             raise urllib2.URLError(err)
 
         # if not a persistent connection, don't try to reuse it
         if r.will_close:
@@ -342,9 +342,9 @@ class KeepAliveHandler(object):
                 if 'content-length' not in headers:
                     h.putheader('Content-length', '%d' % len(data))
             else:
                 h.putrequest('GET', req.get_selector(), **skipheaders)
-        except (socket.error), err:
+        except (socket.error) as err:
             raise urllib2.URLError(err)
         for k, v in headers.items():
             h.putheader(k, v)
         h.endheaders()
@@ -549,9 +549,9 @@ def safesend(self, str):
                 self.sock.sendall(data)
                 data = read(blocksize)
         else:
             self.sock.sendall(str)
-    except socket.error, v:
+    except socket.error as v:
         reraise = True
         if v[0] == errno.EPIPE:      # Broken pipe
             if self._HTTPConnection__state == httplib._CS_REQ_SENT:
                 self._broken_pipe_resp = None
@@ -604,9 +604,9 @@ def error_handler(url):
             try:
                 status, reason = fo.status, fo.reason
             except AttributeError:
                 status, reason = None, None
-        except IOError, e:
+        except IOError as e:
             print "  EXCEPTION: %s" % e
             raise
         else:
             print "  status = %s, reason = %s" % (status, reason)
diff --git a/mercurial/localrepo.py b/mercurial/localrepo.py
--- a/mercurial/localrepo.py
+++ b/mercurial/localrepo.py
@@ -134,9 +134,9 @@ class localpeer(peer.peerrepository):
                     # API is finally improved.
                     stream = util.chunkbuffer(ret.getchunks())
                     ret = bundle2.getunbundler(self.ui, stream)
                 return ret
-            except Exception, exc:
+            except Exception as exc:
                 # If the exception contains output salvaged from a bundle2
                 # reply, we need to make sure it is printed before continuing
                 # to fail. So we build a bundle2 with such output and consume
                 # it directly.
@@ -151,9 +151,9 @@ class localpeer(peer.peerrepository):
                     stream = util.chunkbuffer(bundler.getchunks())
                     b = bundle2.getunbundler(self.ui, stream)
                     bundle2.processbundle(self._repo, b)
                 raise
-        except error.PushRaced, exc:
+        except error.PushRaced as exc:
             raise error.ResponseError(_('push failed:'), str(exc))
 
     def lock(self):
         return self._repo.lock()
@@ -271,9 +271,9 @@ class localrepository(object):
         else:
             try:
                 self.requirements = scmutil.readrequires(
                         self.vfs, self.supported)
-            except IOError, inst:
+            except IOError as inst:
                 if inst.errno != errno.ENOENT:
                     raise
 
         self.sharedpath = self.path
@@ -284,9 +284,9 @@ class localrepository(object):
             if not vfs.exists():
                 raise error.RepoError(
                     _('.hg/sharedpath points to nonexistent directory %s') % s)
             self.sharedpath = s
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
 
         self.store = store.store(
@@ -577,9 +577,9 @@ class localrepository(object):
             return
 
         try:
             fp = self.wfile('.hgtags', 'rb+')
-        except IOError, e:
+        except IOError as e:
             if e.errno != errno.ENOENT:
                 raise
             fp = self.wfile('.hgtags', 'ab')
         else:
@@ -1188,9 +1188,9 @@ class localrepository(object):
 
     def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
         try:
             l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
-        except error.LockHeld, inst:
+        except error.LockHeld as inst:
             if not wait:
                 raise
             self.ui.warn(_("waiting for lock on %s held by %r\n") %
                          (desc, inst.locker))
@@ -1569,12 +1569,12 @@ class localrepository(object):
                             added.append(f)
                             m[f] = self._filecommit(fctx, m1, m2, linkrev,
                                                     trp, changed)
                             m.setflag(f, fctx.flags())
-                    except OSError, inst:
+                    except OSError as inst:
                         self.ui.warn(_("trouble committing %s!\n") % f)
                         raise
-                    except IOError, inst:
+                    except IOError as inst:
                         errcode = getattr(inst, 'errno', errno.ENOENT)
                         if error or errcode and errcode != errno.ENOENT:
                             self.ui.warn(_("trouble committing %s!\n") % f)
                         raise
@@ -1887,9 +1887,9 @@ class localrepository(object):
             hookargs['key'] = key
             hookargs['old'] = old
             hookargs['new'] = new
             self.hook('prepushkey', throw=True, **hookargs)
-        except error.HookAbort, exc:
+        except error.HookAbort as exc:
             self.ui.write_err(_("pushkey-abort: %s\n") % exc)
             if exc.hint:
                 self.ui.write_err(_("(%s)\n") % exc.hint)
             return False
diff --git a/mercurial/lock.py b/mercurial/lock.py
--- a/mercurial/lock.py
+++ b/mercurial/lock.py
@@ -57,9 +57,9 @@ class lock(object):
         while True:
             try:
                 self.trylock()
                 return self.timeout - timeout
-            except error.LockHeld, inst:
+            except error.LockHeld as inst:
                 if timeout != 0:
                     time.sleep(1)
                     if timeout > 0:
                         timeout -= 1
@@ -77,9 +77,9 @@ class lock(object):
         while not self.held:
             try:
                 self.vfs.makelock(lockname, self.f)
                 self.held = 1
-            except (OSError, IOError), why:
+            except (OSError, IOError) as why:
                 if why.errno == errno.EEXIST:
                     locker = self.testlock()
                     if locker is not None:
                         raise error.LockHeld(errno.EAGAIN,
@@ -101,9 +101,9 @@ class lock(object):
 
         """
         try:
             locker = self.vfs.readlock(self.f)
-        except (OSError, IOError), why:
+        except (OSError, IOError) as why:
             if why.errno == errno.ENOENT:
                 return None
             raise
         try:
diff --git a/mercurial/mail.py b/mercurial/mail.py
--- a/mercurial/mail.py
+++ b/mercurial/mail.py
@@ -137,18 +137,18 @@ def _smtp(ui):
         ui.note(_('(authenticating to mail server as %s)\n') %
                   (username))
         try:
             s.login(username, password)
-        except smtplib.SMTPException, inst:
+        except smtplib.SMTPException as inst:
             raise util.Abort(inst)
 
     def send(sender, recipients, msg):
         try:
             return s.sendmail(sender, recipients, msg)
-        except smtplib.SMTPRecipientsRefused, inst:
+        except smtplib.SMTPRecipientsRefused as inst:
             recipients = [r[1] for r in inst.recipients.values()]
             raise util.Abort('\n' + '\n'.join(recipients))
-        except smtplib.SMTPException, inst:
+        except smtplib.SMTPException as inst:
             raise util.Abort(inst)
 
     return send
 
diff --git a/mercurial/match.py b/mercurial/match.py
--- a/mercurial/match.py
+++ b/mercurial/match.py
@@ -292,11 +292,11 @@ class match(object):
                     includepats = readpatternfile(pat, self._warn)
                     for k, p, source in self._normalize(includepats, default,
                                                         root, cwd, auditor):
                         kindpats.append((k, p, source or pat))
-                except util.Abort, inst:
+                except util.Abort as inst:
                     raise util.Abort('%s: %s' % (pat, inst[0]))
-                except IOError, inst:
+                except IOError as inst:
                     if self._warn:
                         self._warn(_("skipping unreadable pattern file "
                                      "'%s': %s\n") % (pat, inst.strerror))
                 continue
diff --git a/mercurial/merge.py b/mercurial/merge.py
--- a/mercurial/merge.py
+++ b/mercurial/merge.py
@@ -144,9 +144,9 @@ class mergestate(object):
                     records.append(('L', l[:-1]))
                 else:
                     records.append(('F', l[:-1]))
             f.close()
-        except IOError, err:
+        except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
         return records
 
@@ -169,9 +169,9 @@ class mergestate(object):
                 record = data[off:(off + length)]
                 off += length
                 records.append((rtype, record))
             f.close()
-        except IOError, err:
+        except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
         return records
 
@@ -659,9 +659,9 @@ def batchremove(repo, actions):
             repo.ui.note(_("removing %s\n") % f)
         audit(f)
         try:
             unlink(wjoin(f), ignoremissing=True)
-        except OSError, inst:
+        except OSError as inst:
             repo.ui.warn(_("update failed to remove %s: %s!\n") %
                          (f, inst.strerror))
         if i == 100:
             yield i, f
diff --git a/mercurial/patch.py b/mercurial/patch.py
--- a/mercurial/patch.py
+++ b/mercurial/patch.py
@@ -434,14 +434,14 @@ class fsbackend(abstractbackend):
 
         isexec = False
         try:
             isexec = self.opener.lstat(fname).st_mode & 0100 != 0
-        except OSError, e:
+        except OSError as e:
             if e.errno != errno.ENOENT:
                 raise
         try:
             return (self.opener.read(fname), (False, isexec))
-        except IOError, e:
+        except IOError as e:
             if e.errno != errno.ENOENT:
                 raise
             return None, None
 
@@ -1366,9 +1366,9 @@ class binhunk(object):
             else:
                 l = ord(l) - ord('a') + 27
             try:
                 dec.append(base85.b85decode(line[1:])[:l])
-            except ValueError, e:
+            except ValueError as e:
                 raise PatchError(_('could not decode "%s" binary patch: %s')
                                  % (self._fname, str(e)))
             line = getline(lr, self.hunk)
         text = zlib.decompress(''.join(dec))
@@ -1941,9 +1941,9 @@ def _applydiff(ui, fp, patcher, backend,
                 continue
             try:
                 current_file = patcher(ui, gp, backend, store,
                                        eolmode=eolmode)
-            except PatchError, inst:
+            except PatchError as inst:
                 ui.warn(str(inst) + '\n')
                 current_file = None
                 rejects += 1
                 continue
diff --git a/mercurial/pathutil.py b/mercurial/pathutil.py
--- a/mercurial/pathutil.py
+++ b/mercurial/pathutil.py
@@ -75,9 +75,9 @@ class pathauditor(object):
                 break
             curpath = os.path.join(self.root, prefix)
             try:
                 st = os.lstat(curpath)
-            except OSError, err:
+            except OSError as err:
                 # EINVAL can be raised as invalid path syntax under win32.
                 # They must be ignored for patterns can be checked too.
                 if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
                     raise
diff --git a/mercurial/phases.py b/mercurial/phases.py
--- a/mercurial/phases.py
+++ b/mercurial/phases.py
@@ -128,9 +128,9 @@ def _readroots(repo, phasedefaults=None)
         f = None
         if 'HG_PENDING' in os.environ:
             try:
                 f = repo.svfs('phaseroots.pending')
-            except IOError, inst:
+            except IOError as inst:
                 if inst.errno != errno.ENOENT:
                     raise
         if f is None:
             f = repo.svfs('phaseroots')
@@ -139,9 +139,9 @@ def _readroots(repo, phasedefaults=None)
                 phase, nh = line.split()
                 roots[int(phase)].add(bin(nh))
         finally:
             f.close()
-    except IOError, inst:
+    except IOError as inst:
         if inst.errno != errno.ENOENT:
             raise
         if phasedefaults:
             for f in phasedefaults:
diff --git a/mercurial/posix.py b/mercurial/posix.py
--- a/mercurial/posix.py
+++ b/mercurial/posix.py
@@ -114,9 +114,9 @@ def copymode(src, dst, mode=None):
     If src doesn't exist, we're using mode instead. If mode is None, we're
     using umask.'''
     try:
         st_mode = os.lstat(src).st_mode & 0777
-    except OSError, inst:
+    except OSError as inst:
         if inst.errno != errno.ENOENT:
             raise
         st_mode = mode
         if st_mode is None:
@@ -165,9 +165,9 @@ def checklink(path):
         finally:
             fd.close()
     except AttributeError:
         return False
-    except OSError, inst:
+    except OSError as inst:
         # sshfs might report failure while successfully creating the link
         if inst[0] == errno.EIO and os.path.exists(name):
             os.unlink(name)
         return False
@@ -354,9 +354,9 @@ def testpid(pid):
         return True
     try:
         os.kill(pid, 0)
         return True
-    except OSError, inst:
+    except OSError as inst:
         return inst.errno != errno.ESRCH
 
 def explainexit(code):
     """return a 2-tuple (desc, code) describing a subprocess status
@@ -409,9 +409,9 @@ def statfiles(files):
         try:
             st = lstat(nf)
             if getkind(st.st_mode) not in _wantedkinds:
                 st = None
-        except OSError, err:
+        except OSError as err:
             if err.errno not in (errno.ENOENT, errno.ENOTDIR):
                 raise
             st = None
         yield st
@@ -476,9 +476,9 @@ def termwidth():
                 except AttributeError:
                     pass
             except ValueError:
                 pass
-            except IOError, e:
+            except IOError as e:
                 if e[0] == errno.EINVAL:
                     pass
                 else:
                     raise
@@ -492,9 +492,9 @@ def makedir(path, notindexed):
 def unlinkpath(f, ignoremissing=False):
     """unlink and remove the directory if it is empty"""
     try:
         os.unlink(f)
-    except OSError, e:
+    except OSError as e:
         if not (ignoremissing and e.errno == errno.ENOENT):
             raise
     # try removing directories that might now be empty
     try:
@@ -559,9 +559,9 @@ class unixdomainserver(socket.socket):
             else:
                 os.unlink(self.path)
         try:
             self.bind(self.realpath)
-        except socket.error, err:
+        except socket.error as err:
             if err.args[0] == 'AF_UNIX path too long':
                 tmpdir = tempfile.mkdtemp(prefix='hg-%s-' % subsystem)
                 self.realpath = os.path.join(tmpdir, sockname)
                 try:
@@ -577,9 +577,9 @@ class unixdomainserver(socket.socket):
     def cleanup(self):
         def okayifmissing(f, path):
             try:
                 f(path)
-            except OSError, err:
+            except OSError as err:
                 if err.errno != errno.ENOENT:
                     raise
 
         okayifmissing(os.unlink, self.path)
diff --git a/mercurial/repair.py b/mercurial/repair.py
--- a/mercurial/repair.py
+++ b/mercurial/repair.py
@@ -204,9 +204,9 @@ def strip(ui, repo, nodelist, backup=Tru
         # remove undo files
         for undovfs, undofile in repo.undofiles():
             try:
                 undovfs.unlink(undofile)
-            except OSError, e:
+            except OSError as e:
                 if e.errno != errno.ENOENT:
                     ui.warn(_('error removing %s: %s\n') %
                             (undovfs.join(undofile), str(e)))
 
diff --git a/mercurial/revlog.py b/mercurial/revlog.py
--- a/mercurial/revlog.py
+++ b/mercurial/revlog.py
@@ -88,9 +88,9 @@ def decompress(bin):
         return bin
     if t == 'x':
         try:
             return _decompress(bin)
-        except zlib.error, e:
+        except zlib.error as e:
             raise RevlogError(_("revlog decompress error: %s") % str(e))
     if t == 'u':
         return bin[1:]
     raise RevlogError(_("unknown compression type %r") % t)
@@ -245,9 +245,9 @@ class revlog(object):
             f.close()
             if len(i) > 0:
                 v = struct.unpack(versionformat, i[:4])[0]
                 self._initempty = False
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
 
         self.version = v
@@ -1570,9 +1570,9 @@ class revlog(object):
             f.seek(0, 2)
             actual = f.tell()
             f.close()
             dd = actual - expected
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
             dd = 0
 
@@ -1589,9 +1589,9 @@ class revlog(object):
                 for r in self:
                     databytes += max(0, self.length(r))
                 dd = 0
                 di = actual - len(self) * s - databytes
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
             di = 0
 
diff --git a/mercurial/revset.py b/mercurial/revset.py
--- a/mercurial/revset.py
+++ b/mercurial/revset.py
@@ -1018,9 +1018,9 @@ def grep(repo, subset, x):
     """
     try:
         # i18n: "grep" is a keyword
         gr = re.compile(getstring(x, _("grep requires a string")))
-    except re.error, e:
+    except re.error as e:
         raise error.ParseError(_('invalid match pattern: %s') % e)
 
     def matches(x):
         c = repo[x]
@@ -1895,9 +1895,9 @@ def _stringmatcher(pattern):
     if pattern.startswith('re:'):
         pattern = pattern[3:]
         try:
             regex = re.compile(pattern)
-        except re.error, e:
+        except re.error as e:
             raise error.ParseError(_('invalid regular expression: %s')
                                    % e)
         return 're', pattern, regex.search
     elif pattern.startswith('literal:'):
@@ -2411,9 +2411,9 @@ def _parsealiasdecl(decl):
                         _("argument names collide with each other"))
             return (name, ('func', ('symbol', name)), args, None)
 
         return (decl, None, None, _("invalid format"))
-    except error.ParseError, inst:
+    except error.ParseError as inst:
         return (decl, None, None, parseerrordetail(inst))
 
 def _parsealiasdefn(defn, args):
     """Parse alias definition ``defn``
@@ -2500,9 +2500,9 @@ class revsetalias(object):
         try:
             self.replacement = _parsealiasdefn(value, self.args)
             # Check for placeholder injection
             _checkaliasarg(self.replacement, self.args)
-        except error.ParseError, inst:
+        except error.ParseError as inst:
             self.error = _('failed to parse the definition of revset alias'
                            ' "%s": %s') % (self.name, parseerrordetail(inst))
 
 def _getalias(aliases, tree):
diff --git a/mercurial/scmutil.py b/mercurial/scmutil.py
--- a/mercurial/scmutil.py
+++ b/mercurial/scmutil.py
@@ -221,18 +221,18 @@ class abstractvfs(object):
     def tryread(self, path):
         '''gracefully return an empty string for missing files'''
         try:
             return self.read(path)
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
         return ""
 
     def tryreadlines(self, path, mode='rb'):
         '''gracefully return an empty array for missing files'''
         try:
             return self.readlines(path, mode=mode)
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
         return []
 
@@ -490,9 +490,9 @@ class vfs(abstractvfs):
                         nlink = util.nlinks(f)
                         if nlink < 1:
                             nlink = 2 # force mktempcopy (issue1922)
                         fd.close()
-                except (OSError, IOError), e:
+                except (OSError, IOError) as e:
                     if e.errno != errno.ENOENT:
                         raise
                     nlink = 0
                     util.ensuredirs(dirname, self.createmode, notindexed)
@@ -518,9 +518,9 @@ class vfs(abstractvfs):
 
         if self._cansymlink:
             try:
                 os.symlink(src, linkname)
-            except OSError, err:
+            except OSError as err:
                 raise OSError(err.errno, _('could not symlink to %r: %s') %
                               (src, err.strerror), linkname)
         else:
             self.write(dst, src)
@@ -1057,9 +1057,9 @@ class filecachesubentry(object):
     @staticmethod
     def stat(path):
         try:
             return util.cachestat(path)
-        except OSError, e:
+        except OSError as e:
             if e.errno != errno.ENOENT:
                 raise
 
 class filecacheentry(object):
diff --git a/mercurial/statichttprepo.py b/mercurial/statichttprepo.py
--- a/mercurial/statichttprepo.py
+++ b/mercurial/statichttprepo.py
@@ -32,12 +32,12 @@ class httprangereader(object):
         try:
             f = self.opener.open(req)
             data = f.read()
             code = f.code
-        except urllib2.HTTPError, inst:
+        except urllib2.HTTPError as inst:
             num = inst.code == 404 and errno.ENOENT or None
             raise IOError(num, inst)
-        except urllib2.URLError, inst:
+        except urllib2.URLError as inst:
             raise IOError(None, inst.reason[1])
 
         if code == 200:
             # HTTPRangeHandler does nothing if remote does not support
@@ -105,9 +105,9 @@ class statichttprepository(localrepo.loc
         self.names = namespaces.namespaces()
 
         try:
             requirements = scmutil.readrequires(self.vfs, self.supported)
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.ENOENT:
                 raise
             requirements = set()
 
@@ -115,9 +115,9 @@ class statichttprepository(localrepo.loc
             try:
                 fp = self.vfs("00changelog.i")
                 fp.read(1)
                 fp.close()
-            except IOError, inst:
+            except IOError as inst:
                 if inst.errno != errno.ENOENT:
                     raise
                 # we do not care about empty old-style repositories here
                 msg = _("'%s' does not appear to be an hg repository") % path
diff --git a/mercurial/store.py b/mercurial/store.py
--- a/mercurial/store.py
+++ b/mercurial/store.py
@@ -488,9 +488,9 @@ class fncachestore(basicstore):
         for f in sorted(self.fncache):
             ef = self.encode(f)
             try:
                 yield f, ef, self.getsize(ef)
-            except OSError, err:
+            except OSError as err:
                 if err.errno != errno.ENOENT:
                     raise
 
     def copylist(self):
@@ -512,9 +512,9 @@ class fncachestore(basicstore):
         ef = self.encode(f)
         try:
             self.getsize(ef)
             return True
-        except OSError, err:
+        except OSError as err:
             if err.errno != errno.ENOENT:
                 raise
             # nonexistent entry
             return False
diff --git a/mercurial/subrepo.py b/mercurial/subrepo.py
--- a/mercurial/subrepo.py
+++ b/mercurial/subrepo.py
@@ -43,12 +43,12 @@ class SubrepoAbort(error.Abort):
 def annotatesubrepoerror(func):
     def decoratedmethod(self, *args, **kargs):
         try:
             res = func(self, *args, **kargs)
-        except SubrepoAbort, ex:
+        except SubrepoAbort as ex:
             # This exception has already been handled
             raise ex
-        except error.Abort, ex:
+        except error.Abort as ex:
             subrepo = subrelpath(self)
             errormsg = str(ex) + ' ' + _('(in subrepo %s)') % subrepo
             # avoid handling this exception by raising a SubrepoAbort exception
             raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
@@ -65,9 +65,9 @@ def state(ctx, ui):
     def read(f, sections=None, remap=None):
         if f in ctx:
             try:
                 data = ctx[f].data()
-            except IOError, err:
+            except IOError as err:
                 if err.errno != errno.ENOENT:
                     raise
                 # handle missing subrepo spec files as removed
                 ui.warn(_("warning: subrepo spec file \'%s\' not found\n") %
@@ -100,9 +100,9 @@ def state(ctx, ui):
                                        "specifier in \'%s\' line %d")
                                      % (util.pathto(repo.root, repo.getcwd(),
                                         '.hgsubstate'), (i + 1)))
                 rev[path] = revision
-        except IOError, err:
+        except IOError as err:
             if err.errno != errno.ENOENT:
                 raise
 
     def remap(src):
@@ -115,9 +115,9 @@ def state(ctx, ui):
             # extra escapes are needed because re.sub string decodes.
             repl = re.sub(r'\\\\([0-9]+)', r'\\\1', repl)
             try:
                 src = re.sub(pattern, repl, src, 1)
-            except re.error, e:
+            except re.error as e:
                 raise util.Abort(_("bad subrepository pattern in %s: %s")
                                  % (p.source('subpaths', pattern), e))
         return src
 
@@ -733,9 +733,9 @@ class hgsubrepo(abstractsubrepo):
             rev1 = self._state[1]
             ctx1 = self._repo[rev1]
             ctx2 = self._repo[rev2]
             return self._repo.status(ctx1, ctx2, **opts)
-        except error.RepoLookupError, inst:
+        except error.RepoLookupError as inst:
             self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
                          % (inst, subrelpath(self)))
             return scmutil.status([], [], [], [], [], [], [])
 
@@ -750,9 +750,9 @@ class hgsubrepo(abstractsubrepo):
             cmdutil.diffordiffstat(ui, self._repo, diffopts,
                                    node1, node2, match,
                                    prefix=posixpath.join(prefix, self._path),
                                    listsubrepos=True, **opts)
-        except error.RepoLookupError, inst:
+        except error.RepoLookupError as inst:
             self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
                           % (inst, subrelpath(self)))
 
     @annotatesubrepoerror
@@ -1279,9 +1279,9 @@ class gitsubrepo(abstractsubrepo):
     def _ensuregit(self):
         try:
             self._gitexecutable = 'git'
             out, err = self._gitnodir(['--version'])
-        except OSError, e:
+        except OSError as e:
             if e.errno != 2 or os.name != 'nt':
                 raise
             self._gitexecutable = 'git.cmd'
             out, err = self._gitnodir(['--version'])
diff --git a/mercurial/tags.py b/mercurial/tags.py
--- a/mercurial/tags.py
+++ b/mercurial/tags.py
@@ -119,9 +119,9 @@ def findglobaltags(ui, repo, alltags, ta
 def readlocaltags(ui, repo, alltags, tagtypes):
     '''Read local tags in repo. Update alltags and tagtypes.'''
     try:
         data = repo.vfs.read("localtags")
-    except IOError, inst:
+    except IOError as inst:
         if inst.errno != errno.ENOENT:
             raise
         return
 
@@ -544,9 +544,9 @@ class hgtagsfnodescache(object):
                 f.write(data)
                 self._dirtyoffset = None
             finally:
                 f.close()
-        except (IOError, OSError), inst:
+        except (IOError, OSError) as inst:
             repo.ui.log('tagscache',
                         "couldn't write %s: %s\n" % (
                         _fnodescachefile, inst))
         finally:
diff --git a/mercurial/templater.py b/mercurial/templater.py
--- a/mercurial/templater.py
+++ b/mercurial/templater.py
@@ -771,9 +771,9 @@ class templater(object):
                 raise SyntaxError(_('%s: missing value') % conf.source('', key))
             if val[0] in "'\"":
                 try:
                     self.cache[key] = unquotestring(val)
-                except SyntaxError, inst:
+                except SyntaxError as inst:
                     raise SyntaxError('%s: %s' %
                                       (conf.source('', key), inst.args[0]))
             else:
                 val = 'default', val
@@ -788,12 +788,12 @@ class templater(object):
         '''Get the template for the given template name. Use a local cache.'''
         if t not in self.cache:
             try:
                 self.cache[t] = util.readfile(self.map[t][1])
-            except KeyError, inst:
+            except KeyError as inst:
                 raise TemplateNotFound(_('"%s" not in template map') %
                                        inst.args[0])
-            except IOError, inst:
+            except IOError as inst:
                 raise IOError(inst.args[0], _('template file %s: %s') %
                               (self.map[t][1], inst.args[1]))
         return self.cache[t]
 
diff --git a/mercurial/transaction.py b/mercurial/transaction.py
--- a/mercurial/transaction.py
+++ b/mercurial/transaction.py
@@ -38,9 +38,9 @@ def _playback(journal, report, opener, v
                 raise
         else:
             try:
                 opener.unlink(f)
-            except (IOError, OSError), inst:
+            except (IOError, OSError) as inst:
                 if inst.errno != errno.ENOENT:
                     raise
 
     backupfiles = []
@@ -61,12 +61,12 @@ def _playback(journal, report, opener, v
             else:
                 target = f or b
                 try:
                     vfs.unlink(target)
-                except (IOError, OSError), inst:
+                except (IOError, OSError) as inst:
                     if inst.errno != errno.ENOENT:
                         raise
-        except (IOError, OSError, util.Abort), inst:
+        except (IOError, OSError, util.Abort) as inst:
             if not c:
                 raise
 
     opener.unlink(journal)
@@ -76,9 +76,9 @@ def _playback(journal, report, opener, v
     try:
         for f in backupfiles:
             if opener.exists(f):
                 opener.unlink(f)
-    except (IOError, OSError, util.Abort), inst:
+    except (IOError, OSError, util.Abort) as inst:
         # only pure backup file remains, it is sage to ignore any error
         pass
 
 class transaction(object):
@@ -404,9 +404,9 @@ class transaction(object):
             vfs = self._vfsmap[l]
             if not f and b and vfs.exists(b):
                 try:
                     vfs.unlink(b)
-                except (IOError, OSError, util.Abort), inst:
+                except (IOError, OSError, util.Abort) as inst:
                     if not c:
                         raise
                     # Abort may be raise by read only opener
                     self.report("couldn't remote %s: %s\n"
@@ -427,9 +427,9 @@ class transaction(object):
                 vfs = self._vfsmap[l]
                 if b and vfs.exists(b):
                     try:
                         vfs.unlink(b)
-                    except (IOError, OSError, util.Abort), inst:
+                    except (IOError, OSError, util.Abort) as inst:
                         if not c:
                             raise
                         # Abort may be raise by read only opener
                         self.report("couldn't remote %s: %s\n"
diff --git a/mercurial/ui.py b/mercurial/ui.py
--- a/mercurial/ui.py
+++ b/mercurial/ui.py
@@ -152,9 +152,9 @@ class ui(object):
 
         try:
             cfg.read(filename, fp, sections=sections, remap=remap)
             fp.close()
-        except error.ConfigError, inst:
+        except error.ConfigError as inst:
             if trusted:
                 raise
             self.warn(_("ignored: %s\n") % str(inst))
 
@@ -604,9 +604,9 @@ class ui(object):
             # stderr may be buffered under win32 when redirected to files,
             # including stdout.
             if not getattr(self.ferr, 'closed', False):
                 self.ferr.flush()
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno not in (errno.EPIPE, errno.EIO, errno.EBADF):
                 raise
 
     def flush(self):
diff --git a/mercurial/url.py b/mercurial/url.py
--- a/mercurial/url.py
+++ b/mercurial/url.py
@@ -158,9 +158,9 @@ if has_https:
                         sock.bind(source_address)
                     sock.connect(sa)
                     return sock
 
-                except socket.error, msg:
+                except socket.error as msg:
                     if sock is not None:
                         sock.close()
 
             raise socket.error(msg)
@@ -410,9 +410,9 @@ class httpdigestauthhandler(urllib2.HTTP
         # somebody is using BasicAuth and types a bad password.
         try:
             return urllib2.HTTPDigestAuthHandler.http_error_auth_reqed(
                         self, auth_header, host, req, headers)
-        except ValueError, inst:
+        except ValueError as inst:
             arg = inst.args[0]
             if arg.startswith("AbstractDigestAuthHandler doesn't know "):
                 return
             raise
diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -815,9 +815,9 @@ def copyfile(src, dest, hardlink=False):
     else:
         try:
             shutil.copyfile(src, dest)
             shutil.copymode(src, dest)
-        except shutil.Error, inst:
+        except shutil.Error as inst:
             raise Abort(str(inst))
 
 def copyfiles(src, dst, hardlink=None, progress=lambda t, pos: None):
     """Copy a directory tree using hardlinks if possible."""
@@ -914,9 +914,9 @@ else:
 
 def makelock(info, pathname):
     try:
         return os.symlink(info, pathname)
-    except OSError, why:
+    except OSError as why:
         if why.errno == errno.EEXIST:
             raise
     except AttributeError: # no symlink in os
         pass
@@ -927,9 +927,9 @@ def makelock(info, pathname):
 
 def readlock(pathname):
     try:
         return os.readlink(pathname)
-    except OSError, why:
+    except OSError as why:
         if why.errno not in (errno.EINVAL, errno.ENOSYS):
             raise
     except AttributeError: # no symlink in os
         pass
@@ -1144,9 +1144,9 @@ def mktempcopy(name, emptyok=False, crea
         return temp
     try:
         try:
             ifp = posixfile(name, "rb")
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno == errno.ENOENT:
                 return temp
             if not getattr(inst, 'filename', None):
                 inst.filename = name
@@ -1203,9 +1203,9 @@ class atomictempfile(object):
 def makedirs(name, mode=None, notindexed=False):
     """recursive directory creation with parent mode inheritance"""
     try:
         makedir(name, notindexed)
-    except OSError, err:
+    except OSError as err:
         if err.errno == errno.EEXIST:
             return
         if err.errno != errno.ENOENT or not name:
             raise
@@ -1230,9 +1230,9 @@ def ensuredirs(name, mode=None, notindex
     if parent != name:
         ensuredirs(parent, mode, notindexed)
     try:
         makedir(name, notindexed)
-    except OSError, err:
+    except OSError as err:
         if err.errno == errno.EEXIST and os.path.isdir(name):
             # someone else seems to have won a directory creation race
             return
         raise
diff --git a/mercurial/verify.py b/mercurial/verify.py
--- a/mercurial/verify.py
+++ b/mercurial/verify.py
@@ -107,9 +107,9 @@ def _verify(repo):
                     (short(p1), short(node)), f)
             if p2 not in seen and p2 != nullid:
                 err(lr, _("unknown parent 2 %s of %s") %
                     (short(p2), short(node)), f)
-        except Exception, inst:
+        except Exception as inst:
             exc(lr, _("checking parents of %s") % short(node), inst, f)
 
         if node in seen:
             err(lr, _("duplicate revision %d (%d)") % (i, seen[node]), f)
@@ -143,9 +143,9 @@ def _verify(repo):
                 mflinkrevs.setdefault(changes[0], []).append(i)
                 refersmf = True
             for f in changes[3]:
                 filelinkrevs.setdefault(_normpath(f), []).append(i)
-        except Exception, inst:
+        except Exception as inst:
             refersmf = True
             exc(i, _("unpacking changeset %s") % short(n), inst)
     ui.progress(_('checking'), None)
 
@@ -170,9 +170,9 @@ def _verify(repo):
                 if not f:
                     err(lr, _("file without name in manifest"))
                 elif f != "/dev/null": # ignore this in very old repos
                     filenodes.setdefault(_normpath(f), {}).setdefault(fn, lr)
-        except Exception, inst:
+        except Exception as inst:
             exc(lr, _("reading manifest delta %s") % short(n), inst)
     ui.progress(_('checking'), None)
 
     ui.status(_("crosschecking files in changesets and manifests\n"))
@@ -235,9 +235,9 @@ def _verify(repo):
             lr = None
 
         try:
             fl = repo.file(f)
-        except error.RevlogError, e:
+        except error.RevlogError as e:
             err(lr, _("broken revlog! (%s)") % e, f)
             continue
 
         for ff in fl.files():
@@ -269,9 +269,9 @@ def _verify(repo):
                             (l, fl.size(i)), f)
             except error.CensoredNodeError:
                 if ui.config("censor", "policy", "abort") == "abort":
                     err(lr, _("censored file data"), f)
-            except Exception, inst:
+            except Exception as inst:
                 exc(lr, _("unpacking %s") % short(n), inst, f)
 
             # check renames
             try:
@@ -295,9 +295,9 @@ def _verify(repo):
                                   " revision is nullid %s:%s\n")
                             % (f, lr, rp[0], short(rp[1])))
                     else:
                         fl2.rev(rp[1])
-            except Exception, inst:
+            except Exception as inst:
                 exc(lr, _("checking rename of %s") % short(n), inst, f)
 
         # cross-check
         if f in filenodes:
diff --git a/mercurial/win32.py b/mercurial/win32.py
--- a/mercurial/win32.py
+++ b/mercurial/win32.py
@@ -466,9 +466,9 @@ def unlink(f):
         temp = '%s-%08x' % (f, random.randint(0, 0xffffffff))
         try:
             os.rename(f, temp)  # raises OSError EEXIST if temp exists
             break
-        except OSError, e:
+        except OSError as e:
             if e.errno != errno.EEXIST:
                 raise
     else:
         raise IOError(errno.EEXIST, "No usable temporary filename found")
diff --git a/mercurial/windows.py b/mercurial/windows.py
--- a/mercurial/windows.py
+++ b/mercurial/windows.py
@@ -37,9 +37,9 @@ def posixfile(name, mode='r', buffering=
         if 'a' in mode:
             fp.seek(0, os.SEEK_END)
 
         return fp
-    except WindowsError, err:
+    except WindowsError as err:
         # convert to a friendlier exception
         raise IOError(err.errno, '%s: %s' % (name, err.strerror))
 
 class winstdout(object):
@@ -68,18 +68,18 @@ class winstdout(object):
             while start < l:
                 end = start + limit
                 self.fp.write(s[start:end])
                 start = end
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != 0:
                 raise
             self.close()
             raise IOError(errno.EPIPE, 'Broken pipe')
 
     def flush(self):
         try:
             return self.fp.flush()
-        except IOError, inst:
+        except IOError as inst:
             if inst.errno != errno.EINVAL:
                 raise
             self.close()
             raise IOError(errno.EPIPE, 'Broken pipe')
@@ -258,9 +258,9 @@ def statfiles(files):
             try:
                 dmap = dict([(normcase(n), s)
                              for n, k, s in osutil.listdir(dir, True)
                              if getkind(s.st_mode) in _wantedkinds])
-            except OSError, err:
+            except OSError as err:
                 # Python >= 2.5 returns ENOENT and adds winerror field
                 # EINVAL is raised if dir is not a directory.
                 if err.errno not in (errno.ENOENT, errno.EINVAL,
                                      errno.ENOTDIR):
@@ -302,9 +302,9 @@ def removedirs(name):
 def unlinkpath(f, ignoremissing=False):
     """unlink and remove the directory if it is empty"""
     try:
         unlink(f)
-    except OSError, e:
+    except OSError as e:
         if not (ignoremissing and e.errno == errno.ENOENT):
             raise
     # try removing directories that might now be empty
     try:
@@ -315,9 +315,9 @@ def unlinkpath(f, ignoremissing=False):
 def rename(src, dst):
     '''atomically rename file src to dst, replacing dst if it exists'''
     try:
         os.rename(src, dst)
-    except OSError, e:
+    except OSError as e:
         if e.errno != errno.EEXIST:
             raise
         unlink(dst)
         os.rename(src, dst)
diff --git a/mercurial/wireproto.py b/mercurial/wireproto.py
--- a/mercurial/wireproto.py
+++ b/mercurial/wireproto.py
@@ -704,9 +704,9 @@ def lookup(repo, proto, key):
         k = encoding.tolocal(key)
         c = repo[k]
         r = c.hex()
         success = 1
-    except Exception, inst:
+    except Exception as inst:
         r = str(inst)
         success = 0
     return "%s %s\n" % (success, r)
 
@@ -799,9 +799,9 @@ def unbundle(repo, proto, heads):
         finally:
             fp.close()
             os.unlink(tempname)
 
-    except (error.BundleValueError, util.Abort, error.PushRaced), exc:
+    except (error.BundleValueError, util.Abort, error.PushRaced) as exc:
         # handle non-bundle2 case first
         if not getattr(exc, 'duringunbundle2', False):
             try:
                 raise
@@ -820,9 +820,9 @@ def unbundle(repo, proto, heads):
             bundler.addpart(out)
         try:
             try:
                 raise
-            except error.PushkeyFailed, exc:
+            except error.PushkeyFailed as exc:
                 # check client caps
                 remotecaps = getattr(exc, '_replycaps', None)
                 if (remotecaps is not None
                         and 'pushkey' not in remotecaps.get('error', ())):
@@ -839,20 +839,20 @@ def unbundle(repo, proto, heads):
                 if exc.old is not None:
                     part.addparam('old', exc.old, mandatory=False)
                 if exc.ret is not None:
                     part.addparam('ret', exc.ret, mandatory=False)
-        except error.BundleValueError, exc:
+        except error.BundleValueError as exc:
             errpart = bundler.newpart('error:unsupportedcontent')
             if exc.parttype is not None:
                 errpart.addparam('parttype', exc.parttype)
             if exc.params:
                 errpart.addparam('params', '\0'.join(exc.params))
-        except util.Abort, exc:
+        except util.Abort as exc:
             manargs = [('message', str(exc))]
             advargs = []
             if exc.hint is not None:
                 advargs.append(('hint', exc.hint))
             bundler.addpart(bundle2.bundlepart('error:abort',
                                                manargs, advargs))
-        except error.PushRaced, exc:
+        except error.PushRaced as exc:
             bundler.newpart('error:pushraced', [('message', str(exc))])
         return streamres(bundler.getchunks())
diff --git a/mercurial/worker.py b/mercurial/worker.py
--- a/mercurial/worker.py
+++ b/mercurial/worker.py
@@ -100,9 +100,9 @@ def _posixworker(ui, func, staticargs, a
         # if one worker bails, there's no good reason to wait for the rest
         for p in pids:
             try:
                 os.kill(p, signal.SIGTERM)
-            except OSError, err:
+            except OSError as err:
                 if err.errno != errno.ESRCH:
                     raise
     def waitforworkers():
         for _pid in pids:
diff --git a/tests/md5sum.py b/tests/md5sum.py
--- a/tests/md5sum.py
+++ b/tests/md5sum.py
@@ -22,9 +22,9 @@ except ImportError:
 
 for filename in sys.argv[1:]:
     try:
         fp = open(filename, 'rb')
-    except IOError, msg:
+    except IOError as msg:
         sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg))
         sys.exit(1)
 
     m = md5()
@@ -33,9 +33,9 @@ for filename in sys.argv[1:]:
             data = fp.read(8192)
             if not data:
                 break
             m.update(data)
-    except IOError, msg:
+    except IOError as msg:
         sys.stderr.write('%s: I/O error: %s\n' % (filename, msg))
         sys.exit(1)
     sys.stdout.write('%s  %s\n' % (m.hexdigest(), filename))
 
diff --git a/tests/readlink.py b/tests/readlink.py
--- a/tests/readlink.py
+++ b/tests/readlink.py
@@ -4,9 +4,9 @@ import errno, os, sys
 
 for f in sys.argv[1:]:
     try:
         print f, '->', os.readlink(f)
-    except OSError, err:
+    except OSError as err:
         if err.errno != errno.EINVAL:
             raise
         print f, 'not a symlink'
 
diff --git a/tests/test-manifest.py b/tests/test-manifest.py
--- a/tests/test-manifest.py
+++ b/tests/test-manifest.py
@@ -324,23 +324,23 @@ class basemanifesttests(object):
             l + '\n' for l in reversed(A_SHORT_MANIFEST.split('\n')) if l)
         try:
             self.parsemanifest(backwards)
             self.fail('Should have raised ValueError')
-        except ValueError, v:
+        except ValueError as v:
             self.assertIn('Manifest lines not in sorted order.', str(v))
 
     def testNoTerminalNewline(self):
         try:
             self.parsemanifest(A_SHORT_MANIFEST + 'wat')
             self.fail('Should have raised ValueError')
-        except ValueError, v:
+        except ValueError as v:
             self.assertIn('Manifest did not end in a newline.', str(v))
 
     def testNoNewLineAtAll(self):
         try:
             self.parsemanifest('wat')
             self.fail('Should have raised ValueError')
-        except ValueError, v:
+        except ValueError as v:
             self.assertIn('Manifest did not end in a newline.', str(v))
 
     def testHugeManifest(self):
         m = self.parsemanifest(A_HUGE_MANIFEST)
diff --git a/tests/test-trusted.py b/tests/test-trusted.py
--- a/tests/test-trusted.py
+++ b/tests/test-trusted.py
@@ -168,9 +168,9 @@ print "# error handling"
 
 def assertraises(f, exc=util.Abort):
     try:
         f()
-    except exc, inst:
+    except exc as inst:
         print 'raised', inst.__class__.__name__
     else:
         print 'no exception?!'
 
@@ -187,11 +187,11 @@ f.write('foo')
 f.close()
 
 try:
     testui(user='abc', group='def', silent=True)
-except error.ParseError, inst:
+except error.ParseError as inst:
     print inst
 
 try:
     testui(debug=True, silent=True)
-except error.ParseError, inst:
+except error.ParseError as inst:
     print inst
diff --git a/tests/test-ui-config.py b/tests/test-ui-config.py
--- a/tests/test-ui-config.py
+++ b/tests/test-ui-config.py
@@ -38,9 +38,9 @@ print repr(testui.config('values', 'bool
 print repr(testui.config('values', 'unknown'))
 print "---"
 try:
     print repr(testui.configbool('values', 'string'))
-except error.ConfigError, inst:
+except error.ConfigError as inst:
     print inst
 print repr(testui.configbool('values', 'bool1'))
 print repr(testui.configbool('values', 'bool2'))
 print repr(testui.configbool('values', 'bool2', True))
diff --git a/tests/tinyproxy.py b/tests/tinyproxy.py
--- a/tests/tinyproxy.py
+++ b/tests/tinyproxy.py
@@ -44,9 +44,9 @@ class ProxyHandler (BaseHTTPServer.BaseH
         else:
             host_port = netloc, 80
         print "\t" "connect to %s:%d" % host_port
         try: soc.connect(host_port)
-        except socket.error, arg:
+        except socket.error as arg:
             try: msg = arg[1]
             except (IndexError, TypeError): msg = arg
             self.send_error(404, msg)
             return 0


More information about the Mercurial-devel mailing list