uClibc: update to 0.9.33.2, fixes #4420
[openwrt.git] / tools / scons / patches / 100-python3-compat.patch
1 --- a/engine/SCons/dblite.py
2 +++ b/engine/SCons/dblite.py
3 @@ -10,11 +10,11 @@ import pickle
4  import shutil
5  import time
6  
7 -keep_all_files = 00000
8 +keep_all_files = 0o0
9  ignore_corrupt_dbfiles = 0
10  
11  def corruption_warning(filename):
12 -    print "Warning: Discarding corrupt database:", filename
13 +    print("Warning: Discarding corrupt database:", filename)
14  
15  try: unicode
16  except NameError:
17 @@ -70,14 +70,14 @@ class dblite(object):
18      self._flag = flag
19      self._mode = mode
20      self._dict = {}
21 -    self._needs_sync = 00000
22 +    self._needs_sync = 0o0
23      if self._os_chown is not None and (os.geteuid()==0 or os.getuid()==0):
24        # running as root; chown back to current owner/group when done
25        try:
26          statinfo = os.stat(self._file_name)
27          self._chown_to = statinfo.st_uid
28          self._chgrp_to = statinfo.st_gid
29 -      except OSError, e:
30 +      except OSError as e:
31          # db file doesn't exist yet.
32          # Check os.environ for SUDO_UID, use if set
33          self._chown_to = int(os.environ.get('SUDO_UID', -1))
34 @@ -90,7 +90,7 @@ class dblite(object):
35      else:
36        try:
37          f = self._open(self._file_name, "rb")
38 -      except IOError, e:
39 +      except IOError as e:
40          if (self._flag != "c"):
41            raise e
42          self._open(self._file_name, "wb", self._mode)
43 @@ -122,7 +122,7 @@ class dblite(object):
44      # (e.g. from a previous run as root).  We should still be able to
45      # unlink() the file if the directory's writable, though, so ignore
46      # any OSError exception  thrown by the chmod() call.
47 -    try: self._os_chmod(self._file_name, 0777)
48 +    try: self._os_chmod(self._file_name, 0o777)
49      except OSError: pass
50      self._os_unlink(self._file_name)
51      self._os_rename(self._tmp_name, self._file_name)
52 @@ -131,7 +131,7 @@ class dblite(object):
53          self._os_chown(self._file_name, self._chown_to, self._chgrp_to)
54        except OSError:
55          pass
56 -    self._needs_sync = 00000
57 +    self._needs_sync = 0o0
58      if (keep_all_files):
59        self._shutil_copyfile(
60          self._file_name,
61 @@ -151,7 +151,7 @@ class dblite(object):
62      if (not is_string(value)):
63        raise TypeError("value `%s' must be a string but is %s" % (value, type(value)))
64      self._dict[key] = value
65 -    self._needs_sync = 0001
66 +    self._needs_sync = 0o1
67  
68    def keys(self):
69      return list(self._dict.keys())
70 @@ -171,7 +171,7 @@ class dblite(object):
71    def __len__(self):
72      return len(self._dict)
73  
74 -def open(file, flag=None, mode=0666):
75 +def open(file, flag=None, mode=0o666):
76    return dblite(file, flag, mode)
77  
78  def _exercise():
79 @@ -198,7 +198,7 @@ def _exercise():
80    assert db[unicode("ubar")] == unicode("ufoo")
81    try:
82      db.sync()
83 -  except IOError, e:
84 +  except IOError as e:
85      assert str(e) == "Read-only database: tmp.dblite"
86    else:
87      raise RuntimeError("IOError expected.")
88 @@ -208,13 +208,13 @@ def _exercise():
89    db.sync()
90    try:
91      db[(1,2)] = "tuple"
92 -  except TypeError, e:
93 +  except TypeError as e:
94      assert str(e) == "key `(1, 2)' must be a string but is <type 'tuple'>", str(e)
95    else:
96      raise RuntimeError("TypeError exception expected")
97    try:
98      db["list"] = [1,2]
99 -  except TypeError, e:
100 +  except TypeError as e:
101      assert str(e) == "value `[1, 2]' must be a string but is <type 'list'>", str(e)
102    else:
103      raise RuntimeError("TypeError exception expected")
104 @@ -238,11 +238,11 @@ def _exercise():
105    os.unlink("tmp.dblite")
106    try:
107      db = open("tmp", "w")
108 -  except IOError, e:
109 +  except IOError as e:
110      assert str(e) == "[Errno 2] No such file or directory: 'tmp.dblite'", str(e)
111    else:
112      raise RuntimeError("IOError expected.")
113 -  print "OK"
114 +  print("OK")
115  
116  if (__name__ == "__main__"):
117    _exercise()
118 --- a/engine/SCons/SConsign.py
119 +++ b/engine/SCons/SConsign.py
120 @@ -84,7 +84,7 @@ def Get_DataBase(dir):
121          DB_sync_list.append(db)
122          return db, "c"
123      except TypeError:
124 -        print "DataBase =", DataBase
125 +        print("DataBase =", DataBase)
126          raise
127  
128  def Reset():
129 @@ -215,7 +215,7 @@ class DB(Base):
130                      raise TypeError
131              except KeyboardInterrupt:
132                  raise
133 -            except Exception, e:
134 +            except Exception as e:
135                  SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning,
136                                      "Ignoring corrupt sconsign entry : %s (%s)\n"%(self.dir.tpath, e))
137              for key, entry in self.entries.items():
138 @@ -340,7 +340,7 @@ class DirFile(Dir):
139          if fname != self.sconsign:
140              try:
141                  mode = os.stat(self.sconsign)[0]
142 -                os.chmod(self.sconsign, 0666)
143 +                os.chmod(self.sconsign, 0o666)
144                  os.unlink(self.sconsign)
145              except (IOError, OSError):
146                  # Try to carry on in the face of either OSError
147 --- a/engine/SCons/Util.py
148 +++ b/engine/SCons/Util.py
149 @@ -264,10 +264,10 @@ def print_tree(root, child_func, prune=0
150      children = child_func(root)
151  
152      if prune and rname in visited and children:
153 -        sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + u'\n')
154 +        sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + '\n')
155          return
156  
157 -    sys.stdout.write(''.join(tags + margins + ['+-', rname]) + u'\n')
158 +    sys.stdout.write(''.join(tags + margins + ['+-', rname]) + '\n')
159  
160      visited[rname] = 1
161  
162 @@ -718,7 +718,7 @@ else:
163                      # raised so as to not mask possibly serious disk or
164                      # network issues.
165                      continue
166 -                if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
167 +                if stat.S_IMODE(st[stat.ST_MODE]) & 0o111:
168                      try:
169                          reject.index(f)
170                      except ValueError:
171 @@ -1355,9 +1355,9 @@ def AddMethod(obj, function, name=None):
172          self.z = x + y
173        AddMethod(f, A, "add")
174        a.add(2, 4)
175 -      print a.z
176 +      print(a.z)
177        AddMethod(lambda self, i: self.l[i], a, "listIndex")
178 -      print a.listIndex(5)
179 +      print(a.listIndex(5))
180      """
181      if name is None:
182          name = function.func_name
183 --- a/setup.py
184 +++ b/setup.py
185 @@ -333,7 +333,7 @@ class install_scripts(_install_scripts):
186                      # log.info("changing mode of %s", file)
187                      pass
188                  else:
189 -                    mode = ((os.stat(file)[stat.ST_MODE]) | 0555) & 07777
190 +                    mode = ((os.stat(file)[stat.ST_MODE]) | 0o555) & 0o7777
191                      # log.info("changing mode of %s to %o", file, mode)
192                      os.chmod(file, mode)
193          # --- /distutils copy/paste ---
194 @@ -414,7 +414,7 @@ arguments = {
195  distutils.core.setup(**arguments)
196  
197  if Installed:
198 -    print '\n'.join(Installed)
199 +    print('\n'.join(Installed))
200  
201  # Local Variables:
202  # tab-width:4
203 --- a/engine/SCons/compat/_scons_subprocess.py
204 +++ b/engine/SCons/compat/_scons_subprocess.py
205 @@ -248,11 +248,11 @@ A more real-world example would look lik
206  try:
207      retcode = call("mycmd" + " myarg", shell=True)
208      if retcode < 0:
209 -        print >>sys.stderr, "Child was terminated by signal", -retcode
210 +        print(>>sys.stderr, "Child was terminated by signal", -retcode)
211      else:
212 -        print >>sys.stderr, "Child returned", retcode
213 -except OSError, e:
214 -    print >>sys.stderr, "Execution failed:", e
215 +        print(>>sys.stderr, "Child returned", retcode)
216 +except OSError as e:
217 +    print(>>sys.stderr, "Execution failed:", e)
218  
219  
220  Replacing os.spawn*
221 @@ -439,7 +439,7 @@ except TypeError:
222      def is_int(obj):
223          return isinstance(obj, type(1))
224      def is_int_or_long(obj):
225 -        return type(obj) in (type(1), type(1L))
226 +        return type(obj) in (type(1), type(1))
227  else:
228      def is_int(obj):
229          return isinstance(obj, int)
230 @@ -802,7 +802,7 @@ class Popen(object):
231                  startupinfo.wShowWindow = SW_HIDE
232                  comspec = os.environ.get("COMSPEC", "cmd.exe")
233                  args = comspec + " /c " + args
234 -                if (GetVersion() >= 0x80000000L or
235 +                if (GetVersion() >= 0x80000000 or
236                          os.path.basename(comspec).lower() == "command.com"):
237                      # Win9x, or using command.com on NT. We need to
238                      # use the w9xpopen intermediate program. For more
239 @@ -830,7 +830,7 @@ class Popen(object):
240                                           env,
241                                           cwd,
242                                           startupinfo)
243 -            except pywintypes.error, e:
244 +            except pywintypes.error as e:
245                  # Translate pywintypes.error to WindowsError, which is
246                  # a subclass of OSError.  FIXME: We should really
247                  # translate errno using _sys_errlist (or simliar), but
248 @@ -1215,8 +1215,8 @@ def _demo_posix():
249      # Example 1: Simple redirection: Get process list
250      #
251      plist = Popen(["ps"], stdout=PIPE).communicate()[0]
252 -    print "Process list:"
253 -    print plist
254 +    print("Process list:")
255 +    print(plist)
256  
257      #
258      # Example 2: Change uid before executing child
259 @@ -1228,25 +1228,25 @@ def _demo_posix():
260      #
261      # Example 3: Connecting several subprocesses
262      #
263 -    print "Looking for 'hda'..."
264 +    print("Looking for 'hda'...")
265      p1 = Popen(["dmesg"], stdout=PIPE)
266      p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
267 -    print repr(p2.communicate()[0])
268 +    print(repr(p2.communicate()[0]))
269  
270      #
271      # Example 4: Catch execution error
272      #
273      print
274 -    print "Trying a weird file..."
275 +    print("Trying a weird file...")
276      try:
277 -        print Popen(["/this/path/does/not/exist"]).communicate()
278 -    except OSError, e:
279 +        print(Popen(["/this/path/does/not/exist"]).communicate())
280 +    except OSError as e:
281          if e.errno == errno.ENOENT:
282 -            print "The file didn't exist.  I thought so..."
283 -            print "Child traceback:"
284 -            print e.child_traceback
285 +            print("The file didn't exist.  I thought so...")
286 +            print("Child traceback:")
287 +            print(e.child_traceback)
288          else:
289 -            print "Error", e.errno
290 +            print("Error", e.errno)
291      else:
292          sys.stderr.write( "Gosh.  No error.\n" )
293  
294 @@ -1255,15 +1255,15 @@ def _demo_windows():
295      #
296      # Example 1: Connecting several subprocesses
297      #
298 -    print "Looking for 'PROMPT' in set output..."
299 +    print("Looking for 'PROMPT' in set output...")
300      p1 = Popen("set", stdout=PIPE, shell=True)
301      p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
302 -    print repr(p2.communicate()[0])
303 +    print(repr(p2.communicate()[0]))
304  
305      #
306      # Example 2: Simple execution of program
307      #
308 -    print "Executing calc..."
309 +    print("Executing calc...")
310      p = Popen("calc")
311      p.wait()
312  
313 --- a/engine/SCons/Memoize.py
314 +++ b/engine/SCons/Memoize.py
315 @@ -143,7 +143,7 @@ class Counter(object):
316          CounterList.append(self)
317      def display(self):
318          fmt = "    %7d hits %7d misses    %s()"
319 -        print fmt % (self.hit, self.miss, self.name)
320 +        print(fmt % (self.hit, self.miss, self.name))
321      def __cmp__(self, other):
322          try:
323              return cmp(self.name, other.name)
324 @@ -215,7 +215,7 @@ class Memoizer(object):
325  
326  def Dump(title=None):
327      if title:
328 -        print title
329 +        print(title)
330      CounterList.sort()
331      for counter in CounterList:
332          counter.display()
333 --- a/engine/SCons/Node/FS.py
334 +++ b/engine/SCons/Node/FS.py
335 @@ -550,7 +550,7 @@ class EntryProxy(SCons.Util.Proxy):
336          except KeyError:
337              try:
338                  attr = SCons.Util.Proxy.__getattr__(self, name)
339 -            except AttributeError, e:
340 +            except AttributeError as e:
341                  # Raise our own AttributeError subclass with an
342                  # overridden __str__() method that identifies the
343                  # name of the entry that caused the exception.
344 @@ -2420,7 +2420,7 @@ class File(Base):
345          fname = self.rfile().abspath
346          try:
347              contents = open(fname, "rb").read()
348 -        except EnvironmentError, e:
349 +        except EnvironmentError as e:
350              if not e.filename:
351                  e.filename = fname
352              raise
353 @@ -2455,7 +2455,7 @@ class File(Base):
354          try:
355              cs = SCons.Util.MD5filesignature(fname,
356                  chunksize=SCons.Node.FS.File.md5_chunksize*1024)
357 -        except EnvironmentError, e:
358 +        except EnvironmentError as e:
359              if not e.filename:
360                  e.filename = fname
361              raise
362 @@ -2793,7 +2793,7 @@ class File(Base):
363      def _rmv_existing(self):
364          self.clear_memoized_values()
365          if print_duplicate:
366 -            print "dup: removing existing target %s"%self
367 +            print("dup: removing existing target %s"%self)
368          e = Unlink(self, [], None)
369          if isinstance(e, SCons.Errors.BuildError):
370              raise e
371 @@ -2817,7 +2817,7 @@ class File(Base):
372              else:
373                  try:
374                      self._createDir()
375 -                except SCons.Errors.StopError, drive:
376 +                except SCons.Errors.StopError as drive:
377                      desc = "No drive `%s' for target `%s'." % (drive, self)
378                      raise SCons.Errors.StopError(desc)
379  
380 @@ -2835,7 +2835,7 @@ class File(Base):
381      def do_duplicate(self, src):
382          self._createDir()
383          if print_duplicate:
384 -            print "dup: relinking variant '%s' from '%s'"%(self, src)
385 +            print("dup: relinking variant '%s' from '%s'"%(self, src))
386          Unlink(self, None, None)
387          e = Link(self, src, None)
388          if isinstance(e, SCons.Errors.BuildError):
389 @@ -2870,7 +2870,7 @@ class File(Base):
390                          # The source file does not exist.  Make sure no old
391                          # copy remains in the variant directory.
392                          if print_duplicate:
393 -                            print "dup: no src for %s, unlinking old variant copy"%self
394 +                            print("dup: no src for %s, unlinking old variant copy"%self)
395                          if Base.exists(self) or self.islink():
396                              self.fs.unlink(self.path)
397                          # Return None explicitly because the Base.exists() call
398 @@ -3199,7 +3199,7 @@ class FileFinder(object):
399          if verbose and not callable(verbose):
400              if not SCons.Util.is_String(verbose):
401                  verbose = "find_file"
402 -            _verbose = u'  %s: ' % verbose
403 +            _verbose = '  %s: ' % verbose
404              verbose = lambda s: sys.stdout.write(_verbose + s)
405  
406          filedir, filename = os.path.split(filename)
407 --- a/engine/SCons/SConf.py
408 +++ b/engine/SCons/SConf.py
409 @@ -239,7 +239,7 @@ class SConfBuildTask(SCons.Taskmaster.Al
410                  # Earlier versions of Python don't have sys.excepthook...
411                  def excepthook(type, value, tb):
412                      traceback.print_tb(tb)
413 -                    print type, value
414 +                    print(type, value)
415              excepthook(*self.exc_info())
416          return SCons.Taskmaster.Task.failed(self)
417  
418 @@ -332,7 +332,7 @@ class SConfBuildTask(SCons.Taskmaster.Al
419              except SystemExit:
420                  exc_value = sys.exc_info()[1]
421                  raise SCons.Errors.ExplicitExit(self.targets[0],exc_value.code)
422 -            except Exception, e:
423 +            except Exception as e:
424                  for t in self.targets:
425                      binfo = t.get_binfo()
426                      binfo.__class__ = SConfBuildInfo
427 --- a/engine/SCons/Script/Interactive.py
428 +++ b/engine/SCons/Script/Interactive.py
429 @@ -129,12 +129,12 @@ class SConsInteractiveCmd(cmd.Cmd):
430              self.shell_variable = 'SHELL'
431  
432      def default(self, argv):
433 -        print "*** Unknown command: %s" % argv[0]
434 +        print("*** Unknown command: %s" % argv[0])
435  
436      def onecmd(self, line):
437          line = line.strip()
438          if not line:
439 -            print self.lastcmd
440 +            print(self.lastcmd)
441              return self.emptyline()
442          self.lastcmd = line
443          if line[0] == '!':
444 @@ -274,7 +274,7 @@ class SConsInteractiveCmd(cmd.Cmd):
445          return self.do_build(['build', '--clean'] + argv[1:])
446  
447      def do_EOF(self, argv):
448 -        print
449 +        print()
450          self.do_exit(argv)
451  
452      def _do_one_help(self, arg):
453 @@ -357,7 +357,7 @@ class SConsInteractiveCmd(cmd.Cmd):
454              # Doing the right thing with an argument list currently
455              # requires different shell= values on Windows and Linux.
456              p = subprocess.Popen(argv, shell=(sys.platform=='win32'))
457 -        except EnvironmentError, e:
458 +        except EnvironmentError as e:
459              sys.stderr.write('scons: %s: %s\n' % (argv[0], e.strerror))
460          else:
461              p.wait()
462 --- a/engine/SCons/Script/Main.py
463 +++ b/engine/SCons/Script/Main.py
464 @@ -224,7 +224,7 @@ class BuildTask(SCons.Taskmaster.OutOfDa
465                      self.exception_set()
466                  self.do_failed()
467              else:
468 -                print "scons: Nothing to be done for `%s'." % t
469 +                print("scons: Nothing to be done for `%s'." % t)
470                  SCons.Taskmaster.OutOfDateTask.executed(self)
471          else:
472              SCons.Taskmaster.OutOfDateTask.executed(self)
473 @@ -290,8 +290,8 @@ class BuildTask(SCons.Taskmaster.OutOfDa
474              if self.options.debug_includes:
475                  tree = t.render_include_tree()
476                  if tree:
477 -                    print
478 -                    print tree
479 +                    print()
480 +                    print(tree)
481          SCons.Taskmaster.OutOfDateTask.postprocess(self)
482  
483      def make_ready(self):
484 @@ -326,10 +326,10 @@ class CleanTask(SCons.Taskmaster.AlwaysT
485                  else:
486                      errstr = "Path '%s' exists but isn't a file or directory."
487                      raise SCons.Errors.UserError(errstr % (pathstr))
488 -        except SCons.Errors.UserError, e:
489 -            print e
490 -        except (IOError, OSError), e:
491 -            print "scons: Could not remove '%s':" % pathstr, e.strerror
492 +        except SCons.Errors.UserError as e:
493 +            print(e)
494 +        except (IOError, OSError) as e:
495 +            print("scons: Could not remove '%s':" % pathstr, e.strerror)
496  
497      def show(self):
498          target = self.targets[0]
499 @@ -348,13 +348,13 @@ class CleanTask(SCons.Taskmaster.AlwaysT
500              for t in self.targets:
501                  try:
502                      removed = t.remove()
503 -                except OSError, e:
504 +                except OSError as e:
505                      # An OSError may indicate something like a permissions
506                      # issue, an IOError would indicate something like
507                      # the file not existing.  In either case, print a
508                      # message and keep going to try to remove as many
509                      # targets aa possible.
510 -                    print "scons: Could not remove '%s':" % str(t), e.strerror
511 +                    print("scons: Could not remove '%s':" % str(t), e.strerror)
512                  else:
513                      if removed:
514                          display("Removed " + str(t))
515 @@ -595,7 +595,7 @@ def _scons_internal_error():
516      """Handle all errors but user errors. Print out a message telling
517      the user what to do in this case and print a normal trace.
518      """
519 -    print 'internal error'
520 +    print('internal error')
521      traceback.print_exc()
522      sys.exit(2)
523  
524 @@ -707,7 +707,7 @@ def _load_site_scons_dir(topdir, site_di
525                  # the error checking makes it longer.
526                  try:
527                      m = sys.modules['SCons.Script']
528 -                except Exception, e:
529 +                except Exception as e:
530                      fmt = 'cannot import site_init.py: missing SCons.Script module %s'
531                      raise SCons.Errors.InternalError(fmt % repr(e))
532                  try:
533 @@ -720,10 +720,10 @@ def _load_site_scons_dir(topdir, site_di
534                              site_m[k] = m.__dict__[k]
535  
536                      # This is the magic.
537 -                    exec fp in site_m
538 +                    exec(fp.read()) in site_m
539                  except KeyboardInterrupt:
540                      raise
541 -                except Exception, e:
542 +                except Exception as e:
543                      fmt = '*** Error loading site_init file %s:\n'
544                      sys.stderr.write(fmt % repr(site_init_file))
545                      raise
546 @@ -733,7 +733,7 @@ def _load_site_scons_dir(topdir, site_di
547                              m.__dict__[k] = site_m[k]
548              except KeyboardInterrupt:
549                  raise
550 -            except ImportError, e:
551 +            except ImportError as e:
552                  fmt = '*** cannot import site init file %s:\n'
553                  sys.stderr.write(fmt % repr(site_init_file))
554                  raise
555 @@ -785,7 +785,7 @@ def _load_all_site_scons_dirs(topdir, ve
556      dirs=sysdirs + [topdir]
557      for d in dirs:
558          if verbose:    # this is used by unit tests.
559 -            print "Loading site dir ", d
560 +            print("Loading site dir ", d)
561          _load_site_scons_dir(d)
562  
563  def test_load_all_site_scons_dirs(d):
564 @@ -976,7 +976,7 @@ def _main(parser):
565      try:
566          for script in scripts:
567              SCons.Script._SConscript._SConscript(fs, script)
568 -    except SCons.Errors.StopError, e:
569 +    except SCons.Errors.StopError as e:
570          # We had problems reading an SConscript file, such as it
571          # couldn't be copied in to the VariantDir.  Since we're just
572          # reading SConscript files and haven't started building
573 @@ -1032,8 +1032,8 @@ def _main(parser):
574              # SConscript files.  Give them the options usage.
575              raise SConsPrintHelpException
576          else:
577 -            print help_text
578 -            print "Use scons -H for help about command-line options."
579 +            print(help_text)
580 +            print("Use scons -H for help about command-line options.")
581          exit_status = 0
582          return
583  
584 @@ -1296,7 +1296,7 @@ def _exec_main(parser, values):
585          prof = Profile()
586          try:
587              prof.runcall(_main, parser)
588 -        except SConsPrintHelpException, e:
589 +        except SConsPrintHelpException as e:
590              prof.dump_stats(options.profile_file)
591              raise e
592          except SystemExit:
593 @@ -1340,22 +1340,22 @@ def main():
594      
595      try:
596          _exec_main(parser, values)
597 -    except SystemExit, s:
598 +    except SystemExit as s:
599          if s:
600              exit_status = s
601      except KeyboardInterrupt:
602          print("scons: Build interrupted.")
603          sys.exit(2)
604 -    except SyntaxError, e:
605 +    except SyntaxError as e:
606          _scons_syntax_error(e)
607      except SCons.Errors.InternalError:
608          _scons_internal_error()
609 -    except SCons.Errors.UserError, e:
610 +    except SCons.Errors.UserError as e:
611          _scons_user_error(e)
612      except SConsPrintHelpException:
613          parser.print_help()
614          exit_status = 0
615 -    except SCons.Errors.BuildError, e:
616 +    except SCons.Errors.BuildError as e:
617          exit_status = e.exitstatus
618      except:
619          # An exception here is likely a builtin Python exception Python
620 @@ -1391,10 +1391,10 @@ def main():
621              else:
622                  ct = last_command_end - first_command_start
623          scons_time = total_time - sconscript_time - ct
624 -        print "Total build time: %f seconds"%total_time
625 -        print "Total SConscript file execution time: %f seconds"%sconscript_time
626 -        print "Total SCons execution time: %f seconds"%scons_time
627 -        print "Total command execution time: %f seconds"%ct
628 +        print("Total build time: %f seconds"%total_time)
629 +        print("Total SConscript file execution time: %f seconds"%sconscript_time)
630 +        print("Total SCons execution time: %f seconds"%scons_time)
631 +        print("Total command execution time: %f seconds"%ct)
632  
633      sys.exit(exit_status)
634  
635 --- a/engine/SCons/Script/SConscript.py
636 +++ b/engine/SCons/Script/SConscript.py
637 @@ -113,7 +113,7 @@ def compute_exports(exports):
638                      retval[export] = loc[export]
639                  except KeyError:
640                      retval[export] = glob[export]
641 -    except KeyError, x:
642 +    except KeyError as x:
643          raise SCons.Errors.UserError("Export of non-existent variable '%s'"%x)
644  
645      return retval
646 @@ -145,7 +145,7 @@ def Return(*vars, **kw):
647          for var in fvars:
648              for v in var.split():
649                  retval.append(call_stack[-1].globals[v])
650 -    except KeyError, x:
651 +    except KeyError as x:
652          raise SCons.Errors.UserError("Return of non-existent variable '%s'"%x)
653  
654      if len(retval) == 1:
655 @@ -174,7 +174,7 @@ def _SConscript(fs, *files, **kw):
656          try:
657              SCons.Script.sconscript_reading = SCons.Script.sconscript_reading + 1
658              if fn == "-":
659 -                exec sys.stdin in call_stack[-1].globals
660 +                exec(sys.stdin.read()) in call_stack[-1].globals
661              else:
662                  if isinstance(fn, SCons.Node.Node):
663                      f = fn
664 @@ -257,7 +257,7 @@ def _SConscript(fs, *files, **kw):
665                          pass
666                      try:
667                          try:
668 -                            exec _file_ in call_stack[-1].globals
669 +                            exec(_file_.read()) in call_stack[-1].globals
670                          except SConscriptReturn:
671                              pass
672                      finally:
673 @@ -282,7 +282,7 @@ def _SConscript(fs, *files, **kw):
674                  rdir._create()  # Make sure there's a directory there.
675                  try:
676                      os.chdir(rdir.get_abspath())
677 -                except OSError, e:
678 +                except OSError as e:
679                      # We still couldn't chdir there, so raise the error,
680                      # but only if actions are being executed.
681                      #
682 @@ -467,8 +467,8 @@ class SConsEnvironment(SCons.Environment
683                  scons_ver_string = '%d.%d.%d' % (major, minor, revision)
684              else:
685                  scons_ver_string = '%d.%d' % (major, minor)
686 -            print "SCons %s or greater required, but you have SCons %s" % \
687 -                  (scons_ver_string, SCons.__version__)
688 +            print("SCons %s or greater required, but you have SCons %s" % \
689 +                  (scons_ver_string, SCons.__version__))
690              sys.exit(2)
691  
692      def EnsurePythonVersion(self, major, minor):
693 @@ -480,7 +480,7 @@ class SConsEnvironment(SCons.Environment
694              python_ver = self._get_major_minor_revision(sys.version)[:2]
695          if python_ver < (major, minor):
696              v = sys.version.split(" ", 1)[0]
697 -            print "Python %d.%d or greater required, but you have Python %s" %(major,minor,v)
698 +            print("Python %d.%d or greater required, but you have Python %s" %(major,minor,v))
699              sys.exit(2)
700  
701      def Exit(self, value=0):
702 @@ -519,7 +519,7 @@ class SConsEnvironment(SCons.Environment
703                              globals[v] = exports[v]
704                          else:
705                              globals[v] = global_exports[v]
706 -        except KeyError,x:
707 +        except KeyError as x:
708              raise SCons.Errors.UserError("Import of non-existent variable '%s'"%x)
709  
710      def SConscript(self, *ls, **kw):
711 --- a/engine/SCons/Taskmaster.py
712 +++ b/engine/SCons/Taskmaster.py
713 @@ -107,7 +107,7 @@ fmt = "%(considered)3d "\
714  
715  def dump_stats():
716      for n in sorted(StatsNodes, key=lambda a: str(a)):
717 -        print (fmt % n.stats.__dict__) + str(n)
718 +        print((fmt % n.stats.__dict__) + str(n))
719  
720  
721  
722 @@ -164,7 +164,7 @@ class Task(object):
723          """
724          global print_prepare
725          T = self.tm.trace
726 -        if T: T.write(self.trace_message(u'Task.prepare()', self.node))
727 +        if T: T.write(self.trace_message('Task.prepare()', self.node))
728  
729          # Now that it's the appropriate time, give the TaskMaster a
730          # chance to raise any exceptions it encountered while preparing
731 @@ -189,13 +189,13 @@ class Task(object):
732          executor.prepare()
733          for t in executor.get_action_targets():
734              if print_prepare:
735 -                print "Preparing target %s..."%t
736 +                print("Preparing target %s..."%t)
737                  for s in t.side_effects:
738 -                    print "...with side-effect %s..."%s
739 +                    print("...with side-effect %s..."%s)
740              t.prepare()
741              for s in t.side_effects:
742                  if print_prepare:
743 -                    print "...Preparing side-effect %s..."%s
744 +                    print("...Preparing side-effect %s..."%s)
745                  s.prepare()
746  
747      def get_target(self):
748 @@ -224,7 +224,7 @@ class Task(object):
749          prepare(), executed() or failed().
750          """
751          T = self.tm.trace
752 -        if T: T.write(self.trace_message(u'Task.execute()', self.node))
753 +        if T: T.write(self.trace_message('Task.execute()', self.node))
754  
755          try:
756              everything_was_cached = 1
757 @@ -248,7 +248,7 @@ class Task(object):
758              raise
759          except SCons.Errors.BuildError:
760              raise
761 -        except Exception, e:
762 +        except Exception as e:
763              buildError = SCons.Errors.convert_to_BuildError(e)
764              buildError.node = self.targets[0]
765              buildError.exc_info = sys.exc_info()
766 @@ -376,7 +376,7 @@ class Task(object):
767          This is the default behavior for building only what's necessary.
768          """
769          T = self.tm.trace
770 -        if T: T.write(self.trace_message(u'Task.make_ready_current()',
771 +        if T: T.write(self.trace_message('Task.make_ready_current()',
772                                           self.node))
773  
774          self.out_of_date = []
775 @@ -386,7 +386,7 @@ class Task(object):
776                  t.disambiguate().make_ready()
777                  is_up_to_date = not t.has_builder() or \
778                                  (not t.always_build and t.is_up_to_date())
779 -            except EnvironmentError, e:
780 +            except EnvironmentError as e:
781                  raise SCons.Errors.BuildError(node=t, errstr=e.strerror, filename=e.filename)
782  
783              if not is_up_to_date:
784 @@ -421,7 +421,7 @@ class Task(object):
785          that can be put back on the candidates list.
786          """
787          T = self.tm.trace
788 -        if T: T.write(self.trace_message(u'Task.postprocess()', self.node))
789 +        if T: T.write(self.trace_message('Task.postprocess()', self.node))
790  
791          # We may have built multiple targets, some of which may have
792          # common parents waiting for this build.  Count up how many
793 @@ -438,7 +438,7 @@ class Task(object):
794              # A node can only be in the pending_children set if it has
795              # some waiting_parents.
796              if t.waiting_parents:
797 -                if T: T.write(self.trace_message(u'Task.postprocess()',
798 +                if T: T.write(self.trace_message('Task.postprocess()',
799                                                   t,
800                                                   'removing'))
801                  pending_children.discard(t)
802 @@ -457,7 +457,7 @@ class Task(object):
803  
804          for p, subtract in parents.items():
805              p.ref_count = p.ref_count - subtract
806 -            if T: T.write(self.trace_message(u'Task.postprocess()',
807 +            if T: T.write(self.trace_message('Task.postprocess()',
808                                               p,
809                                               'adjusted parent ref count'))
810              if p.ref_count == 0:
811 @@ -517,7 +517,9 @@ class Task(object):
812          except ValueError:
813              exc_type, exc_value = exc
814              exc_traceback = None
815 -        raise exc_type, exc_value, exc_traceback
816 +        e = exc_type(exc_value)
817 +        e.__traceback__ = exc_traceback
818 +        raise e
819  
820  class AlwaysTask(Task):
821      def needs_execute(self):
822 @@ -741,12 +743,12 @@ class Taskmaster(object):
823          self.ready_exc = None
824  
825          T = self.trace
826 -        if T: T.write(u'\n' + self.trace_message('Looking for a node to evaluate'))
827 +        if T: T.write('\n' + self.trace_message('Looking for a node to evaluate'))
828  
829          while True:
830              node = self.next_candidate()
831              if node is None:
832 -                if T: T.write(self.trace_message('No candidate anymore.') + u'\n')
833 +                if T: T.write(self.trace_message('No candidate anymore.') + '\n')
834                  return None
835  
836              node = node.disambiguate()
837 @@ -769,7 +771,7 @@ class Taskmaster(object):
838              else:
839                  S = None
840  
841 -            if T: T.write(self.trace_message(u'    Considering node %s and its children:' % self.trace_node(node)))
842 +            if T: T.write(self.trace_message('    Considering node %s and its children:' % self.trace_node(node)))
843  
844              if state == NODE_NO_STATE:
845                  # Mark this node as being on the execution stack:
846 @@ -777,7 +779,7 @@ class Taskmaster(object):
847              elif state > NODE_PENDING:
848                  # Skip this node if it has already been evaluated:
849                  if S: S.already_handled = S.already_handled + 1
850 -                if T: T.write(self.trace_message(u'       already handled (executed)'))
851 +                if T: T.write(self.trace_message('       already handled (executed)'))
852                  continue
853  
854              executor = node.get_executor()
855 @@ -790,7 +792,7 @@ class Taskmaster(object):
856                  self.ready_exc = (SCons.Errors.ExplicitExit, e)
857                  if T: T.write(self.trace_message('       SystemExit'))
858                  return node
859 -            except Exception, e:
860 +            except Exception as e:
861                  # We had a problem just trying to figure out the
862                  # children (like a child couldn't be linked in to a
863                  # VariantDir, or a Scanner threw something).  Arrange to
864 @@ -808,7 +810,7 @@ class Taskmaster(object):
865              for child in chain(executor.get_all_prerequisites(), children):
866                  childstate = child.get_state()
867  
868 -                if T: T.write(self.trace_message(u'       ' + self.trace_node(child)))
869 +                if T: T.write(self.trace_message('       ' + self.trace_node(child)))
870  
871                  if childstate == NODE_NO_STATE:
872                      children_not_visited.append(child)
873 @@ -867,7 +869,7 @@ class Taskmaster(object):
874                      # count so we can be put back on the list for
875                      # re-evaluation when they've all finished.
876                      node.ref_count =  node.ref_count + child.add_to_waiting_parents(node)
877 -                    if T: T.write(self.trace_message(u'     adjusted ref count: %s, child %s' %
878 +                    if T: T.write(self.trace_message('     adjusted ref count: %s, child %s' %
879                                    (self.trace_node(node), repr(str(child)))))
880  
881                  if T:
882 @@ -893,7 +895,7 @@ class Taskmaster(object):
883              # The default when we've gotten through all of the checks above:
884              # this node is ready to be built.
885              if S: S.build = S.build + 1
886 -            if T: T.write(self.trace_message(u'Evaluating %s\n' %
887 +            if T: T.write(self.trace_message('Evaluating %s\n' %
888                                               self.trace_node(node)))
889  
890              # For debugging only:
891 --- a/engine/SCons/Tool/FortranCommon.py
892 +++ b/engine/SCons/Tool/FortranCommon.py
893 @@ -61,7 +61,7 @@ def isfortran(env, source):
894  def _fortranEmitter(target, source, env):
895      node = source[0].rfile()
896      if not node.exists() and not node.is_derived():
897 -       print "Could not locate " + str(node.name)
898 +       print("Could not locate " + str(node.name))
899         return ([], [])
900      mod_regex = """(?i)^\s*MODULE\s+(?!PROCEDURE)(\w+)"""
901      cre = re.compile(mod_regex,re.M)
902 @@ -167,7 +167,7 @@ def add_fortran_to_env(env):
903      except KeyError:
904          FortranSuffixes = ['.f', '.for', '.ftn']
905  
906 -    #print "Adding %s to fortran suffixes" % FortranSuffixes
907 +    #print("Adding %s to fortran suffixes" % FortranSuffixes)
908      try:
909          FortranPPSuffixes = env['FORTRANPPFILESUFFIXES']
910      except KeyError:
911 @@ -191,7 +191,7 @@ def add_f77_to_env(env):
912      except KeyError:
913          F77Suffixes = ['.f77']
914  
915 -    #print "Adding %s to f77 suffixes" % F77Suffixes
916 +    #print("Adding %s to f77 suffixes" % F77Suffixes)
917      try:
918          F77PPSuffixes = env['F77PPFILESUFFIXES']
919      except KeyError:
920 @@ -206,7 +206,7 @@ def add_f90_to_env(env):
921      except KeyError:
922          F90Suffixes = ['.f90']
923  
924 -    #print "Adding %s to f90 suffixes" % F90Suffixes
925 +    #print("Adding %s to f90 suffixes" % F90Suffixes)
926      try:
927          F90PPSuffixes = env['F90PPFILESUFFIXES']
928      except KeyError:
929 @@ -222,7 +222,7 @@ def add_f95_to_env(env):
930      except KeyError:
931          F95Suffixes = ['.f95']
932  
933 -    #print "Adding %s to f95 suffixes" % F95Suffixes
934 +    #print("Adding %s to f95 suffixes" % F95Suffixes)
935      try:
936          F95PPSuffixes = env['F95PPFILESUFFIXES']
937      except KeyError:
938 @@ -238,7 +238,7 @@ def add_f03_to_env(env):
939      except KeyError:
940          F03Suffixes = ['.f03']
941  
942 -    #print "Adding %s to f95 suffixes" % F95Suffixes
943 +    #print("Adding %s to f95 suffixes" % F95Suffixes)
944      try:
945          F03PPSuffixes = env['F03PPFILESUFFIXES']
946      except KeyError:
947 --- a/engine/SCons/Tool/intelc.py
948 +++ b/engine/SCons/Tool/intelc.py
949 @@ -205,17 +205,17 @@ def get_all_compiler_versions():
950                          # Registry points to nonexistent dir.  Ignore this
951                          # version.
952                          value = get_intel_registry_value('ProductDir', subkey, 'IA32')
953 -                    except MissingRegistryError, e:
954 +                    except MissingRegistryError as e:
955  
956                          # Registry key is left dangling (potentially
957                          # after uninstalling).
958  
959 -                        print \
960 +                        print(\
961                              "scons: *** Ignoring the registry key for the Intel compiler version %s.\n" \
962                              "scons: *** It seems that the compiler was uninstalled and that the registry\n" \
963 -                            "scons: *** was not cleaned up properly.\n" % subkey
964 +                            "scons: *** was not cleaned up properly.\n" % subkey)
965                      else:
966 -                        print "scons: *** Ignoring "+str(value)
967 +                        print("scons: *** Ignoring "+str(value))
968  
969                  i = i + 1
970          except EnvironmentError:
971 @@ -294,7 +294,7 @@ def get_intel_compiler_top(version, abi)
972                      break
973              return top
974          top = find_in_2010style_dir(version) or find_in_2008style_dir(version)
975 -        print "INTELC: top=",top
976 +        print("INTELC: top=",top)
977          if not top:
978              raise MissingDirError("Can't find version %s Intel compiler in %s (abi='%s')"%(version,top, abi))
979      return top
980 @@ -394,8 +394,8 @@ def generate(env, version=None, abi=None
981              bindir="bin"
982              libdir="lib"
983          if verbose:
984 -            print "Intel C compiler: using version %s (%g), abi %s, in '%s/%s'"%\
985 -                  (repr(version), linux_ver_normalize(version),abi,topdir,bindir)
986 +            print("Intel C compiler: using version %s (%g), abi %s, in '%s/%s'"%\
987 +                  (repr(version), linux_ver_normalize(version),abi,topdir,bindir))
988              if is_linux:
989                  # Show the actual compiler version by running the compiler.
990                  os.system('%s/%s/icc --version'%(topdir,bindir))
991 @@ -439,7 +439,7 @@ def generate(env, version=None, abi=None
992                      env.PrependENVPath(p[0], os.path.join(topdir, p[2]))
993                  else:
994                      env.PrependENVPath(p[0], path.split(os.pathsep))
995 -                    # print "ICL %s: %s, final=%s"%(p[0], path, str(env['ENV'][p[0]]))
996 +                    # print("ICL %s: %s, final=%s"%(p[0], path, str(env['ENV'][p[0]])))
997  
998      if is_windows:
999          env['CC']        = 'icl'
1000 --- a/engine/SCons/Tool/MSCommon/common.py
1001 +++ b/engine/SCons/Tool/MSCommon/common.py
1002 @@ -38,7 +38,7 @@ import SCons.Util
1003  logfile = os.environ.get('SCONS_MSCOMMON_DEBUG')
1004  if logfile == '-':
1005      def debug(x):
1006 -        print x
1007 +        print(x)
1008  elif logfile:
1009      try:
1010          import logging
1011 --- a/engine/SCons/Tool/mslink.py
1012 +++ b/engine/SCons/Tool/mslink.py
1013 @@ -186,7 +186,7 @@ def RegServerFunc(target, source, env):
1014          if ret:
1015              raise SCons.Errors.UserError("Unable to register %s" % target[0])
1016          else:
1017 -            print "Registered %s sucessfully" % target[0]
1018 +            print("Registered %s sucessfully" % target[0])
1019          return ret
1020      return 0
1021  
1022 @@ -203,10 +203,10 @@ def embedManifestDllCheck(target, source
1023          if os.path.exists(manifestSrc):
1024              ret = (embedManifestDllAction) ([target[0]],None,env)        
1025              if ret:
1026 -                raise SCons.Errors.UserError, "Unable to embed manifest into %s" % (target[0])
1027 +                raise SCons.Errors.UserError("Unable to embed manifest into %s" % (target[0]))
1028              return ret
1029          else:
1030 -            print '(embed: no %s.manifest found; not embedding.)'%str(target[0])
1031 +            print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))
1032      return 0
1033  
1034  def embedManifestExeCheck(target, source, env):
1035 @@ -217,10 +217,10 @@ def embedManifestExeCheck(target, source
1036          if os.path.exists(manifestSrc):
1037              ret = (embedManifestExeAction) ([target[0]],None,env)
1038              if ret:
1039 -                raise SCons.Errors.UserError, "Unable to embed manifest into %s" % (target[0])
1040 +                raise SCons.Errors.UserError("Unable to embed manifest into %s" % (target[0]))
1041              return ret
1042          else:
1043 -            print '(embed: no %s.manifest found; not embedding.)'%str(target[0])
1044 +            print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))
1045      return 0
1046  
1047  embedManifestDllCheckAction = SCons.Action.Action(embedManifestDllCheck, None)
1048 --- a/engine/SCons/Tool/msvs.py
1049 +++ b/engine/SCons/Tool/msvs.py
1050 @@ -195,7 +195,7 @@ def makeHierarchy(sources):
1051                  dict = dict[part]
1052              dict[path[-1]] = file
1053          #else:
1054 -        #    print 'Warning: failed to decompose path for '+str(file)
1055 +        #    print('Warning: failed to decompose path for '+str(file))
1056      return hierarchy
1057  
1058  class _DSPGenerator(object):
1059 @@ -351,7 +351,7 @@ class _DSPGenerator(object):
1060                  config.platform = 'Win32'
1061  
1062              self.configs[variant] = config
1063 -            print "Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dspfile) + "'"
1064 +            print("Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dspfile) + "'")
1065  
1066          for i in range(len(variants)):
1067              AddConfig(self, variants[i], buildtarget[i], outdir[i], runfile[i], cmdargs)
1068 @@ -551,7 +551,7 @@ class _GenerateV6DSP(_DSPGenerator):
1069      def Build(self):
1070          try:
1071              self.file = open(self.dspabs,'w')
1072 -        except IOError, detail:
1073 +        except IOError as detail:
1074              raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail))
1075          else:
1076              self.PrintHeader()
1077 @@ -865,7 +865,7 @@ class _GenerateV7DSP(_DSPGenerator):
1078      def Build(self):
1079          try:
1080              self.file = open(self.dspabs,'w')
1081 -        except IOError, detail:
1082 +        except IOError as detail:
1083              raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail))
1084          else:
1085              self.PrintHeader()
1086 @@ -1033,7 +1033,7 @@ class _GenerateV10DSP(_DSPGenerator):
1087          self.filtersabs = self.dspabs + '.filters'
1088          try:
1089              self.filters_file = open(self.filtersabs, 'w')
1090 -        except IOError, detail:
1091 +        except IOError as detail:
1092              raise SCons.Errors.InternalError('Unable to open "' + self.filtersabs + '" for writing:' + str(detail))
1093              
1094          self.filters_file.write('<?xml version="1.0" encoding="utf-8"?>\n'
1095 @@ -1105,7 +1105,7 @@ class _GenerateV10DSP(_DSPGenerator):
1096          cats = sorted([k for k in categories.keys() if self.sources[k]],
1097                               key = lambda a: a.lower())
1098          
1099 -        # print vcxproj.filters file first
1100 +        # print(vcxproj.filters file first)
1101          self.filters_file.write('\t<ItemGroup>\n')
1102          for kind in cats:
1103              self.filters_file.write('\t\t<Filter Include="%s">\n'
1104 @@ -1135,7 +1135,7 @@ class _GenerateV10DSP(_DSPGenerator):
1105              
1106          self.filters_file.write('\t</ItemGroup>\n')
1107              
1108 -        # then print files and filters
1109 +        # then print(files and filters)
1110          for kind in cats:
1111              self.file.write('\t<ItemGroup>\n')
1112              self.filters_file.write('\t<ItemGroup>\n')
1113 @@ -1170,12 +1170,12 @@ class _GenerateV10DSP(_DSPGenerator):
1114                          '\t</ItemGroup>\n' % str(self.sconscript))
1115  
1116      def Parse(self):
1117 -        print "_GenerateV10DSP.Parse()"
1118 +        print("_GenerateV10DSP.Parse()")
1119  
1120      def Build(self):
1121          try:
1122              self.file = open(self.dspabs, 'w')
1123 -        except IOError, detail:
1124 +        except IOError as detail:
1125              raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail))
1126          else:
1127              self.PrintHeader()
1128 @@ -1252,7 +1252,7 @@ class _GenerateV7DSW(_DSWGenerator):
1129                  config.platform = 'Win32'
1130  
1131              self.configs[variant] = config
1132 -            print "Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dswfile) + "'"
1133 +            print("Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dswfile) + "'")
1134  
1135          if 'variant' not in env:
1136              raise SCons.Errors.InternalError("You must specify a 'variant' argument (i.e. 'Debug' or " +\
1137 @@ -1431,7 +1431,7 @@ class _GenerateV7DSW(_DSWGenerator):
1138      def Build(self):
1139          try:
1140              self.file = open(self.dswfile,'w')
1141 -        except IOError, detail:
1142 +        except IOError as detail:
1143              raise SCons.Errors.InternalError('Unable to open "' + self.dswfile + '" for writing:' + str(detail))
1144          else:
1145              self.PrintSolution()
1146 @@ -1480,7 +1480,7 @@ class _GenerateV6DSW(_DSWGenerator):
1147      def Build(self):
1148          try:
1149              self.file = open(self.dswfile,'w')
1150 -        except IOError, detail:
1151 +        except IOError as detail:
1152              raise SCons.Errors.InternalError('Unable to open "' + self.dswfile + '" for writing:' + str(detail))
1153          else:
1154              self.PrintWorkspace()
1155 @@ -1537,8 +1537,8 @@ def GenerateProject(target, source, env)
1156      if not dspfile is builddspfile:
1157          try:
1158              bdsp = open(str(builddspfile), "w+")
1159 -        except IOError, detail:
1160 -            print 'Unable to open "' + str(dspfile) + '" for writing:',detail,'\n'
1161 +        except IOError as detail:
1162 +            print('Unable to open "' + str(dspfile) + '" for writing:',detail,'\n')
1163              raise
1164  
1165          bdsp.write("This is just a placeholder file.\nThe real project file is here:\n%s\n" % dspfile.get_abspath())
1166 @@ -1553,8 +1553,8 @@ def GenerateProject(target, source, env)
1167  
1168              try:
1169                  bdsw = open(str(builddswfile), "w+")
1170 -            except IOError, detail:
1171 -                print 'Unable to open "' + str(dspfile) + '" for writing:',detail,'\n'
1172 +            except IOError as detail:
1173 +                print('Unable to open "' + str(dspfile) + '" for writing:',detail,'\n')
1174                  raise
1175  
1176              bdsw.write("This is just a placeholder file.\nThe real workspace file is here:\n%s\n" % dswfile.get_abspath())
1177 --- a/engine/SCons/Tool/qt.py
1178 +++ b/engine/SCons/Tool/qt.py
1179 @@ -130,12 +130,12 @@ class _Automoc(object):
1180              if not obj.has_builder():
1181                  # binary obj file provided
1182                  if debug:
1183 -                    print "scons: qt: '%s' seems to be a binary. Discarded." % str(obj)
1184 +                    print("scons: qt: '%s' seems to be a binary. Discarded." % str(obj))
1185                  continue
1186              cpp = obj.sources[0]
1187              if not splitext(str(cpp))[1] in cxx_suffixes:
1188                  if debug:
1189 -                    print "scons: qt: '%s' is no cxx file. Discarded." % str(cpp) 
1190 +                    print("scons: qt: '%s' is no cxx file. Discarded." % str(cpp) )
1191                  # c or fortran source
1192                  continue
1193              #cpp_contents = comment.sub('', cpp.get_text_contents())
1194 @@ -148,12 +148,12 @@ class _Automoc(object):
1195                  h = find_file(hname, (cpp.get_dir(),), env.File)
1196                  if h:
1197                      if debug:
1198 -                        print "scons: qt: Scanning '%s' (header of '%s')" % (str(h), str(cpp))
1199 +                        print("scons: qt: Scanning '%s' (header of '%s')" % (str(h), str(cpp)))
1200                      #h_contents = comment.sub('', h.get_text_contents())
1201                      h_contents = h.get_text_contents()
1202                      break
1203              if not h and debug:
1204 -                print "scons: qt: no header for '%s'." % (str(cpp))
1205 +                print("scons: qt: no header for '%s'." % (str(cpp)))
1206              if h and q_object_search.search(h_contents):
1207                  # h file with the Q_OBJECT macro found -> add moc_cpp
1208                  moc_cpp = env.Moc(h)
1209 @@ -161,14 +161,14 @@ class _Automoc(object):
1210                  out_sources.append(moc_o)
1211                  #moc_cpp.target_scanner = SCons.Defaults.CScan
1212                  if debug:
1213 -                    print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(h), str(moc_cpp))
1214 +                    print("scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(h), str(moc_cpp)))
1215              if cpp and q_object_search.search(cpp_contents):
1216                  # cpp file with Q_OBJECT macro found -> add moc
1217                  # (to be included in cpp)
1218                  moc = env.Moc(cpp)
1219                  env.Ignore(moc, moc)
1220                  if debug:
1221 -                    print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(cpp), str(moc))
1222 +                    print("scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(cpp), str(moc)))
1223                  #moc.source_scanner = SCons.Defaults.CScan
1224          # restore the original env attributes (FIXME)
1225          objBuilder.env = objBuilderEnv
1226 --- a/engine/SCons/Tool/tex.py
1227 +++ b/engine/SCons/Tool/tex.py
1228 @@ -147,15 +147,15 @@ def FindFile(name,suffixes,paths,env,req
1229          if ext:
1230              name = name + ext
1231      if Verbose:
1232 -        print " searching for '%s' with extensions: " % name,suffixes
1233 +        print(" searching for '%s' with extensions: " % name,suffixes)
1234  
1235      for path in paths:
1236          testName = os.path.join(path,name)
1237          if Verbose:
1238 -            print " look for '%s'" % testName
1239 +            print(" look for '%s'" % testName)
1240          if os.path.isfile(testName):
1241              if Verbose:
1242 -                print " found '%s'" % testName
1243 +                print(" found '%s'" % testName)
1244              return env.fs.File(testName)
1245          else:
1246              name_ext = SCons.Util.splitext(testName)[1]
1247 @@ -166,14 +166,14 @@ def FindFile(name,suffixes,paths,env,req
1248              for suffix in suffixes:
1249                  testNameExt = testName + suffix
1250                  if Verbose:
1251 -                    print " look for '%s'" % testNameExt
1252 +                    print(" look for '%s'" % testNameExt)
1253  
1254                  if os.path.isfile(testNameExt):
1255                      if Verbose:
1256 -                        print " found '%s'" % testNameExt
1257 +                        print(" found '%s'" % testNameExt)
1258                      return env.fs.File(testNameExt)
1259      if Verbose:
1260 -        print " did not find '%s'" % name
1261 +        print(" did not find '%s'" % name)
1262      return None
1263  
1264  def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None):
1265 @@ -232,7 +232,7 @@ def InternalLaTeXAuxAction(XXXLaTeXActio
1266          saved_hashes[suffix] = theNode.get_csig()
1267  
1268      if Verbose:
1269 -        print "hashes: ",saved_hashes
1270 +        print("hashes: ",saved_hashes)
1271  
1272      must_rerun_latex = True
1273  
1274 @@ -248,12 +248,12 @@ def InternalLaTeXAuxAction(XXXLaTeXActio
1275  
1276          if saved_hashes[suffix] == new_md5:
1277              if Verbose:
1278 -                print "file %s not changed" % (targetbase+suffix)
1279 +                print("file %s not changed" % (targetbase+suffix))
1280              return False        # unchanged
1281          saved_hashes[suffix] = new_md5
1282          must_rerun_latex = True
1283          if Verbose:
1284 -            print "file %s changed, rerunning Latex, new hash = " % (targetbase+suffix), new_md5
1285 +            print("file %s changed, rerunning Latex, new hash = " % (targetbase+suffix), new_md5)
1286          return True     # changed
1287  
1288      # generate the file name that latex will generate
1289 @@ -292,7 +292,7 @@ def InternalLaTeXAuxAction(XXXLaTeXActio
1290              auxfiles = list(dups.keys())
1291  
1292          if Verbose:
1293 -            print "auxfiles ",auxfiles
1294 +            print("auxfiles ",auxfiles)
1295  
1296          # Now decide if bibtex will need to be run.
1297          # The information that bibtex reads from the .aux file is
1298 @@ -306,7 +306,7 @@ def InternalLaTeXAuxAction(XXXLaTeXActio
1299                      content = open(target_aux, "rb").read()
1300                      if content.find("bibdata") != -1:
1301                          if Verbose:
1302 -                            print "Need to run bibtex"
1303 +                            print("Need to run bibtex")
1304                          bibfile = env.fs.File(SCons.Util.splitext(target_aux)[0])
1305                          result = BibTeXAction(bibfile, bibfile, env)
1306                          if result != 0:
1307 @@ -317,7 +317,7 @@ def InternalLaTeXAuxAction(XXXLaTeXActio
1308          if check_MD5(suffix_nodes['.idx'],'.idx') or (count == 1 and run_makeindex):
1309              # We must run makeindex
1310              if Verbose:
1311 -                print "Need to run makeindex"
1312 +                print("Need to run makeindex")
1313              idxfile = suffix_nodes['.idx']
1314              result = MakeIndexAction(idxfile, idxfile, env)
1315              if result != 0:
1316 @@ -335,7 +335,7 @@ def InternalLaTeXAuxAction(XXXLaTeXActio
1317          if check_MD5(suffix_nodes['.nlo'],'.nlo') or (count == 1 and run_nomenclature):
1318              # We must run makeindex
1319              if Verbose:
1320 -                print "Need to run makeindex for nomenclature"
1321 +                print("Need to run makeindex for nomenclature")
1322              nclfile = suffix_nodes['.nlo']
1323              result = MakeNclAction(nclfile, nclfile, env)
1324              if result != 0:
1325 @@ -347,7 +347,7 @@ def InternalLaTeXAuxAction(XXXLaTeXActio
1326          if check_MD5(suffix_nodes['.glo'],'.glo') or (count == 1 and run_glossaries) or (count == 1 and run_glossary):
1327              # We must run makeindex
1328              if Verbose:
1329 -                print "Need to run makeindex for glossary"
1330 +                print("Need to run makeindex for glossary")
1331              glofile = suffix_nodes['.glo']
1332              result = MakeGlossaryAction(glofile, glofile, env)
1333              if result != 0:
1334 @@ -359,7 +359,7 @@ def InternalLaTeXAuxAction(XXXLaTeXActio
1335          if check_MD5(suffix_nodes['.acn'],'.acn') or (count == 1 and run_acronyms):
1336              # We must run makeindex
1337              if Verbose:
1338 -                print "Need to run makeindex for acronyms"
1339 +                print("Need to run makeindex for acronyms")
1340              acrfile = suffix_nodes['.acn']
1341              result = MakeAcronymsAction(acrfile, acrfile, env)
1342              if result != 0:
1343 @@ -371,26 +371,26 @@ def InternalLaTeXAuxAction(XXXLaTeXActio
1344          if warning_rerun_re.search(logContent):
1345              must_rerun_latex = True
1346              if Verbose:
1347 -                print "rerun Latex due to latex or package rerun warning"
1348 +                print("rerun Latex due to latex or package rerun warning")
1349  
1350          if rerun_citations_re.search(logContent):
1351              must_rerun_latex = True
1352              if Verbose:
1353 -                print "rerun Latex due to 'Rerun to get citations correct' warning"
1354 +                print("rerun Latex due to 'Rerun to get citations correct' warning")
1355  
1356          if undefined_references_re.search(logContent):
1357              must_rerun_latex = True
1358              if Verbose:
1359 -                print "rerun Latex due to undefined references or citations"
1360 +                print("rerun Latex due to undefined references or citations")
1361  
1362          if (count >= int(env.subst('$LATEXRETRIES')) and must_rerun_latex):
1363 -            print "reached max number of retries on Latex ,",int(env.subst('$LATEXRETRIES'))
1364 +            print("reached max number of retries on Latex ,",int(env.subst('$LATEXRETRIES')))
1365  # end of while loop
1366  
1367      # rename Latex's output to what the target name is
1368      if not (str(target[0]) == resultfilename  and  os.path.isfile(resultfilename)):
1369          if os.path.isfile(resultfilename):
1370 -            print "move %s to %s" % (resultfilename, str(target[0]), )
1371 +            print("move %s to %s" % (resultfilename, str(target[0]), ))
1372              shutil.move(resultfilename,str(target[0]))
1373  
1374      # Original comment (when TEXPICTS was not restored):
1375 @@ -444,27 +444,27 @@ def is_LaTeX(flist,env,abspath):
1376      else:
1377          env['ENV']['TEXINPUTS'] = savedpath
1378      if Verbose:
1379 -        print "is_LaTeX search path ",paths
1380 -        print "files to search :",flist
1381 +        print("is_LaTeX search path ",paths)
1382 +        print("files to search :",flist)
1383  
1384      # Now that we have the search path and file list, check each one
1385      for f in flist:
1386          if Verbose:
1387 -            print " checking for Latex source ",str(f)
1388 +            print(" checking for Latex source ",str(f))
1389  
1390          content = f.get_text_contents()
1391          if LaTeX_re.search(content):
1392              if Verbose:
1393 -                print "file %s is a LaTeX file" % str(f)
1394 +                print("file %s is a LaTeX file" % str(f))
1395              return 1
1396          if Verbose:
1397 -            print "file %s is not a LaTeX file" % str(f)
1398 +            print("file %s is not a LaTeX file" % str(f))
1399  
1400          # now find included files
1401          inc_files = [ ]
1402          inc_files.extend( include_re.findall(content) )
1403          if Verbose:
1404 -            print "files included by '%s': "%str(f),inc_files
1405 +            print("files included by '%s': "%str(f),inc_files)
1406          # inc_files is list of file names as given. need to find them
1407          # using TEXINPUTS paths.
1408  
1409 @@ -474,7 +474,7 @@ def is_LaTeX(flist,env,abspath):
1410              # make this a list since is_LaTeX takes a list.
1411              fileList = [srcNode,]
1412              if Verbose:
1413 -                print "FindFile found ",srcNode
1414 +                print("FindFile found ",srcNode)
1415              if srcNode is not None:
1416                  file_test = is_LaTeX(fileList, env, abspath)
1417  
1418 @@ -483,7 +483,7 @@ def is_LaTeX(flist,env,abspath):
1419                  return file_test
1420  
1421          if Verbose:
1422 -            print " done scanning ",str(f)
1423 +            print(" done scanning ",str(f))
1424  
1425      return 0
1426  
1427 @@ -548,7 +548,7 @@ def ScanFiles(theFile, target, paths, fi
1428  
1429      content = theFile.get_text_contents()
1430      if Verbose:
1431 -        print " scanning ",str(theFile)
1432 +        print(" scanning ",str(theFile))
1433  
1434      for i in range(len(file_tests_search)):
1435          if file_tests[i][0] is None:
1436 @@ -558,12 +558,12 @@ def ScanFiles(theFile, target, paths, fi
1437      if incResult:
1438          aux_files.append(os.path.join(targetdir, incResult.group(1)))
1439      if Verbose:
1440 -        print "\include file names : ", aux_files
1441 +        print("\include file names : ", aux_files)
1442      # recursively call this on each of the included files
1443      inc_files = [ ]
1444      inc_files.extend( include_re.findall(content) )
1445      if Verbose:
1446 -        print "files included by '%s': "%str(theFile),inc_files
1447 +        print("files included by '%s': "%str(theFile),inc_files)
1448      # inc_files is list of file names as given. need to find them
1449      # using TEXINPUTS paths.
1450  
1451 @@ -572,7 +572,7 @@ def ScanFiles(theFile, target, paths, fi
1452          if srcNode is not None:
1453              file_tests = ScanFiles(srcNode, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files)
1454      if Verbose:
1455 -        print " done scanning ",str(theFile)
1456 +        print(" done scanning ",str(theFile))
1457      return file_tests
1458  
1459  def tex_emitter_core(target, source, env, graphics_extensions):
1460 @@ -602,7 +602,7 @@ def tex_emitter_core(target, source, env
1461      env.SideEffect(logfilename,target[0])
1462      env.SideEffect(flsfilename,target[0])
1463      if Verbose:
1464 -        print "side effect :",auxfilename,logfilename,flsfilename
1465 +        print("side effect :",auxfilename,logfilename,flsfilename)
1466      env.Clean(target[0],auxfilename)
1467      env.Clean(target[0],logfilename)
1468      env.Clean(target[0],flsfilename)
1469 @@ -671,7 +671,7 @@ def tex_emitter_core(target, source, env
1470      else:
1471          env['ENV']['TEXINPUTS'] = savedpath
1472      if Verbose:
1473 -        print "search path ",paths
1474 +        print("search path ",paths)
1475  
1476      aux_files = []
1477      file_tests = ScanFiles(source[0], target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files)
1478 @@ -692,14 +692,14 @@ def tex_emitter_core(target, source, env
1479                  for suffix in suffix_list[:-1]:
1480                      env.SideEffect(file_name + suffix,target[0])
1481                      if Verbose:
1482 -                        print "side effect :",file_name + suffix
1483 +                        print("side effect :",file_name + suffix)
1484                      env.Clean(target[0],file_name + suffix)
1485  
1486      for aFile in aux_files:
1487          aFile_base = SCons.Util.splitext(aFile)[0]
1488          env.SideEffect(aFile_base + '.aux',target[0])
1489          if Verbose:
1490 -            print "side effect :",aFile_base + '.aux'
1491 +            print("side effect :",aFile_base + '.aux')
1492          env.Clean(target[0],aFile_base + '.aux')
1493      # read fls file to get all other files that latex creates and will read on the next pass
1494      # remove files from list that we explicitly dealt with above
1495 @@ -712,7 +712,7 @@ def tex_emitter_core(target, source, env
1496                  out_files.remove(filename)
1497          env.SideEffect(out_files,target[0])
1498          if Verbose:
1499 -            print "side effect :",out_files
1500 +            print("side effect :",out_files)
1501          env.Clean(target[0],out_files)
1502  
1503      return (target, source)
1504 --- a/engine/SCons/Action.py
1505 +++ b/engine/SCons/Action.py
1506 @@ -553,7 +553,7 @@ class _ActionAction(ActionBase):
1507                  source = executor.get_all_sources()
1508              t = ' and '.join(map(str, target))
1509              l = '\n  '.join(self.presub_lines(env))
1510 -            out = u"Building %s with action:\n  %s\n" % (t, l)
1511 +            out = "Building %s with action:\n  %s\n" % (t, l)
1512              sys.stdout.write(out)
1513          cmd = None
1514          if show and self.strfunction:
1515 @@ -672,7 +672,7 @@ def _subproc(scons_env, cmd, error = 'ig
1516  
1517      try:
1518          return subprocess.Popen(cmd, **kw)
1519 -    except EnvironmentError, e:
1520 +    except EnvironmentError as e:
1521          if error == 'raise': raise
1522          # return a dummy Popen instance that only returns error
1523          class dummyPopen(object):
1524 @@ -1060,11 +1060,11 @@ class FunctionAction(_ActionAction):
1525              rsources = list(map(rfile, source))
1526              try:
1527                  result = self.execfunction(target=target, source=rsources, env=env)
1528 -            except KeyboardInterrupt, e:
1529 +            except KeyboardInterrupt as e:
1530                  raise
1531 -            except SystemExit, e:
1532 +            except SystemExit as e:
1533                  raise
1534 -            except Exception, e:
1535 +            except Exception as e:
1536                  result = e
1537                  exc_info = sys.exc_info()
1538  
1539 --- a/engine/SCons/Builder.py
1540 +++ b/engine/SCons/Builder.py
1541 @@ -167,7 +167,7 @@ class DictCmdGenerator(SCons.Util.Select
1542  
1543          try:
1544              ret = SCons.Util.Selector.__call__(self, env, source, ext)
1545 -        except KeyError, e:
1546 +        except KeyError as e:
1547              raise UserError("Ambiguous suffixes after environment substitution: %s == %s == %s" % (e.args[0], e.args[1], e.args[2]))
1548          if ret is None:
1549              raise UserError("While building `%s' from `%s': Don't know how to build from a source file with suffix `%s'.  Expected a suffix in this list: %s." % \
1550 --- a/engine/SCons/Defaults.py
1551 +++ b/engine/SCons/Defaults.py
1552 @@ -221,7 +221,7 @@ def mkdir_func(dest):
1553      for entry in dest:
1554          try:
1555              os.makedirs(str(entry))
1556 -        except os.error, e:
1557 +        except os.error as e:
1558              p = str(entry)
1559              if (e.args[0] == errno.EEXIST or
1560                      (sys.platform=='win32' and e.args[0]==183)) \
1561 --- a/engine/SCons/Job.py
1562 +++ b/engine/SCons/Job.py
1563 @@ -278,14 +278,14 @@ else:
1564  
1565              try:
1566                  prev_size = threading.stack_size(stack_size*1024) 
1567 -            except AttributeError, e:
1568 +            except AttributeError as e:
1569                  # Only print a warning if the stack size has been
1570                  # explicitly set.
1571                  if not explicit_stack_size is None:
1572                      msg = "Setting stack size is unsupported by this version of Python:\n    " + \
1573                          e.args[0]
1574                      SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
1575 -            except ValueError, e:
1576 +            except ValueError as e:
1577                  msg = "Setting stack size failed:\n    " + str(e)
1578                  SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
1579  
1580 --- a/engine/SCons/Node/__init__.py
1581 +++ b/engine/SCons/Node/__init__.py
1582 @@ -370,7 +370,7 @@ class Node(object):
1583          """
1584          try:
1585              self.get_executor()(self, **kw)
1586 -        except SCons.Errors.BuildError, e:
1587 +        except SCons.Errors.BuildError as e:
1588              e.node = self
1589              raise
1590  
1591 @@ -826,7 +826,7 @@ class Node(object):
1592          """Adds dependencies."""
1593          try:
1594              self._add_child(self.depends, self.depends_set, depend)
1595 -        except TypeError, e:
1596 +        except TypeError as e:
1597              e = e.args[0]
1598              if SCons.Util.is_List(e):
1599                  s = list(map(str, e))
1600 @@ -843,7 +843,7 @@ class Node(object):
1601          """Adds dependencies to ignore."""
1602          try:
1603              self._add_child(self.ignore, self.ignore_set, depend)
1604 -        except TypeError, e:
1605 +        except TypeError as e:
1606              e = e.args[0]
1607              if SCons.Util.is_List(e):
1608                  s = list(map(str, e))
1609 @@ -857,7 +857,7 @@ class Node(object):
1610              return
1611          try:
1612              self._add_child(self.sources, self.sources_set, source)
1613 -        except TypeError, e:
1614 +        except TypeError as e:
1615              e = e.args[0]
1616              if SCons.Util.is_List(e):
1617                  s = list(map(str, e))
1618 --- a/engine/SCons/Platform/posix.py
1619 +++ b/engine/SCons/Platform/posix.py
1620 @@ -77,7 +77,7 @@ def exec_fork(l, env): 
1621          exitval = 127
1622          try:
1623              os.execvpe(l[0], l, env)
1624 -        except OSError, e:
1625 +        except OSError as e:
1626              exitval = exitvalmap.get(e[0], e[0])
1627              sys.stderr.write("scons: %s: %s\n" % (l[0], e[1]))
1628          os._exit(exitval)
1629 @@ -125,8 +125,8 @@ def process_cmd_output(cmd_stdout, cmd_s
1630                  else:
1631                      #sys.__stderr__.write( "str(stderr) = %s\n" % str )
1632                      stderr.write(str)
1633 -        except select.error, (_errno, _strerror):
1634 -            if _errno != errno.EINTR:
1635 +        except OSError as e:
1636 +            if e.errno != errno.EINTR:
1637                  raise
1638  
1639  def exec_popen3(l, env, stdout, stderr):
1640 @@ -164,7 +164,7 @@ def exec_piped_fork(l, env, stdout, stde
1641          exitval = 127
1642          try:
1643              os.execvpe(l[0], l, env)
1644 -        except OSError, e:
1645 +        except OSError as e:
1646              exitval = exitvalmap.get(e[0], e[0])
1647              stderr.write("scons: %s: %s\n" % (l[0], e[1]))
1648          os._exit(exitval)
1649 --- a/engine/SCons/Platform/win32.py
1650 +++ b/engine/SCons/Platform/win32.py
1651 @@ -125,7 +125,7 @@ def piped_spawn(sh, escape, cmd, args, e
1652          try:
1653              args = [sh, '/C', escape(' '.join(args)) ]
1654              ret = os.spawnve(os.P_WAIT, sh, args, env)
1655 -        except OSError, e:
1656 +        except OSError as e:
1657              # catch any error
1658              try:
1659                  ret = exitvalmap[e[0]]
1660 @@ -153,7 +153,7 @@ def piped_spawn(sh, escape, cmd, args, e
1661  def exec_spawn(l, env):
1662      try:
1663          result = os.spawnve(os.P_WAIT, l[0], l, env)
1664 -    except OSError, e:
1665 +    except OSError as e:
1666          try:
1667              result = exitvalmap[e[0]]
1668              sys.stderr.write("scons: %s: %s\n" % (l[0], e[1]))
1669 --- a/engine/SCons/Scanner/C.py
1670 +++ b/engine/SCons/Scanner/C.py
1671 @@ -59,7 +59,7 @@ class SConsCPPScanner(SCons.cpp.PreProce
1672      def read_file(self, file):
1673          try:
1674              fp = open(str(file.rfile()))
1675 -        except EnvironmentError, e:
1676 +        except EnvironmentError as e:
1677              self.missing.append((file, self.current_file))
1678              return ''
1679          else:
1680 --- a/engine/SCons/Script/SConsOptions.py
1681 +++ b/engine/SCons/Script/SConsOptions.py
1682 @@ -161,7 +161,7 @@ class SConsValues(optparse.Values):
1683          elif name == 'diskcheck':
1684              try:
1685                  value = diskcheck_convert(value)
1686 -            except ValueError, v:
1687 +            except ValueError as v:
1688                  raise SCons.Errors.UserError("Not a valid diskcheck value: %s"%v)
1689              if 'diskcheck' not in self.__dict__:
1690                  # No --diskcheck= option was specified on the command line.
1691 @@ -629,7 +629,7 @@ def Parser(version):
1692      def opt_diskcheck(option, opt, value, parser):
1693          try:
1694              diskcheck_value = diskcheck_convert(value)
1695 -        except ValueError, e:
1696 +        except ValueError as e:
1697              raise OptionValueError("Warning: `%s' is not a valid diskcheck type" % e)
1698          setattr(parser.values, option.dest, diskcheck_value)
1699  
1700 --- a/engine/SCons/Subst.py
1701 +++ b/engine/SCons/Subst.py
1702 @@ -438,7 +438,7 @@ def scons_subst(strSubst, env, mode=SUBS
1703                              s = eval(key, self.gvars, lvars)
1704                          except KeyboardInterrupt:
1705                              raise
1706 -                        except Exception, e:
1707 +                        except Exception as e:
1708                              if e.__class__ in AllowableExceptions:
1709                                  return ''
1710                              raise_exception(e, lvars['TARGETS'], s)
1711 @@ -653,7 +653,7 @@ def scons_subst_list(strSubst, env, mode
1712                              s = eval(key, self.gvars, lvars)
1713                          except KeyboardInterrupt:
1714                              raise
1715 -                        except Exception, e:
1716 +                        except Exception as e:
1717                              if e.__class__ in AllowableExceptions:
1718                                  return
1719                              raise_exception(e, lvars['TARGETS'], s)
1720 --- a/engine/SCons/Tool/filesystem.py
1721 +++ b/engine/SCons/Tool/filesystem.py
1722 @@ -66,7 +66,7 @@ def generate(env):
1723      try:
1724          env['BUILDERS']['CopyTo']
1725          env['BUILDERS']['CopyAs']
1726 -    except KeyError, e:
1727 +    except KeyError as e:
1728          global copyToBuilder
1729          if copyToBuilder is None:
1730              copyToBuilder = SCons.Builder.Builder(
1731 --- a/engine/SCons/Tool/__init__.py
1732 +++ b/engine/SCons/Tool/__init__.py
1733 @@ -110,7 +110,7 @@ class Tool(object):
1734                  finally:
1735                      if file:
1736                          file.close()
1737 -            except ImportError, e:
1738 +            except ImportError as e:
1739                  if str(e)!="No module named %s"%self.name:
1740                      raise SCons.Errors.EnvironmentError(e)
1741                  try:
1742 @@ -122,7 +122,7 @@ class Tool(object):
1743                          try:
1744                              importer = zipimport.zipimporter(aPath)
1745                              return importer.load_module(self.name)
1746 -                        except ImportError, e:
1747 +                        except ImportError as e:
1748                              pass
1749          finally:
1750              sys.path = oldpythonpath
1751 @@ -140,7 +140,7 @@ class Tool(object):
1752                      if file:
1753                          file.close()
1754                      return module
1755 -                except ImportError, e:
1756 +                except ImportError as e:
1757                      if str(e)!="No module named %s"%self.name:
1758                          raise SCons.Errors.EnvironmentError(e)
1759                      try:
1760 @@ -149,10 +149,10 @@ class Tool(object):
1761                          module = importer.load_module(full_name)
1762                          setattr(SCons.Tool, self.name, module)
1763                          return module
1764 -                    except ImportError, e:
1765 +                    except ImportError as e:
1766                          m = "No tool named '%s': %s" % (self.name, e)
1767                          raise SCons.Errors.EnvironmentError(m)
1768 -            except ImportError, e:
1769 +            except ImportError as e:
1770                  m = "No tool named '%s': %s" % (self.name, e)
1771                  raise SCons.Errors.EnvironmentError(m)
1772  
1773 --- a/engine/SCons/Tool/install.py
1774 +++ b/engine/SCons/Tool/install.py
1775 @@ -81,21 +81,21 @@ def scons_copytree(src, dst, symlinks=Fa
1776              else:
1777                  shutil.copy2(srcname, dstname)
1778              # XXX What about devices, sockets etc.?
1779 -        except (IOError, os.error), why:
1780 +        except (IOError, os.error) as why:
1781              errors.append((srcname, dstname, str(why)))
1782          # catch the CopytreeError from the recursive copytree so that we can
1783          # continue with other files
1784 -        except CopytreeError, err:
1785 +        except CopytreeError as err:
1786              errors.extend(err.args[0])
1787      try:
1788          shutil.copystat(src, dst)
1789      except WindowsError:
1790          # can't copy file access times on Windows
1791          pass
1792 -    except OSError, why:
1793 +    except OSError as why:
1794          errors.extend((src, dst, str(why)))
1795      if errors:
1796 -        raise CopytreeError, errors
1797 +        raise CopytreeError(errors)
1798  
1799  
1800  #
1801 --- a/engine/SCons/Tool/MSCommon/netframework.py
1802 +++ b/engine/SCons/Tool/MSCommon/netframework.py
1803 @@ -40,7 +40,7 @@ def find_framework_root():
1804      try:
1805          froot = read_reg(_FRAMEWORKDIR_HKEY_ROOT)
1806          debug("Found framework install root in registry: %s" % froot)
1807 -    except WindowsError, e:
1808 +    except WindowsError as e:
1809          debug("Could not read reg key %s" % _FRAMEWORKDIR_HKEY_ROOT)
1810          return None
1811  
1812 --- a/engine/SCons/Tool/MSCommon/sdk.py
1813 +++ b/engine/SCons/Tool/MSCommon/sdk.py
1814 @@ -80,7 +80,7 @@ class SDKDefinition(object):
1815  
1816          try:
1817              sdk_dir = common.read_reg(hkey)
1818 -        except WindowsError, e:
1819 +        except WindowsError as e:
1820              debug('find_sdk_dir(): no SDK registry key %s' % repr(hkey))
1821              return None
1822  
1823 @@ -299,7 +299,7 @@ def get_cur_sdk_dir_from_reg():
1824      try:
1825          val = common.read_reg(_CURINSTALLED_SDK_HKEY_ROOT)
1826          debug("Found current sdk dir in registry: %s" % val)
1827 -    except WindowsError, e:
1828 +    except WindowsError as e:
1829          debug("Did not find current sdk in registry")
1830          return None
1831  
1832 --- a/engine/SCons/Tool/MSCommon/vc.py
1833 +++ b/engine/SCons/Tool/MSCommon/vc.py
1834 @@ -117,13 +117,13 @@ def get_host_target(env):
1835          
1836      try:
1837          host = _ARCH_TO_CANONICAL[host_platform.lower()]
1838 -    except KeyError, e:
1839 +    except KeyError as e:
1840          msg = "Unrecognized host architecture %s"
1841          raise ValueError(msg % repr(host_platform))
1842  
1843      try:
1844          target = _ARCH_TO_CANONICAL[target_platform.lower()]
1845 -    except KeyError, e:
1846 +    except KeyError as e:
1847          raise ValueError("Unrecognized target architecture %s" % target_platform)
1848  
1849      return (host, target,req_target_platform)
1850 @@ -161,7 +161,7 @@ def msvc_version_to_maj_min(msvc_version
1851         maj = int(t[0])
1852         min = int(t[1])
1853         return maj, min
1854 -   except ValueError, e:
1855 +   except ValueError as e:
1856         raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
1857  
1858  def is_host_target_supported(host_target, msvc_version):
1859 @@ -210,7 +210,7 @@ def find_vc_pdir(msvc_version):
1860          key = root + key
1861          try:
1862              comps = common.read_reg(key)
1863 -        except WindowsError, e:
1864 +        except WindowsError as e:
1865              debug('find_vc_dir(): no VC registry key %s' % repr(key))
1866          else:
1867              debug('find_vc_dir(): found VC in registry: %s' % comps)
1868 @@ -282,7 +282,7 @@ def get_installed_vcs():
1869                  installed_versions.append(ver)
1870              else:
1871                  debug('find_vc_pdir return None for ver %s' % ver)
1872 -        except VisualCException, e:
1873 +        except VisualCException as e:
1874              debug('did not find VC %s: caught exception %s' % (ver, str(e)))
1875      return installed_versions
1876  
1877 @@ -376,7 +376,7 @@ def msvc_find_valid_batch_script(env,ver
1878          try:
1879              (vc_script,sdk_script) = find_batch_file(env,version,host_platform,tp)
1880              debug('vc.py:msvc_find_valid_batch_script() vc_script:%s sdk_script:%s'%(vc_script,sdk_script))
1881 -        except VisualCException, e:
1882 +        except VisualCException as e:
1883              msg = str(e)
1884              debug('Caught exception while looking for batch file (%s)' % msg)
1885              warn_msg = "VC version %s not installed.  " + \
1886 @@ -391,14 +391,14 @@ def msvc_find_valid_batch_script(env,ver
1887          if vc_script:
1888              try:
1889                  d = script_env(vc_script, args=arg)
1890 -            except BatchFileExecutionError, e:
1891 +            except BatchFileExecutionError as e:
1892                  debug('vc.py:msvc_find_valid_batch_script() use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e))
1893                  vc_script=None
1894          if not vc_script and sdk_script:
1895              debug('vc.py:msvc_find_valid_batch_script() use_script 4: trying sdk script: %s'%(sdk_script))
1896              try:
1897                  d = script_env(sdk_script,args=[])
1898 -            except BatchFileExecutionError,e:
1899 +            except BatchFileExecutionError as e:
1900                  debug('vc.py:msvc_find_valid_batch_script() use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e))
1901                  continue
1902          elif not vc_script and not sdk_script:
1903 --- a/engine/SCons/Tool/MSCommon/vs.py
1904 +++ b/engine/SCons/Tool/MSCommon/vs.py
1905 @@ -85,7 +85,7 @@ class VisualStudio(object):
1906              key = root + key
1907              try:
1908                  comps = read_reg(key)
1909 -            except WindowsError, e:
1910 +            except WindowsError as e:
1911                  debug('find_vs_dir_by_reg(): no VS registry key %s' % repr(key))
1912              else:
1913                  debug('find_vs_dir_by_reg(): found VS in registry: %s' % comps)
1914 --- a/engine/SCons/Tool/packaging/__init__.py
1915 +++ b/engine/SCons/Tool/packaging/__init__.py
1916 @@ -120,7 +120,7 @@ def Package(env, target=None, source=Non
1917          try:
1918              file,path,desc=imp.find_module(type, __path__)
1919              return imp.load_module(type, file, path, desc)
1920 -        except ImportError, e:
1921 +        except ImportError as e:
1922              raise EnvironmentError("packager %s not available: %s"%(type,str(e)))
1923  
1924      packagers=list(map(load_packager, PACKAGETYPE))
1925 @@ -141,7 +141,7 @@ def Package(env, target=None, source=Non
1926          if 'PACKAGEROOT' not in kw:
1927              kw['PACKAGEROOT'] = default_name%kw
1928  
1929 -    except KeyError, e:
1930 +    except KeyError as e:
1931          raise SCons.Errors.UserError( "Missing Packagetag '%s'"%e.args[0] )
1932  
1933      # setup the source files
1934 @@ -157,10 +157,10 @@ def Package(env, target=None, source=Non
1935  
1936          assert( len(target) == 0 )
1937  
1938 -    except KeyError, e:
1939 +    except KeyError as e:
1940          raise SCons.Errors.UserError( "Missing Packagetag '%s' for %s packager"\
1941                                        % (e.args[0],packager.__name__) )
1942 -    except TypeError, e:
1943 +    except TypeError as e:
1944          # this exception means that a needed argument for the packager is
1945          # missing. As our packagers get their "tags" as named function
1946          # arguments we need to find out which one is missing.
1947 --- a/engine/SCons/Tool/packaging/msi.py
1948 +++ b/engine/SCons/Tool/packaging/msi.py
1949 @@ -216,7 +216,7 @@ def build_wxsfile(target, source, env):
1950          if 'CHANGE_SPECFILE' in env:
1951              env['CHANGE_SPECFILE'](target, source)
1952  
1953 -    except KeyError, e:
1954 +    except KeyError as e:
1955          raise SCons.Errors.UserError( '"%s" package field for MSI is missing.' % e.args[0] )
1956  
1957  #
1958 --- a/engine/SCons/Tool/packaging/rpm.py
1959 +++ b/engine/SCons/Tool/packaging/rpm.py
1960 @@ -115,7 +115,7 @@ def collectintargz(target, source, env):
1961      try:
1962          #tarball = env['SOURCE_URL'].split('/')[-1]
1963          tarball = env['SOURCE_URL'].split('/')[-1]
1964 -    except KeyError, e:
1965 +    except KeyError as e:
1966          raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )
1967  
1968      tarball = src_targz.package(env, source=sources, target=tarball,
1969 @@ -151,7 +151,7 @@ def build_specfile(target, source, env):
1970          if 'CHANGE_SPECFILE' in env:
1971              env['CHANGE_SPECFILE'](target, source)
1972  
1973 -    except KeyError, e:
1974 +    except KeyError as e:
1975          raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] )
1976  
1977  
1978 @@ -339,7 +339,7 @@ class SimpleTagCompiler(object):
1979          for key, replacement in domestic:
1980              try:
1981                  str = str + replacement % values[key]
1982 -            except KeyError, e:
1983 +            except KeyError as e:
1984                  if self.mandatory:
1985                      raise e
1986  
1987 @@ -352,7 +352,7 @@ class SimpleTagCompiler(object):
1988                  int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x]
1989                  for v in int_values_for_key:
1990                      str = str + replacement % v
1991 -            except KeyError, e:
1992 +            except KeyError as e:
1993                  if self.mandatory:
1994                      raise e
1995  
1996 --- a/engine/SCons/Tool/textfile.py
1997 +++ b/engine/SCons/Tool/textfile.py
1998 @@ -107,7 +107,7 @@ def _action(target, source, env):
1999      # write the file
2000      try:
2001          fd = open(target[0].get_path(), "wb")
2002 -    except (OSError,IOError), e:
2003 +    except (OSError,IOError) as e:
2004          raise SCons.Errors.UserError("Can't write target file %s" % target[0])
2005      # separate lines by 'linesep' only if linesep is not empty
2006      lsep = None
2007 --- a/engine/SCons/Variables/__init__.py
2008 +++ b/engine/SCons/Variables/__init__.py
2009 @@ -170,7 +170,7 @@ class Variables(object):
2010                      sys.path.insert(0, dir)
2011                  try:
2012                      values['__name__'] = filename
2013 -                    exec open(filename, 'rU').read() in {}, values
2014 +                    exec(open(filename, 'rU').read() in {}, values)
2015                  finally:
2016                      if dir:
2017                          del sys.path[0]
2018 @@ -206,7 +206,7 @@ class Variables(object):
2019                          env[option.key] = option.converter(value)
2020                      except TypeError:
2021                          env[option.key] = option.converter(value, env)
2022 -                except ValueError, x:
2023 +                except ValueError as x:
2024                      raise SCons.Errors.UserError('Error converting option: %s\n%s'%(option.key, x))
2025  
2026  
2027 @@ -268,7 +268,7 @@ class Variables(object):
2028              finally:
2029                  fh.close()
2030  
2031 -        except IOError, x:
2032 +        except IOError as x:
2033              raise SCons.Errors.UserError('Error writing options to file: %s\n%s' % (filename, x))
2034  
2035      def GenerateHelpText(self, env, sort=None):
2036 --- a/engine/SCons/Script/__init__.py
2037 +++ b/engine/SCons/Script/__init__.py
2038 @@ -364,7 +364,7 @@ GlobalDefaultBuilders = [
2039  ]
2040  
2041  for name in GlobalDefaultEnvironmentFunctions + GlobalDefaultBuilders:
2042 -    exec "%s = _SConscript.DefaultEnvironmentCall(%s)" % (name, repr(name))
2043 +    exec("%s = _SConscript.DefaultEnvironmentCall(%s)" % (name, repr(name)))
2044  del name
2045  
2046  # There are a handful of variables that used to live in the