Bug 1567642 - [lint.flake8] Fix misc flake8 under Python 3 lint issues r=gbrown
authorAndrew Halberstadt <ahalberstadt@mozilla.com>
Tue, 24 Sep 2019 14:44:01 +0000
changeset 494714 bb843f6f9594b817a48166e3621266d4688464dc
parent 494713 39d6726824977bb7560061922ab63bcea5cf0142
child 494715 7527ad7c590be244aa93fdc437baf56af3cd77ab
push id36613
push userrgurzau@mozilla.com
push dateTue, 24 Sep 2019 21:52:37 +0000
treeherdermozilla-central@55f5d719d035 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersgbrown
bugs1567642
milestone71.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1567642 - [lint.flake8] Fix misc flake8 under Python 3 lint issues r=gbrown Differential Revision: https://phabricator.services.mozilla.com/D45417
accessible/xpcom/AccEventGen.py
build/win32/autobinscope.py
js/src/gdb/mozilla/JSString.py
python/mach_commands.py
python/mozboot/mozboot/archlinux.py
python/mozboot/mozboot/base.py
python/mozboot/mozboot/bootstrap.py
python/mozboot/mozboot/solus.py
python/mozrelease/mozrelease/update_verify.py
security/sandbox/test/mac_register_font.py
taskcluster/docker/funsize-update-generator/scripts/funsize.py
testing/marionette/harness/marionette_harness/marionette_test/testcases.py
testing/mochitest/runtests.py
testing/raptor/raptor/output.py
testing/raptor/raptor/profiler/symFileManager.py
testing/talos/talos/profiler/symFileManager.py
testing/tools/mach_test_package_bootstrap.py
testing/tps/create_venv.py
tools/rb/find_leakers.py
tools/rb/fix_linux_stack.py
tools/rb/fix_macosx_stack.py
tools/tryselect/templates.py
xpcom/components/gen_static_components.py
xpcom/idl-parser/xpidl/xpidl.py
--- a/accessible/xpcom/AccEventGen.py
+++ b/accessible/xpcom/AccEventGen.py
@@ -16,19 +16,17 @@ xpidl_dir = mozpath.join(buildconfig.top
                          'xpidl')
 xpidl_cachedir = mozpath.join(buildconfig.topobjdir, 'xpcom', 'idl-parser',
                               'xpidl')
 sys.path.extend([xpidl_dir, xpidl_cachedir])
 import xpidl
 
 # Load the webidl configuration file.
 glbl = {}
-execfile(mozpath.join(buildconfig.topsrcdir,
-                      'dom', 'bindings', 'Bindings.conf'),
-         glbl)
+exec(open(mozpath.join(buildconfig.topsrcdir, 'dom', 'bindings', 'Bindings.conf')).read(), glbl)
 webidlconfig = glbl['DOMInterfaces']
 
 # Instantiate the parser.
 p = xpidl.IDLParser()
 
 
 def findIDL(includePath, interfaceFileName):
     for d in includePath:
@@ -46,17 +44,17 @@ def loadEventIDL(parser, includePath, ev
     idl = p.parse(open(idlFile).read(), idlFile)
     idl.resolve(includePath, p, webidlconfig)
     return idl, idlFile
 
 
 class Configuration:
     def __init__(self, filename):
         config = {}
-        execfile(filename, config)
+        exec(open(filename).read(), config)
         self.simple_events = config.get('simple_events', [])
 
 
 def firstCap(str):
     return str[0].upper() + str[1:]
 
 
 def writeAttributeParams(a):
--- a/build/win32/autobinscope.py
+++ b/build/win32/autobinscope.py
@@ -69,17 +69,17 @@ try:
         "/Checks", "RSA32Check",
         "/Checks", "SafeSEHCheck",
         "/Checks", "SharedSectionCheck",
         # VB6Check triggers a crash in msdia120: bug 1525113
         "/SkippedChecks", "VB6Check",
         "/Checks", "WXCheck"
     ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
-except WindowsError, (errno, strerror):
+except WindowsError, (errno, strerror):  # noqa
     if errno != 2 and errno != 3:
         print("TEST-UNEXPECTED-FAIL | autobinscope.py | Unexpected error %d : %s" (
             errno, strerror))
         sys.exit(0)
     else:
         print("TEST-UNEXPECTED-FAIL | autobinscope.py | Could not locate binscope at location : "
               "%s\n" % binscope_path)
         sys.exit(0)
--- a/js/src/gdb/mozilla/JSString.py
+++ b/js/src/gdb/mozilla/JSString.py
@@ -5,17 +5,17 @@
 # Pretty-printers for SpiderMonkey strings.
 
 import gdb
 import mozilla.prettyprinters
 from mozilla.prettyprinters import ptr_pretty_printer
 
 try:
     chr(10000)  # UPPER RIGHT PENCIL
-except ValueError as exc:  # yuck, we are in Python 2.x, so chr() is 8-bit
+except ValueError:  # yuck, we are in Python 2.x, so chr() is 8-bit
     chr = unichr  # replace with teh unicodes
 
 # Forget any printers from previous loads of this module.
 mozilla.prettyprinters.clear_module_printers(__name__)
 
 
 class JSStringTypeCache(object):
     # Cache information about the JSString type for this objfile.
--- a/python/mach_commands.py
+++ b/python/mach_commands.py
@@ -56,17 +56,17 @@ class MachCommands(MachCommandBase):
         if no_virtualenv:
             python_path = sys.executable
             append_env[b'PYTHONPATH'] = os.pathsep.join(sys.path)
         else:
             self._activate_virtualenv()
             python_path = self.virtualenv_manager.python_path
 
         if exec_file:
-            execfile(exec_file)
+            exec(open(exec_file).read())
             return 0
 
         return self.run_process([python_path] + args,
                                 pass_thru=True,  # Allow user to run Python interactively.
                                 ensure_exit_code=False,  # Don't throw on non-zero exit code.
                                 append_env=append_env)
 
     @Command('python-test', category='testing',
--- a/python/mozboot/mozboot/archlinux.py
+++ b/python/mozboot/mozboot/archlinux.py
@@ -17,17 +17,17 @@ from mozboot.linux_common import (
     SccacheInstall,
     StyloInstall,
 )
 
 # NOTE: This script is intended to be run with a vanilla Python install.  We
 # have to rely on the standard library instead of Python 2+3 helpers like
 # the six module.
 if sys.version_info < (3,):
-    input = raw_input
+    input = raw_input  # noqa
 
 
 class ArchlinuxBootstrapper(NodeInstall, StyloInstall, SccacheInstall,
                             ClangStaticAnalysisInstall, BaseBootstrapper):
     '''Archlinux experimental bootstrapper.'''
 
     SYSTEM_PACKAGES = [
         'autoconf2.13',
--- a/python/mozboot/mozboot/base.py
+++ b/python/mozboot/mozboot/base.py
@@ -13,17 +13,17 @@ import sys
 from distutils.version import LooseVersion
 from mozboot import rust
 
 # NOTE: This script is intended to be run with a vanilla Python install.  We
 # have to rely on the standard library instead of Python 2+3 helpers like
 # the six module.
 if sys.version_info < (3,):
     from urllib2 import urlopen
-    input = raw_input
+    input = raw_input  # noqa
 else:
     from urllib.request import urlopen
 
 
 NO_MERCURIAL = '''
 Could not find Mercurial (hg) in the current shell's path. Try starting a new
 shell and running the bootstrapper again.
 '''
--- a/python/mozboot/mozboot/bootstrap.py
+++ b/python/mozboot/mozboot/bootstrap.py
@@ -12,17 +12,17 @@ import subprocess
 # NOTE: This script is intended to be run with a vanilla Python install.  We
 # have to rely on the standard library instead of Python 2+3 helpers like
 # the six module.
 if sys.version_info < (3,):
     from ConfigParser import (
         Error as ConfigParserError,
         RawConfigParser,
     )
-    input = raw_input
+    input = raw_input  # noqa
 else:
     from configparser import (
         Error as ConfigParserError,
         RawConfigParser,
     )
 
 # Don't forgot to add new mozboot modules to the bootstrap download
 # list in bin/bootstrap.py!
--- a/python/mozboot/mozboot/solus.py
+++ b/python/mozboot/mozboot/solus.py
@@ -14,17 +14,17 @@ from mozboot.linux_common import (
     SccacheInstall,
     StyloInstall,
 )
 
 # NOTE: This script is intended to be run with a vanilla Python install.  We
 # have to rely on the standard library instead of Python 2+3 helpers like
 # the six module.
 if sys.version_info < (3,):
-    input = raw_input
+    input = raw_input  # noqa
 
 
 class SolusBootstrapper(NodeInstall, StyloInstall, SccacheInstall,
                         ClangStaticAnalysisInstall, BaseBootstrapper):
     '''Solus experimental bootstrapper.'''
 
     SYSTEM_PACKAGES = [
         'autoconf213',
--- a/python/mozrelease/mozrelease/update_verify.py
+++ b/python/mozrelease/mozrelease/update_verify.py
@@ -3,16 +3,18 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function
 
 import os
 import re
 
+from six import string_types
+
 from .chunking import getChunk
 
 
 class UpdateVerifyError(Exception):
     pass
 
 
 class UpdateVerifyConfig(object):
@@ -123,19 +125,19 @@ class UpdateVerifyConfig(object):
                    mar_channel_IDs=None, platform=None, updater_package=None):
         """Locales and patch_types can be passed as either a string or a list.
            If a string is passed, they will be converted to a list for internal
            storage"""
         if self.getRelease(build_id, from_path):
             raise UpdateVerifyError(
                 "Couldn't add release identified by build_id '%s' and from_path '%s': "
                 "already exists in config" % (build_id, from_path))
-        if isinstance(locales, basestring):
+        if isinstance(locales, string_types):
             locales = sorted(list(locales.split()))
-        if isinstance(patch_types, basestring):
+        if isinstance(patch_types, string_types):
             patch_types = list(patch_types.split())
         self.releases.append({
             "release": release,
             "build_id": build_id,
             "locales": locales,
             "patch_types": patch_types,
             "from": from_path,
             "ftp_server_from": ftp_server_from,
--- a/security/sandbox/test/mac_register_font.py
+++ b/security/sandbox/test/mac_register_font.py
@@ -4,16 +4,18 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 """
 mac_register_font.py
 
 Mac-specific utility command to register a font file with the OS.
 """
 
+from __future__ import print_function
+
 import CoreText
 import Cocoa
 import argparse
 import sys
 
 
 def main():
     parser = argparse.ArgumentParser()
@@ -36,23 +38,23 @@ def main():
         scopeDesc = "session"
 
     failureCount = 0
     for fontPath in args.file:
         fontURL = Cocoa.NSURL.fileURLWithPath_(fontPath)
         (result, error) = register_or_unregister_font(fontURL,
                                                       args.unregister, scope)
         if result:
-            print ("%sregistered font %s with %s scope" %
-                   (("un" if args.unregister else ""), fontPath, scopeDesc))
+            print("%sregistered font %s with %s scope" %
+                  (("un" if args.unregister else ""), fontPath, scopeDesc))
         else:
-            print ("Failed to %sregister font %s with %s scope" %
-                   (("un" if args.unregister else ""), fontPath, scopeDesc))
+            print("Failed to %sregister font %s with %s scope" %
+                  (("un" if args.unregister else ""), fontPath, scopeDesc))
             if args.verbose:
-                print (error)
+                print(error)
             failureCount += 1
 
     sys.exit(failureCount)
 
 
 def register_or_unregister_font(fontURL, unregister, scope):
     return (CoreText.CTFontManagerUnregisterFontsForURL(fontURL,
                                                         scope, None) if unregister
--- a/taskcluster/docker/funsize-update-generator/scripts/funsize.py
+++ b/taskcluster/docker/funsize-update-generator/scripts/funsize.py
@@ -10,19 +10,17 @@ import aiohttp
 import configparser
 import argparse
 import hashlib
 import json
 import logging
 import os
 import shutil
 import tempfile
-import time
 import requests
-import sh
 from distutils.util import strtobool
 
 import redo
 from scriptworker.utils import retry_async
 from mardor.reader import MarReader
 from mardor.signing import get_keysize
 
 
--- a/testing/marionette/harness/marionette_harness/marionette_test/testcases.py
+++ b/testing/marionette/harness/marionette_harness/marionette_test/testcases.py
@@ -135,17 +135,17 @@ class CommonTestCase(unittest.TestCase):
                     try:
                         self.setUp()
                     except Exception:
                         raise _ExpectedFailure(sys.exc_info())
                 else:
                     self.setUp()
             except SkipTest as e:
                 self._addSkip(result, str(e))
-            except (KeyboardInterrupt, UnresponsiveInstanceException) as e:
+            except (KeyboardInterrupt, UnresponsiveInstanceException):
                 raise
             except _ExpectedFailure as e:
                 expected_failure(result, e.exc_info)
             except Exception:
                 self._enter_pm()
                 result.addError(self, sys.exc_info())
             else:
                 try:
@@ -155,17 +155,17 @@ class CommonTestCase(unittest.TestCase):
                         except Exception:
                             raise _ExpectedFailure(sys.exc_info())
                         raise _UnexpectedSuccess
                     else:
                         testMethod()
                 except self.failureException:
                     self._enter_pm()
                     result.addFailure(self, sys.exc_info())
-                except (KeyboardInterrupt, UnresponsiveInstanceException) as e:
+                except (KeyboardInterrupt, UnresponsiveInstanceException):
                     raise
                 except _ExpectedFailure as e:
                     expected_failure(result, e.exc_info)
                 except _UnexpectedSuccess:
                     addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
                     if addUnexpectedSuccess is not None:
                         addUnexpectedSuccess(self)
                     else:
@@ -183,17 +183,17 @@ class CommonTestCase(unittest.TestCase):
                 try:
                     if self.expected == "fail":
                         try:
                             self.tearDown()
                         except Exception:
                             raise _ExpectedFailure(sys.exc_info())
                     else:
                         self.tearDown()
-                except (KeyboardInterrupt, UnresponsiveInstanceException) as e:
+                except (KeyboardInterrupt, UnresponsiveInstanceException):
                     raise
                 except _ExpectedFailure as e:
                     expected_failure(result, e.exc_info)
                 except Exception:
                     self._enter_pm()
                     result.addError(self, sys.exc_info())
                     success = False
             # Here we could handle doCleanups() instead of calling cleanTest directly
--- a/testing/mochitest/runtests.py
+++ b/testing/mochitest/runtests.py
@@ -51,20 +51,20 @@ from manifestparser.filters import (
     pathprefix,
     subsuite,
     tags,
 )
 
 try:
     from marionette_driver.addons import Addons
     from marionette_harness import Marionette
-except ImportError as e:
+except ImportError as e:  # noqa
     # Defer ImportError until attempt to use Marionette
     def reraise(*args, **kwargs):
-        raise(e)
+        raise(e)  # noqa
     Marionette = reraise
 
 from leaks import ShutdownLeaks, LSANLeaks
 from mochitest_options import (
     MochitestArgumentParser, build_obj, get_default_valgrind_suppression_files
 )
 from mozprofile import Profile
 from mozprofile.cli import parse_preferences, parse_key_value, KeyValueParseError
--- a/testing/raptor/raptor/output.py
+++ b/testing/raptor/raptor/output.py
@@ -1,17 +1,17 @@
 
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # some parts of this originally taken from /testing/talos/talos/output.py
 
 """output raptor test results"""
-from __future__ import absolute_import
+from __future__ import absolute_import, print_function
 
 import filters
 
 import json
 import os
 
 from abc import ABCMeta, abstractmethod
 from logger.logger import RaptorLogger
@@ -805,17 +805,17 @@ class RaptorOutput(PerftestOutput):
                 },{
                   "name": "engine-instantiate",
                   "time": 1263
                 ...
                 }]}
         '''
         _subtests = {}
         data = test.measurements['wasm-godot']
-        print (data)
+        print(data)
         for page_cycle in data:
             for item in page_cycle[0]:
                 # for each pagecycle, build a list of subtests and append all related replicates
                 sub = item['name']
                 if sub not in _subtests.keys():
                     # subtest not added yet, first pagecycle, so add new one
                     _subtests[sub] = {'unit': test.subtest_unit,
                                       'alertThreshold': float(test.alert_threshold),
--- a/testing/raptor/raptor/profiler/symFileManager.py
+++ b/testing/raptor/raptor/profiler/symFileManager.py
@@ -164,17 +164,17 @@ class SymFileManager:
                     # some have the form "address space symbol".
                     # The letter has a meaning, but we ignore it.
                     if line[addressLength + 2] == " ":
                         symbol = line[addressLength + 3:].rstrip()
                     else:
                         symbol = line[addressLength + 1:].rstrip()
                     symbolMap[address] = symbol
                     publicCount += 1
-        except Exception as e:
+        except Exception:
             LogError("Error parsing SYM file " + path)
             return None
 
         logString = "Found " + \
             str(len(symbolMap.keys())) + " unique entries from "
         logString += str(publicCount) + " PUBLIC lines, " + \
             str(funcCount) + " FUNC lines"
         LogTrace(logString)
--- a/testing/talos/talos/profiler/symFileManager.py
+++ b/testing/talos/talos/profiler/symFileManager.py
@@ -164,17 +164,17 @@ class SymFileManager:
                     # some have the form "address space symbol".
                     # The letter has a meaning, but we ignore it.
                     if line[addressLength + 2] == " ":
                         symbol = line[addressLength + 3:].rstrip()
                     else:
                         symbol = line[addressLength + 1:].rstrip()
                     symbolMap[address] = symbol
                     publicCount += 1
-        except Exception as e:
+        except Exception:
             LogError("Error parsing SYM file " + path)
             return None
 
         logString = "Found " + \
             str(len(symbolMap.keys())) + " unique entries from "
         logString += str(publicCount) + " PUBLIC lines, " + \
             str(funcCount) + " FUNC lines"
         LogTrace(logString)
--- a/testing/tools/mach_test_package_bootstrap.py
+++ b/testing/tools/mach_test_package_bootstrap.py
@@ -77,16 +77,22 @@ CATEGORIES = {
                 'These commands are unavailable for your current context, '
                 'run "mach <command>" to see why.',
         'priority': 0,
     }
 }
 
 
 IS_WIN = sys.platform in ('win32', 'cygwin')
+PY3 = sys.version_info[0] == 3
+
+if PY3:
+    text_type = str
+else:
+    text_type = unicode  # noqa
 
 
 def ancestors(path, depth=0):
     """Emit the parent directories of a path."""
     count = 1
     while path and count != depth:
         yield path
         newpath = os.path.dirname(path)
@@ -103,19 +109,19 @@ def activate_mozharness_venv(context):
 
     if not os.path.isdir(venv):
         print("No mozharness virtualenv detected at '{}'.".format(venv))
         return 1
 
     venv_bin = os.path.join(venv, 'Scripts' if IS_WIN else 'bin')
     activate_path = os.path.join(venv_bin, 'activate_this.py')
 
-    execfile(activate_path, dict(__file__=activate_path))
+    exec(open(activate_path).read(), dict(__file__=activate_path))
 
-    if isinstance(os.environ['PATH'], unicode):
+    if isinstance(os.environ['PATH'], text_type):
         os.environ['PATH'] = os.environ['PATH'].encode('utf-8')
 
     # sys.executable is used by mochitest-media to start the websocketprocessbridge,
     # for some reason it doesn't get set when calling `activate_this.py` so set it
     # here instead.
     binary = 'python'
     if IS_WIN:
         binary += '.exe'
--- a/testing/tps/create_venv.py
+++ b/testing/tps/create_venv.py
@@ -154,17 +154,17 @@ def main():
         parser.error('Path to the environment has to be specified')
     target = args[0]
     assert(target)
 
     setup_virtualenv(target, python_bin=options.python)
 
     # Activate tps environment
     tps_env = os.path.join(target, activate_env)
-    execfile(tps_env, dict(__file__=tps_env))
+    exec(open(tps_env).read(), dict(__file__=tps_env))
 
     # Install TPS in environment
     subprocess.check_call([os.path.join(target, python_env),
                            os.path.join(here, 'setup.py'), 'install'])
 
     # Get the path to tests and extensions directory by checking check where
     # the tests and extensions directories are located
     sync_dir = os.path.abspath(os.path.join(here, '..', '..', 'services',
--- a/tools/rb/find_leakers.py
+++ b/tools/rb/find_leakers.py
@@ -4,33 +4,34 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # This script processes a `refcount' log, and finds out if any object leaked.
 # It simply goes through the log, finds `AddRef' or `Ctor' lines, and then
 # sees if they `Release' or `Dtor'. If not, it reports them as leaks.
 # Please see README file in the same directory.
 
+from __future__ import print_function
 
 import sys
 
 
 def print_output(allocation, obj_to_class):
     '''Formats and prints output.'''
     items = []
     for obj, count, in allocation.iteritems():
         # Adding items to a list, so we can sort them.
         items.append((obj, count))
     # Sorting by count.
     items.sort(key=lambda item: item[1])
 
     for obj, count, in items:
-        print "{obj} ({count}) @ {class_name}".format(obj=obj,
+        print("{obj} ({count}) @ {class_name}".format(obj=obj,
                                                       count=count,
-                                                      class_name=obj_to_class[obj])
+                                                      class_name=obj_to_class[obj]))
 
 
 def process_log(log_lines):
     '''Process through the log lines, and print out the result.
 
     @param log_lines: List of strings.
     '''
     allocation = {}
@@ -60,44 +61,44 @@ def process_log(log_lines):
             obj_to_class[obj] = class_name
 
         elif ((operation == 'Release' and count == '0') or
               operation == 'Dtor'):
             # Examples:
             #     <nsStringBuffer> 0x01AFD3B8 1 Release 0
             #     <PStreamNotifyParent> 0x08880BD0 8 Dtor (20)
             if obj not in allocation:
-                print "An object was released that wasn't allocated!",
-                print obj, "@", class_name
+                print("An object was released that wasn't allocated!",)
+                print(obj, "@", class_name)
             else:
                 allocation.pop(obj)
             obj_to_class.pop(obj)
 
     # Printing out the result.
     print_output(allocation, obj_to_class)
 
 
 def print_usage():
-    print
-    print "Usage: find-leakers.py [log-file]"
-    print
-    print "If `log-file' provided, it will read that as the input log."
-    print "Else, it will read the stdin as the input log."
-    print
+    print('')
+    print("Usage: find-leakers.py [log-file]")
+    print('')
+    print("If `log-file' provided, it will read that as the input log.")
+    print("Else, it will read the stdin as the input log.")
+    print('')
 
 
 def main():
     '''Main method of the script.'''
     if len(sys.argv) == 1:
         # Reading log from stdin.
         process_log(sys.stdin.readlines())
     elif len(sys.argv) == 2:
         # Reading log from file.
         with open(sys.argv[1], 'r') as log_file:
             log_lines = log_file.readlines()
         process_log(log_lines)
     else:
-        print 'ERROR: Invalid number of arguments'
+        print('ERROR: Invalid number of arguments')
         print_usage()
 
 
 if __name__ == '__main__':
     main()
--- a/tools/rb/fix_linux_stack.py
+++ b/tools/rb/fix_linux_stack.py
@@ -147,17 +147,17 @@ def separate_debug_file_for(file):
             break
     readelf.terminate()
     if endian is None:
         sys.stderr.write("Could not determine endianness of " + file + "\n")
         return None
 
     def word32(s):
         if type(s) != str or len(s) != 4:
-            raise StandardError("expected 4 byte string input")
+            raise Exception("expected 4 byte string input")
         s = list(s)
         if endian == "big":
             s.reverse()
         return sum(map(lambda idx: ord(s[idx]) * (256 ** idx), range(0, 4)))
 
     buildid = elf_section(file, ".note.gnu.build-id")
     if buildid is not None:
         # The build ID is an ELF note section, so it begins with a
--- a/tools/rb/fix_macosx_stack.py
+++ b/tools/rb/fix_macosx_stack.py
@@ -3,16 +3,18 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # This script uses |atos| to post-process the entries produced by
 # NS_FormatCodeAddress(), which on Mac often lack a file name and a line
 # number.
 
+from __future__ import print_function
+
 import json
 import os
 import pty
 import re
 import subprocess
 import sys
 import termios
 
@@ -40,17 +42,17 @@ class unbufferedLineConverter:
     def convert(self, line):
         self.w.write(line + "\n")
         return self.r.readline().rstrip("\r\n")
 
     @staticmethod
     def test():
         assert unbufferedLineConverter("rev").convert("123") == "321"
         assert unbufferedLineConverter("cut", ["-c3"]).convert("abcde") == "c"
-        print "Pass"
+        print("Pass")
 
 
 def separate_debug_file_for(file):
     return None
 
 
 address_adjustments = {}
 
@@ -61,23 +63,23 @@ def address_adjustment(file):
         otool = subprocess.Popen(["otool", "-l", file], stdout=subprocess.PIPE)
         while True:
             line = otool.stdout.readline()
             if line == "":
                 break
             if line == "  segname __TEXT\n":
                 line = otool.stdout.readline()
                 if not line.startswith("   vmaddr "):
-                    raise StandardError("unexpected otool output")
+                    raise Exception("unexpected otool output")
                 result = int(line[10:], 16)
                 break
         otool.stdout.close()
 
         if result is None:
-            raise StandardError("unexpected otool output")
+            raise Exception("unexpected otool output")
 
         address_adjustments[file] = result
 
     return address_adjustments[file]
 
 
 atoses = {}
 
--- a/tools/tryselect/templates.py
+++ b/tools/tryselect/templates.py
@@ -286,17 +286,17 @@ class VisualMetricsJobs(TryConfig):
         if not file_path:
             return None
 
         try:
             with open(file_path) as f:
                 visual_metrics_jobs = json.load(f)
 
             visual_metrics_jobs_schema(visual_metrics_jobs)
-        except (IOError, OSError) as e:
+        except (IOError, OSError):
             print('Failed to read file %s: %s' % (file_path, f))
             sys.exit(1)
         except TypeError:
             print('Failed to parse file %s as JSON: %s' % (file_path, f))
             sys.exit(1)
         except voluptuous.Error as e:
             print(
                 'The file %s does not match the expected format: %s\n'
--- a/xpcom/components/gen_static_components.py
+++ b/xpcom/components/gen_static_components.py
@@ -679,17 +679,17 @@ def gen_substs(manifests):
 def defined(subst):
     return bool(buildconfig.substs.get(subst))
 
 
 def read_manifest(filename):
     glbl = {'buildconfig': buildconfig,
             'defined': defined,
             'ProcessSelector': ProcessSelector}
-    execfile(filename, glbl)
+    exec(open(filename).read(), glbl)
     return glbl
 
 
 def main(fd, conf_file, template_file):
     def open_output(filename):
         return FileAvoidWrite(os.path.join(os.path.dirname(fd.name), filename))
 
     conf = json.load(open(conf_file, 'r'))
--- a/xpcom/idl-parser/xpidl/xpidl.py
+++ b/xpcom/idl-parser/xpidl/xpidl.py
@@ -1238,31 +1238,31 @@ class Param(object):
             kwargs['shared'] = True
         if self.const:
             kwargs['const'] = True
 
         try:
             return self.realtype.nativeType(self.paramtype, **kwargs)
         except IDLError as e:
             raise IDLError(e.message, self.location)
-        except TypeError as e:
+        except TypeError:
             raise IDLError("Unexpected parameter attribute", self.location)
 
     def rustType(self):
         kwargs = {}
         if self.shared:
             kwargs['shared'] = True
         if self.const:
             kwargs['const'] = True
 
         try:
             return self.realtype.rustType(self.paramtype, **kwargs)
         except IDLError as e:
             raise IDLError(e.message, self.location)
-        except TypeError as e:
+        except TypeError:
             raise IDLError("Unexpected parameter attribute", self.location)
 
     def toIDL(self):
         return "%s%s %s %s" % (paramAttlistToIDL(self.attlist),
                                self.paramtype,
                                self.type,
                                self.name)