From 46f126c10c85588d445a57bab6ab79d4af6c3edb Mon Sep 17 00:00:00 2001 From: Jeremy Andrews Date: Wed, 4 Mar 2026 15:00:58 -0600 Subject: [PATCH] Issue #2974 - Part 8: Adapt except 2to3 . --fix except -wpn Python 3 exception syntax is different. Comma-based syntax is gone, much like print syntax is changed. This lets you have the old behavior. Mechanical. Ref: PEP 3110 https://peps.python.org/pep-3110/ --- build/checksums.py | 2 +- build/pymake/pymake/builtins.py | 8 ++-- build/pymake/pymake/command.py | 4 +- build/pymake/pymake/data.py | 4 +- build/pymake/pymake/functions.py | 2 +- build/pymake/pymake/process.py | 6 +-- build/release/info.py | 2 +- build/upload.py | 2 +- build/util/hg.py | 8 ++-- build/win32/autobinscope.py | 4 +- config/expandlibs.py | 2 +- config/expandlibs_exec.py | 2 +- dom/bindings/Codegen.py | 2 +- dom/bindings/parser/WebIDL.py | 8 ++-- dom/bindings/parser/runtests.py | 2 +- dom/bindings/parser/tests/test_attr.py | 8 ++-- dom/bindings/parser/tests/test_cereactions.py | 4 +- .../test_conditional_dictionary_member.py | 6 +-- .../test_empty_sequence_default_value.py | 2 +- dom/bindings/parser/tests/test_error_colno.py | 2 +- .../parser/tests/test_error_lineno.py | 2 +- .../tests/test_exposed_extended_attribute.py | 12 +++--- dom/bindings/parser/tests/test_float_types.py | 10 ++--- .../parser/tests/test_identifier_conflict.py | 6 +-- .../test_interface_maplikesetlikeiterable.py | 4 +- dom/bindings/parser/tests/test_method.py | 10 ++--- dom/bindings/parser/tests/test_mozmap.py | 2 +- dom/bindings/parser/tests/test_namespace.py | 18 ++++----- .../tests/test_unenumerable_own_properties.py | 6 +-- dom/bindings/parser/tests/test_unforgeable.py | 4 +- .../src/third_party/libevent/event_rpcgen.py | 4 +- ipc/ipdl/ipdl/parser.py | 2 +- layout/tools/reftest/runreftest.py | 2 +- media/libaom/src/tools/lint-hunks.py | 4 +- .../build/android/pylib/run_java_tests.py | 2 +- media/webrtc/trunk/build/compiler_version.py | 2 +- .../webrtc/trunk/build/copy_test_data_ios.py | 2 +- .../trunk/testing/gtest/scripts/pump.py | 2 +- .../trunk/testing/gtest/scripts/upload.py | 18 +++++---- .../gtest/test/gtest_xml_output_unittest.py | 2 +- .../trunk/tools/gyp/pylib/gyp/MSVSSettings.py | 4 +- .../trunk/tools/gyp/pylib/gyp/MSVSVersion.py | 2 +- .../trunk/tools/gyp/pylib/gyp/__init__.py | 2 +- .../trunk/tools/gyp/pylib/gyp/common.py | 2 +- .../tools/gyp/pylib/gyp/generator/cmake.py | 2 +- .../tools/gyp/pylib/gyp/generator/ninja.py | 2 +- .../tools/gyp/pylib/gyp/generator/xcode.py | 6 +-- .../webrtc/trunk/tools/gyp/pylib/gyp/input.py | 24 +++++------ .../tools/gyp/pylib/gyp/xcode_emulation.py | 2 +- .../trunk/tools/gyp/pylib/gyp/xcode_ninja.py | 2 +- .../tools/gyp/pylib/gyp/xcodeproj_file.py | 2 +- .../gyptest-target_platform.py | 2 +- .../trunk/tools/gyp/test/lib/TestCmd.py | 12 +++--- .../trunk/tools/gyp/test/lib/TestCommon.py | 2 +- .../trunk/tools/gyp/test/lib/TestWin.py | 2 +- .../tools/barcode_tools/barcode_decoder.py | 4 +- python/blessings/blessings/tests.py | 8 ++-- .../compare-locales/compare_locales/checks.py | 6 +-- .../compare_locales/commands.py | 2 +- .../compare_locales/compare.py | 6 +-- .../compare-locales/compare_locales/parser.py | 2 +- .../compare_locales/webapps.py | 2 +- python/configobj/configobj.py | 10 ++--- python/configobj/validate.py | 4 +- python/mozbuild/mozbuild/doctor.py | 2 +- python/mozbuild/mozbuild/jar.py | 8 ++-- python/mozbuild/mozbuild/util.py | 2 +- python/pyyaml/lib/yaml/constructor.py | 8 ++-- python/pyyaml/lib/yaml/reader.py | 2 +- python/pyyaml/lib/yaml/scanner.py | 2 +- python/which/which.py | 2 +- .../google_test/gtest/scripts/upload.py | 18 +++++---- .../taskgraph/test/test_transforms_base.py | 2 +- testing/gtest/rungtests.py | 2 +- .../mod_pywebsocket/_stream_base.py | 6 +-- .../mod_pywebsocket/_stream_hybi.py | 10 ++--- .../pywebsocket/mod_pywebsocket/common.py | 2 +- .../pywebsocket/mod_pywebsocket/dispatch.py | 20 +++++----- .../pywebsocket/mod_pywebsocket/extensions.py | 6 +-- .../mod_pywebsocket/handshake/__init__.py | 6 +-- .../mod_pywebsocket/handshake/_base.py | 2 +- .../mod_pywebsocket/handshake/hybi.py | 8 ++-- .../mod_pywebsocket/headerparserhandler.py | 10 ++--- .../mod_pywebsocket/http_header_util.py | 4 +- .../pywebsocket/mod_pywebsocket/mux.py | 40 +++++++++---------- .../mod_pywebsocket/xhr_benchmark_handler.py | 2 +- testing/mochitest/pywebsocket/standalone.py | 27 +++++++------ testing/mochitest/runtests.py | 2 +- .../manifestparser/manifestparser/cli.py | 6 +-- testing/mozbase/mozdevice/mozdevice/sutini.py | 4 +- .../mozinstall/mozinstall/mozinstall.py | 2 +- .../mozprocess/tests/test_mozprocess.py | 4 +- .../mozrunner/devices/android_device.py | 4 +- .../mozscreenshot/mozscreenshot/__init__.py | 2 +- .../external_tools/download_file.py | 8 ++-- .../mouse_and_screen_resolution.py | 16 ++++---- testing/mozharness/mozfile/mozfile.py | 2 +- testing/mozharness/mozharness/base/config.py | 8 ++-- testing/mozharness/mozharness/base/script.py | 24 +++++------ .../mozharness/base/vcs/mercurial.py | 6 +-- .../mozharness/mozharness/mozilla/mapper.py | 2 +- .../mozharness/mozilla/testing/device.py | 6 +-- .../mozharness/mozilla/testing/mozpool.py | 6 +-- .../mozharness/mozilla/testing/testbase.py | 2 +- .../mozharness/mozprocess/processhandler.py | 6 +-- .../scripts/android_emulator_unittest.py | 4 +- testing/remotecppunittests.py | 2 +- testing/tools/proxyserver/proxyserver.py | 4 +- testing/xpcshell/runxpcshelltests.py | 4 +- testing/xpcshell/selftest.py | 4 +- tools/update-packaging/generatesnippet.py | 4 +- .../make_incremental_updates.py | 2 +- xpcom/idl-parser/xpidl/xpidl.py | 4 +- 113 files changed, 321 insertions(+), 314 deletions(-) diff --git a/build/checksums.py b/build/checksums.py index 777d0cbf53..abecbe5b6a 100755 --- a/build/checksums.py +++ b/build/checksums.py @@ -140,7 +140,7 @@ def main(): try: for digest in options.digests: hashlib.new(digest) - except ValueError, ve: + except ValueError as ve: logger.error('Could not create a "%s" hash object (%s)' % (digest, ve.args[0])) exit(1) diff --git a/build/pymake/pymake/builtins.py b/build/pymake/pymake/builtins.py index 27862c1658..946adf7e1e 100644 --- a/build/pymake/pymake/builtins.py +++ b/build/pymake/pymake/builtins.py @@ -13,7 +13,7 @@ def mkdir(args): """ try: opts, args = getopt(args, "p", ["parents"]) - except GetoptError, e: + except GetoptError as e: raise PythonException("mkdir: %s" % e, 1) parents = False for o, a in opts: @@ -25,7 +25,7 @@ def mkdir(args): os.makedirs(f) else: os.mkdir(f) - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST and parents: pass else: @@ -38,7 +38,7 @@ def rm(args): """ try: opts, args = getopt(args, "rRf", ["force", "recursive"]) - except GetoptError, e: + except GetoptError as e: raise PythonException("rm: %s" % e, 1) force = False recursive = False @@ -88,7 +88,7 @@ def touch(args): """ try: opts, args = getopt(args, "t:") - except GetoptError, e: + except GetoptError as e: raise PythonException("touch: %s" % e, 1) opts = dict(opts) times = None diff --git a/build/pymake/pymake/command.py b/build/pymake/pymake/command.py index 7a5e9084d1..3d18a2cc12 100644 --- a/build/pymake/pymake/command.py +++ b/build/pymake/pymake/command.py @@ -124,7 +124,7 @@ class _MakeContext(object): self.makefile.include(f) self.makefile.finishparsing() self.makefile.remakemakefiles(self.remakecb) - except util.MakeError, e: + except util.MakeError as e: print(e) self.context.defer(self.cb, 2) @@ -269,7 +269,7 @@ def main(args, env, cwd, cb): ostmts, targets, overrides = parserdata.parsecommandlineargs(arguments) _MakeContext(makeflags, makelevel, workdir, context, env, targets, options, ostmts, overrides, cb) - except (util.MakeError), e: + except (util.MakeError) as e: print(e) if options.printdir: print("make.py[%i]: Leaving directory '%s'" % (makelevel, workdir)) diff --git a/build/pymake/pymake/data.py b/build/pymake/pymake/data.py index dc479f7005..68b1f03769 100644 --- a/build/pymake/pymake/data.py +++ b/build/pymake/pymake/data.py @@ -949,7 +949,7 @@ class RemakeRuleContext(object): self.target.didanything = True try: self.commands = [c for c in self.rule.getcommands(self.target, self.makefile)] - except util.MakeError, e: + except util.MakeError as e: print(e) sys.stdout.flush() cb(error=True) @@ -1283,7 +1283,7 @@ class Target(object): try: self.resolvedeps(makefile, targetstack, [], False) - except util.MakeError, e: + except util.MakeError as e: if printerror: print(e) self.error = True diff --git a/build/pymake/pymake/functions.py b/build/pymake/pymake/functions.py index 4c336e3bba..e193eba466 100644 --- a/build/pymake/pymake/functions.py +++ b/build/pymake/pymake/functions.py @@ -785,7 +785,7 @@ class ShellFunction(Function): try: p = subprocess.Popen(cline, executable=executable, env=makefile.env, shell=False, stdout=subprocess.PIPE, cwd=makefile.workdir) - except OSError, e: + except OSError as e: print("Error executing command %s" % cline[0], e, file=sys.stderr) return finally: diff --git a/build/pymake/pymake/process.py b/build/pymake/pymake/process.py index 070a6b21bb..650b54242c 100644 --- a/build/pymake/pymake/process.py +++ b/build/pymake/pymake/process.py @@ -194,7 +194,7 @@ def clinetoargv(cline, cwd): str = _escapednewlines.sub('', cline) try: args = ClineSplitter(str, cwd) - except MetaCharacterException, e: + except MetaCharacterException as e: return None, e.char if len(args) and args[0].find('=') != -1: @@ -331,7 +331,7 @@ class PopenJob(Job): os.environ['PATH'] = self.env['PATH'] p = subprocess.Popen(self.argv, executable=self.executable, shell=self.shell, env=self.env, cwd=self.cwd) return p.wait() - except OSError, e: + except OSError as e: print(e, file=sys.stderr) return -127 finally: @@ -398,7 +398,7 @@ class PythonJob(Job): (self.module, self.method, rv)), file=sys.stderr) return (rv if isinstance(rv, int) else 1) - except PythonException, e: + except PythonException as e: print(e, file=sys.stderr) return e.exitcode except: diff --git a/build/release/info.py b/build/release/info.py index 2fe8a6817b..560629de50 100644 --- a/build/release/info.py +++ b/build/release/info.py @@ -50,7 +50,7 @@ def findOldBuildIDs(product, version, buildNumber, platforms, id = getBuildID(platform, product, version, n, nightlyDir, server) ids[platform].append(id) - except Exception, e: + except Exception as e: log.error("Hit exception: %s" % e) return ids diff --git a/build/upload.py b/build/upload.py index 1252f3d8b9..5a6ec9b7ca 100644 --- a/build/upload.py +++ b/build/upload.py @@ -370,6 +370,6 @@ if __name__ == '__main__': package=options.package, verbose=True) WriteProperties(args, options.properties_file, url_properties, options.package) - except IOError, (strerror): + except IOError as strerror: print(strerror) sys.exit(1) diff --git a/build/util/hg.py b/build/util/hg.py index 962d96f445..546f9916c1 100644 --- a/build/util/hg.py +++ b/build/util/hg.py @@ -105,7 +105,7 @@ def purge(dest): try: run_cmd(['hg', '--config', 'extensions.purge=', 'purge', '-a', '--all', dest], cwd=dest) - except subprocess.CalledProcessError, e: + except subprocess.CalledProcessError as e: log.debug('purge failed: %s' % e) raise @@ -306,7 +306,7 @@ def out(src, remote, **kwargs): branch = "default" revs.append((rev, branch)) return revs - except subprocess.CalledProcessError, inst: + except subprocess.CalledProcessError as inst: # In some situations, some versions of Mercurial return "1" # if no changes are found, so we need to ignore this return code if inst.returncode == 1: @@ -500,7 +500,7 @@ def apply_and_push(localrepo, remote, changer, max_attempts=10, push(src=localrepo, remote=remote, ssh_username=ssh_username, ssh_key=ssh_key, force=force) return - except subprocess.CalledProcessError, e: + except subprocess.CalledProcessError as e: log.debug("Hit error when trying to push: %s" % str(e)) if n == max_attempts: log.debug("Tried %d times, giving up" % max_attempts) @@ -515,7 +515,7 @@ def apply_and_push(localrepo, remote, changer, max_attempts=10, try: run_cmd(['hg', '--config', 'ui.merge=internal:merge', 'rebase'], cwd=localrepo) - except subprocess.CalledProcessError, e: + except subprocess.CalledProcessError as e: log.debug("Failed to rebase: %s" % str(e)) update(localrepo, branch=branch) for r in reversed(new_revs): diff --git a/build/win32/autobinscope.py b/build/win32/autobinscope.py index 3c0ca8477f..f86c25299d 100644 --- a/build/win32/autobinscope.py +++ b/build/win32/autobinscope.py @@ -51,7 +51,9 @@ try: "/c", "CompilerVersionCheck", "/c", "SafeSEHCheck", "/c", "SNCheck", "/c", "DBCheck"], stdout=subprocess.PIPE) -except WindowsError, (errno, strerror): +except OSError as e: + errno = e.errno + strerror = e.strerror or str(e) if errno != 2 and errno != 3: print("Unexpected error ! \nError " + str(errno) + " : " + strerror + "\nExiting !\n") sys.exit(0) diff --git a/config/expandlibs.py b/config/expandlibs.py index 71ba9145f6..d27fdf1370 100644 --- a/config/expandlibs.py +++ b/config/expandlibs.py @@ -36,7 +36,7 @@ def ensureParentDir(file): if dir and not os.path.exists(dir): try: os.makedirs(dir) - except OSError, error: + except OSError as error: if error.errno != errno.EEXIST: raise diff --git a/config/expandlibs_exec.py b/config/expandlibs_exec.py index 9e287ddb77..e64f04c72d 100644 --- a/config/expandlibs_exec.py +++ b/config/expandlibs_exec.py @@ -339,7 +339,7 @@ def main(args, proc_callback=None): proc = subprocess.Popen(args, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) if proc_callback: proc_callback(proc) - except Exception, e: + except Exception as e: print('error: Launching', args, ':', e, file=sys.stderr) raise e (stdout, stderr) = proc.communicate() diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py index 79d7845789..4ffd2cee2a 100644 --- a/dom/bindings/Codegen.py +++ b/dom/bindings/Codegen.py @@ -7743,7 +7743,7 @@ class CGPerSignatureCall(CGThing): } try: wrapCode += wrapForType(self.returnType, self.descriptor, resultTemplateValues) - except MethodNotNewObjectError, err: + except MethodNotNewObjectError as err: assert not returnsNewObject raise TypeError("%s being returned from non-NewObject method or property %s.%s" % (err.typename, diff --git a/dom/bindings/parser/WebIDL.py b/dom/bindings/parser/WebIDL.py index 69d5e92616..cb263615dc 100644 --- a/dom/bindings/parser/WebIDL.py +++ b/dom/bindings/parser/WebIDL.py @@ -5417,7 +5417,7 @@ class Parser(Tokenizer): [location, existingObj.location]) existingObj.setNonPartial(*nonPartialArgs) return existingObj - except Exception, ex: + except Exception as ex: if isinstance(ex, WebIDLError): raise ex pass @@ -5455,7 +5455,7 @@ class Parser(Tokenizer): "%s and %s" % (identifier.name, p[0]), [location, p[0].location]) return - except Exception, ex: + except Exception as ex: if isinstance(ex, WebIDLError): raise ex pass @@ -5518,7 +5518,7 @@ class Parser(Tokenizer): "non-%s object" % (prettyname, prettyname), [location, nonPartialObject.location]) - except Exception, ex: + except Exception as ex: if isinstance(ex, WebIDLError): raise ex pass @@ -6964,7 +6964,7 @@ def main(): print(fullPath) parser.parse(''.join(lines), fullPath) parser.finish() - except WebIDLError, e: + except WebIDLError as e: if options.verbose_errors: traceback.print_exc() else: diff --git a/dom/bindings/parser/runtests.py b/dom/bindings/parser/runtests.py index 26646c1870..f8d972150e 100644 --- a/dom/bindings/parser/runtests.py +++ b/dom/bindings/parser/runtests.py @@ -68,7 +68,7 @@ def run_tests(tests, verbose): harness.start() try: _test.WebIDLTest.__call__(WebIDL.Parser(), harness) - except Exception, ex: + except Exception as ex: harness.test_fail("Unhandled exception in test %s: %s" % (testpath, ex)) traceback.print_exc() diff --git a/dom/bindings/parser/tests/test_attr.py b/dom/bindings/parser/tests/test_attr.py index ad7aabc191..35f680aaa8 100644 --- a/dom/bindings/parser/tests/test_attr.py +++ b/dom/bindings/parser/tests/test_attr.py @@ -133,7 +133,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should not allow [SetterThrows] on readonly attributes") @@ -146,7 +146,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should spell [Throws] correctly") @@ -159,7 +159,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should not allow [SameObject] on attributes not of interface type") @@ -172,6 +172,6 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(not threw, "Should allow [SameObject] on attributes of interface type") diff --git a/dom/bindings/parser/tests/test_cereactions.py b/dom/bindings/parser/tests/test_cereactions.py index 2f9397d903..d7ef94b079 100644 --- a/dom/bindings/parser/tests/test_cereactions.py +++ b/dom/bindings/parser/tests/test_cereactions.py @@ -38,7 +38,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, e: + except Exception as e: harness.ok(False, "Shouldn't have thrown for [CEReactions] used on writable attribute. %s" % e) threw = True @@ -52,7 +52,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, e: + except Exception as e: harness.ok(False, "Shouldn't have thrown for [CEReactions] used on regular operations. %s" % e) threw = True diff --git a/dom/bindings/parser/tests/test_conditional_dictionary_member.py b/dom/bindings/parser/tests/test_conditional_dictionary_member.py index 433b7e501a..066300e8bb 100644 --- a/dom/bindings/parser/tests/test_conditional_dictionary_member.py +++ b/dom/bindings/parser/tests/test_conditional_dictionary_member.py @@ -44,7 +44,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, exception: + except Exception as exception: pass harness.ok(exception, "Should have thrown.") @@ -70,7 +70,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, exception: + except Exception as exception: pass harness.ok(exception, "Should have thrown (2).") @@ -100,7 +100,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, exception: + except Exception as exception: pass harness.ok(exception, "Should have thrown (3).") diff --git a/dom/bindings/parser/tests/test_empty_sequence_default_value.py b/dom/bindings/parser/tests/test_empty_sequence_default_value.py index 350ae72f02..a713266c88 100644 --- a/dom/bindings/parser/tests/test_empty_sequence_default_value.py +++ b/dom/bindings/parser/tests/test_empty_sequence_default_value.py @@ -10,7 +10,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Constant cannot have [] as a default value") diff --git a/dom/bindings/parser/tests/test_error_colno.py b/dom/bindings/parser/tests/test_error_colno.py index ca0674aec0..7afd15513c 100644 --- a/dom/bindings/parser/tests/test_error_colno.py +++ b/dom/bindings/parser/tests/test_error_colno.py @@ -8,7 +8,7 @@ def WebIDLTest(parser, harness): try: parser.parse(input) results = parser.finish() - except WebIDL.WebIDLError, e: + except WebIDL.WebIDLError as e: threw = True lines = str(e).split('\n') diff --git a/dom/bindings/parser/tests/test_error_lineno.py b/dom/bindings/parser/tests/test_error_lineno.py index f11222e7a4..70bb188368 100644 --- a/dom/bindings/parser/tests/test_error_lineno.py +++ b/dom/bindings/parser/tests/test_error_lineno.py @@ -14,7 +14,7 @@ interface ?""" try: parser.parse(input) results = parser.finish() - except WebIDL.WebIDLError, e: + except WebIDL.WebIDLError as e: threw = True lines = str(e).split('\n') diff --git a/dom/bindings/parser/tests/test_exposed_extended_attribute.py b/dom/bindings/parser/tests/test_exposed_extended_attribute.py index 48957098bf..a6c04e30ca 100644 --- a/dom/bindings/parser/tests/test_exposed_extended_attribute.py +++ b/dom/bindings/parser/tests/test_exposed_extended_attribute.py @@ -124,7 +124,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown on invalid Exposed value on interface.") @@ -140,7 +140,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown on invalid Exposed value on attribute.") @@ -156,7 +156,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown on invalid Exposed value on operation.") @@ -172,7 +172,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown on invalid Exposed value on constant.") @@ -192,7 +192,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown on member exposed where its interface is not.") @@ -216,7 +216,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown on LHS of implements being exposed where RHS is not.") diff --git a/dom/bindings/parser/tests/test_float_types.py b/dom/bindings/parser/tests/test_float_types.py index 718f09c114..b7325cf9d2 100644 --- a/dom/bindings/parser/tests/test_float_types.py +++ b/dom/bindings/parser/tests/test_float_types.py @@ -68,7 +68,7 @@ def WebIDLTest(parser, harness): long m(float arg); }; """) - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "[LenientFloat] only allowed on void methods") @@ -81,7 +81,7 @@ def WebIDLTest(parser, harness): void m(unrestricted float arg); }; """) - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "[LenientFloat] only allowed on methods with unrestricted float args") @@ -94,7 +94,7 @@ def WebIDLTest(parser, harness): void m(sequence arg); }; """) - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "[LenientFloat] only allowed on methods with unrestricted float args (2)") @@ -107,7 +107,7 @@ def WebIDLTest(parser, harness): void m((unrestricted float or FloatTypes) arg); }; """) - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "[LenientFloat] only allowed on methods with unrestricted float args (3)") @@ -120,6 +120,6 @@ def WebIDLTest(parser, harness): readonly attribute float foo; }; """) - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "[LenientFloat] only allowed on writable attributes") diff --git a/dom/bindings/parser/tests/test_identifier_conflict.py b/dom/bindings/parser/tests/test_identifier_conflict.py index b510a30c04..0e9a6654aa 100644 --- a/dom/bindings/parser/tests/test_identifier_conflict.py +++ b/dom/bindings/parser/tests/test_identifier_conflict.py @@ -9,7 +9,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() harness.ok(False, "Should fail to parse") - except Exception, e: + except Exception as e: harness.ok("Name collision" in e.message, "Should have name collision for interface") @@ -21,7 +21,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() harness.ok(False, "Should fail to parse") - except Exception, e: + except Exception as e: harness.ok("Name collision" in e.message, "Should have name collision for dictionary") @@ -33,7 +33,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() harness.ok(False, "Should fail to parse") - except Exception, e: + except Exception as e: harness.ok("Multiple unresolvable definitions" in e.message, "Should have name collision for dictionary") diff --git a/dom/bindings/parser/tests/test_interface_maplikesetlikeiterable.py b/dom/bindings/parser/tests/test_interface_maplikesetlikeiterable.py index ee5d870c20..72aa7617b8 100644 --- a/dom/bindings/parser/tests/test_interface_maplikesetlikeiterable.py +++ b/dom/bindings/parser/tests/test_interface_maplikesetlikeiterable.py @@ -37,10 +37,10 @@ def WebIDLTest(parser, harness): p.finish() harness.ok(False, prefix + " - Interface passed when should've failed") - except WebIDL.WebIDLError, e: + except WebIDL.WebIDLError as e: harness.ok(True, prefix + " - Interface failed as expected") - except Exception, e: + except Exception as e: harness.ok(False, prefix + " - Interface failed but not as a WebIDLError exception: %s" % e) diff --git a/dom/bindings/parser/tests/test_method.py b/dom/bindings/parser/tests/test_method.py index 2e3fbb0c9a..2f5f4b0b2b 100644 --- a/dom/bindings/parser/tests/test_method.py +++ b/dom/bindings/parser/tests/test_method.py @@ -121,7 +121,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(not threw, "Should allow integer to float type corecion") @@ -134,7 +134,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should not allow [GetterThrows] on methods") @@ -147,7 +147,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should not allow [SetterThrows] on methods") @@ -160,7 +160,7 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should spell [Throws] correctly on methods") @@ -173,6 +173,6 @@ def WebIDLTest(parser, harness): }; """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should not allow __noSuchMethod__ methods") diff --git a/dom/bindings/parser/tests/test_mozmap.py b/dom/bindings/parser/tests/test_mozmap.py index 1a36fdd62c..fa852c02a0 100644 --- a/dom/bindings/parser/tests/test_mozmap.py +++ b/dom/bindings/parser/tests/test_mozmap.py @@ -33,7 +33,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") diff --git a/dom/bindings/parser/tests/test_namespace.py b/dom/bindings/parser/tests/test_namespace.py index 74533a1770..62edb270c6 100644 --- a/dom/bindings/parser/tests/test_namespace.py +++ b/dom/bindings/parser/tests/test_namespace.py @@ -70,7 +70,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -85,7 +85,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -104,7 +104,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -123,7 +123,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -142,7 +142,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -161,7 +161,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -180,7 +180,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -199,7 +199,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -218,6 +218,6 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") diff --git a/dom/bindings/parser/tests/test_unenumerable_own_properties.py b/dom/bindings/parser/tests/test_unenumerable_own_properties.py index d017d5ce09..d28cc1ec05 100644 --- a/dom/bindings/parser/tests/test_unenumerable_own_properties.py +++ b/dom/bindings/parser/tests/test_unenumerable_own_properties.py @@ -24,7 +24,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -39,7 +39,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") @@ -59,6 +59,6 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception, x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown.") diff --git a/dom/bindings/parser/tests/test_unforgeable.py b/dom/bindings/parser/tests/test_unforgeable.py index 3787e8c6af..44a168670e 100644 --- a/dom/bindings/parser/tests/test_unforgeable.py +++ b/dom/bindings/parser/tests/test_unforgeable.py @@ -111,7 +111,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown when shadowing unforgeable attribute on " @@ -130,7 +130,7 @@ def WebIDLTest(parser, harness): """) results = parser.finish() - except Exception,x: + except Exception as x: threw = True harness.ok(threw, "Should have thrown when shadowing unforgeable operation on " diff --git a/ipc/chromium/src/third_party/libevent/event_rpcgen.py b/ipc/chromium/src/third_party/libevent/event_rpcgen.py index ca4a351133..19784915ad 100755 --- a/ipc/chromium/src/third_party/libevent/event_rpcgen.py +++ b/ipc/chromium/src/third_party/libevent/event_rpcgen.py @@ -1700,11 +1700,11 @@ if __name__ == '__main__': CommandLine(sys.argv).run() sys.exit(0) - except RpcGenError, e: + except RpcGenError as e: print(e, file=sys.stderr) sys.exit(1) - except EnvironmentError, e: + except EnvironmentError as e: if e.filename and e.strerror: print("%s: %s" % (e.filename, e.strerror), file=sys.stderr) sys.exit(1) diff --git a/ipc/ipdl/ipdl/parser.py b/ipc/ipdl/ipdl/parser.py index 7170f009cc..f90342ec13 100644 --- a/ipc/ipdl/ipdl/parser.py +++ b/ipc/ipdl/ipdl/parser.py @@ -78,7 +78,7 @@ class Parser: try: ast = self.parser.parse(input=input, lexer=self.lexer, debug=self.debug) - except ParseError, p: + except ParseError as p: print(p, file=errout) return None diff --git a/layout/tools/reftest/runreftest.py b/layout/tools/reftest/runreftest.py index cd0516b2f8..a3489870be 100644 --- a/layout/tools/reftest/runreftest.py +++ b/layout/tools/reftest/runreftest.py @@ -37,7 +37,7 @@ from mozscreenshot import printstatus, dump_screen try: from marionette_driver.addons import Addons from marionette_harness import Marionette -except ImportError, e: +except ImportError as e: # Defer ImportError until attempt to use Marionette def reraise(*args, **kwargs): raise(e) diff --git a/media/libaom/src/tools/lint-hunks.py b/media/libaom/src/tools/lint-hunks.py index 9d8d2d4fa9..e9088b3e3e 100755 --- a/media/libaom/src/tools/lint-hunks.py +++ b/media/libaom/src/tools/lint-hunks.py @@ -65,7 +65,7 @@ def main(argv=None): try: try: opts, args = getopt.getopt(argv[1:], SHORT_OPTIONS, LONG_OPTIONS) - except getopt.error, msg: + except getopt.error as msg: raise Usage(msg) # process options @@ -137,7 +137,7 @@ def main(argv=None): if lint_failed: return 1 - except Usage, err: + except Usage as err: print(err, file=sys.stderr) print("for help use --help", file=sys.stderr) return 2 diff --git a/media/webrtc/trunk/build/android/pylib/run_java_tests.py b/media/webrtc/trunk/build/android/pylib/run_java_tests.py index fc0a13fd81..a409db96c0 100644 --- a/media/webrtc/trunk/build/android/pylib/run_java_tests.py +++ b/media/webrtc/trunk/build/android/pylib/run_java_tests.py @@ -477,7 +477,7 @@ class TestRunner(BaseTestRunner): # See ../../third_party/android/testrunner/adb_interface.py except (errors.WaitForResponseTimedOutError, errors.DeviceUnresponsiveError, - errors.InstrumentationError), e: + errors.InstrumentationError) as e: if start_date_ms: duration_ms = int(time.time()) * 1000 - start_date_ms else: diff --git a/media/webrtc/trunk/build/compiler_version.py b/media/webrtc/trunk/build/compiler_version.py index 4651b0e295..7ecf8d25cc 100755 --- a/media/webrtc/trunk/build/compiler_version.py +++ b/media/webrtc/trunk/build/compiler_version.py @@ -26,7 +26,7 @@ def GetVersion(compiler): result = re.match(r"(\d+)\.(\d+)", gcc_output) return result.group(1) + result.group(2) - except Exception, e: + except Exception as e: if gcc_error: sys.stderr.write(gcc_error) print("compiler_version.py failed to execute:", compiler, file=sys.stderr) diff --git a/media/webrtc/trunk/build/copy_test_data_ios.py b/media/webrtc/trunk/build/copy_test_data_ios.py index caa80a7536..e05c714581 100755 --- a/media/webrtc/trunk/build/copy_test_data_ios.py +++ b/media/webrtc/trunk/build/copy_test_data_ios.py @@ -93,7 +93,7 @@ def DoMain(argv): def main(argv): try: result = DoMain(argv[1:]) - except WrongNumberOfArgumentsException, e: + except WrongNumberOfArgumentsException as e: print(e, file=sys.stderr) return 1 if result: diff --git a/media/webrtc/trunk/testing/gtest/scripts/pump.py b/media/webrtc/trunk/testing/gtest/scripts/pump.py index 5092490ab0..d2a7247b16 100755 --- a/media/webrtc/trunk/testing/gtest/scripts/pump.py +++ b/media/webrtc/trunk/testing/gtest/scripts/pump.py @@ -622,7 +622,7 @@ class Env: def EvalExp(self, exp): try: result = eval(exp.python_exp) - except Exception, e: + except Exception as e: print('ERROR: caught exception %s: %s' % (e.__class__.__name__, e)) print(('ERROR: failed to evaluate meta expression %s at %s' % (exp.python_exp, exp.token.start))) diff --git a/media/webrtc/trunk/testing/gtest/scripts/upload.py b/media/webrtc/trunk/testing/gtest/scripts/upload.py index bfdd4d47f4..e7c4363ef7 100755 --- a/media/webrtc/trunk/testing/gtest/scripts/upload.py +++ b/media/webrtc/trunk/testing/gtest/scripts/upload.py @@ -79,7 +79,7 @@ def GetEmail(prompt): last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email - except IOError, e: + except IOError as e: pass email = raw_input(prompt + ": ").strip() if email: @@ -87,7 +87,7 @@ def GetEmail(prompt): last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() - except IOError, e: + except IOError as e: pass else: email = last_email @@ -203,7 +203,7 @@ class AbstractRpcServer(object): response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) @@ -228,7 +228,7 @@ class AbstractRpcServer(object): (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: response = e if (response.code != 302 or response.info()["location"] != continue_location): @@ -255,7 +255,7 @@ class AbstractRpcServer(object): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) - except ClientLoginError, e: + except ClientLoginError as e: if e.reason == "BadAuthentication": print("Invalid username or password.", file=sys.stderr) continue @@ -327,7 +327,7 @@ class AbstractRpcServer(object): response = f.read() f.close() return response - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if tries > 3: raise elif e.code == 401: @@ -1223,7 +1223,8 @@ def GuessVCS(options): out, returncode = RunShellWithReturnCode(["hg", "root"]) if returncode == 0: return MercurialVCS(options, out.strip()) - except OSError, (errno, message): + except OSError as e: + errno, message = e.args if errno != 2: # ENOENT -- they don't have hg installed. raise @@ -1239,7 +1240,8 @@ def GuessVCS(options): "--is-inside-work-tree"]) if returncode == 0: return GitVCS(options) - except OSError, (errno, message): + except OSError as e: + errno, message = e.args if errno != 2: # ENOENT -- they don't have git installed. raise diff --git a/media/webrtc/trunk/testing/gtest/test/gtest_xml_output_unittest.py b/media/webrtc/trunk/testing/gtest/test/gtest_xml_output_unittest.py index 8cdfb56b68..e235d7e671 100755 --- a/media/webrtc/trunk/testing/gtest/test/gtest_xml_output_unittest.py +++ b/media/webrtc/trunk/testing/gtest/test/gtest_xml_output_unittest.py @@ -199,7 +199,7 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): 'gtest_no_test_unittest') try: os.remove(output_file) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSSettings.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSSettings.py index e2ba0c1e00..2240cfe7fe 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSSettings.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSSettings.py @@ -461,7 +461,7 @@ def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr): # Invoke the translation function. try: msvs_tool[msvs_setting](msvs_value, msbuild_settings) - except ValueError, e: + except ValueError as e: print(('Warning: while converting %s/%s to MSBuild, ' '%s' % (msvs_tool_name, msvs_setting, e)), file=stderr) else: @@ -517,7 +517,7 @@ def _ValidateSettings(validators, settings, stderr): if setting in tool_validators: try: tool_validators[setting](value) - except ValueError, e: + except ValueError as e: print(('Warning: for %s/%s, %s' % (tool_name, setting, e)), file=stderr) else: diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSVersion.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSVersion.py index edaf6eed00..bf7326fed1 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSVersion.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSVersion.py @@ -168,7 +168,7 @@ def _RegistryQuery(key, value=None): text = None try: text = _RegistryQueryBase('Sysnative', key, value) - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: text = _RegistryQueryBase('System32', key, value) else: diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py index 2ac7afa0fa..77fd48def0 100755 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py @@ -539,7 +539,7 @@ def gyp_main(args): def main(args): try: return gyp_main(args) - except GypError, e: + except GypError as e: sys.stderr.write("gyp: %s\n" % e) return 1 diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/common.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/common.py index a1e1db5f12..bc7d3df0cb 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/common.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/common.py @@ -363,7 +363,7 @@ def WriteOnDiff(filename): same = False try: same = filecmp.cmp(self.tmp_path, filename, False) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/cmake.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/cmake.py index de97aba007..3ab47852ee 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/cmake.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/cmake.py @@ -1239,7 +1239,7 @@ def GenerateOutput(target_list, target_dicts, data, params): arglists.append((target_list, target_dicts, data, params, config_name)) pool.map(CallGenerateOutputForConfig, arglists) - except KeyboardInterrupt, e: + except KeyboardInterrupt as e: pool.terminate() raise e else: diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py index e1e920c305..e80651696c 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py @@ -2474,7 +2474,7 @@ def GenerateOutput(target_list, target_dicts, data, params): arglists.append( (target_list, target_dicts, data, params, config_name)) pool.map(CallGenerateOutputForConfig, arglists) - except KeyboardInterrupt, e: + except KeyboardInterrupt as e: pool.terminate() raise e else: diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/xcode.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/xcode.py index 233b3bbc09..7b0a1aca96 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/xcode.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/xcode.py @@ -129,7 +129,7 @@ class XcodeProject(object): try: os.makedirs(self.path) self.created_dir = True - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise @@ -454,7 +454,7 @@ sys.exit(subprocess.call(sys.argv[1:]))" """ same = False try: same = filecmp.cmp(pbxproj_path, new_pbxproj_path, False) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise @@ -744,7 +744,7 @@ def GenerateOutput(target_list, target_dicts, data, params): xctarget_type = gyp.xcodeproj_file.PBXNativeTarget try: target_properties['productType'] = _types[type_bundle_key] - except KeyError, e: + except KeyError as e: gyp.common.ExceptionAppend(e, "-- unknown product type while " "writing target %s" % target_name) raise diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py index fe62de0c31..c322c83b28 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py @@ -242,10 +242,10 @@ def LoadOneBuildFile(build_file_path, data, aux_data, includes, else: build_file_data = eval(build_file_contents, {'__builtins__': None}, None) - except SyntaxError, e: + except SyntaxError as e: e.filename = build_file_path raise - except Exception, e: + except Exception as e: gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path) raise @@ -265,7 +265,7 @@ def LoadOneBuildFile(build_file_path, data, aux_data, includes, else: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, None, check) - except Exception, e: + except Exception as e: gyp.common.ExceptionAppend(e, 'while reading includes of ' + build_file_path) raise @@ -467,7 +467,7 @@ def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, try: LoadTargetBuildFile(dependency, data, aux_data, variables, includes, depth, check, load_dependencies) - except Exception, e: + except Exception as e: gyp.common.ExceptionAppend( e, 'while loading dependencies of %s' % build_file_path) raise @@ -510,10 +510,10 @@ def CallLoadTargetBuildFile(global_flags, return (build_file_path, build_file_data, dependencies) - except GypError, e: + except GypError as e: sys.stderr.write("gyp: %s\n" % e) return None - except Exception, e: + except Exception as e: print('Exception:', e, file=sys.stderr) print(traceback.format_exc(), file=sys.stderr) return None @@ -605,7 +605,7 @@ def LoadTargetBuildFilesParallel(build_files, data, variables, includes, depth, args = (global_flags, dependency, variables, includes, depth, check, generator_input_info), callback = parallel_state.LoadTargetBuildFileCallback) - except KeyboardInterrupt, e: + except KeyboardInterrupt as e: parallel_state.pool.terminate() raise e @@ -905,7 +905,7 @@ def ExpandVariables(input, phase, variables, build_file): stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=build_file_dir) - except Exception, e: + except Exception as e: raise GypError("%s while executing command '%s' in %s" % (e, contents, build_file)) @@ -1090,13 +1090,13 @@ def EvalSingleCondition( if eval(ast_code, {'__builtins__': None}, variables): return true_dict return false_dict - except SyntaxError, e: + except SyntaxError as e: syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s ' 'at character %d.' % (str(e.args[0]), e.text, build_file, e.offset), e.filename, e.lineno, e.offset, e.text) raise syntax_error - except NameError, e: + except NameError as e: gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' % (cond_expr_expanded, build_file)) raise GypError(e) @@ -1857,7 +1857,7 @@ def VerifyNoGYPFileCircularDependencies(targets): for dependency in target_dependencies: try: dependency_build_file = gyp.common.BuildFile(dependency) - except GypError, e: + except GypError as e: gyp.common.ExceptionAppend( e, 'while computing dependencies of .gyp file %s' % build_file) raise @@ -2780,7 +2780,7 @@ def Load(build_files, variables, includes, depth, generator_input_info, check, try: LoadTargetBuildFile(build_file, data, aux_data, variables, includes, depth, check, True) - except Exception, e: + except Exception as e: gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file) raise diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py index 2a7202e713..ea688bf893 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py @@ -1737,7 +1737,7 @@ def _TopologicallySortedEnvVarKeys(env): order = gyp.common.TopologicallySorted(list(env.keys()), GetEdges) order.reverse() return order - except gyp.common.CycleError, e: + except gyp.common.CycleError as e: raise GypError( 'Xcode environment variables are cyclically dependent: ' + str(e.nodes)) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_ninja.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_ninja.py index b2ad90d99e..1d71b8c5f8 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_ninja.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_ninja.py @@ -28,7 +28,7 @@ def _WriteWorkspace(main_gyp, sources_gyp, params): workspace_path = os.path.join(options.generator_output, workspace_path) try: os.makedirs(workspace_path) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise output_string = '\n' + \ diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcodeproj_file.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcodeproj_file.py index 79509d6ef2..a99f95e1d2 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcodeproj_file.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcodeproj_file.py @@ -691,7 +691,7 @@ class XCObject(object): printable_value[0] == '"' and printable_value[-1] == '"': printable_value = printable_value[1:-1] printable += printable_key + ' = ' + printable_value + ';' + after_kv - except TypeError, e: + except TypeError as e: gyp.common.ExceptionAppend(e, 'while printing key "%s"' % key) raise diff --git a/media/webrtc/trunk/tools/gyp/test/configurations/target_platform/gyptest-target_platform.py b/media/webrtc/trunk/tools/gyp/test/configurations/target_platform/gyptest-target_platform.py index ae4e9e5a2d..1645d6ec08 100755 --- a/media/webrtc/trunk/tools/gyp/test/configurations/target_platform/gyptest-target_platform.py +++ b/media/webrtc/trunk/tools/gyp/test/configurations/target_platform/gyptest-target_platform.py @@ -15,7 +15,7 @@ import TestCommon def RunX64(exe, stdout): try: test.run_built_executable(exe, stdout=stdout) - except WindowsError, e: + except WindowsError as e: # Assume the exe is 64-bit if it can't load on 32-bit systems. # Both versions of the error are required because different versions # of python seem to return different errors for invalid exe type. diff --git a/media/webrtc/trunk/tools/gyp/test/lib/TestCmd.py b/media/webrtc/trunk/tools/gyp/test/lib/TestCmd.py index cb0401dca8..a0967be3ca 100644 --- a/media/webrtc/trunk/tools/gyp/test/lib/TestCmd.py +++ b/media/webrtc/trunk/tools/gyp/test/lib/TestCmd.py @@ -433,7 +433,7 @@ def match_re(lines = None, res = None): s = "^" + res[i] + "$" try: expr = re.compile(s) - except re.error, e: + except re.error as e: msg = "Regular expression error in %s: %s" raise re.error(msg % (repr(s), e[0])) if not expr.search(lines[i]): @@ -450,7 +450,7 @@ def match_re_dotall(lines = None, res = None): s = "^" + res + "$" try: expr = re.compile(s, re.DOTALL) - except re.error, e: + except re.error as e: msg = "Regular expression error in %s: %s" raise re.error(msg % (repr(s), e[0])) if expr.match(lines): @@ -506,7 +506,7 @@ def diff_re(a, b, fromfile='', tofile='', s = "^" + aline + "$" try: expr = re.compile(s) - except re.error, e: + except re.error as e: msg = "Regular expression error in %s: %s" raise re.error(msg % (repr(s), e[0])) if not expr.search(bline): @@ -722,7 +722,7 @@ class Popen(subprocess.Popen): (errCode, written) = WriteFile(x, input) except ValueError: return self._close('stdin') - except (subprocess.pywintypes.error, Exception), why: + except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): return self._close('stdin') raise @@ -743,7 +743,7 @@ class Popen(subprocess.Popen): (errCode, read) = ReadFile(x, nAvail, None) except ValueError: return self._close(which) - except (subprocess.pywintypes.error, Exception), why: + except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): return self._close(which) raise @@ -762,7 +762,7 @@ class Popen(subprocess.Popen): try: written = os.write(self.stdin.fileno(), input) - except OSError, why: + except OSError as why: if why[0] == errno.EPIPE: #broken pipe return self._close('stdin') raise diff --git a/media/webrtc/trunk/tools/gyp/test/lib/TestCommon.py b/media/webrtc/trunk/tools/gyp/test/lib/TestCommon.py index 2dc3858970..a85ca9857a 100644 --- a/media/webrtc/trunk/tools/gyp/test/lib/TestCommon.py +++ b/media/webrtc/trunk/tools/gyp/test/lib/TestCommon.py @@ -468,7 +468,7 @@ class TestCommon(TestCmd): kw) except KeyboardInterrupt: raise - except Exception, e: + except Exception as e: print(self.banner('STDOUT ')) try: print(self.stdout()) diff --git a/media/webrtc/trunk/tools/gyp/test/lib/TestWin.py b/media/webrtc/trunk/tools/gyp/test/lib/TestWin.py index 7627197b1f..2234253a35 100644 --- a/media/webrtc/trunk/tools/gyp/test/lib/TestWin.py +++ b/media/webrtc/trunk/tools/gyp/test/lib/TestWin.py @@ -63,7 +63,7 @@ class Registry(object): text = None try: text = self._QueryBase('Sysnative', key, value) - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: text = self._QueryBase('System32', key, value) else: diff --git a/media/webrtc/trunk/webrtc/tools/barcode_tools/barcode_decoder.py b/media/webrtc/trunk/webrtc/tools/barcode_tools/barcode_decoder.py index 5ea2e63367..510058459c 100755 --- a/media/webrtc/trunk/webrtc/tools/barcode_tools/barcode_decoder.py +++ b/media/webrtc/trunk/webrtc/tools/barcode_tools/barcode_decoder.py @@ -52,7 +52,7 @@ def convert_yuv_to_png_files(yuv_file_name, yuv_frame_width, yuv_frame_height, print(' '.join(command)) helper_functions.run_shell_command( command, fail_msg='Error during YUV to PNG conversion') - except helper_functions.HelperError, err: + except helper_functions.HelperError as err: print('Error executing command: %s. Error: %s' % (command, err)) return False except OSError: @@ -106,7 +106,7 @@ def _decode_barcode_in_file(file_name, command_line_decoder): text_file = open('%s.txt' % file_name[:-4], 'w') text_file.write(out) text_file.close() - except helper_functions.HelperError, err: + except helper_functions.HelperError as err: print('Barcode in %s cannot be decoded.' % file_name) print(err) return False diff --git a/python/blessings/blessings/tests.py b/python/blessings/blessings/tests.py index a02a3924a8..7c755d6229 100644 --- a/python/blessings/blessings/tests.py +++ b/python/blessings/blessings/tests.py @@ -206,22 +206,22 @@ def test_nice_formatting_errors(): t = TestTerminal() try: t.bold_misspelled('hey') - except TypeError, e: + except TypeError as e: assert 'probably misspelled' in e.args[0] try: t.bold_misspelled(u'hey') # unicode - except TypeError, e: + except TypeError as e: assert 'probably misspelled' in e.args[0] try: t.bold_misspelled(None) # an arbitrary non-string - except TypeError, e: + except TypeError as e: assert 'probably misspelled' not in e.args[0] try: t.bold_misspelled('a', 'b') # >1 string arg - except TypeError, e: + except TypeError as e: assert 'probably misspelled' not in e.args[0] diff --git a/python/compare-locales/compare_locales/checks.py b/python/compare-locales/compare_locales/checks.py index 810de8519e..474757843a 100644 --- a/python/compare-locales/compare_locales/checks.py +++ b/python/compare-locales/compare_locales/checks.py @@ -95,7 +95,7 @@ class PropertiesChecker(Checker): def checkPrintf(self, refSpecs, l10nValue): try: l10nSpecs = self.getPrintfSpecs(l10nValue) - except PrintfException, e: + except PrintfException as e: yield ('error', e.pos, e.msg, 'printf') return if refSpecs != l10nSpecs: @@ -253,7 +253,7 @@ class DTDChecker(Checker): parser.parse(StringIO(self.tmpl % (refEnt.all.encode('utf-8') + entities, '&%s;' % refEnt.key.encode('utf-8')))) - except sax.SAXParseException, e: + except sax.SAXParseException as e: yield ('warning', (0, 0), "can't parse en-US value", 'xmlparse') @@ -275,7 +275,7 @@ class DTDChecker(Checker): parser.parse(StringIO(self.tmpl % ( l10nEnt.all.encode('utf-8') + _entities, '&%s;' % l10nEnt.key.encode('utf-8')))) - except sax.SAXParseException, e: + except sax.SAXParseException as e: # xml parse error, yield error # sometimes, the error is reported on our fake closing # element, make that the end of the last line diff --git a/python/compare-locales/compare_locales/commands.py b/python/compare-locales/compare_locales/commands.py index 3104fb271f..ecf2aaae55 100644 --- a/python/compare-locales/compare_locales/commands.py +++ b/python/compare-locales/compare_locales/commands.py @@ -109,7 +109,7 @@ Be careful to specify the right merge directory when using this option."""), try: observer = compareApp(app, merge_stage=options.merge, clobber=options.clobber) - except (OSError, IOError), exc: + except (OSError, IOError) as exc: print("FAIL: " + str(exc)) self.parser.exit(2) return observer diff --git a/python/compare-locales/compare_locales/compare.py b/python/compare-locales/compare_locales/compare.py index b2700d8384..2333c0299b 100644 --- a/python/compare-locales/compare_locales/compare.py +++ b/python/compare-locales/compare_locales/compare.py @@ -448,7 +448,7 @@ class ContentComparer: # we didn't parse this before try: p.readContents(ref_file.getContents()) - except Exception, e: + except Exception as e: self.notify('error', ref_file, str(e)) return self.reference[ref_file] = p.parse() @@ -458,7 +458,7 @@ class ContentComparer: try: p.readContents(l10n.getContents()) l10n_entities, l10n_map = p.parse() - except Exception, e: + except Exception as e: self.notify('error', l10n, str(e)) return lines = [] @@ -573,7 +573,7 @@ class ContentComparer: try: p.readContents(f.getContents()) entities, map = p.parse() - except Exception, e: + except Exception as e: self.notify('error', f, str(e)) return self.notify('missingInFiles', missing, len(map)) diff --git a/python/compare-locales/compare_locales/parser.py b/python/compare-locales/compare_locales/parser.py index 10fd32d942..7bd53f79e5 100644 --- a/python/compare-locales/compare_locales/parser.py +++ b/python/compare-locales/compare_locales/parser.py @@ -122,7 +122,7 @@ class Parser: f = codecs.open(file, 'r', self.encoding) try: self.contents = f.read() - except UnicodeDecodeError, e: + except UnicodeDecodeError as e: (logging.getLogger('locales') .error("Can't read file: " + file + '; ' + str(e))) self.contents = u'' diff --git a/python/compare-locales/compare_locales/webapps.py b/python/compare-locales/compare_locales/webapps.py index 5cc4d638d9..4181668255 100644 --- a/python/compare-locales/compare_locales/webapps.py +++ b/python/compare-locales/compare_locales/webapps.py @@ -80,7 +80,7 @@ class Manifest(object): def load_and_parse(self): try: manifest = json.load(open(self.file.fullpath)) - except (ValueError, IOError), e: + except (ValueError, IOError) as e: if self.watcher: self.watcher.notify('error', self.file, str(e)) return False diff --git a/python/configobj/configobj.py b/python/configobj/configobj.py index bc049a0ae8..fc39fe191e 100644 --- a/python/configobj/configobj.py +++ b/python/configobj/configobj.py @@ -1641,7 +1641,7 @@ class ConfigObj(Section): comment = '' try: value = unrepr(value) - except Exception, e: + except Exception as e: if type(e) == UnknownType: msg = 'Unknown name or type in value at line %s.' else: @@ -1654,7 +1654,7 @@ class ConfigObj(Section): comment = '' try: value = unrepr(value) - except Exception, e: + except Exception as e: if isinstance(e, UnknownType): msg = 'Unknown name or type in value at line %s.' else: @@ -1929,11 +1929,11 @@ class ConfigObj(Section): raise_errors=True, file_error=True, _inspec=True) - except ConfigObjError, e: + except ConfigObjError as e: # FIXME: Should these errors have a reference # to the already parsed ConfigObj ? raise ConfigspecError('Parsing configspec failed: %s' % e) - except IOError, e: + except IOError as e: raise IOError('Reading configspec failed: %s' % e) self.configspec = configspec @@ -2189,7 +2189,7 @@ class ConfigObj(Section): val, missing=missing ) - except validator.baseErrorClass, e: + except validator.baseErrorClass as e: if not preserve_errors or isinstance(e, self._vdtMissingValue): out[entry] = False else: diff --git a/python/configobj/validate.py b/python/configobj/validate.py index 4f587e7ae0..ff724cef90 100644 --- a/python/configobj/validate.py +++ b/python/configobj/validate.py @@ -739,7 +739,7 @@ def _is_num_param(names, values, to_float=False): elif isinstance(val, (int, long, float, basestring)): try: out_params.append(fun(val)) - except ValueError, e: + except ValueError as e: raise VdtParamError(name, val) else: raise VdtParamError(name, val) @@ -1292,7 +1292,7 @@ def is_mixed_list(value, *args): raise VdtValueTooLongError(value) try: return [fun_dict[arg](val) for arg, val in zip(args, value)] - except KeyError, e: + except KeyError as e: raise VdtParamError('mixed_list', e) diff --git a/python/mozbuild/mozbuild/doctor.py b/python/mozbuild/mozbuild/doctor.py index 81db9f851c..c5e3c710c2 100644 --- a/python/mozbuild/mozbuild/doctor.py +++ b/python/mozbuild/mozbuild/doctor.py @@ -212,7 +212,7 @@ class Doctor(object): fsutil_output = subprocess.check_output(command) status = 'GOOD, FIXED' desc = 'lastaccess disabled systemwide' - except subprocess.CalledProcessError, e: + except subprocess.CalledProcessError as e: desc = 'lastaccess enabled systemwide' if e.output.find('denied') != -1: status = 'BAD, FIX DENIED' diff --git a/python/mozbuild/mozbuild/jar.py b/python/mozbuild/mozbuild/jar.py index f38b066059..b0d8219a9d 100644 --- a/python/mozbuild/mozbuild/jar.py +++ b/python/mozbuild/mozbuild/jar.py @@ -372,7 +372,7 @@ class JarMaker(object): jarfilepath = jarfile + '.jar' try: os.makedirs(os.path.dirname(jarfilepath)) - except OSError, error: + except OSError as error: if error.errno != errno.EEXIST: raise jf = ZipFile(jarfilepath, 'a', lock=True) @@ -514,7 +514,7 @@ class JarMaker(object): # remove previous link or file try: os.remove(out) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise return open(out, 'wb') @@ -525,7 +525,7 @@ class JarMaker(object): if not os.path.isdir(outdir): try: os.makedirs(outdir) - except OSError, error: + except OSError as error: if error.errno != errno.EEXIST: raise return out @@ -541,7 +541,7 @@ class JarMaker(object): # remove previous link or file try: os.remove(out) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise if sys.platform != 'win32': diff --git a/python/mozbuild/mozbuild/util.py b/python/mozbuild/mozbuild/util.py index c9d4742d9d..8340875726 100644 --- a/python/mozbuild/mozbuild/util.py +++ b/python/mozbuild/mozbuild/util.py @@ -152,7 +152,7 @@ def ensureParentDir(path): if d and not os.path.exists(path): try: os.makedirs(d) - except OSError, error: + except OSError as error: if error.errno != errno.EEXIST: raise diff --git a/python/pyyaml/lib/yaml/constructor.py b/python/pyyaml/lib/yaml/constructor.py index e30a04586a..f74d4f1493 100644 --- a/python/pyyaml/lib/yaml/constructor.py +++ b/python/pyyaml/lib/yaml/constructor.py @@ -127,7 +127,7 @@ class BaseConstructor(object): key = self.construct_object(key_node, deep=deep) try: hash(key) - except TypeError, exc: + except TypeError as exc: raise ConstructorError("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) value = self.construct_object(value_node, deep=deep) @@ -285,7 +285,7 @@ class SafeConstructor(BaseConstructor): value = self.construct_scalar(node) try: return str(value).decode('base64') - except (binascii.Error, UnicodeEncodeError), exc: + except (binascii.Error, UnicodeEncodeError) as exc: raise ConstructorError(None, None, "failed to decode base64 data: %s" % exc, node.start_mark) @@ -487,7 +487,7 @@ class Constructor(SafeConstructor): "expected non-empty name appended to the tag", mark) try: __import__(name) - except ImportError, exc: + except ImportError as exc: raise ConstructorError("while constructing a Python module", mark, "cannot find module %r (%s)" % (name.encode('utf-8'), exc), mark) return sys.modules[name] @@ -503,7 +503,7 @@ class Constructor(SafeConstructor): object_name = name try: __import__(module_name) - except ImportError, exc: + except ImportError as exc: raise ConstructorError("while constructing a Python object", mark, "cannot find module %r (%s)" % (module_name.encode('utf-8'), exc), mark) module = sys.modules[module_name] diff --git a/python/pyyaml/lib/yaml/reader.py b/python/pyyaml/lib/yaml/reader.py index 3249e6b9f5..079d03e2ed 100644 --- a/python/pyyaml/lib/yaml/reader.py +++ b/python/pyyaml/lib/yaml/reader.py @@ -155,7 +155,7 @@ class Reader(object): try: data, converted = self.raw_decode(self.raw_buffer, 'strict', self.eof) - except UnicodeDecodeError, exc: + except UnicodeDecodeError as exc: character = exc.object[exc.start] if self.stream is not None: position = self.stream_pointer-len(self.raw_buffer)+exc.start diff --git a/python/pyyaml/lib/yaml/scanner.py b/python/pyyaml/lib/yaml/scanner.py index 53042fca67..6041c0f1d2 100644 --- a/python/pyyaml/lib/yaml/scanner.py +++ b/python/pyyaml/lib/yaml/scanner.py @@ -1424,7 +1424,7 @@ class Scanner(object): self.forward(2) try: value = unicode(''.join(bytes), 'utf-8') - except UnicodeDecodeError, exc: + except UnicodeDecodeError as exc: raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark) return value diff --git a/python/which/which.py b/python/which/which.py index 7da0512521..b2a66d0922 100644 --- a/python/which/which.py +++ b/python/which/which.py @@ -280,7 +280,7 @@ def main(argv): try: optlist, args = getopt.getopt(argv[1:], 'haVvqp:e:', ['help', 'all', 'version', 'verbose', 'quiet', 'path=', 'exts=']) - except getopt.GetoptError, msg: + except getopt.GetoptError as msg: sys.stderr.write("which: error: %s. Your invocation was: %s\n"\ % (msg, argv)) sys.stderr.write("Try 'which --help'.\n") diff --git a/security/nss/gtests/google_test/gtest/scripts/upload.py b/security/nss/gtests/google_test/gtest/scripts/upload.py index 30e07b5a91..b36ed8da1b 100755 --- a/security/nss/gtests/google_test/gtest/scripts/upload.py +++ b/security/nss/gtests/google_test/gtest/scripts/upload.py @@ -94,7 +94,7 @@ def GetEmail(prompt): last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email - except IOError, e: + except IOError as e: pass email = raw_input(prompt + ": ").strip() if email: @@ -102,7 +102,7 @@ def GetEmail(prompt): last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() - except IOError, e: + except IOError as e: pass else: email = last_email @@ -218,7 +218,7 @@ class AbstractRpcServer(object): response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) @@ -243,7 +243,7 @@ class AbstractRpcServer(object): (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: response = e if (response.code != 302 or response.info()["location"] != continue_location): @@ -270,7 +270,7 @@ class AbstractRpcServer(object): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) - except ClientLoginError, e: + except ClientLoginError as e: if e.reason == "BadAuthentication": print("Invalid username or password.", file=sys.stderr) continue @@ -342,7 +342,7 @@ class AbstractRpcServer(object): response = f.read() f.close() return response - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if tries > 3: raise elif e.code == 401: @@ -1238,7 +1238,8 @@ def GuessVCS(options): out, returncode = RunShellWithReturnCode(["hg", "root"]) if returncode == 0: return MercurialVCS(options, out.strip()) - except OSError, (errno, message): + except OSError as e: + errno, message = e.args if errno != 2: # ENOENT -- they don't have hg installed. raise @@ -1254,7 +1255,8 @@ def GuessVCS(options): "--is-inside-work-tree"]) if returncode == 0: return GitVCS(options) - except OSError, (errno, message): + except OSError as e: + errno, message = e.args if errno != 2: # ENOENT -- they don't have git installed. raise diff --git a/taskcluster/taskgraph/test/test_transforms_base.py b/taskcluster/taskgraph/test/test_transforms_base.py index 0a0dfcaf29..1b6c2cf1de 100644 --- a/taskcluster/taskgraph/test/test_transforms_base.py +++ b/taskcluster/taskgraph/test/test_transforms_base.py @@ -55,7 +55,7 @@ class TestValidateSchema(unittest.TestCase): try: validate_schema(schema, {'x': 'not-int'}, "pfx") self.fail("no exception raised") - except Exception, e: + except Exception as e: self.failUnless(str(e).startswith("pfx\n")) diff --git a/testing/gtest/rungtests.py b/testing/gtest/rungtests.py index 98753ca1a6..62dc86d116 100644 --- a/testing/gtest/rungtests.py +++ b/testing/gtest/rungtests.py @@ -189,7 +189,7 @@ def main(): options.cwd, symbols_path=options.symbols_path, utility_path=options.utility_path) - except Exception, e: + except Exception as e: log.error(str(e)) result = False sys.exit(0 if result else 1) diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/_stream_base.py b/testing/mochitest/pywebsocket/mod_pywebsocket/_stream_base.py index 8235666bbb..21a1254ae6 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/_stream_base.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/_stream_base.py @@ -118,7 +118,7 @@ class StreamBase(object): 'Receiving %d byte failed. Peer (%r) closed connection' % (length, (self._request.connection.remote_addr,))) return read_bytes - except socket.error, e: + except socket.error as e: # Catch a socket.error. Because it's not a child class of the # IOError prior to Python 2.6, we cannot omit this except clause. # Use %s rather than %r for the exception to use human friendly @@ -126,7 +126,7 @@ class StreamBase(object): raise ConnectionTerminatedException( 'Receiving %d byte failed. socket.error (%s) occurred' % (length, e)) - except IOError, e: + except IOError as e: # Also catch an IOError because mod_python throws it. raise ConnectionTerminatedException( 'Receiving %d byte failed. IOError (%s) occurred' % @@ -139,7 +139,7 @@ class StreamBase(object): try: self._request.connection.write(bytes_to_write) - except Exception, e: + except Exception as e: util.prepend_message_to_exception( 'Failed to send message to %r: ' % (self._request.connection.remote_addr,), diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/_stream_hybi.py b/testing/mochitest/pywebsocket/mod_pywebsocket/_stream_hybi.py index 104221b4c3..718e8ffa39 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/_stream_hybi.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/_stream_hybi.py @@ -538,7 +538,7 @@ class Stream(StreamBase): # at least one frame is sent. if len(message) <= bytes_written: break - except ValueError, e: + except ValueError as e: raise BadOperationException(e) def _get_message_from_frame(self, frame): @@ -677,7 +677,7 @@ class Stream(StreamBase): if handler: handler(self._request, message) return - except AttributeError, e: + except AttributeError as e: pass self._send_pong(message) @@ -704,7 +704,7 @@ class Stream(StreamBase): break else: inflight_pings.append(expected_body) - except IndexError, e: + except IndexError as e: # The received pong was unsolicited pong. Keep the # ping queue as is. self._ping_queue = inflight_pings @@ -715,7 +715,7 @@ class Stream(StreamBase): handler = self._request.on_pong_handler if handler: handler(self._request, message) - except AttributeError, e: + except AttributeError as e: pass def receive_message(self): @@ -780,7 +780,7 @@ class Stream(StreamBase): # CHARACTER. try: return message.decode('utf-8') - except UnicodeDecodeError, e: + except UnicodeDecodeError as e: raise InvalidUTF8Exception(e) elif self._original_opcode == common.OPCODE_BINARY: return message diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/common.py b/testing/mochitest/pywebsocket/mod_pywebsocket/common.py index 8c15242841..f80734c48c 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/common.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/common.py @@ -233,7 +233,7 @@ def _parse_extension(state): try: _parse_extension_param(state, extension) - except ExtensionParsingException, e: + except ExtensionParsingException as e: raise ExtensionParsingException( 'Failed to parse parameter for %r (%r)' % (extension_token, e)) diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/dispatch.py b/testing/mochitest/pywebsocket/mod_pywebsocket/dispatch.py index 96c91e0c90..2a1ba55fb9 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/dispatch.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/dispatch.py @@ -254,12 +254,12 @@ class Dispatcher(object): do_extra_handshake_ = handler_suite.do_extra_handshake try: do_extra_handshake_(request) - except handshake.AbortedByUserException, e: + except handshake.AbortedByUserException as e: # Re-raise to tell the caller of this function to finish this # connection without sending any error. self._logger.debug('%s', util.get_stack_trace()) raise - except Exception, e: + except Exception as e: util.prepend_message_to_exception( '%s raised exception for %s: ' % ( _DO_EXTRA_HANDSHAKE_HANDLER_NAME, @@ -296,28 +296,28 @@ class Dispatcher(object): if not request.server_terminated: request.ws_stream.close_connection() # Catch non-critical exceptions the handler didn't handle. - except handshake.AbortedByUserException, e: + except handshake.AbortedByUserException as e: self._logger.debug('%s', util.get_stack_trace()) raise - except msgutil.BadOperationException, e: + except msgutil.BadOperationException as e: self._logger.debug('%s', e) request.ws_stream.close_connection( common.STATUS_INTERNAL_ENDPOINT_ERROR) - except msgutil.InvalidFrameException, e: + except msgutil.InvalidFrameException as e: # InvalidFrameException must be caught before # ConnectionTerminatedException that catches InvalidFrameException. self._logger.debug('%s', e) request.ws_stream.close_connection(common.STATUS_PROTOCOL_ERROR) - except msgutil.UnsupportedFrameException, e: + except msgutil.UnsupportedFrameException as e: self._logger.debug('%s', e) request.ws_stream.close_connection(common.STATUS_UNSUPPORTED_DATA) - except stream.InvalidUTF8Exception, e: + except stream.InvalidUTF8Exception as e: self._logger.debug('%s', e) request.ws_stream.close_connection( common.STATUS_INVALID_FRAME_PAYLOAD_DATA) - except msgutil.ConnectionTerminatedException, e: + except msgutil.ConnectionTerminatedException as e: self._logger.debug('%s', e) - except Exception, e: + except Exception as e: # Any other exceptions are forwarded to the caller of this # function. util.prepend_message_to_exception( @@ -379,7 +379,7 @@ class Dispatcher(object): continue try: handler_suite = _source_handler_file(open(path).read()) - except DispatchException, e: + except DispatchException as e: self._source_warnings.append('%s: %s' % (path, e)) continue resource = convert(path) diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/extensions.py b/testing/mochitest/pywebsocket/mod_pywebsocket/extensions.py index 1edd988f61..6ab90ce1ae 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/extensions.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/extensions.py @@ -185,7 +185,7 @@ class DeflateFrameExtensionProcessor(ExtensionProcessorInterface): self._WINDOW_BITS_PARAM) try: window_bits = _parse_window_bits(window_bits) - except ValueError, e: + except ValueError as e: return None no_context_takeover = self._request.has_parameter( @@ -381,7 +381,7 @@ class PerMessageDeflateExtensionProcessor(ExtensionProcessorInterface): try: server_max_window_bits = _parse_window_bits( server_max_window_bits) - except ValueError, e: + except ValueError as e: self._logger.debug('Bad %s parameter: %r', self._SERVER_MAX_WINDOW_BITS_PARAM, e) @@ -717,7 +717,7 @@ class MuxExtensionProcessor(ExtensionProcessorInterface): if quota is not None: try: quota = int(quota) - except ValueError, e: + except ValueError as e: return None if quota < 0 or quota >= 2 ** 32: return None diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/__init__.py b/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/__init__.py index 194f6b395a..707263a69f 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/__init__.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/__init__.py @@ -90,15 +90,15 @@ def do_handshake(request, dispatcher, allowDraft75=False, strict=False): handshaker.do_handshake() _LOGGER.info('Established (%s protocol)', name) return - except HandshakeException, e: + except HandshakeException as e: _LOGGER.debug( 'Failed to complete opening handshake as %s protocol: %r', name, e) if e.status: raise e - except AbortedByUserException, e: + except AbortedByUserException as e: raise - except VersionException, e: + except VersionException as e: raise # TODO(toyoshim): Add a test to cover the case all handshakers fail. diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/_base.py b/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/_base.py index c993a584b7..0af05242bf 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/_base.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/_base.py @@ -111,7 +111,7 @@ def parse_host_header(request): return fields[0], get_default_port(request.is_https()) try: return fields[0], int(fields[1]) - except ValueError, e: + except ValueError as e: raise HandshakeException('Invalid port number format: %r' % e) diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/hybi.py b/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/hybi.py index 824dc10bae..853c928bcb 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/hybi.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/handshake/hybi.py @@ -112,7 +112,7 @@ class Handshaker(object): try: connection_tokens = parse_token_list(connection) - except HandshakeException, e: + except HandshakeException as e: raise HandshakeException( 'Failed to parse %s: %s' % (common.CONNECTION_HEADER, e)) @@ -270,7 +270,7 @@ class Handshaker(object): 'request any subprotocol') self._send_handshake(accept) - except HandshakeException, e: + except HandshakeException as e: if not e.status: # Fallback to 400 bad request by default. e.status = common.HTTP_STATUS_BAD_REQUEST @@ -327,7 +327,7 @@ class Handshaker(object): try: self._request.ws_requested_extensions = common.parse_extensions( extensions_header) - except common.ExtensionParsingException, e: + except common.ExtensionParsingException as e: raise HandshakeException( 'Failed to parse Sec-WebSocket-Extensions header: %r' % e) @@ -353,7 +353,7 @@ class Handshaker(object): decoded_key = base64.b64decode(key) if len(decoded_key) == 16: key_is_valid = True - except TypeError, e: + except TypeError as e: pass if not key_is_valid: diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/headerparserhandler.py b/testing/mochitest/pywebsocket/mod_pywebsocket/headerparserhandler.py index c244421cf7..bfee5c3359 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/headerparserhandler.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/headerparserhandler.py @@ -199,7 +199,7 @@ def headerparserhandler(request): request.log_error( 'mod_pywebsocket: Fallback to Apache', apache.APLOG_INFO) return apache.DECLINED - except dispatch.DispatchException, e: + except dispatch.DispatchException as e: request.log_error( 'mod_pywebsocket: Dispatch failed for error: %s' % e, apache.APLOG_INFO) @@ -215,14 +215,14 @@ def headerparserhandler(request): try: handshake.do_handshake( request, _dispatcher, allowDraft75=allow_draft75) - except handshake.VersionException, e: + except handshake.VersionException as e: request.log_error( 'mod_pywebsocket: Handshake failed for version error: %s' % e, apache.APLOG_INFO) request.err_headers_out.add(common.SEC_WEBSOCKET_VERSION_HEADER, e.supported_versions) return apache.HTTP_BAD_REQUEST - except handshake.HandshakeException, e: + except handshake.HandshakeException as e: # Handshake for ws/wss failed. # Send http response with error status. request.log_error( @@ -233,9 +233,9 @@ def headerparserhandler(request): handshake_is_done = True request._dispatcher = _dispatcher _dispatcher.transfer_data(request) - except handshake.AbortedByUserException, e: + except handshake.AbortedByUserException as e: request.log_error('mod_pywebsocket: Aborted: %s' % e, apache.APLOG_INFO) - except Exception, e: + except Exception as e: # DispatchException can also be thrown if something is wrong in # pywebsocket code. It's caught here, then. diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/http_header_util.py b/testing/mochitest/pywebsocket/mod_pywebsocket/http_header_util.py index b774653932..cb3aa29e24 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/http_header_util.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/http_header_util.py @@ -230,7 +230,7 @@ def parse_uri(uri): port = None try: port = parsed.port - except ValueError, e: + except ValueError as e: # port property cause ValueError on invalid null port description like # 'ws://host:/path'. return None, None, None @@ -254,7 +254,7 @@ def parse_uri(uri): try: urlparse.uses_netloc.index('ws') -except ValueError, e: +except ValueError as e: # urlparse in Python2.5.1 doesn't have 'ws' and 'wss' entries. urlparse.uses_netloc.append('ws') urlparse.uses_netloc.append('wss') diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/mux.py b/testing/mochitest/pywebsocket/mod_pywebsocket/mux.py index 02528b645c..7eed4e118d 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/mux.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/mux.py @@ -353,7 +353,7 @@ class _MuxFramePayloadParser(object): try: size = self._read_number() - except ValueError, e: + except ValueError as e: raise PhysicalConnectionError(_DROP_CODE_INVALID_MUX_CONTROL_BLOCK, str(e)) pos = self._read_position @@ -376,7 +376,7 @@ class _MuxFramePayloadParser(object): encoding = first_byte & 0x3 try: control_block.channel_id = self.read_channel_id() - except ValueError, e: + except ValueError as e: raise PhysicalConnectionError(_DROP_CODE_INVALID_MUX_CONTROL_BLOCK) control_block.encoding = encoding encoded_handshake = self._read_size_and_contents() @@ -394,7 +394,7 @@ class _MuxFramePayloadParser(object): control_block.encoding = first_byte & 0x3 try: control_block.channel_id = self.read_channel_id() - except ValueError, e: + except ValueError as e: raise PhysicalConnectionError(_DROP_CODE_INVALID_MUX_CONTROL_BLOCK) control_block.encoded_handshake = self._read_size_and_contents() return control_block @@ -409,7 +409,7 @@ class _MuxFramePayloadParser(object): try: control_block.channel_id = self.read_channel_id() control_block.send_quota = self._read_number() - except ValueError, e: + except ValueError as e: raise PhysicalConnectionError(_DROP_CODE_INVALID_MUX_CONTROL_BLOCK, str(e)) @@ -424,7 +424,7 @@ class _MuxFramePayloadParser(object): try: control_block.channel_id = self.read_channel_id() - except ValueError, e: + except ValueError as e: raise PhysicalConnectionError(_DROP_CODE_INVALID_MUX_CONTROL_BLOCK) reason = self._read_size_and_contents() if len(reason) == 0: @@ -449,7 +449,7 @@ class _MuxFramePayloadParser(object): try: control_block.slots = self._read_number() control_block.send_quota = self._read_number() - except ValueError, e: + except ValueError as e: raise PhysicalConnectionError(_DROP_CODE_INVALID_MUX_CONTROL_BLOCK, str(e)) return control_block @@ -921,7 +921,7 @@ class _LogicalStream(Stream): opcode = common.OPCODE_CONTINUATION - except ValueError, e: + except ValueError as e: raise BadOperationException(e) finally: self._write_inner_frame_semaphore.release() @@ -1029,7 +1029,7 @@ class _LogicalStream(Stream): # connection has closed gracefully. try: return Stream.receive_message(self) - except LogicalConnectionClosedException, e: + except LogicalConnectionClosedException as e: self._logger.debug('%s', e) return None @@ -1144,7 +1144,7 @@ class _PhysicalConnectionWriter(threading.Thread): try: self._mux_handler.physical_stream.send_message( message=message, end=True, binary=True) - except Exception, e: + except Exception as e: util.prepend_message_to_exception( 'Failed to send message to %r: ' % (self._mux_handler.physical_connection.remote_addr,), e) @@ -1185,7 +1185,7 @@ class _PhysicalConnectionWriter(threading.Thread): # by the reader thread. self._mux_handler.physical_stream.close_connection( self._close_code, wait_response=False) - except Exception, e: + except Exception as e: util.prepend_message_to_exception( 'Failed to close the physical connection: %r' % e) raise @@ -1233,20 +1233,20 @@ class _PhysicalConnectionReader(threading.Thread): 'Received a text message on physical connection') break - except ConnectionTerminatedException, e: + except ConnectionTerminatedException as e: self._logger.debug('%s', e) break try: self._mux_handler.dispatch_message(message) - except PhysicalConnectionError, e: + except PhysicalConnectionError as e: self._mux_handler.fail_physical_connection( e.drop_code, e.message) break - except LogicalChannelError, e: + except LogicalChannelError as e: self._mux_handler.fail_logical_channel( e.channel_id, e.drop_code, e.message) - except Exception, e: + except Exception as e: self._logger.debug(traceback.format_exc()) break @@ -1278,7 +1278,7 @@ class _Worker(threading.Thread): try: # Non-critical exceptions will be handled by dispatcher. self._mux_handler.dispatcher.transfer_data(self._request) - except LogicalChannelError, e: + except LogicalChannelError as e: self._mux_handler.fail_logical_channel( e.channel_id, e.drop_code, e.message) finally: @@ -1621,19 +1621,19 @@ class _MuxHandler(object): send_quota, receive_quota) try: handshaker.do_handshake() - except handshake.VersionException, e: + except handshake.VersionException as e: self._logger.info('%s', e) self._send_error_add_channel_response( request.channel_id, status=common.HTTP_STATUS_BAD_REQUEST) return False - except handshake.HandshakeException, e: + except handshake.HandshakeException as e: # TODO(bashi): Should we _Fail the Logical Channel_ with 3001 # instead? self._logger.info('%s', e) self._send_error_add_channel_response(request.channel_id, status=e.status) return False - except handshake.AbortedByUserException, e: + except handshake.AbortedByUserException as e: self._logger.info('%s', e) self._send_error_add_channel_response(request.channel_id) return False @@ -1660,7 +1660,7 @@ class _MuxHandler(object): def _process_add_channel_request(self, block): try: logical_request = self._create_logical_request(block) - except ValueError, e: + except ValueError as e: self._logger.debug('Failed to create logical request: %r' % e) self._send_error_add_channel_response( block.channel_id, status=common.HTTP_STATUS_BAD_REQUEST) @@ -1767,7 +1767,7 @@ class _MuxHandler(object): parser = _MuxFramePayloadParser(message) try: channel_id = parser.read_channel_id() - except ValueError, e: + except ValueError as e: raise PhysicalConnectionError(_DROP_CODE_CHANNEL_ID_TRUNCATED) if channel_id == _CONTROL_CHANNEL_ID: self._process_control_blocks(parser) diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/xhr_benchmark_handler.py b/testing/mochitest/pywebsocket/mod_pywebsocket/xhr_benchmark_handler.py index 6735c7e2a3..dd227a410b 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/xhr_benchmark_handler.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/xhr_benchmark_handler.py @@ -60,7 +60,7 @@ class XHRBenchmarkHandler(object): bytes_to_send = request_array[0] try: bytes_to_send = int(bytes_to_send) - except ValueError, e: + except ValueError as e: self._logger.debug('Malformed size parameter: %r', bytes_to_send) return self._logger.debug('Requested to send %s bytes', bytes_to_send) diff --git a/testing/mochitest/pywebsocket/standalone.py b/testing/mochitest/pywebsocket/standalone.py index e176327439..2b65cec9d2 100755 --- a/testing/mochitest/pywebsocket/standalone.py +++ b/testing/mochitest/pywebsocket/standalone.py @@ -347,7 +347,8 @@ class _StandaloneSSLConnection(object): try: return self._connection.recv(bufsize) - except OpenSSL.SSL.SysCallError, (err, message): + except OpenSSL.SSL.SysCallError as e: + err, message = e.args if err == -1: # Suppress "unexpected EOF" exception. See the OpenSSL document # for SSL_get_error. @@ -375,7 +376,7 @@ def _alias_handlers(dispatcher, websock_handlers_map_file): try: dispatcher.add_resource_path_alias( m.group(1), m.group(2)) - except dispatch.DispatchException, e: + except dispatch.DispatchException as e: logging.error(str(e)) finally: fp.close() @@ -451,7 +452,7 @@ class WebSocketServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): family, socktype, proto, canonname, sockaddr = addrinfo try: socket_ = socket.socket(family, socktype) - except Exception, e: + except Exception as e: self._logger.info('Skip by failure: %r', e) continue server_options = self.websocket_server_options @@ -489,7 +490,7 @@ class WebSocketServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): socket_.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: socket_.bind(self.server_address) - except Exception, e: + except Exception as e: self._logger.info('Skip by failure: %r', e) socket_.close() failed_sockets.append(socketinfo) @@ -518,7 +519,7 @@ class WebSocketServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): self._logger.info('Listen on: %r', addrinfo) try: socket_.listen(self.request_queue_size) - except Exception, e: + except Exception as e: self._logger.info('Skip by failure: %r', e) socket_.close() failed_sockets.append(socketinfo) @@ -569,7 +570,7 @@ class WebSocketServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): if server_options.tls_module == _TLS_BY_STANDARD_MODULE: try: accepted_socket.do_handshake() - except ssl.SSLError, e: + except ssl.SSLError as e: self._logger.debug('%r', e) raise @@ -608,7 +609,7 @@ class WebSocketServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): # TODO(tyoshino): Convert all kinds of errors. try: accepted_socket.do_handshake() - except OpenSSL.SSL.Error, e: + except OpenSSL.SSL.Error as e: # Set errno part to 1 (SSL_ERROR_SSL) like the ssl module # does. self._logger.debug('%r', e) @@ -772,7 +773,7 @@ class WebSocketRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler): self.path) self._logger.info('Fallback to CGIHTTPRequestHandler') return True - except dispatch.DispatchException, e: + except dispatch.DispatchException as e: self._logger.info('Dispatch failed for error: %s', e) self.send_error(e.status) return False @@ -788,14 +789,14 @@ class WebSocketRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler): self._options.dispatcher, allowDraft75=self._options.allow_draft75, strict=self._options.strict) - except handshake.VersionException, e: + except handshake.VersionException as e: self._logger.info('Handshake failed for version error: %s', e) self.send_response(common.HTTP_STATUS_BAD_REQUEST) self.send_header(common.SEC_WEBSOCKET_VERSION_HEADER, e.supported_versions) self.end_headers() return False - except handshake.HandshakeException, e: + except handshake.HandshakeException as e: # Handshake for ws(s) failed. self._logger.info('Handshake failed for error: %s', e) self.send_error(e.status) @@ -803,7 +804,7 @@ class WebSocketRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler): request._dispatcher = self._options.dispatcher self._options.dispatcher.transfer_data(request) - except handshake.AbortedByUserException, e: + except handshake.AbortedByUserException as e: self._logger.info('Aborted: %s', e) return False @@ -1044,7 +1045,7 @@ def _parse_args_and_config(args): if temporary_options.config_file: try: config_fp = open(temporary_options.config_file, 'r') - except IOError, e: + except IOError as e: logging.critical( 'Failed to open configuration file %r: %r', temporary_options.config_file, @@ -1172,7 +1173,7 @@ def _main(args=None): server = WebSocketServer(options) server.serve_forever() - except Exception, e: + except Exception as e: logging.critical('mod_pywebsocket: %s' % e) logging.critical('mod_pywebsocket: %s' % util.get_stack_trace()) sys.exit(1) diff --git a/testing/mochitest/runtests.py b/testing/mochitest/runtests.py index 6e4da8d865..2fc6180c7f 100644 --- a/testing/mochitest/runtests.py +++ b/testing/mochitest/runtests.py @@ -51,7 +51,7 @@ from manifestparser.filters import ( try: from marionette_driver.addons import Addons from marionette_harness import Marionette -except ImportError, e: +except ImportError as e: # Defer ImportError until attempt to use Marionette def reraise(*args, **kwargs): raise(e) diff --git a/testing/mozbase/manifestparser/manifestparser/cli.py b/testing/mozbase/manifestparser/manifestparser/cli.py index 603054afb4..29fdf66088 100644 --- a/testing/mozbase/manifestparser/manifestparser/cli.py +++ b/testing/mozbase/manifestparser/manifestparser/cli.py @@ -81,7 +81,7 @@ class Copy(CLICommand): # parse the arguments try: kwargs, tags, args = parse_args(args) - except ParserError, e: + except ParserError as e: self._parser.error(e.message) # make sure we have some manifests, otherwise it will @@ -146,7 +146,7 @@ class WriteCLI(CLICommand): # parse the arguments try: kwargs, tags, args = parse_args(args) - except ParserError, e: + except ParserError as e: self._parser.error(e.message) # make sure we have some manifests, otherwise it will @@ -190,7 +190,7 @@ class UpdateCLI(CLICommand): # parse the arguments try: kwargs, tags, args = parse_args(args) - except ParserError, e: + except ParserError as e: self._parser.error(e.message) # make sure we have some manifests, otherwise it will diff --git a/testing/mozbase/mozdevice/mozdevice/sutini.py b/testing/mozbase/mozdevice/mozdevice/sutini.py index 9c763fc8e4..1b2145263c 100644 --- a/testing/mozbase/mozdevice/mozdevice/sutini.py +++ b/testing/mozbase/mozdevice/mozdevice/sutini.py @@ -41,7 +41,7 @@ def put_cfg(d, cfg, ini_path): t.close() try: d.pushFile(t.name, ini_path) - except DMError, e: + except DMError as e: print(e) else: print('Done.') @@ -103,7 +103,7 @@ def main(): sys.exit(1) try: d = DroidSUT(host, retryLimit=1) - except DMError, e: + except DMError as e: print(e) sys.exit(1) # check if using Negatus and change path accordingly diff --git a/testing/mozbase/mozinstall/mozinstall/mozinstall.py b/testing/mozbase/mozinstall/mozinstall/mozinstall.py index cf59fbdbe6..3ef69cfe4f 100755 --- a/testing/mozbase/mozinstall/mozinstall/mozinstall.py +++ b/testing/mozbase/mozinstall/mozinstall/mozinstall.py @@ -222,7 +222,7 @@ def uninstall(install_folder): if time.time() > end_time: raise Exception('Failure removing uninstall folder.') - except Exception, ex: + except Exception as ex: cls, exc, trbk = sys.exc_info() error = UninstallError('Failed to uninstall %s (%s)' % (install_folder, str(ex))) raise UninstallError(error).with_traceback(trbk) diff --git a/testing/mozbase/mozprocess/tests/test_mozprocess.py b/testing/mozbase/mozprocess/tests/test_mozprocess.py index d4f4d0f6f1..4a2285c5f9 100644 --- a/testing/mozbase/mozprocess/tests/test_mozprocess.py +++ b/testing/mozbase/mozprocess/tests/test_mozprocess.py @@ -110,7 +110,7 @@ class ProcTest(proctest.ProcTest): processhandler.ProcessHandler([self.proclaunch, "process_normal_finish.ini"], args=["1", "2", "3"], cwd=here) - except TypeError, e: + except TypeError as e: err = e self.assertTrue(err) @@ -128,7 +128,7 @@ class ProcTest(proctest.ProcTest): processhandler.ProcessHandler([self.proclaunch, "process_normal_finish.ini"], args=["1", "2", "3"], cwd=here) - except TypeError, e: + except TypeError as e: err = e self.assertTrue(err) diff --git a/testing/mozbase/mozrunner/mozrunner/devices/android_device.py b/testing/mozbase/mozrunner/mozrunner/devices/android_device.py index 85294abe68..a18f7f521c 100644 --- a/testing/mozbase/mozrunner/mozrunner/devices/android_device.py +++ b/testing/mozbase/mozrunner/mozrunner/devices/android_device.py @@ -662,7 +662,7 @@ def _download_file(url, filename, path): if not os.path.isdir(path): try: os.makedirs(path) - except Exception, e: + except Exception as e: _log_warning(str(e)) return False local_file = open(os.path.join(path, filename), 'wb') @@ -676,7 +676,7 @@ def _get_tooltool_manifest(substs, src_path, dst_path, filename): if not os.path.isdir(dst_path): try: os.makedirs(dst_path) - except Exception, e: + except Exception as e: _log_warning(str(e)) copied = False if substs and 'top_srcdir' in substs: diff --git a/testing/mozbase/mozscreenshot/mozscreenshot/__init__.py b/testing/mozbase/mozscreenshot/mozscreenshot/__init__.py index 468fa8ac38..643ec1a097 100644 --- a/testing/mozbase/mozscreenshot/mozscreenshot/__init__.py +++ b/testing/mozbase/mozscreenshot/mozscreenshot/__init__.py @@ -56,6 +56,6 @@ def dump_screen(utilityPath, log): log.process_exit(utilityname, returncode) else: printstatus(utilityname, returncode) - except OSError, err: + except OSError as err: log.info("Failed to start %s for screenshot: %s" % (utility[0], err.strerror)) diff --git a/testing/mozharness/external_tools/download_file.py b/testing/mozharness/external_tools/download_file.py index c40138997e..00e6cfb8af 100755 --- a/testing/mozharness/external_tools/download_file.py +++ b/testing/mozharness/external_tools/download_file.py @@ -35,19 +35,19 @@ def download_file(url, file_name): got_length += len(block) local_file.close() print("%s downloaded to %s" % (url, file_name)) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: print("Warning: Server returned status %s %s for %s" % (str(e.code), str(e), url)) raise - except urllib2.URLError, e: + except urllib2.URLError as e: print("URL Error: %s" % url) remote_host = urlparse.urlsplit(url)[1] if remote_host: os.system("nslookup %s" % remote_host) raise - except socket.timeout, e: + except socket.timeout as e: print("Timed out accessing %s: %s" % (url, str(e))) raise - except socket.error, e: + except socket.error as e: print("Socket error when accessing %s: %s" % (url, str(e))) raise diff --git a/testing/mozharness/external_tools/mouse_and_screen_resolution.py b/testing/mozharness/external_tools/mouse_and_screen_resolution.py index 1d633c9bc9..d0b73f5999 100755 --- a/testing/mozharness/external_tools/mouse_and_screen_resolution.py +++ b/testing/mozharness/external_tools/mouse_and_screen_resolution.py @@ -29,13 +29,13 @@ def wfetch(url, retries=5): while True: try: return urllib2.urlopen(url, timeout=30).read() - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: print(("Failed to fetch '%s': %s" % (url, str(e)))) - except urllib2.URLError, e: + except urllib2.URLError as e: print(("Failed to fetch '%s': %s" % (url, str(e)))) - except socket.timeout, e: + except socket.timeout as e: print(("Time out accessing %s: %s" % (url, str(e)))) - except socket.error, e: + except socket.error as e: print(("Socket error when accessing %s: %s" % (url, str(e)))) if retries < 0: raise Exception("Could not fetch url '%s'" % url) @@ -74,15 +74,15 @@ def main(): conf_dict = json.loads(wfetch(options.configuration_url)) new_screen_resolution = conf_dict["win7"]["screen_resolution"] new_mouse_position = conf_dict["win7"]["mouse_position"] - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: print("This branch does not seem to have the configuration file %s" % str(e)) print("Let's fail over to 1024x768.") new_screen_resolution = default_screen_resolution new_mouse_position = default_mouse_position - except urllib2.URLError, e: + except urllib2.URLError as e: print("INFRA-ERROR: We couldn't reach hg.mozilla.org: %s" % str(e)) return 1 - except Exception, e: + except Exception as e: print("ERROR: We were not expecting any more exceptions: %s" % str(e)) return 1 @@ -95,7 +95,7 @@ def main(): print("Changing the screen resolution...") try: changeScreenResolution(new_screen_resolution["x"], new_screen_resolution["y"]) - except Exception, e: + except Exception as e: print("INFRA-ERROR: We have attempted to change the screen resolution but " + \ "something went wrong: %s" % str(e)) return 1 diff --git a/testing/mozharness/mozfile/mozfile.py b/testing/mozharness/mozfile/mozfile.py index 862c55abcb..72377d4d10 100644 --- a/testing/mozharness/mozfile/mozfile.py +++ b/testing/mozharness/mozfile/mozfile.py @@ -54,7 +54,7 @@ def extract_zip(src, dest): else: try: bundle = zipfile.ZipFile(src) - except Exception, e: + except Exception as e: print("src: %s" % src) raise diff --git a/testing/mozharness/mozharness/base/config.py b/testing/mozharness/mozharness/base/config.py index 1257b4213b..7a1a2be19d 100644 --- a/testing/mozharness/mozharness/base/config.py +++ b/testing/mozharness/mozharness/base/config.py @@ -182,11 +182,11 @@ def download_config_file(url, file_name): try: contents = urllib2.urlopen(url, timeout=30).read() break - except urllib2.URLError, e: + except urllib2.URLError as e: print("Error downloading from url %s: %s" % (url, str(e))) - except socket.timeout, e: + except socket.timeout as e: print("Time out accessing %s: %s" % (url, str(e))) - except socket.error, e: + except socket.error as e: print("Socket error when accessing %s: %s" % (url, str(e))) print("Sleeping %d seconds before retrying" % sleeptime) time.sleep(sleeptime) @@ -199,7 +199,7 @@ def download_config_file(url, file_name): f = open(file_name, 'w') f.write(contents) f.close() - except IOError, e: + except IOError as e: print("Error writing downloaded contents to file %s: %s" % (file_name, str(e))) raise SystemError(-1) diff --git a/testing/mozharness/mozharness/base/script.py b/testing/mozharness/mozharness/base/script.py index 662317d2b1..5e4a5674ad 100755 --- a/testing/mozharness/mozharness/base/script.py +++ b/testing/mozharness/mozharness/base/script.py @@ -460,10 +460,10 @@ class ScriptMixin(PlatformMixin): got_length += len(block) local_file.close() return file_name - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: self.warning("Server returned status %s %s for %s" % (str(e.code), str(e), url)) raise - except urllib2.URLError, e: + except urllib2.URLError as e: self.warning("URL Error: %s" % url) # Failures due to missing local files won't benefit from retry. @@ -482,10 +482,10 @@ class ScriptMixin(PlatformMixin): self.run_command([nslookup, remote_host], error_list=error_list) raise - except socket.timeout, e: + except socket.timeout as e: self.warning("Timed out accessing %s: %s" % (url, str(e))) raise - except socket.error, e: + except socket.error as e: self.warning("Socket error when accessing %s: %s" % (url, str(e))) raise @@ -768,11 +768,11 @@ class ScriptMixin(PlatformMixin): try: shutil.move(src, dest) # http://docs.python.org/tutorial/errors.html - except IOError, e: + except IOError as e: self.log("IO error: %s" % str(e), level=error_level, exit_code=exit_code) return -1 - except shutil.Error, e: + except shutil.Error as e: self.log("shutil error: %s" % str(e), level=error_level, exit_code=exit_code) return -1 @@ -819,7 +819,7 @@ class ScriptMixin(PlatformMixin): outfile.writelines(infile) outfile.close() infile.close() - except IOError, e: + except IOError as e: self.log("Can't compress %s to %s: %s!" % (src, dest, str(e)), level=error_level) return -1 @@ -827,7 +827,7 @@ class ScriptMixin(PlatformMixin): self.log("Copying %s to %s" % (src, dest), level=log_level) try: shutil.copyfile(src, dest) - except (IOError, shutil.Error), e: + except (IOError, shutil.Error) as e: self.log("Can't copy %s to %s: %s!" % (src, dest, str(e)), level=error_level) return -1 @@ -835,7 +835,7 @@ class ScriptMixin(PlatformMixin): if copystat: try: shutil.copystat(src, dest) - except (IOError, shutil.Error), e: + except (IOError, shutil.Error) as e: self.log("Can't copy attributes of %s to %s: %s!" % (src, dest, str(e)), level=error_level) return -1 @@ -968,7 +968,7 @@ class ScriptMixin(PlatformMixin): self.info("Reading from file %s" % file_path) try: fh = open(file_path, open_mode) - except IOError, err: + except IOError as err: self.log("unable to open %s: %s" % (file_path, err.strerror), level=error_level) yield None, err @@ -1111,7 +1111,7 @@ class ScriptMixin(PlatformMixin): status = action(*args, **kwargs) if good_statuses and status not in good_statuses: retry = True - except retry_exceptions, e: + except retry_exceptions as e: retry = True error_message = "%s\nCaught exception: %s" % (error_message, str(e)) self.log('retry: attempt #%d caught exception: %s' % (n, str(e)), level=INFO) @@ -1390,7 +1390,7 @@ class ScriptMixin(PlatformMixin): break parser.add_lines(line) returncode = p.returncode - except OSError, e: + except OSError as e: level = error_level if halt_on_failure: level = FATAL diff --git a/testing/mozharness/mozharness/base/vcs/mercurial.py b/testing/mozharness/mozharness/base/vcs/mercurial.py index 057ba9842f..de641f5a10 100755 --- a/testing/mozharness/mozharness/base/vcs/mercurial.py +++ b/testing/mozharness/mozharness/base/vcs/mercurial.py @@ -299,7 +299,7 @@ class MercurialVCS(ScriptMixin, LogMixin, TransferMixin): branch = "default" revs.append((rev, branch)) return revs - except subprocess.CalledProcessError, inst: + except subprocess.CalledProcessError as inst: # In some situations, some versions of Mercurial return "1" # if no changes are found, so we need to ignore this return # code @@ -419,7 +419,7 @@ class MercurialVCS(ScriptMixin, LogMixin, TransferMixin): ssh_username=ssh_username, ssh_key=ssh_key) return - except VCSException, e: + except VCSException as e: self.debug("Hit error when trying to push: %s" % str(e)) if n == max_attempts: self.debug("Tried %d times, giving up" % max_attempts) @@ -435,7 +435,7 @@ class MercurialVCS(ScriptMixin, LogMixin, TransferMixin): self.run_command(self.hg + ['rebase'], cwd=localrepo, error_list=HgErrorList, throw_exception=True) - except subprocess.CalledProcessError, e: + except subprocess.CalledProcessError as e: self.debug("Failed to rebase: %s" % str(e)) # clean up any hanging rebase. ignore errors if we aren't # in the middle of a rebase. diff --git a/testing/mozharness/mozharness/mozilla/mapper.py b/testing/mozharness/mozharness/mozilla/mapper.py index c5a2d48959..56f29bcacf 100644 --- a/testing/mozharness/mozharness/mozilla/mapper.py +++ b/testing/mozharness/mozharness/mozilla/mapper.py @@ -55,7 +55,7 @@ class MapperMixin: else: self.warning("Mapper returned a revision of None. Accepting because require_answer is False.") return j['%s_rev' % vcs] - except Exception, err: + except Exception as err: self.warning('Error: %s' % str(err)) if n == attempts: self.fatal('Giving up on %s %s revision for %s.' % (project_name, vcs, rev)) diff --git a/testing/mozharness/mozharness/mozilla/testing/device.py b/testing/mozharness/mozharness/mozilla/testing/device.py index 7d94128cb7..fe0b0a1dc4 100644 --- a/testing/mozharness/mozharness/mozilla/testing/device.py +++ b/testing/mozharness/mozharness/mozilla/testing/device.py @@ -438,7 +438,7 @@ class SUTDeviceHandler(BaseDeviceHandler): self.devicemanager = DeviceManagerSUT(c['device_ip']) # TODO configurable? self.devicemanager.debug = c.get('devicemanager_debug_level', 0) - except ImportError, e: + except ImportError as e: self.fatal("Can't import DeviceManagerSUT! %s\nDid you check out talos?" % str(e)) return self.devicemanager @@ -524,7 +524,7 @@ class SUTDeviceHandler(BaseDeviceHandler): try: dm.sendCMD(['settime %s' % s]) return True - except self.DMError, e: + except self.DMError as e: self.add_device_flag(DEVICE_CANT_SET_TIME) self.fatal("Exception while setting device time: %s" % str(e)) @@ -564,7 +564,7 @@ class SUTDeviceHandler(BaseDeviceHandler): self.info(repr(dm.getInfo('memory'))) self.info(repr(dm.getInfo('uptime'))) self.info(repr(dm.sendCMD(['exec su -c "logcat -d -v time *:W"']))) - except Exception, e: + except Exception as e: self.info("Exception hit while trying to run logcat: %s" % str(e)) self.fatal("Remote Device Error: can't run logcat") except self.DMError: diff --git a/testing/mozharness/mozharness/mozilla/testing/mozpool.py b/testing/mozharness/mozharness/mozilla/testing/mozpool.py index f9da6c1908..74061ed934 100644 --- a/testing/mozharness/mozharness/mozilla/testing/mozpool.py +++ b/testing/mozharness/mozharness/mozilla/testing/mozpool.py @@ -48,7 +48,7 @@ class MozpoolMixin(object): self.MozpoolException = MozpoolException self.MozpoolConflictException = MozpoolConflictException self.mozpool_handler = MozpoolHandler(self.mozpool_api_url, log_obj=self) - except ImportError, e: + except ImportError as e: self.fatal("Can't instantiate MozpoolHandler until mozpoolclient python " "package is installed! (VirtualenvMixin?): \n%s" % str(e)) return self.mozpool_handler @@ -66,7 +66,7 @@ class MozpoolMixin(object): break except self.MozpoolConflictException: self.warning("Device unavailable. Retry#%i.." % retry) - except self.MozpoolException, e: + except self.MozpoolException as e: self.buildbot_status(TBPL_RETRY) self.fatal("We could not request the device: %s" % str(e)) @@ -87,7 +87,7 @@ class MozpoolMixin(object): break except self.MozpoolConflictException: self.warning("Device unavailable. Retry#%i.." % retry) - except self.MozpoolException, e: + except self.MozpoolException as e: self.buildbot_status(TBPL_RETRY) self.fatal("We could not request the device: %s" % str(e)) diff --git a/testing/mozharness/mozharness/mozilla/testing/testbase.py b/testing/mozharness/mozharness/mozilla/testing/testbase.py index c35b44125b..e36d0e70fe 100755 --- a/testing/mozharness/mozharness/mozilla/testing/testbase.py +++ b/testing/mozharness/mozharness/mozilla/testing/testbase.py @@ -331,7 +331,7 @@ class TestingMixin(VirtualenvMixin, BuildbotMixin, ResourceMonitoringMixin, if not self.installer_url: self.installer_url = str(f['name']) self.info("Found installer url %s." % self.installer_url) - except IndexError, e: + except IndexError as e: self.error(str(e)) def find_artifacts_from_taskcluster(self): diff --git a/testing/mozharness/mozprocess/processhandler.py b/testing/mozharness/mozprocess/processhandler.py index 3c522ef788..1e5742749d 100644 --- a/testing/mozharness/mozprocess/processhandler.py +++ b/testing/mozharness/mozprocess/processhandler.py @@ -94,7 +94,7 @@ class ProcessHandlerMixin(object): preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags) - except OSError, e: + except OSError as e: print(args, file=sys.stderr) raise @@ -131,7 +131,7 @@ class ProcessHandlerMixin(object): if not self._ignore_children: try: os.killpg(self.pid, sig) - except BaseException, e: + except BaseException as e: if getattr(e, "errno", None) != 3: # Error 3 is "no such process", which is ok print("Could not kill process, could not find pid: %s, assuming it's already dead" % self.pid, file=sys.stdout) @@ -546,7 +546,7 @@ falling back to not using job objects for managing child processes""", file=sys. if status > 255: return status >> 8 return -status - except OSError, e: + except OSError as e: if getattr(e, "errno", None) != 10: # Error 10 is "no child process", which could indicate normal # close diff --git a/testing/mozharness/scripts/android_emulator_unittest.py b/testing/mozharness/scripts/android_emulator_unittest.py index 32cf6e4a93..bb17819300 100644 --- a/testing/mozharness/scripts/android_emulator_unittest.py +++ b/testing/mozharness/scripts/android_emulator_unittest.py @@ -298,7 +298,7 @@ class AndroidEmulatorTest(BlobUploadMixin, TestingMixin, EmulatorMixin, VCSMixin telnet_ok = True else: self.warning('Unable to connect to port %d' % port) - except socket.error, e: + except socket.error as e: self.info('Trying again after socket error: %s' % str(e)) pass except EOFError: @@ -398,7 +398,7 @@ class AndroidEmulatorTest(BlobUploadMixin, TestingMixin, EmulatorMixin, VCSMixin os.close(tmpfd) self.info("Taking screenshot with %s; saving to %s" % (utility, filename)) subprocess.call([utility, filename], env=self.query_env()) - except OSError, err: + except OSError as err: self.warning("Failed to take screenshot: %s" % err.strerror) def _query_package_name(self): diff --git a/testing/remotecppunittests.py b/testing/remotecppunittests.py index 3c368fd124..92a5023099 100644 --- a/testing/remotecppunittests.py +++ b/testing/remotecppunittests.py @@ -274,7 +274,7 @@ def main(): {"tbpl": sys.stdout}) try: result = run_test_harness(options, args) - except Exception, e: + except Exception as e: log.error(str(e)) result = False sys.exit(0 if result else 1) diff --git a/testing/tools/proxyserver/proxyserver.py b/testing/tools/proxyserver/proxyserver.py index f91c26078a..d1caaf76a7 100644 --- a/testing/tools/proxyserver/proxyserver.py +++ b/testing/tools/proxyserver/proxyserver.py @@ -69,7 +69,7 @@ class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): if content: try: self.wfile.write(content) - except socket.error, e: + except socket.error as e: if options.verbose: print("Got socket error %s" % e) #self.close_connection = 1 @@ -133,7 +133,7 @@ class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): if "Content-Length" not in headers: self.send_header("Content-Length", str(len(content))) self.end_headers() - except socket.error, e: + except socket.error as e: if options.verbose: print("Got socket error %s" % e) return None diff --git a/testing/xpcshell/runxpcshelltests.py b/testing/xpcshell/runxpcshelltests.py index 5f6a8794bd..540e6364d7 100755 --- a/testing/xpcshell/runxpcshelltests.py +++ b/testing/xpcshell/runxpcshelltests.py @@ -1002,7 +1002,7 @@ class XPCShellTests(object): # node did not support ALPN until this version. if version >= LooseVersion("5.0.0"): nodeBin = localPath - except (subprocess.CalledProcessError, OSError), e: + except (subprocess.CalledProcessError, OSError) as e: self.log.error('Could not retrieve node version: %s' % str(e)) if os.getenv('MOZ_ASSUME_NODE_RUNNING', None): @@ -1030,7 +1030,7 @@ class XPCShellTests(object): searchObj = re.search( r'HTTP2 server listening on port (.*)', msg, 0) if searchObj: self.env["MOZHTTP2_PORT"] = searchObj.group(1) - except OSError, e: + except OSError as e: # This occurs if the subprocess couldn't be started self.log.error('Could not run %s server: %s' % (name, str(e))) diff --git a/testing/xpcshell/selftest.py b/testing/xpcshell/selftest.py index 071ab5eda6..68cb419813 100755 --- a/testing/xpcshell/selftest.py +++ b/testing/xpcshell/selftest.py @@ -1041,7 +1041,7 @@ add_test({ try: # The actual return value is never checked because we raise. self.assertTestResult(True) - except Exception, ex: + except Exception as ex: raised = True self.assertEquals(ex.message[0:9], "head file") @@ -1058,7 +1058,7 @@ add_test({ try: self.assertTestResult(True) - except Exception, ex: + except Exception as ex: raised = True self.assertEquals(ex.message[0:9], "tail file") diff --git a/tools/update-packaging/generatesnippet.py b/tools/update-packaging/generatesnippet.py index 75c0af736e..b6b0601419 100644 --- a/tools/update-packaging/generatesnippet.py +++ b/tools/update-packaging/generatesnippet.py @@ -88,7 +88,7 @@ def generateSnippet(abstDistDir, applicationIniFile, locale, c = ConfigParser() try: c.readfp(open(applicationIniFile)) - except IOError, (stderror): + except IOError as stderror: sys.exit(stderror) buildid = c.get("App", "BuildID") appVersion = c.get("App", "Version") @@ -141,7 +141,7 @@ def getFileHashAndSize(filepath): shaObj = sha.new(f.read()) sha1Hash = shaObj.hexdigest() size = os.stat(filepath)[ST_SIZE] - except IOError, (stderror): + except IOError as stderror: sys.exit(stderror) return (sha1Hash, size) diff --git a/tools/update-packaging/make_incremental_updates.py b/tools/update-packaging/make_incremental_updates.py index 3d83ac9526..36facc3610 100755 --- a/tools/update-packaging/make_incremental_updates.py +++ b/tools/update-packaging/make_incremental_updates.py @@ -460,7 +460,7 @@ def decode_filename(filepath): '(?P\w+)(-)(?P\w+\.\w+(\.\w+){0,2})(\.)(?P.+?)(\.)(?P.+?)(\.)(?P\w+)(.mar)', os.path.basename(filepath)) return m.groupdict() - except Exception, exc: + except Exception as exc: try: m = re.search( '(?P.+?)\/(?P.+?)\/(?P\w+)-(?P\w+\.\w+)\.(?P\w+).mar', diff --git a/xpcom/idl-parser/xpidl/xpidl.py b/xpcom/idl-parser/xpidl/xpidl.py index 68040f86b7..45003e8e35 100755 --- a/xpcom/idl-parser/xpidl/xpidl.py +++ b/xpcom/idl-parser/xpidl/xpidl.py @@ -1003,9 +1003,9 @@ class Param(object): try: return self.realtype.nativeType(self.paramtype, **kwargs) - except IDLError, e: + except IDLError as e: raise IDLError(e.message, self.location) - except TypeError, e: + except TypeError as e: raise IDLError("Unexpected parameter attribute", self.location) def toIDL(self):