summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorGary Oberbrunner <garyo@oberbrunner.com>2013-09-22 17:08:12 (GMT)
committerGary Oberbrunner <garyo@oberbrunner.com>2013-09-22 17:08:12 (GMT)
commit953dc41b8b720fdcec7955de67d23206214e5125 (patch)
treeb95b2144ccf82d8227cec025af152f4eadfa7282 /src
parent328e541f40849c270fc75f0932594d18d2e6340b (diff)
downloadSCons-953dc41b8b720fdcec7955de67d23206214e5125.zip
SCons-953dc41b8b720fdcec7955de67d23206214e5125.tar.gz
SCons-953dc41b8b720fdcec7955de67d23206214e5125.tar.bz2
Result of raw 2to3 run (2to3-2.7); checkpoint for python3 conversion.
Diffstat (limited to 'src')
-rw-r--r--src/engine/SCons/Action.py47
-rw-r--r--src/engine/SCons/ActionTests.py12
-rw-r--r--src/engine/SCons/Builder.py20
-rw-r--r--src/engine/SCons/BuilderTests.py28
-rw-r--r--src/engine/SCons/CacheDirTests.py2
-rw-r--r--src/engine/SCons/Debug.py4
-rw-r--r--src/engine/SCons/Defaults.py11
-rw-r--r--src/engine/SCons/DefaultsTests.py2
-rw-r--r--src/engine/SCons/Environment.py59
-rw-r--r--src/engine/SCons/EnvironmentTests.py44
-rw-r--r--src/engine/SCons/ErrorsTests.py12
-rw-r--r--src/engine/SCons/ExecutorTests.py2
-rw-r--r--src/engine/SCons/Job.py4
-rw-r--r--src/engine/SCons/Memoize.py4
-rw-r--r--src/engine/SCons/MemoizeTests.py4
-rw-r--r--src/engine/SCons/Node/FS.py23
-rw-r--r--src/engine/SCons/Node/FSTests.py34
-rw-r--r--src/engine/SCons/Node/__init__.py12
-rw-r--r--src/engine/SCons/Options/__init__.py10
-rw-r--r--src/engine/SCons/Platform/__init__.py4
-rw-r--r--src/engine/SCons/Platform/aix.py2
-rw-r--r--src/engine/SCons/Platform/cygwin.py2
-rw-r--r--src/engine/SCons/Platform/darwin.py2
-rw-r--r--src/engine/SCons/Platform/hpux.py2
-rw-r--r--src/engine/SCons/Platform/irix.py2
-rw-r--r--src/engine/SCons/Platform/os2.py2
-rw-r--r--src/engine/SCons/Platform/posix.py9
-rw-r--r--src/engine/SCons/Platform/sunos.py2
-rw-r--r--src/engine/SCons/Platform/win32.py4
-rw-r--r--src/engine/SCons/SConf.py10
-rw-r--r--src/engine/SCons/SConfTests.py2
-rw-r--r--src/engine/SCons/SConsign.py16
-rw-r--r--src/engine/SCons/Scanner/C.py2
-rw-r--r--src/engine/SCons/Scanner/Fortran.py3
-rw-r--r--src/engine/SCons/Scanner/LaTeX.py4
-rw-r--r--src/engine/SCons/Scanner/Prog.py3
-rw-r--r--src/engine/SCons/Scanner/ProgTests.py4
-rw-r--r--src/engine/SCons/Scanner/ScannerTests.py2
-rw-r--r--src/engine/SCons/Scanner/__init__.py5
-rw-r--r--src/engine/SCons/Script/Interactive.py12
-rw-r--r--src/engine/SCons/Script/Main.py61
-rw-r--r--src/engine/SCons/Script/SConsOptions.py8
-rw-r--r--src/engine/SCons/Script/SConscript.py22
-rw-r--r--src/engine/SCons/Script/__init__.py8
-rw-r--r--src/engine/SCons/Subst.py8
-rw-r--r--src/engine/SCons/SubstTests.py48
-rw-r--r--src/engine/SCons/Taskmaster.py44
-rw-r--r--src/engine/SCons/TaskmasterTests.py10
-rw-r--r--src/engine/SCons/Tool/FortranCommon.py2
-rw-r--r--src/engine/SCons/Tool/GettextCommon.py12
-rw-r--r--src/engine/SCons/Tool/MSCommon/common.py6
-rw-r--r--src/engine/SCons/Tool/MSCommon/netframework.py4
-rw-r--r--src/engine/SCons/Tool/MSCommon/sdk.py8
-rw-r--r--src/engine/SCons/Tool/MSCommon/vc.py24
-rw-r--r--src/engine/SCons/Tool/MSCommon/vs.py6
-rw-r--r--src/engine/SCons/Tool/__init__.py36
-rw-r--r--src/engine/SCons/Tool/aixcc.py2
-rw-r--r--src/engine/SCons/Tool/aixf77.py2
-rw-r--r--src/engine/SCons/Tool/aixlink.py4
-rw-r--r--src/engine/SCons/Tool/applelink.py2
-rw-r--r--src/engine/SCons/Tool/cvf.py2
-rw-r--r--src/engine/SCons/Tool/cyglink.py2
-rw-r--r--src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/docbook.py10
-rw-r--r--src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/xslt.py12
-rw-r--r--src/engine/SCons/Tool/dvipdf.py2
-rw-r--r--src/engine/SCons/Tool/f03.py2
-rw-r--r--src/engine/SCons/Tool/f95.py2
-rw-r--r--src/engine/SCons/Tool/filesystem.py2
-rw-r--r--src/engine/SCons/Tool/gcc.py2
-rw-r--r--src/engine/SCons/Tool/gfortran.py2
-rw-r--r--src/engine/SCons/Tool/gnulink.py2
-rw-r--r--src/engine/SCons/Tool/gs.py2
-rw-r--r--src/engine/SCons/Tool/hpcc.py2
-rw-r--r--src/engine/SCons/Tool/hplink.py2
-rw-r--r--src/engine/SCons/Tool/icc.py2
-rw-r--r--src/engine/SCons/Tool/ifl.py2
-rw-r--r--src/engine/SCons/Tool/ifort.py2
-rw-r--r--src/engine/SCons/Tool/install.py26
-rw-r--r--src/engine/SCons/Tool/intelc.py19
-rw-r--r--src/engine/SCons/Tool/latex.py4
-rw-r--r--src/engine/SCons/Tool/link.py18
-rw-r--r--src/engine/SCons/Tool/midl.py2
-rw-r--r--src/engine/SCons/Tool/msgfmt.py2
-rw-r--r--src/engine/SCons/Tool/msginit.py4
-rw-r--r--src/engine/SCons/Tool/msgmerge.py2
-rw-r--r--src/engine/SCons/Tool/mslib.py2
-rw-r--r--src/engine/SCons/Tool/mslink.py12
-rw-r--r--src/engine/SCons/Tool/mssdk.py2
-rw-r--r--src/engine/SCons/Tool/msvc.py2
-rw-r--r--src/engine/SCons/Tool/msvs.py44
-rw-r--r--src/engine/SCons/Tool/msvsTests.py2
-rw-r--r--src/engine/SCons/Tool/packaging/__init__.py10
-rw-r--r--src/engine/SCons/Tool/packaging/ipk.py2
-rw-r--r--src/engine/SCons/Tool/packaging/msi.py8
-rw-r--r--src/engine/SCons/Tool/packaging/rpm.py12
-rw-r--r--src/engine/SCons/Tool/pdflatex.py2
-rw-r--r--src/engine/SCons/Tool/pdftex.py2
-rw-r--r--src/engine/SCons/Tool/qt.py12
-rw-r--r--src/engine/SCons/Tool/rpmutils.py6
-rw-r--r--src/engine/SCons/Tool/sgicc.py2
-rw-r--r--src/engine/SCons/Tool/sgilink.py2
-rw-r--r--src/engine/SCons/Tool/suncc.py2
-rw-r--r--src/engine/SCons/Tool/sunf77.py2
-rw-r--r--src/engine/SCons/Tool/sunf90.py2
-rw-r--r--src/engine/SCons/Tool/sunf95.py2
-rw-r--r--src/engine/SCons/Tool/sunlink.py2
-rw-r--r--src/engine/SCons/Tool/tex.py94
-rw-r--r--src/engine/SCons/Tool/textfile.py5
-rw-r--r--src/engine/SCons/Tool/xgettext.py8
-rw-r--r--src/engine/SCons/Util.py39
-rw-r--r--src/engine/SCons/UtilTests.py28
-rw-r--r--src/engine/SCons/Variables/EnumVariableTests.py4
-rw-r--r--src/engine/SCons/Variables/PathVariableTests.py16
-rw-r--r--src/engine/SCons/Variables/VariablesTests.py2
-rw-r--r--src/engine/SCons/Variables/__init__.py18
-rw-r--r--src/engine/SCons/compat/__init__.py2
-rw-r--r--src/engine/SCons/compat/_scons_subprocess.py48
-rw-r--r--src/engine/SCons/cpp.py11
-rw-r--r--src/engine/SCons/cppTests.py2
-rw-r--r--src/engine/SCons/dblite.py42
-rw-r--r--src/script/scons-time.py47
-rw-r--r--src/script/sconsign.py40
-rw-r--r--src/test_files.py10
-rw-r--r--src/test_interrupts.py6
-rw-r--r--src/test_pychecker.py2
-rw-r--r--src/test_setup.py6
-rw-r--r--src/test_strings.py8
127 files changed, 727 insertions, 717 deletions
diff --git a/src/engine/SCons/Action.py b/src/engine/SCons/Action.py
index c1eef75..e8574cb 100644
--- a/src/engine/SCons/Action.py
+++ b/src/engine/SCons/Action.py
@@ -114,6 +114,7 @@ import SCons.Errors
import SCons.Executor
import SCons.Util
import SCons.Subst
+import collections
# we use these a lot, so try to optimize them
is_String = SCons.Util.is_String
@@ -165,12 +166,12 @@ def _callable_contents(obj):
"""
try:
# Test if obj is a method.
- return _function_contents(obj.im_func)
+ return _function_contents(obj.__func__)
except AttributeError:
try:
# Test if obj is a callable object.
- return _function_contents(obj.__call__.im_func)
+ return _function_contents(obj.__call__.__func__)
except AttributeError:
try:
@@ -190,12 +191,12 @@ def _object_contents(obj):
"""
try:
# Test if obj is a method.
- return _function_contents(obj.im_func)
+ return _function_contents(obj.__func__)
except AttributeError:
try:
# Test if obj is a callable object.
- return _function_contents(obj.__call__.im_func)
+ return _function_contents(obj.__call__.__func__)
except AttributeError:
try:
@@ -269,17 +270,17 @@ def _code_contents(code):
def _function_contents(func):
"""Return the signature contents of a function."""
- contents = [_code_contents(func.func_code)]
+ contents = [_code_contents(func.__code__)]
# The function contents depends on the value of defaults arguments
- if func.func_defaults:
- contents.append(',(' + ','.join(map(_object_contents,func.func_defaults)) + ')')
+ if func.__defaults__:
+ contents.append(',(' + ','.join(map(_object_contents,func.__defaults__)) + ')')
else:
contents.append(',()')
# The function contents depends on the closure captured cell values.
try:
- closure = func.func_closure or []
+ closure = func.__closure__ or []
except AttributeError:
# Older versions of Python do not support closures.
closure = []
@@ -328,7 +329,7 @@ def _do_create_keywords(args, kw):
cmdstrfunc = args[0]
if cmdstrfunc is None or is_String(cmdstrfunc):
kw['cmdstr'] = cmdstrfunc
- elif callable(cmdstrfunc):
+ elif isinstance(cmdstrfunc, collections.Callable):
kw['strfunction'] = cmdstrfunc
else:
raise SCons.Errors.UserError(
@@ -359,7 +360,7 @@ def _do_create_action(act, kw):
if is_List(act):
return CommandAction(act, **kw)
- if callable(act):
+ if isinstance(act, collections.Callable):
try:
gen = kw['generator']
del kw['generator']
@@ -492,7 +493,7 @@ class _ActionAction(ActionBase):
self.targets = targets
if batch_key:
- if not callable(batch_key):
+ if not isinstance(batch_key, collections.Callable):
# They have set batch_key, but not to their own
# callable. The default behavior here will batch
# *all* targets+sources using this action, separated
@@ -512,7 +513,7 @@ class _ActionAction(ActionBase):
# This code assumes s is a regular string, but should
# work if it's unicode too.
try:
- sys.stdout.write(unicode(s + "\n"))
+ sys.stdout.write(str(s + "\n"))
except UnicodeDecodeError:
sys.stdout.write(s + "\n")
@@ -553,7 +554,7 @@ class _ActionAction(ActionBase):
source = executor.get_all_sources()
t = ' and '.join(map(str, target))
l = '\n '.join(self.presub_lines(env))
- out = u"Building %s with action:\n %s\n" % (t, l)
+ out = "Building %s with action:\n %s\n" % (t, l)
sys.stdout.write(out)
cmd = None
if show and self.strfunction:
@@ -653,7 +654,7 @@ def _subproc(scons_env, cmd, error = 'ignore', **kw):
# Ensure that the ENV values are all strings:
new_env = {}
- for key, value in ENV.items():
+ for key, value in list(ENV.items()):
if is_List(value):
# If the value is a list, then we assume it is a path list,
# because that's a pretty common list-like value to stick
@@ -672,7 +673,7 @@ def _subproc(scons_env, cmd, error = 'ignore', **kw):
try:
return subprocess.Popen(cmd, **kw)
- except EnvironmentError, e:
+ except EnvironmentError as e:
if error == 'raise': raise
# return a dummy Popen instance that only returns error
class dummyPopen(object):
@@ -779,7 +780,7 @@ class CommandAction(_ActionAction):
ENV = get_default_ENV(env)
# Ensure that the ENV values are all strings:
- for key, value in ENV.items():
+ for key, value in list(ENV.items()):
if not is_String(value):
if is_List(value):
# If the value is a list, then we assume it is a
@@ -1038,7 +1039,7 @@ class FunctionAction(_ActionAction):
else:
if strfunc is None:
return None
- if callable(strfunc):
+ if isinstance(strfunc, collections.Callable):
return strfunc(target, source, env)
name = self.function_name()
tstr = array(target)
@@ -1060,11 +1061,11 @@ class FunctionAction(_ActionAction):
rsources = list(map(rfile, source))
try:
result = self.execfunction(target=target, source=rsources, env=env)
- except KeyboardInterrupt, e:
+ except KeyboardInterrupt as e:
raise
- except SystemExit, e:
+ except SystemExit as e:
raise
- except Exception, e:
+ except Exception as e:
result = e
exc_info = sys.exc_info()
@@ -1179,11 +1180,11 @@ class ActionCaller(object):
actfunc = self.parent.actfunc
try:
# "self.actfunc" is a function.
- contents = str(actfunc.func_code.co_code)
+ contents = str(actfunc.__code__.co_code)
except AttributeError:
# "self.actfunc" is a callable object.
try:
- contents = str(actfunc.__call__.im_func.func_code.co_code)
+ contents = str(actfunc.__call__.__func__.__code__.co_code)
except AttributeError:
# No __call__() method, so it might be a builtin
# or something like that. Do the best we can.
@@ -1214,7 +1215,7 @@ class ActionCaller(object):
def subst_kw(self, target, source, env):
kw = {}
- for key in self.kw.keys():
+ for key in list(self.kw.keys()):
kw[key] = self.subst(self.kw[key], target, source, env)
return kw
diff --git a/src/engine/SCons/ActionTests.py b/src/engine/SCons/ActionTests.py
index 13c3b6c..6edf373 100644
--- a/src/engine/SCons/ActionTests.py
+++ b/src/engine/SCons/ActionTests.py
@@ -133,7 +133,7 @@ class Environment(object):
self.d['SPAWN'] = scons_env['SPAWN']
self.d['PSPAWN'] = scons_env['PSPAWN']
self.d['ESCAPE'] = scons_env['ESCAPE']
- for k, v in kw.items():
+ for k, v in list(kw.items()):
self.d[k] = v
# Just use the underlying scons_subst*() utility methods.
def subst(self, strSubst, raw=0, target=[], source=[], conv=None):
@@ -158,12 +158,12 @@ class Environment(object):
def Clone(self, **kw):
res = Environment()
res.d = SCons.Util.semi_deepcopy(self.d)
- for k, v in kw.items():
+ for k, v in list(kw.items()):
res.d[k] = v
return res
def sig_dict(self):
d = {}
- for k,v in self.items(): d[k] = v
+ for k,v in list(self.items()): d[k] = v
d['TARGETS'] = ['__t1__', '__t2__', '__t3__', '__t4__', '__t5__', '__t6__']
d['TARGET'] = d['TARGETS'][0]
d['SOURCES'] = ['__s1__', '__s2__', '__s3__', '__s4__', '__s5__', '__s6__']
@@ -270,7 +270,7 @@ def test_positional_args(pos_callback, cmd, **kw):
try:
#FUTURE a = SCons.Action.Action(cmd, [], **kw)
a = SCons.Action.Action(cmd, [], **kw)
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
s = str(e)
m = 'Invalid command display variable'
assert s.find(m) != -1, 'Unexpected string: %s' % s
@@ -305,7 +305,7 @@ class ActionTestCase(unittest.TestCase):
# a singleton list returns the contained action
test_positional_args(cmd_action, ["string"])
- try: unicode
+ try: str
except NameError: pass
else:
a2 = eval("SCons.Action.Action(u'string')")
@@ -493,7 +493,7 @@ class _ActionActionTestCase(unittest.TestCase):
def func(): pass
try:
a = SCons.Action.Action('foo', cmdstr='string', strfunction=func)
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
s = str(e)
m = 'Cannot have both strfunction and cmdstr args to Action()'
assert s.find(m) != -1, 'Unexpected string: %s' % s
diff --git a/src/engine/SCons/Builder.py b/src/engine/SCons/Builder.py
index 6dc9e17..6abcbcf 100644
--- a/src/engine/SCons/Builder.py
+++ b/src/engine/SCons/Builder.py
@@ -167,7 +167,7 @@ class DictCmdGenerator(SCons.Util.Selector):
try:
ret = SCons.Util.Selector.__call__(self, env, source, ext)
- except KeyError, e:
+ except KeyError as e:
raise UserError("Ambiguous suffixes after environment substitution: %s == %s == %s" % (e.args[0], e.args[1], e.args[2]))
if ret is None:
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." % \
@@ -179,7 +179,7 @@ class CallableSelector(SCons.Util.Selector):
finds if it can."""
def __call__(self, env, source):
value = SCons.Util.Selector.__call__(self, env, source)
- if callable(value):
+ if isinstance(value, collections.Callable):
value = value(env, source)
return value
@@ -230,7 +230,7 @@ class OverrideWarner(collections.UserDict):
def warn(self):
if self.already_warned:
return
- for k in self.keys():
+ for k in list(self.keys()):
if k in misleading_keywords:
alt = misleading_keywords[k]
msg = "Did you mean to use `%s' instead of `%s'?" % (alt, k)
@@ -336,7 +336,7 @@ class EmitterProxy(object):
# in strings. Maybe we should change that?
while SCons.Util.is_String(emitter) and emitter in env:
emitter = env[emitter]
- if callable(emitter):
+ if isinstance(emitter, collections.Callable):
target, source = emitter(target, source, env)
elif SCons.Util.is_List(emitter):
for e in emitter:
@@ -426,7 +426,7 @@ class BuilderBase(object):
src_builder = [ src_builder ]
self.src_builder = src_builder
- def __nonzero__(self):
+ def __bool__(self):
raise InternalError("Do not test for the Node.builder attribute directly; use Node.has_builder() instead")
def get_name(self, env):
@@ -638,18 +638,18 @@ class BuilderBase(object):
def get_prefix(self, env, sources=[]):
prefix = self.prefix
- if callable(prefix):
+ if isinstance(prefix, collections.Callable):
prefix = prefix(env, sources)
return env.subst(prefix)
def set_suffix(self, suffix):
- if not callable(suffix):
+ if not isinstance(suffix, collections.Callable):
suffix = self.adjust_suffix(suffix)
self.suffix = suffix
def get_suffix(self, env, sources=[]):
suffix = self.suffix
- if callable(suffix):
+ if isinstance(suffix, collections.Callable):
suffix = suffix(env, sources)
return env.subst(suffix)
@@ -658,7 +658,7 @@ class BuilderBase(object):
src_suffix = []
elif not SCons.Util.is_List(src_suffix):
src_suffix = [ src_suffix ]
- self.src_suffix = [callable(suf) and suf or self.adjust_suffix(suf) for suf in src_suffix]
+ self.src_suffix = [isinstance(suf, collections.Callable) and suf or self.adjust_suffix(suf) for suf in src_suffix]
def get_src_suffix(self, env):
"""Get the first src_suffix in the list of src_suffixes."""
@@ -868,7 +868,7 @@ def is_a_Builder(obj):
"""
return (isinstance(obj, BuilderBase)
or isinstance(obj, CompositeBuilder)
- or callable(obj))
+ or isinstance(obj, collections.Callable))
# Local Variables:
# tab-width:4
diff --git a/src/engine/SCons/BuilderTests.py b/src/engine/SCons/BuilderTests.py
index 766b8fe..da03a3c 100644
--- a/src/engine/SCons/BuilderTests.py
+++ b/src/engine/SCons/BuilderTests.py
@@ -77,7 +77,7 @@ class Environment(object):
self.d['SHELL'] = scons_env['SHELL']
self.d['SPAWN'] = scons_env['SPAWN']
self.d['ESCAPE'] = scons_env['ESCAPE']
- for k, v in kw.items():
+ for k, v in list(kw.items()):
self.d[k] = v
global env_arg2nodes_called
env_arg2nodes_called = None
@@ -138,7 +138,7 @@ class Environment(object):
return list(self.d.items())
def sig_dict(self):
d = {}
- for k,v in self.items(): d[k] = v
+ for k,v in list(self.items()): d[k] = v
d['TARGETS'] = ['__t1__', '__t2__', '__t3__', '__t4__', '__t5__', '__t6__']
d['TARGET'] = d['TARGETS'][0]
d['SOURCES'] = ['__s1__', '__s2__', '__s3__', '__s4__', '__s5__', '__s6__']
@@ -305,11 +305,11 @@ class BuilderTestCase(unittest.TestCase):
#be = target.get_build_env()
#assert be['VAR'] == 'foo', be['VAR']
- try: unicode
+ try: str
except NameError:
uni = str
else:
- uni = unicode
+ uni = str
target = builder(env, target = uni('n12 n13'),
source = [uni('n14 n15')])[0]
@@ -325,7 +325,7 @@ class BuilderTestCase(unittest.TestCase):
flag = 0
try:
target = builder(env, None, source=n20)
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
flag = 1
assert flag, "UserError should be thrown if a source node can't create a target."
@@ -341,7 +341,7 @@ class BuilderTestCase(unittest.TestCase):
suffix = '.s')
try:
builder(env, target = 'n22', source = 'n22')
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
pass
else:
raise Exception("Did not catch expected UserError.")
@@ -1497,7 +1497,7 @@ class CompositeBuilderTestCase(unittest.TestCase):
flag = 0
try:
builder(env, target='test3', source=['test2.bar', 'test1.foo'])[0]
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
flag = 1
assert flag, "UserError should be thrown when we call a builder with files of different suffixes."
expect = "While building `['test3']' from `test1.foo': Cannot build multiple sources with different extensions: .bar, .foo"
@@ -1528,8 +1528,8 @@ class CompositeBuilderTestCase(unittest.TestCase):
try:
tgt.build()
flag = 1
- except SCons.Errors.UserError, e:
- print e
+ except SCons.Errors.UserError as e:
+ print(e)
flag = 0
assert flag, "It should be possible to define actions in composite builders using variables."
env['FOO_SUFFIX'] = '.BAR2'
@@ -1581,7 +1581,7 @@ class CompositeBuilderTestCase(unittest.TestCase):
flag = 0
try:
builder(env, target='t5', source=['test5a.foo', 'test5b.inb'])[0]
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
flag = 1
assert flag, "UserError should be thrown when we call a builder with files of different suffixes."
expect = "While building `['t5']' from `test5b.bar': Cannot build multiple sources with different extensions: .foo, .bar"
@@ -1590,7 +1590,7 @@ class CompositeBuilderTestCase(unittest.TestCase):
flag = 0
try:
builder(env, target='t6', source=['test6a.bar', 'test6b.ina'])[0]
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
flag = 1
assert flag, "UserError should be thrown when we call a builder with files of different suffixes."
expect = "While building `['t6']' from `test6b.foo': Cannot build multiple sources with different extensions: .bar, .foo"
@@ -1599,7 +1599,7 @@ class CompositeBuilderTestCase(unittest.TestCase):
flag = 0
try:
builder(env, target='t4', source=['test4a.ina', 'test4b.inb'])[0]
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
flag = 1
assert flag, "UserError should be thrown when we call a builder with files of different suffixes."
expect = "While building `['t4']' from `test4b.bar': Cannot build multiple sources with different extensions: .foo, .bar"
@@ -1608,7 +1608,7 @@ class CompositeBuilderTestCase(unittest.TestCase):
flag = 0
try:
builder(env, target='t7', source=[env.fs.File('test7')])[0]
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
flag = 1
assert flag, "UserError should be thrown when we call a builder with files of different suffixes."
expect = "While building `['t7']': Cannot deduce file extension from source files: ['test7']"
@@ -1617,7 +1617,7 @@ class CompositeBuilderTestCase(unittest.TestCase):
flag = 0
try:
builder(env, target='t8', source=['test8.unknown'])[0]
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
flag = 1
assert flag, "UserError should be thrown when we call a builder target with an unknown suffix."
expect = "While building `['t8']' from `['test8.unknown']': Don't know how to build from a source file with suffix `.unknown'. Expected a suffix in this list: ['.foo', '.bar']."
diff --git a/src/engine/SCons/CacheDirTests.py b/src/engine/SCons/CacheDirTests.py
index 21b435a..269040d 100644
--- a/src/engine/SCons/CacheDirTests.py
+++ b/src/engine/SCons/CacheDirTests.py
@@ -241,7 +241,7 @@ class FileTestCase(BaseTestCase):
warn_caught = 0
try:
f7.push_to_cache()
- except SCons.Errors.BuildError, e:
+ except SCons.Errors.BuildError as e:
assert e.exc_info[0] == SCons.Warnings.CacheWriteErrorWarning
warn_caught = 1
assert warn_caught
diff --git a/src/engine/SCons/Debug.py b/src/engine/SCons/Debug.py
index 1c0c638..363c8b7 100644
--- a/src/engine/SCons/Debug.py
+++ b/src/engine/SCons/Debug.py
@@ -73,7 +73,7 @@ def dumpLoggedInstances(classes, file=sys.stdout):
obj = ref()
if obj is not None:
file.write(' %s:\n' % obj)
- for key, value in obj.__dict__.items():
+ for key, value in list(obj.__dict__.items()):
file.write(' %20s : %s\n' % (key, value))
@@ -143,7 +143,7 @@ def caller_trace(back=0):
# print a single caller and its callers, if any
def _dump_one_caller(key, file, level=0):
leader = ' '*level
- for v,c in sorted([(-v,c) for c,v in caller_dicts[key].items()]):
+ for v,c in sorted([(-v,c) for c,v in list(caller_dicts[key].items())]):
file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:])))
if c in caller_dicts:
_dump_one_caller(c, file, level+1)
diff --git a/src/engine/SCons/Defaults.py b/src/engine/SCons/Defaults.py
index a99bcc7..fe1f87b 100644
--- a/src/engine/SCons/Defaults.py
+++ b/src/engine/SCons/Defaults.py
@@ -31,7 +31,7 @@ from distutils.msvccompiler.
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
-from __future__ import division
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -50,6 +50,7 @@ import SCons.Environment
import SCons.PathList
import SCons.Subst
import SCons.Tool
+import collections
# A placeholder for a default Environment (for fetching source files
# from source code management systems and the like). This must be
@@ -221,7 +222,7 @@ def mkdir_func(dest):
for entry in dest:
try:
os.makedirs(str(entry))
- except os.error, e:
+ except os.error as e:
p = str(entry)
if (e.args[0] == errno.EEXIST or
(sys.platform=='win32' and e.args[0]==183)) \
@@ -325,9 +326,9 @@ def _stripixes(prefix, itms, suffix, stripprefixes, stripsuffixes, env, c=None):
if not itms:
return itms
- if not callable(c):
+ if not isinstance(c, collections.Callable):
env_c = env['_concat']
- if env_c != _concat and callable(env_c):
+ if env_c != _concat and isinstance(env_c, collections.Callable):
# There's a custom _concat() method in the construction
# environment, and we've allowed people to set that in
# the past (see test/custom-concat.py), so preserve the
@@ -381,7 +382,7 @@ def processDefines(defs):
else:
l.append(str(d[0]))
elif SCons.Util.is_Dict(d):
- for macro,value in d.iteritems():
+ for macro,value in d.items():
if value is not None:
l.append(str(macro) + '=' + str(value))
else:
diff --git a/src/engine/SCons/DefaultsTests.py b/src/engine/SCons/DefaultsTests.py
index fd10c12..a36ca7c 100644
--- a/src/engine/SCons/DefaultsTests.py
+++ b/src/engine/SCons/DefaultsTests.py
@@ -69,7 +69,7 @@ class DefaultsTestCase(unittest.TestCase):
test.write(file, "test\n")
try:
mkdir_func(file)
- except os.error, e:
+ except os.error as e:
pass
else:
fail("expected os.error")
diff --git a/src/engine/SCons/Environment.py b/src/engine/SCons/Environment.py
index 55a8206..88b0553 100644
--- a/src/engine/SCons/Environment.py
+++ b/src/engine/SCons/Environment.py
@@ -58,6 +58,7 @@ import SCons.Subst
import SCons.Tool
import SCons.Util
import SCons.Warnings
+import collections
class _Null(object):
pass
@@ -127,7 +128,7 @@ future_reserved_construction_var_names = [
def copy_non_reserved_keywords(dict):
result = semi_deepcopy(dict)
- for k in result.keys():
+ for k in list(result.keys()):
if k in reserved_construction_var_names:
msg = "Ignoring attempt to set reserved variable `$%s'"
SCons.Warnings.warn(SCons.Warnings.ReservedVariableWarning, msg % k)
@@ -146,12 +147,12 @@ def _set_future_reserved(env, key, value):
def _set_BUILDERS(env, key, value):
try:
bd = env._dict[key]
- for k in bd.keys():
+ for k in list(bd.keys()):
del bd[k]
except KeyError:
bd = BuilderDict(kwbd, env)
env._dict[key] = bd
- for k, v in value.items():
+ for k, v in list(value.items()):
if not SCons.Builder.is_a_Builder(v):
raise SCons.Errors.UserError('%s is not a Builder.' % repr(v))
bd.update(value)
@@ -323,7 +324,7 @@ class BuilderDict(UserDict):
delattr(self.env, item)
def update(self, dict):
- for i, v in dict.items():
+ for i, v in list(dict.items()):
self.__setitem__(i, v)
@@ -517,7 +518,7 @@ class SubstitutionEnvironment(object):
def subst_kw(self, kw, raw=0, target=None, source=None):
nkw = {}
- for k, v in kw.items():
+ for k, v in list(kw.items()):
k = self.subst(k, raw, target, source)
if SCons.Util.is_String(v):
v = self.subst(v, raw, target, source)
@@ -591,7 +592,7 @@ class SubstitutionEnvironment(object):
out,err = p.communicate()
status = p.wait()
if err:
- sys.stderr.write(unicode(err))
+ sys.stderr.write(str(err))
if status:
raise OSError("'%s' exited %d" % (command, status))
return out
@@ -629,7 +630,7 @@ class SubstitutionEnvironment(object):
if not o: return self
overrides = {}
merges = None
- for key, value in o.items():
+ for key, value in list(o.items()):
if key == 'parse_flags':
merges = value
else:
@@ -814,7 +815,7 @@ class SubstitutionEnvironment(object):
if not unique:
self.Append(**args)
return self
- for key, value in args.items():
+ for key, value in list(args.items()):
if not value:
continue
try:
@@ -1004,7 +1005,7 @@ class Base(SubstitutionEnvironment):
# Now restore the passed-in and customized variables
# to the environment, since the values the user set explicitly
# should override any values set by the tools.
- for key, val in save.items():
+ for key, val in list(save.items()):
self._dict[key] = val
# Finally, apply any flags to be merged in
@@ -1152,7 +1153,7 @@ class Base(SubstitutionEnvironment):
in an Environment.
"""
kw = copy_non_reserved_keywords(kw)
- for key, val in kw.items():
+ for key, val in list(kw.items()):
# It would be easier on the eyes to write this using
# "continue" statements whenever we finish processing an item,
# but Python 1.5.2 apparently doesn't let you use "continue"
@@ -1205,7 +1206,7 @@ class Base(SubstitutionEnvironment):
# based on what we think the value looks like.
if SCons.Util.is_List(val):
if key == 'CPPDEFINES':
- orig = orig.items()
+ orig = list(orig.items())
orig += val
self._dict[key] = orig
else:
@@ -1216,7 +1217,7 @@ class Base(SubstitutionEnvironment):
update_dict(val)
except (AttributeError, TypeError, ValueError):
if SCons.Util.is_Dict(val):
- for k, v in val.items():
+ for k, v in list(val.items()):
orig[k] = v
else:
orig[val] = None
@@ -1262,7 +1263,7 @@ class Base(SubstitutionEnvironment):
values move to end.
"""
kw = copy_non_reserved_keywords(kw)
- for key, val in kw.items():
+ for key, val in list(kw.items()):
if SCons.Util.is_List(val):
val = _delete_duplicates(val, delete_existing)
if key not in self._dict or self._dict[key] in ('', None):
@@ -1286,7 +1287,7 @@ class Base(SubstitutionEnvironment):
tmp.append((i,))
val = tmp
if SCons.Util.is_Dict(dk):
- dk = dk.items()
+ dk = list(dk.items())
elif SCons.Util.is_String(dk):
dk = [(dk,)]
else:
@@ -1327,11 +1328,11 @@ class Base(SubstitutionEnvironment):
tmp.append((i,))
dk = tmp
if SCons.Util.is_Dict(val):
- val = val.items()
+ val = list(val.items())
elif SCons.Util.is_String(val):
val = [(val,)]
if delete_existing:
- dk = filter(lambda x, val=val: x not in val, dk)
+ dk = list(filter(lambda x, val=val: x not in val, dk))
self._dict[key] = dk + val
else:
dk = [x for x in dk if x not in val]
@@ -1340,7 +1341,7 @@ class Base(SubstitutionEnvironment):
# By elimination, val is not a list. Since dk is a
# list, wrap val in a list first.
if delete_existing:
- dk = filter(lambda x, val=val: x not in val, dk)
+ dk = list(filter(lambda x, val=val: x not in val, dk))
self._dict[key] = dk + [val]
else:
if not val in dk:
@@ -1350,7 +1351,7 @@ class Base(SubstitutionEnvironment):
if SCons.Util.is_String(dk):
dk = [dk]
elif SCons.Util.is_Dict(dk):
- dk = dk.items()
+ dk = list(dk.items())
if SCons.Util.is_String(val):
if val in dk:
val = []
@@ -1358,7 +1359,7 @@ class Base(SubstitutionEnvironment):
val = [val]
elif SCons.Util.is_Dict(val):
tmp = []
- for i,j in val.iteritems():
+ for i,j in val.items():
if j is not None:
tmp.append((i,j))
else:
@@ -1402,7 +1403,7 @@ class Base(SubstitutionEnvironment):
# so the tools can use the new variables
kw = copy_non_reserved_keywords(kw)
new = {}
- for key, value in kw.items():
+ for key, value in list(kw.items()):
new[key] = SCons.Subst.scons_subst_once(value, self, key)
clone.Replace(**new)
@@ -1469,7 +1470,7 @@ class Base(SubstitutionEnvironment):
copy_function = self._copy_from_cache
elif function == 'timestamp-match':
function = self._changed_timestamp_match
- elif not callable(function):
+ elif not isinstance(function, collections.Callable):
raise UserError("Unknown Decider value %s" % repr(function))
# We don't use AddMethod because we don't want to turn the
@@ -1602,7 +1603,7 @@ class Base(SubstitutionEnvironment):
in an Environment.
"""
kw = copy_non_reserved_keywords(kw)
- for key, val in kw.items():
+ for key, val in list(kw.items()):
# It would be easier on the eyes to write this using
# "continue" statements whenever we finish processing an item,
# but Python 1.5.2 apparently doesn't let you use "continue"
@@ -1656,7 +1657,7 @@ class Base(SubstitutionEnvironment):
update_dict(val)
except (AttributeError, TypeError, ValueError):
if SCons.Util.is_Dict(val):
- for k, v in val.items():
+ for k, v in list(val.items()):
orig[k] = v
else:
orig[val] = None
@@ -1693,7 +1694,7 @@ class Base(SubstitutionEnvironment):
values move to front.
"""
kw = copy_non_reserved_keywords(kw)
- for key, val in kw.items():
+ for key, val in list(kw.items()):
if SCons.Util.is_List(val):
val = _delete_duplicates(val, not delete_existing)
if key not in self._dict or self._dict[key] in ('', None):
@@ -1768,7 +1769,7 @@ class Base(SubstitutionEnvironment):
return os.path.join(dir, new_prefix+name+new_suffix)
def SetDefault(self, **kw):
- for k in kw.keys():
+ for k in list(kw.keys()):
if k in self._dict:
del kw[k]
self.Replace(**kw)
@@ -1830,7 +1831,7 @@ class Base(SubstitutionEnvironment):
uniq = {}
for executor in [n.get_executor() for n in nodes]:
uniq[executor] = 1
- for executor in uniq.keys():
+ for executor in list(uniq.keys()):
executor.add_pre_action(action)
return nodes
@@ -1840,7 +1841,7 @@ class Base(SubstitutionEnvironment):
uniq = {}
for executor in [n.get_executor() for n in nodes]:
uniq[executor] = 1
- for executor in uniq.keys():
+ for executor in list(uniq.keys()):
executor.add_post_action(action)
return nodes
@@ -2235,7 +2236,7 @@ class Base(SubstitutionEnvironment):
while (node != node.srcnode()):
node = node.srcnode()
return node
- sources = map( final_source, sources );
+ sources = list(map( final_source, sources ));
# remove duplicates
return list(set(sources))
@@ -2378,7 +2379,7 @@ def NoSubstitutionProxy(subject):
def __setattr__(self, name, value):
return setattr(self.__dict__['__subject'], name, value)
def executor_to_lvars(self, kwdict):
- if kwdict.has_key('executor'):
+ if 'executor' in kwdict:
kwdict['lvars'] = kwdict['executor'].get_lvars()
del kwdict['executor']
else:
diff --git a/src/engine/SCons/EnvironmentTests.py b/src/engine/SCons/EnvironmentTests.py
index 45cf876..3af879a 100644
--- a/src/engine/SCons/EnvironmentTests.py
+++ b/src/engine/SCons/EnvironmentTests.py
@@ -160,7 +160,7 @@ class TestEnvironmentFixture(object):
default_keys = { 'CC' : 'cc',
'CCFLAGS' : '-DNDEBUG',
'ENV' : { 'TMP' : '/tmp' } }
- for key, value in default_keys.items():
+ for key, value in list(default_keys.items()):
if key not in kw:
kw[key] = value
if 'BUILDERS' not in kw:
@@ -263,7 +263,7 @@ class SubstitutionTestCase(unittest.TestCase):
assert isinstance(nodes[0], X)
assert nodes[0].name == "Util.py UtilTests.py"
- try: unicode
+ try: str
except NameError: pass
else:
code = """if 1:
@@ -272,7 +272,7 @@ class SubstitutionTestCase(unittest.TestCase):
assert isinstance(nodes[0], X)
assert nodes[0].name == u"Util.py UtilTests.py"
\n"""
- exec code in globals(), locals()
+ exec(code, globals(), locals())
nodes = env.arg2nodes(["Util.py", "UtilTests.py"], Factory)
assert len(nodes) == 2, nodes
@@ -655,7 +655,7 @@ sys.exit(0)
cmd = '%s %s' % (python, test.workpath('fail.py'))
try:
env.backtick(cmd)
- except OSError, e:
+ except OSError as e:
assert str(e) == "'%s' exited 1" % cmd, str(e)
else:
self.fail("did not catch expected OSError")
@@ -1586,17 +1586,17 @@ def exists(env):
env['XXX'] = copy.copy(input)
try:
env.Append(XXX = append)
- except Exception, e:
- if failed == 0: print
- print " %s Append %s exception: %s" % \
- (repr(input), repr(append), e)
+ except Exception as e:
+ if failed == 0: print()
+ print(" %s Append %s exception: %s" % \
+ (repr(input), repr(append), e))
failed = failed + 1
else:
result = env['XXX']
if result != expect:
- if failed == 0: print
- print " %s Append %s => %s did not match %s" % \
- (repr(input), repr(append), repr(result), repr(expect))
+ if failed == 0: print()
+ print(" %s Append %s => %s did not match %s" % \
+ (repr(input), repr(append), repr(result), repr(expect)))
failed = failed + 1
del cases[:3]
assert failed == 0, "%d Append() cases failed" % failed
@@ -1935,7 +1935,7 @@ def generate(env):
assert x is None, x
sub2_xxx_exe = test.workpath('sub2', 'xxx.exe')
- os.chmod(sub2_xxx_exe, 0755)
+ os.chmod(sub2_xxx_exe, 0o755)
env = self.TestEnvironment(ENV = { 'PATH' : [sub1, sub2] })
@@ -1943,7 +1943,7 @@ def generate(env):
assert x == 'xxx.exe', x
sub1_xxx_exe = test.workpath('sub1', 'xxx.exe')
- os.chmod(sub1_xxx_exe, 0755)
+ os.chmod(sub1_xxx_exe, 0o755)
x = env.Detect('xxx.exe')
assert x == 'xxx.exe', x
@@ -2258,17 +2258,17 @@ f5: \
env['XXX'] = copy.copy(input)
try:
env.Prepend(XXX = prepend)
- except Exception, e:
- if failed == 0: print
- print " %s Prepend %s exception: %s" % \
- (repr(input), repr(prepend), e)
+ except Exception as e:
+ if failed == 0: print()
+ print(" %s Prepend %s exception: %s" % \
+ (repr(input), repr(prepend), e))
failed = failed + 1
else:
result = env['XXX']
if result != expect:
- if failed == 0: print
- print " %s Prepend %s => %s did not match %s" % \
- (repr(input), repr(prepend), repr(result), repr(expect))
+ if failed == 0: print()
+ print(" %s Prepend %s => %s did not match %s" % \
+ (repr(input), repr(prepend), repr(result), repr(expect)))
failed = failed + 1
del cases[:3]
assert failed == 0, "%d Prepend() cases failed" % failed
@@ -2506,10 +2506,10 @@ def generate(env):
os.mkdir(sub2_xxx_exe)
test.write(sub3_xxx_exe, "\n")
- os.chmod(sub3_xxx_exe, 0777)
+ os.chmod(sub3_xxx_exe, 0o777)
test.write(sub4_xxx_exe, "\n")
- os.chmod(sub4_xxx_exe, 0777)
+ os.chmod(sub4_xxx_exe, 0o777)
env_path = os.environ['PATH']
diff --git a/src/engine/SCons/ErrorsTests.py b/src/engine/SCons/ErrorsTests.py
index 9c8b925..97c9d55 100644
--- a/src/engine/SCons/ErrorsTests.py
+++ b/src/engine/SCons/ErrorsTests.py
@@ -35,7 +35,7 @@ class ErrorsTestCase(unittest.TestCase):
raise SCons.Errors.BuildError(
errstr = "foo", status=57, filename="file", exc_info=(1,2,3),
node = "n", executor="e", action="a", command="c")
- except SCons.Errors.BuildError, e:
+ except SCons.Errors.BuildError as e:
assert e.errstr == "foo"
assert e.status == 57
assert e.exitstatus == 2, e.exitstatus
@@ -50,7 +50,7 @@ class ErrorsTestCase(unittest.TestCase):
try:
raise SCons.Errors.BuildError("n", "foo", 57, 3, "file",
"e", "a", "c", (1,2,3))
- except SCons.Errors.BuildError, e:
+ except SCons.Errors.BuildError as e:
assert e.errstr == "foo", e.errstr
assert e.status == 57, e.status
assert e.exitstatus == 3, e.exitstatus
@@ -64,7 +64,7 @@ class ErrorsTestCase(unittest.TestCase):
try:
raise SCons.Errors.BuildError()
- except SCons.Errors.BuildError, e:
+ except SCons.Errors.BuildError as e:
assert e.errstr == "Unknown error"
assert e.status == 2
assert e.exitstatus == 2
@@ -80,21 +80,21 @@ class ErrorsTestCase(unittest.TestCase):
"""Test the InternalError exception."""
try:
raise SCons.Errors.InternalError("test internal error")
- except SCons.Errors.InternalError, e:
+ except SCons.Errors.InternalError as e:
assert e.args == ("test internal error",)
def test_UserError(self):
"""Test the UserError exception."""
try:
raise SCons.Errors.UserError("test user error")
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
assert e.args == ("test user error",)
def test_ExplicitExit(self):
"""Test the ExplicitExit exception."""
try:
raise SCons.Errors.ExplicitExit("node")
- except SCons.Errors.ExplicitExit, e:
+ except SCons.Errors.ExplicitExit as e:
assert e.node == "node"
if __name__ == "__main__":
diff --git a/src/engine/SCons/ExecutorTests.py b/src/engine/SCons/ExecutorTests.py
index 6268984..3bc5bee 100644
--- a/src/engine/SCons/ExecutorTests.py
+++ b/src/engine/SCons/ExecutorTests.py
@@ -307,7 +307,7 @@ class ExecutorTestCase(unittest.TestCase):
try:
r = x.prepare()
- except SCons.Errors.StopError, e:
+ except SCons.Errors.StopError as e:
assert str(e) == "Source `s2' not found, needed by target `t1'.", e
else:
raise AssertionError("did not catch expected StopError: %s" % r)
diff --git a/src/engine/SCons/Job.py b/src/engine/SCons/Job.py
index 184f5ba..226a34e 100644
--- a/src/engine/SCons/Job.py
+++ b/src/engine/SCons/Job.py
@@ -278,14 +278,14 @@ else:
try:
prev_size = threading.stack_size(stack_size*1024)
- except AttributeError, e:
+ except AttributeError as e:
# Only print a warning if the stack size has been
# explicitly set.
if not explicit_stack_size is None:
msg = "Setting stack size is unsupported by this version of Python:\n " + \
e.args[0]
SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
- except ValueError, e:
+ except ValueError as e:
msg = "Setting stack size failed:\n " + str(e)
SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
diff --git a/src/engine/SCons/Memoize.py b/src/engine/SCons/Memoize.py
index e77aacf..9fe6851 100644
--- a/src/engine/SCons/Memoize.py
+++ b/src/engine/SCons/Memoize.py
@@ -143,7 +143,7 @@ class Counter(object):
CounterList.append(self)
def display(self):
fmt = " %7d hits %7d misses %s()"
- print fmt % (self.hit, self.miss, self.name)
+ print(fmt % (self.hit, self.miss, self.name))
def __cmp__(self, other):
try:
return cmp(self.name, other.name)
@@ -215,7 +215,7 @@ class Memoizer(object):
def Dump(title=None):
if title:
- print title
+ print(title)
CounterList.sort()
for counter in CounterList:
counter.display()
diff --git a/src/engine/SCons/MemoizeTests.py b/src/engine/SCons/MemoizeTests.py
index 9876c27..b6750e0 100644
--- a/src/engine/SCons/MemoizeTests.py
+++ b/src/engine/SCons/MemoizeTests.py
@@ -30,9 +30,7 @@ import SCons.Memoize
-class FakeObject(object):
-
- __metaclass__ = SCons.Memoize.Memoized_Metaclass
+class FakeObject(object, metaclass=SCons.Memoize.Memoized_Metaclass):
memoizer_counters = []
diff --git a/src/engine/SCons/Node/FS.py b/src/engine/SCons/Node/FS.py
index f31ca83..22dca1f 100644
--- a/src/engine/SCons/Node/FS.py
+++ b/src/engine/SCons/Node/FS.py
@@ -54,6 +54,7 @@ import SCons.Util
import SCons.Warnings
from SCons.Debug import Trace
+import collections
do_store_info = True
print_duplicate = 0
@@ -550,7 +551,7 @@ class EntryProxy(SCons.Util.Proxy):
except KeyError:
try:
attr = SCons.Util.Proxy.__getattr__(self, name)
- except AttributeError, e:
+ except AttributeError as e:
# Raise our own AttributeError subclass with an
# overridden __str__() method that identifies the
# name of the entry that caused the exception.
@@ -1508,7 +1509,7 @@ class Dir(Base):
This clears any cached information that is invalidated by changing
the repository."""
- for node in self.entries.values():
+ for node in list(self.entries.values()):
if node != self.dir:
if node != self and isinstance(node, Dir):
node.__clearRepositoryCache(duplicate)
@@ -2055,7 +2056,7 @@ class Dir(Base):
# We use the .name attribute from the Node because the keys of
# the dir.entries dictionary are normalized (that is, all upper
# case) on case-insensitive systems like Windows.
- node_names = [ v.name for k, v in dir.entries.items()
+ node_names = [ v.name for k, v in list(dir.entries.items())
if k not in ('.', '..') ]
names.extend(node_names)
if not strings:
@@ -2420,7 +2421,7 @@ class File(Base):
fname = self.rfile().abspath
try:
contents = open(fname, "rb").read()
- except EnvironmentError, e:
+ except EnvironmentError as e:
if not e.filename:
e.filename = fname
raise
@@ -2455,7 +2456,7 @@ class File(Base):
try:
cs = SCons.Util.MD5filesignature(fname,
chunksize=SCons.Node.FS.File.md5_chunksize*1024)
- except EnvironmentError, e:
+ except EnvironmentError as e:
if not e.filename:
e.filename = fname
raise
@@ -2793,7 +2794,7 @@ class File(Base):
def _rmv_existing(self):
self.clear_memoized_values()
if print_duplicate:
- print "dup: removing existing target %s"%self
+ print("dup: removing existing target %s"%self)
e = Unlink(self, [], None)
if isinstance(e, SCons.Errors.BuildError):
raise e
@@ -2817,7 +2818,7 @@ class File(Base):
else:
try:
self._createDir()
- except SCons.Errors.StopError, drive:
+ except SCons.Errors.StopError as drive:
desc = "No drive `%s' for target `%s'." % (drive, self)
raise SCons.Errors.StopError(desc)
@@ -2835,7 +2836,7 @@ class File(Base):
def do_duplicate(self, src):
self._createDir()
if print_duplicate:
- print "dup: relinking variant '%s' from '%s'"%(self, src)
+ print("dup: relinking variant '%s' from '%s'"%(self, src))
Unlink(self, None, None)
e = Link(self, src, None)
if isinstance(e, SCons.Errors.BuildError):
@@ -2870,7 +2871,7 @@ class File(Base):
# The source file does not exist. Make sure no old
# copy remains in the variant directory.
if print_duplicate:
- print "dup: no src for %s, unlinking old variant copy"%self
+ print("dup: no src for %s, unlinking old variant copy"%self)
if Base.exists(self) or self.islink():
self.fs.unlink(self.path)
# Return None explicitly because the Base.exists() call
@@ -3196,10 +3197,10 @@ class FileFinder(object):
except KeyError:
pass
- if verbose and not callable(verbose):
+ if verbose and not isinstance(verbose, collections.Callable):
if not SCons.Util.is_String(verbose):
verbose = "find_file"
- _verbose = u' %s: ' % verbose
+ _verbose = ' %s: ' % verbose
verbose = lambda s: sys.stdout.write(_verbose + s)
filedir, filename = os.path.split(filename)
diff --git a/src/engine/SCons/Node/FSTests.py b/src/engine/SCons/Node/FSTests.py
index a60b8a4..e8442e9 100644
--- a/src/engine/SCons/Node/FSTests.py
+++ b/src/engine/SCons/Node/FSTests.py
@@ -20,7 +20,7 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
-from __future__ import division
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -567,13 +567,13 @@ class VariantDirTestCase(unittest.TestCase):
dp = dnode.srcnode().path
expect = os.path.normpath(srcnode_map.get(dir, dir))
if dp != expect:
- print "Dir `%s' srcnode() `%s' != expected `%s'" % (dir, dp, expect)
+ print("Dir `%s' srcnode() `%s' != expected `%s'" % (dir, dp, expect))
errors = errors + 1
fp = fnode.srcnode().path
expect = os.path.normpath(srcnode_map.get(f, f))
if fp != expect:
- print "File `%s' srcnode() `%s' != expected `%s'" % (f, fp, expect)
+ print("File `%s' srcnode() `%s' != expected `%s'" % (f, fp, expect))
errors = errors + 1
for dir in dir_list:
@@ -585,14 +585,14 @@ class VariantDirTestCase(unittest.TestCase):
tp = t[0].path
expect = os.path.normpath(alter_map.get(dir, dir))
if tp != expect:
- print "Dir `%s' alter_targets() `%s' != expected `%s'" % (dir, tp, expect)
+ print("Dir `%s' alter_targets() `%s' != expected `%s'" % (dir, tp, expect))
errors = errors + 1
t, m = fnode.alter_targets()
tp = t[0].path
expect = os.path.normpath(alter_map.get(f, f))
if tp != expect:
- print "File `%s' alter_targets() `%s' != expected `%s'" % (f, tp, expect)
+ print("File `%s' alter_targets() `%s' != expected `%s'" % (f, tp, expect))
errors = errors + 1
self.failIf(errors)
@@ -1088,7 +1088,7 @@ class FSTestCase(_tempdirTestCase):
try:
f2 = fs.File(sep.join(['f1', 'f2']), directory = d1)
- except TypeError, x:
+ except TypeError as x:
assert str(x) == ("Tried to lookup File '%s' as a Dir." %
d1_f1), x
except:
@@ -1096,7 +1096,7 @@ class FSTestCase(_tempdirTestCase):
try:
dir = fs.Dir(sep.join(['d1', 'f1']))
- except TypeError, x:
+ except TypeError as x:
assert str(x) == ("Tried to lookup File '%s' as a Dir." %
d1_f1), x
except:
@@ -1104,7 +1104,7 @@ class FSTestCase(_tempdirTestCase):
try:
f2 = fs.File('d1')
- except TypeError, x:
+ except TypeError as x:
assert str(x) == ("Tried to lookup Dir '%s' as a File." %
'd1'), x
except:
@@ -1305,7 +1305,7 @@ class FSTestCase(_tempdirTestCase):
assert f1.get_contents() == "Foo\x1aBar", f1.get_contents()
# This tests to make sure we can decode UTF-8 text files.
- test_string = u"Foo\x1aBar"
+ test_string = "Foo\x1aBar"
test.write("utf8_file", test_string.encode('utf-8'))
f1 = fs.File(test.workpath("utf8_file"))
assert eval('f1.get_text_contents() == u"Foo\x1aBar"'), \
@@ -1645,7 +1645,7 @@ class FSTestCase(_tempdirTestCase):
def unc_workpath(dirs, test=test):
import ntpath
- x = apply(test.workpath, dirs)
+ x = test.workpath(*dirs)
drive, path = ntpath.splitdrive(x)
unc, path = ntpath.splitunc(path)
path = strip_slash(path)
@@ -1911,9 +1911,9 @@ class FSTestCase(_tempdirTestCase):
del cases[:3]
result = dir.rel_path(other)
if result != expect:
- if failed == 0: print
+ if failed == 0: print()
fmt = " dir_path(%(dir)s, %(other)s) => '%(result)s' did not match '%(expect)s'"
- print fmt % locals()
+ print(fmt % locals())
failed = failed + 1
assert failed == 0, "%d rel_path() cases failed" % failed
@@ -2520,9 +2520,9 @@ class GlobTestCase(_tempdirTestCase):
fmt = lambda n: n
if r != result:
import pprint
- print "Glob(%s) expected:" % repr(input)
+ print("Glob(%s) expected:" % repr(input))
pprint.pprint(list(map(fmt, result)))
- print "Glob(%s) got:" % repr(input)
+ print("Glob(%s) got:" % repr(input))
pprint.pprint(list(map(fmt, r)))
self.fail()
@@ -3621,7 +3621,7 @@ class SpecialAttrTestCase(unittest.TestCase):
caught = None
try:
fs.Dir('ddd').get_subst_proxy().no_such_attr
- except AttributeError, e:
+ except AttributeError as e:
assert str(e) == "Dir instance 'ddd' has no attribute 'no_such_attr'", e
caught = 1
assert caught, "did not catch expected AttributeError"
@@ -3629,7 +3629,7 @@ class SpecialAttrTestCase(unittest.TestCase):
caught = None
try:
fs.Entry('eee').get_subst_proxy().no_such_attr
- except AttributeError, e:
+ except AttributeError as e:
# Gets disambiguated to File instance by get_subst_proxy().
assert str(e) == "File instance 'eee' has no attribute 'no_such_attr'", e
caught = 1
@@ -3638,7 +3638,7 @@ class SpecialAttrTestCase(unittest.TestCase):
caught = None
try:
fs.File('fff').get_subst_proxy().no_such_attr
- except AttributeError, e:
+ except AttributeError as e:
assert str(e) == "File instance 'fff' has no attribute 'no_such_attr'", e
caught = 1
assert caught, "did not catch expected AttributeError"
diff --git a/src/engine/SCons/Node/__init__.py b/src/engine/SCons/Node/__init__.py
index 992284d..8f48d86 100644
--- a/src/engine/SCons/Node/__init__.py
+++ b/src/engine/SCons/Node/__init__.py
@@ -371,7 +371,7 @@ class Node(object):
"""
try:
self.get_executor()(self, **kw)
- except SCons.Errors.BuildError, e:
+ except SCons.Errors.BuildError as e:
e.node = self
raise
@@ -827,7 +827,7 @@ class Node(object):
"""Adds dependencies."""
try:
self._add_child(self.depends, self.depends_set, depend)
- except TypeError, e:
+ except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
@@ -844,7 +844,7 @@ class Node(object):
"""Adds dependencies to ignore."""
try:
self._add_child(self.ignore, self.ignore_set, depend)
- except TypeError, e:
+ except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
@@ -858,7 +858,7 @@ class Node(object):
return
try:
self._add_child(self.sources, self.sources_set, source)
- except TypeError, e:
+ except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
@@ -1197,8 +1197,8 @@ class Node(object):
new_bkids = new.bsources + new.bdepends + new.bimplicit
new_bkidsigs = new.bsourcesigs + new.bdependsigs + new.bimplicitsigs
- osig = dict(zip(old_bkids, old_bkidsigs))
- nsig = dict(zip(new_bkids, new_bkidsigs))
+ osig = dict(list(zip(old_bkids, old_bkidsigs)))
+ nsig = dict(list(zip(new_bkids, new_bkidsigs)))
# The sources and dependencies we'll want to report are all stored
# as relative paths to this target's directory, but we want to
diff --git a/src/engine/SCons/Options/__init__.py b/src/engine/SCons/Options/__init__.py
index f6c8483..2544aec 100644
--- a/src/engine/SCons/Options/__init__.py
+++ b/src/engine/SCons/Options/__init__.py
@@ -33,11 +33,11 @@ and will then be removed entirely (some day).
import SCons.Variables
import SCons.Warnings
-from BoolOption import BoolOption # okay
-from EnumOption import EnumOption # okay
-from ListOption import ListOption # naja
-from PackageOption import PackageOption # naja
-from PathOption import PathOption # okay
+from .BoolOption import BoolOption # okay
+from .EnumOption import EnumOption # okay
+from .ListOption import ListOption # naja
+from .PackageOption import PackageOption # naja
+from .PathOption import PathOption # okay
warned = False
diff --git a/src/engine/SCons/Platform/__init__.py b/src/engine/SCons/Platform/__init__.py
index 81a49e7..6ef8b05 100644
--- a/src/engine/SCons/Platform/__init__.py
+++ b/src/engine/SCons/Platform/__init__.py
@@ -223,8 +223,8 @@ class TempFileMunge(object):
# purity get in the way of just being helpful, so we'll
# reach into SCons.Action directly.
if SCons.Action.print_actions:
- print("Using tempfile "+native_tmp+" for command line:\n"+
- str(cmd[0]) + " " + " ".join(args))
+ print(("Using tempfile "+native_tmp+" for command line:\n"+
+ str(cmd[0]) + " " + " ".join(args)))
return [ cmd[0], prefix + native_tmp + '\n' + rm, native_tmp ]
def Platform(name = platform_default()):
diff --git a/src/engine/SCons/Platform/aix.py b/src/engine/SCons/Platform/aix.py
index 0229112..f6853b5 100644
--- a/src/engine/SCons/Platform/aix.py
+++ b/src/engine/SCons/Platform/aix.py
@@ -34,7 +34,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os
-import posix
+from . import posix
def get_xlc(env, xlc=None, xlc_r=None, packages=[]):
# Use the AIX package installer tool lslpp to figure out where a
diff --git a/src/engine/SCons/Platform/cygwin.py b/src/engine/SCons/Platform/cygwin.py
index a012682..e7c8b8a 100644
--- a/src/engine/SCons/Platform/cygwin.py
+++ b/src/engine/SCons/Platform/cygwin.py
@@ -32,7 +32,7 @@ selection method.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import posix
+from . import posix
from SCons.Platform import TempFileMunge
def generate(env):
diff --git a/src/engine/SCons/Platform/darwin.py b/src/engine/SCons/Platform/darwin.py
index 005673b..1cf4aeb 100644
--- a/src/engine/SCons/Platform/darwin.py
+++ b/src/engine/SCons/Platform/darwin.py
@@ -32,7 +32,7 @@ selection method.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import posix
+from . import posix
import os
def generate(env):
diff --git a/src/engine/SCons/Platform/hpux.py b/src/engine/SCons/Platform/hpux.py
index 43d284b..0e0bbcf 100644
--- a/src/engine/SCons/Platform/hpux.py
+++ b/src/engine/SCons/Platform/hpux.py
@@ -32,7 +32,7 @@ selection method.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import posix
+from . import posix
def generate(env):
posix.generate(env)
diff --git a/src/engine/SCons/Platform/irix.py b/src/engine/SCons/Platform/irix.py
index 2baee0b..2e5f217 100644
--- a/src/engine/SCons/Platform/irix.py
+++ b/src/engine/SCons/Platform/irix.py
@@ -32,7 +32,7 @@ selection method.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import posix
+from . import posix
def generate(env):
posix.generate(env)
diff --git a/src/engine/SCons/Platform/os2.py b/src/engine/SCons/Platform/os2.py
index 0fa4553..5ca26bc 100644
--- a/src/engine/SCons/Platform/os2.py
+++ b/src/engine/SCons/Platform/os2.py
@@ -31,7 +31,7 @@ selection method.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import win32
+from . import win32
def generate(env):
if 'ENV' not in env:
diff --git a/src/engine/SCons/Platform/posix.py b/src/engine/SCons/Platform/posix.py
index ece48d7..d1f6c78 100644
--- a/src/engine/SCons/Platform/posix.py
+++ b/src/engine/SCons/Platform/posix.py
@@ -77,7 +77,7 @@ def exec_fork(l, env):
exitval = 127
try:
os.execvpe(l[0], l, env)
- except OSError, e:
+ except OSError as e:
exitval = exitvalmap.get(e[0], e[0])
sys.stderr.write("scons: %s: %s\n" % (l[0], e[1]))
os._exit(exitval)
@@ -92,7 +92,7 @@ def _get_env_command(sh, escape, cmd, args, env):
s = ' '.join(args)
if env:
l = ['env', '-'] + \
- [escape(t[0])+'='+escape(t[1]) for t in env.items()] + \
+ [escape(t[0])+'='+escape(t[1]) for t in list(env.items())] + \
[sh, '-c', escape(s)]
s = ' '.join(l)
return s
@@ -125,7 +125,8 @@ def process_cmd_output(cmd_stdout, cmd_stderr, stdout, stderr):
else:
#sys.__stderr__.write( "str(stderr) = %s\n" % str )
stderr.write(str)
- except select.error, (_errno, _strerror):
+ except select.error as xxx_todo_changeme:
+ (_errno, _strerror) = xxx_todo_changeme.args
if _errno != errno.EINTR:
raise
@@ -164,7 +165,7 @@ def exec_piped_fork(l, env, stdout, stderr):
exitval = 127
try:
os.execvpe(l[0], l, env)
- except OSError, e:
+ except OSError as e:
exitval = exitvalmap.get(e[0], e[0])
stderr.write("scons: %s: %s\n" % (l[0], e[1]))
os._exit(exitval)
diff --git a/src/engine/SCons/Platform/sunos.py b/src/engine/SCons/Platform/sunos.py
index d23d65c..057fddf 100644
--- a/src/engine/SCons/Platform/sunos.py
+++ b/src/engine/SCons/Platform/sunos.py
@@ -32,7 +32,7 @@ selection method.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import posix
+from . import posix
def generate(env):
posix.generate(env)
diff --git a/src/engine/SCons/Platform/win32.py b/src/engine/SCons/Platform/win32.py
index 5f20685..879817d 100644
--- a/src/engine/SCons/Platform/win32.py
+++ b/src/engine/SCons/Platform/win32.py
@@ -155,7 +155,7 @@ def piped_spawn(sh, escape, cmd, args, env, stdout, stderr):
try:
args = [sh, '/C', escape(' '.join(args)) ]
ret = spawnve(os.P_WAIT, sh, args, env)
- except OSError, e:
+ except OSError as e:
# catch any error
try:
ret = exitvalmap[e[0]]
@@ -183,7 +183,7 @@ def piped_spawn(sh, escape, cmd, args, env, stdout, stderr):
def exec_spawn(l, env):
try:
result = spawnve(os.P_WAIT, l[0], l, env)
- except OSError, e:
+ except OSError as e:
try:
result = exitvalmap[e[0]]
sys.stderr.write("scons: %s: %s\n" % (l[0], e[1]))
diff --git a/src/engine/SCons/SConf.py b/src/engine/SCons/SConf.py
index f3a3545..987f88d 100644
--- a/src/engine/SCons/SConf.py
+++ b/src/engine/SCons/SConf.py
@@ -118,7 +118,7 @@ def CreateConfigHBuilder(env):
_stringConfigH)
sconfigHBld = SCons.Builder.Builder(action=action)
env.Append( BUILDERS={'SConfigHBuilder':sconfigHBld} )
- for k in _ac_config_hs.keys():
+ for k in list(_ac_config_hs.keys()):
env.SConfigHBuilder(k, env.Value(_ac_config_hs[k]))
class SConfWarning(SCons.Warnings.Warning):
@@ -239,7 +239,7 @@ class SConfBuildTask(SCons.Taskmaster.AlwaysTask):
# Earlier versions of Python don't have sys.excepthook...
def excepthook(type, value, tb):
traceback.print_tb(tb)
- print type, value
+ print(type, value)
excepthook(*self.exc_info())
return SCons.Taskmaster.Task.failed(self)
@@ -318,7 +318,7 @@ class SConfBuildTask(SCons.Taskmaster.AlwaysTask):
env_decider=env.decide_source):
env_decider(dependency, target, prev_ni)
return True
- if env.decide_source.func_code is not force_build.func_code:
+ if env.decide_source.__code__ is not force_build.__code__:
env.Decider(force_build)
env['PSTDOUT'] = env['PSTDERR'] = s
try:
@@ -332,7 +332,7 @@ class SConfBuildTask(SCons.Taskmaster.AlwaysTask):
except SystemExit:
exc_value = sys.exc_info()[1]
raise SCons.Errors.ExplicitExit(self.targets[0],exc_value.code)
- except Exception, e:
+ except Exception as e:
for t in self.targets:
binfo = t.get_binfo()
binfo.__class__ = SConfBuildInfo
@@ -652,7 +652,7 @@ class SConfBase(object):
"""Adds all the tests given in the tests dictionary to this SConf
instance
"""
- for name in tests.keys():
+ for name in list(tests.keys()):
self.AddTest(name, tests[name])
def _createDir( self, node ):
diff --git a/src/engine/SCons/SConfTests.py b/src/engine/SCons/SConfTests.py
index e604886..ba524fd 100644
--- a/src/engine/SCons/SConfTests.py
+++ b/src/engine/SCons/SConfTests.py
@@ -60,7 +60,7 @@ class SConfTestCase(unittest.TestCase):
# We try to reset scons' state (including all global variables)
import SCons.SConsign
SCons.SConsign.write() # simulate normal scons-finish
- for n in sys.modules.keys():
+ for n in list(sys.modules.keys()):
if n.split('.')[0] == 'SCons' and n[:12] != 'SCons.compat':
m = sys.modules[n]
if isinstance(m, ModuleType):
diff --git a/src/engine/SCons/SConsign.py b/src/engine/SCons/SConsign.py
index 6555fcb..5ce61be 100644
--- a/src/engine/SCons/SConsign.py
+++ b/src/engine/SCons/SConsign.py
@@ -84,7 +84,7 @@ def Get_DataBase(dir):
DB_sync_list.append(db)
return db, "c"
except TypeError:
- print "DataBase =", DataBase
+ print("DataBase =", DataBase)
raise
def Reset():
@@ -172,7 +172,7 @@ class Base(object):
pass
def merge(self):
- for key, node in self.to_be_merged.items():
+ for key, node in list(self.to_be_merged.items()):
entry = node.get_stored_info()
try:
ninfo = entry.ninfo
@@ -215,10 +215,10 @@ class DB(Base):
raise TypeError
except KeyboardInterrupt:
raise
- except Exception, e:
+ except Exception as e:
SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning,
"Ignoring corrupt sconsign entry : %s (%s)\n"%(self.dir.tpath, e))
- for key, entry in self.entries.items():
+ for key, entry in list(self.entries.items()):
entry.convert_from_sconsign(dir, key)
if mode == "r":
@@ -245,7 +245,7 @@ class DB(Base):
# the Repository; we only write to our own .sconsign file,
# not to .sconsign files in Repositories.
path = normcase(self.dir.path)
- for key, entry in self.entries.items():
+ for key, entry in list(self.entries.items()):
entry.convert_to_sconsign()
db[path] = pickle.dumps(self.entries, 1)
@@ -274,7 +274,7 @@ class Dir(Base):
raise TypeError
if dir:
- for key, entry in self.entries.items():
+ for key, entry in list(self.entries.items()):
entry.convert_from_sconsign(dir, key)
class DirFile(Dir):
@@ -333,14 +333,14 @@ class DirFile(Dir):
fname = self.sconsign
except IOError:
return
- for key, entry in self.entries.items():
+ for key, entry in list(self.entries.items()):
entry.convert_to_sconsign()
pickle.dump(self.entries, file, 1)
file.close()
if fname != self.sconsign:
try:
mode = os.stat(self.sconsign)[0]
- os.chmod(self.sconsign, 0666)
+ os.chmod(self.sconsign, 0o666)
os.unlink(self.sconsign)
except (IOError, OSError):
# Try to carry on in the face of either OSError
diff --git a/src/engine/SCons/Scanner/C.py b/src/engine/SCons/Scanner/C.py
index 3311a09..74b01a4 100644
--- a/src/engine/SCons/Scanner/C.py
+++ b/src/engine/SCons/Scanner/C.py
@@ -59,7 +59,7 @@ class SConsCPPScanner(SCons.cpp.PreProcessor):
def read_file(self, file):
try:
fp = open(str(file.rfile()))
- except EnvironmentError, e:
+ except EnvironmentError as e:
self.missing.append((file, self.current_file))
return ''
else:
diff --git a/src/engine/SCons/Scanner/Fortran.py b/src/engine/SCons/Scanner/Fortran.py
index 1b55130..5339ab2 100644
--- a/src/engine/SCons/Scanner/Fortran.py
+++ b/src/engine/SCons/Scanner/Fortran.py
@@ -35,6 +35,7 @@ import SCons.Node.FS
import SCons.Scanner
import SCons.Util
import SCons.Warnings
+import collections
class F90Scanner(SCons.Scanner.Classic):
"""
@@ -109,7 +110,7 @@ class F90Scanner(SCons.Scanner.Classic):
# is actually found in a Repository or locally.
nodes = []
source_dir = node.get_dir()
- if callable(path):
+ if isinstance(path, collections.Callable):
path = path()
for dep in mods_and_includes:
n, i = self.find_include(dep, source_dir, path)
diff --git a/src/engine/SCons/Scanner/LaTeX.py b/src/engine/SCons/Scanner/LaTeX.py
index 2cb1ed5..1e0fea1 100644
--- a/src/engine/SCons/Scanner/LaTeX.py
+++ b/src/engine/SCons/Scanner/LaTeX.py
@@ -200,14 +200,14 @@ class LaTeX(SCons.Scanner.Base):
"""
def __init__(self, dictionary):
self.dictionary = {}
- for k,n in dictionary.items():
+ for k,n in list(dictionary.items()):
self.dictionary[k] = ( SCons.Scanner.FindPathDirs(n),
FindENVPathDirs(n) )
def __call__(self, env, dir=None, target=None, source=None,
argument=None):
di = {}
- for k,(c,cENV) in self.dictionary.items():
+ for k,(c,cENV) in list(self.dictionary.items()):
di[k] = ( c(env, dir=None, target=None, source=None,
argument=None) ,
cENV(env, dir=None, target=None, source=None,
diff --git a/src/engine/SCons/Scanner/Prog.py b/src/engine/SCons/Scanner/Prog.py
index 49e93a5..6e2da21 100644
--- a/src/engine/SCons/Scanner/Prog.py
+++ b/src/engine/SCons/Scanner/Prog.py
@@ -27,6 +27,7 @@ import SCons.Node
import SCons.Node.FS
import SCons.Scanner
import SCons.Util
+import collections
# global, set by --debug=findlibs
print_find_libs = None
@@ -76,7 +77,7 @@ def scan(node, env, libpath = ()):
result = []
- if callable(libpath):
+ if isinstance(libpath, collections.Callable):
libpath = libpath()
find_file = SCons.Node.FS.find_file
diff --git a/src/engine/SCons/Scanner/ProgTests.py b/src/engine/SCons/Scanner/ProgTests.py
index 411e035..f564c91 100644
--- a/src/engine/SCons/Scanner/ProgTests.py
+++ b/src/engine/SCons/Scanner/ProgTests.py
@@ -230,7 +230,7 @@ def suite():
suite.addTest(ProgramScannerTestCase6())
suite.addTest(ProgramScannerTestCase7())
suite.addTest(ProgramScannerTestCase8())
- try: unicode
+ try: str
except NameError: pass
else:
code = """if 1:
@@ -245,7 +245,7 @@ def suite():
assert deps_match(deps, ['d1/l2.lib', 'd1/d2/l3.lib']), map(str, deps)
suite.addTest(ProgramScannerTestCase4())
\n"""
- exec code
+ exec(code)
return suite
if __name__ == "__main__":
diff --git a/src/engine/SCons/Scanner/ScannerTests.py b/src/engine/SCons/Scanner/ScannerTests.py
index ee26922..5a4639d 100644
--- a/src/engine/SCons/Scanner/ScannerTests.py
+++ b/src/engine/SCons/Scanner/ScannerTests.py
@@ -569,7 +569,7 @@ class ClassicCPPTestCase(unittest.TestCase):
assert n == 'path/bbb', n
assert i == 'bbb', i
- n, i = s.find_include(('<', u'ccc'), 'foo', ('path',))
+ n, i = s.find_include(('<', 'ccc'), 'foo', ('path',))
assert n == 'path/ccc', n
assert i == 'ccc', i
diff --git a/src/engine/SCons/Scanner/__init__.py b/src/engine/SCons/Scanner/__init__.py
index 562a361..6ec8df9 100644
--- a/src/engine/SCons/Scanner/__init__.py
+++ b/src/engine/SCons/Scanner/__init__.py
@@ -33,6 +33,7 @@ import re
import SCons.Node.FS
import SCons.Util
+import collections
class _Null(object):
@@ -178,7 +179,7 @@ class Base(object):
self.node_class = node_class
self.node_factory = node_factory
self.scan_check = scan_check
- if callable(recursive):
+ if isinstance(recursive, collections.Callable):
self.recurse_nodes = recursive
elif recursive:
self.recurse_nodes = self._recurse_all_nodes
@@ -369,7 +370,7 @@ class Classic(Current):
# is actually found in a Repository or locally.
nodes = []
source_dir = node.get_dir()
- if callable(path):
+ if isinstance(path, collections.Callable):
path = path()
for include in includes:
n, i = self.find_include(include, source_dir, path)
diff --git a/src/engine/SCons/Script/Interactive.py b/src/engine/SCons/Script/Interactive.py
index ffb5096..87fe1cf 100644
--- a/src/engine/SCons/Script/Interactive.py
+++ b/src/engine/SCons/Script/Interactive.py
@@ -120,7 +120,7 @@ class SConsInteractiveCmd(cmd.Cmd):
def __init__(self, **kw):
cmd.Cmd.__init__(self)
- for key, val in kw.items():
+ for key, val in list(kw.items()):
setattr(self, key, val)
if sys.platform == 'win32':
@@ -129,12 +129,12 @@ class SConsInteractiveCmd(cmd.Cmd):
self.shell_variable = 'SHELL'
def default(self, argv):
- print "*** Unknown command: %s" % argv[0]
+ print("*** Unknown command: %s" % argv[0])
def onecmd(self, line):
line = line.strip()
if not line:
- print self.lastcmd
+ print(self.lastcmd)
return self.emptyline()
self.lastcmd = line
if line[0] == '!':
@@ -249,7 +249,7 @@ class SConsInteractiveCmd(cmd.Cmd):
while n:
n = walker.get_next()
- for node in seen_nodes.keys():
+ for node in list(seen_nodes.keys()):
# Call node.clear() to clear most of the state
node.clear()
# node.clear() doesn't reset node.state, so call
@@ -274,7 +274,7 @@ class SConsInteractiveCmd(cmd.Cmd):
return self.do_build(['build', '--clean'] + argv[1:])
def do_EOF(self, argv):
- print
+ print()
self.do_exit(argv)
def _do_one_help(self, arg):
@@ -357,7 +357,7 @@ class SConsInteractiveCmd(cmd.Cmd):
# Doing the right thing with an argument list currently
# requires different shell= values on Windows and Linux.
p = subprocess.Popen(argv, shell=(sys.platform=='win32'))
- except EnvironmentError, e:
+ except EnvironmentError as e:
sys.stderr.write('scons: %s: %s\n' % (argv[0], e.strerror))
else:
p.wait()
diff --git a/src/engine/SCons/Script/Main.py b/src/engine/SCons/Script/Main.py
index 837c103..9a52937 100644
--- a/src/engine/SCons/Script/Main.py
+++ b/src/engine/SCons/Script/Main.py
@@ -68,6 +68,7 @@ import SCons.Util
import SCons.Warnings
import SCons.Script.Interactive
+import collections
def fetch_win32_parallel_msg():
# A subsidiary function that exists solely to isolate this import
@@ -104,7 +105,7 @@ class Progressor(object):
self.interval = interval
self.overwrite = overwrite
- if callable(obj):
+ if isinstance(obj, collections.Callable):
self.func = obj
elif SCons.Util.is_List(obj):
self.func = self.spinner
@@ -224,7 +225,7 @@ class BuildTask(SCons.Taskmaster.OutOfDateTask):
self.exception_set()
self.do_failed()
else:
- print "scons: Nothing to be done for `%s'." % t
+ print("scons: Nothing to be done for `%s'." % t)
SCons.Taskmaster.OutOfDateTask.executed(self)
else:
SCons.Taskmaster.OutOfDateTask.executed(self)
@@ -290,8 +291,8 @@ class BuildTask(SCons.Taskmaster.OutOfDateTask):
if self.options.debug_includes:
tree = t.render_include_tree()
if tree:
- print
- print tree
+ print()
+ print(tree)
SCons.Taskmaster.OutOfDateTask.postprocess(self)
def make_ready(self):
@@ -326,10 +327,10 @@ class CleanTask(SCons.Taskmaster.AlwaysTask):
else:
errstr = "Path '%s' exists but isn't a file or directory."
raise SCons.Errors.UserError(errstr % (pathstr))
- except SCons.Errors.UserError, e:
- print e
- except (IOError, OSError), e:
- print "scons: Could not remove '%s':" % pathstr, e.strerror
+ except SCons.Errors.UserError as e:
+ print(e)
+ except (IOError, OSError) as e:
+ print("scons: Could not remove '%s':" % pathstr, e.strerror)
def show(self):
target = self.targets[0]
@@ -348,13 +349,13 @@ class CleanTask(SCons.Taskmaster.AlwaysTask):
for t in self.targets:
try:
removed = t.remove()
- except OSError, e:
+ except OSError as e:
# An OSError may indicate something like a permissions
# issue, an IOError would indicate something like
# the file not existing. In either case, print a
# message and keep going to try to remove as many
# targets aa possible.
- print "scons: Could not remove '%s':" % str(t), e.strerror
+ print("scons: Could not remove '%s':" % str(t), e.strerror)
else:
if removed:
display("Removed " + str(t))
@@ -595,7 +596,7 @@ def _scons_internal_error():
"""Handle all errors but user errors. Print out a message telling
the user what to do in this case and print a normal trace.
"""
- print 'internal error'
+ print('internal error')
traceback.print_exc()
sys.exit(2)
@@ -707,7 +708,7 @@ def _load_site_scons_dir(topdir, site_dir_name=None):
# the error checking makes it longer.
try:
m = sys.modules['SCons.Script']
- except Exception, e:
+ except Exception as e:
fmt = 'cannot import site_init.py: missing SCons.Script module %s'
raise SCons.Errors.InternalError(fmt % repr(e))
try:
@@ -715,15 +716,15 @@ def _load_site_scons_dir(topdir, site_dir_name=None):
modname = os.path.basename(pathname)[:-len(sfx)]
site_m = {"__file__": pathname, "__name__": modname, "__doc__": None}
re_special = re.compile("__[^_]+__")
- for k in m.__dict__.keys():
+ for k in list(m.__dict__.keys()):
if not re_special.match(k):
site_m[k] = m.__dict__[k]
# This is the magic.
- exec fp in site_m
+ exec(fp, site_m)
except KeyboardInterrupt:
raise
- except Exception, e:
+ except Exception as e:
fmt = '*** Error loading site_init file %s:\n'
sys.stderr.write(fmt % repr(site_init_file))
raise
@@ -733,7 +734,7 @@ def _load_site_scons_dir(topdir, site_dir_name=None):
m.__dict__[k] = site_m[k]
except KeyboardInterrupt:
raise
- except ImportError, e:
+ except ImportError as e:
fmt = '*** cannot import site init file %s:\n'
sys.stderr.write(fmt % repr(site_init_file))
raise
@@ -785,7 +786,7 @@ def _load_all_site_scons_dirs(topdir, verbose=None):
dirs=sysdirs + [topdir]
for d in dirs:
if verbose: # this is used by unit tests.
- print "Loading site dir ", d
+ print("Loading site dir ", d)
_load_site_scons_dir(d)
def test_load_all_site_scons_dirs(d):
@@ -977,7 +978,7 @@ def _main(parser):
try:
for script in scripts:
SCons.Script._SConscript._SConscript(fs, script)
- except SCons.Errors.StopError, e:
+ except SCons.Errors.StopError as e:
# We had problems reading an SConscript file, such as it
# couldn't be copied in to the VariantDir. Since we're just
# reading SConscript files and haven't started building
@@ -1034,8 +1035,8 @@ def _main(parser):
# SConscript files. Give them the options usage.
raise SConsPrintHelpException
else:
- print help_text
- print "Use scons -H for help about command-line options."
+ print(help_text)
+ print("Use scons -H for help about command-line options.")
exit_status = 0
return
@@ -1298,7 +1299,7 @@ def _exec_main(parser, values):
prof = Profile()
try:
prof.runcall(_main, parser)
- except SConsPrintHelpException, e:
+ except SConsPrintHelpException as e:
prof.dump_stats(options.profile_file)
raise e
except SystemExit:
@@ -1334,7 +1335,7 @@ def main():
parts.append("__COPYRIGHT__")
version = ''.join(parts)
- import SConsOptions
+ from . import SConsOptions
parser = SConsOptions.Parser(version)
values = SConsOptions.SConsValues(parser.get_default_values())
@@ -1342,22 +1343,22 @@ def main():
try:
_exec_main(parser, values)
- except SystemExit, s:
+ except SystemExit as s:
if s:
exit_status = s
except KeyboardInterrupt:
print("scons: Build interrupted.")
sys.exit(2)
- except SyntaxError, e:
+ except SyntaxError as e:
_scons_syntax_error(e)
except SCons.Errors.InternalError:
_scons_internal_error()
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
_scons_user_error(e)
except SConsPrintHelpException:
parser.print_help()
exit_status = 0
- except SCons.Errors.BuildError, e:
+ except SCons.Errors.BuildError as e:
exit_status = e.exitstatus
except:
# An exception here is likely a builtin Python exception Python
@@ -1393,10 +1394,10 @@ def main():
else:
ct = last_command_end - first_command_start
scons_time = total_time - sconscript_time - ct
- print "Total build time: %f seconds"%total_time
- print "Total SConscript file execution time: %f seconds"%sconscript_time
- print "Total SCons execution time: %f seconds"%scons_time
- print "Total command execution time: %f seconds"%ct
+ print("Total build time: %f seconds"%total_time)
+ print("Total SConscript file execution time: %f seconds"%sconscript_time)
+ print("Total SCons execution time: %f seconds"%scons_time)
+ print("Total command execution time: %f seconds"%ct)
sys.exit(exit_status)
diff --git a/src/engine/SCons/Script/SConsOptions.py b/src/engine/SCons/Script/SConsOptions.py
index 645ab11..559db97 100644
--- a/src/engine/SCons/Script/SConsOptions.py
+++ b/src/engine/SCons/Script/SConsOptions.py
@@ -161,7 +161,7 @@ class SConsValues(optparse.Values):
elif name == 'diskcheck':
try:
value = diskcheck_convert(value)
- except ValueError, v:
+ except ValueError as v:
raise SCons.Errors.UserError("Not a valid diskcheck value: %s"%v)
if 'diskcheck' not in self.__dict__:
# No --diskcheck= option was specified on the command line.
@@ -611,7 +611,7 @@ def Parser(version):
deprecated_debug_options=deprecated_debug_options):
if value in debug_options:
parser.values.debug.append(value)
- elif value in deprecated_debug_options.keys():
+ elif value in list(deprecated_debug_options.keys()):
parser.values.debug.append(value)
try:
parser.values.delayed_warnings
@@ -635,7 +635,7 @@ def Parser(version):
def opt_diskcheck(option, opt, value, parser):
try:
diskcheck_value = diskcheck_convert(value)
- except ValueError, e:
+ except ValueError as e:
raise OptionValueError("`%s' is not a valid diskcheck type" % e)
setattr(parser.values, option.dest, diskcheck_value)
@@ -802,7 +802,7 @@ def Parser(version):
tree_options = ["all", "derived", "prune", "status"]
def opt_tree(option, opt, value, parser, tree_options=tree_options):
- import Main
+ from . import Main
tp = Main.TreePrinter()
for o in value.split(','):
if o == 'all':
diff --git a/src/engine/SCons/Script/SConscript.py b/src/engine/SCons/Script/SConscript.py
index bd515d2..fefffef 100644
--- a/src/engine/SCons/Script/SConscript.py
+++ b/src/engine/SCons/Script/SConscript.py
@@ -26,7 +26,7 @@ files.
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-from __future__ import division
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -113,7 +113,7 @@ def compute_exports(exports):
retval[export] = loc[export]
except KeyError:
retval[export] = glob[export]
- except KeyError, x:
+ except KeyError as x:
raise SCons.Errors.UserError("Export of non-existent variable '%s'"%x)
return retval
@@ -145,7 +145,7 @@ def Return(*vars, **kw):
for var in fvars:
for v in var.split():
retval.append(call_stack[-1].globals[v])
- except KeyError, x:
+ except KeyError as x:
raise SCons.Errors.UserError("Return of non-existent variable '%s'"%x)
if len(retval) == 1:
@@ -174,7 +174,7 @@ def _SConscript(fs, *files, **kw):
try:
SCons.Script.sconscript_reading = SCons.Script.sconscript_reading + 1
if fn == "-":
- exec sys.stdin in call_stack[-1].globals
+ exec(sys.stdin, call_stack[-1].globals)
else:
if isinstance(fn, SCons.Node.Node):
f = fn
@@ -257,7 +257,7 @@ def _SConscript(fs, *files, **kw):
pass
try:
try:
- exec _file_ in call_stack[-1].globals
+ exec(_file_, call_stack[-1].globals)
except SConscriptReturn:
pass
finally:
@@ -282,7 +282,7 @@ def _SConscript(fs, *files, **kw):
rdir._create() # Make sure there's a directory there.
try:
os.chdir(rdir.get_abspath())
- except OSError, e:
+ except OSError as e:
# We still couldn't chdir there, so raise the error,
# but only if actions are being executed.
#
@@ -467,15 +467,15 @@ class SConsEnvironment(SCons.Environment.Base):
scons_ver_string = '%d.%d.%d' % (major, minor, revision)
else:
scons_ver_string = '%d.%d' % (major, minor)
- print "SCons %s or greater required, but you have SCons %s" % \
- (scons_ver_string, SCons.__version__)
+ print("SCons %s or greater required, but you have SCons %s" % \
+ (scons_ver_string, SCons.__version__))
sys.exit(2)
def EnsurePythonVersion(self, major, minor):
"""Exit abnormally if the Python version is not late enough."""
if sys.version_info < (major, minor):
v = sys.version.split()[0]
- print "Python %d.%d or greater required, but you have Python %s" %(major,minor,v)
+ print("Python %d.%d or greater required, but you have Python %s" %(major,minor,v))
sys.exit(2)
def Exit(self, value=0):
@@ -514,7 +514,7 @@ class SConsEnvironment(SCons.Environment.Base):
globals[v] = exports[v]
else:
globals[v] = global_exports[v]
- except KeyError,x:
+ except KeyError as x:
raise SCons.Errors.UserError("Import of non-existent variable '%s'"%x)
def SConscript(self, *ls, **kw):
@@ -529,7 +529,7 @@ class SConsEnvironment(SCons.Environment.Base):
return x
ls = list(map(subst_element, ls))
subst_kw = {}
- for key, val in kw.items():
+ for key, val in list(kw.items()):
if SCons.Util.is_String(val):
val = self.subst(val)
elif SCons.Util.is_List(val):
diff --git a/src/engine/SCons/Script/__init__.py b/src/engine/SCons/Script/__init__.py
index bb7b632..9f2837c 100644
--- a/src/engine/SCons/Script/__init__.py
+++ b/src/engine/SCons/Script/__init__.py
@@ -66,7 +66,7 @@ if "--debug=memoizer" in _args:
except SCons.Warnings.Warning:
# Some warning was thrown. Arrange for it to be displayed
# or not after warnings are configured.
- import Main
+ from . import Main
exc_type, exc_value, tb = sys.exc_info()
Main.delayed_warnings.append((exc_type, exc_value))
del _args
@@ -85,7 +85,7 @@ import SCons.Util
import SCons.Variables
import SCons.Defaults
-import Main
+from . import Main
main = Main.main
@@ -128,7 +128,7 @@ GetBuildFailures = Main.GetBuildFailures
#repositories = Main.repositories
#
-import SConscript
+from . import SConscript
_SConscript = SConscript
call_stack = _SConscript.call_stack
@@ -364,7 +364,7 @@ GlobalDefaultBuilders = [
]
for name in GlobalDefaultEnvironmentFunctions + GlobalDefaultBuilders:
- exec "%s = _SConscript.DefaultEnvironmentCall(%s)" % (name, repr(name))
+ exec("%s = _SConscript.DefaultEnvironmentCall(%s)" % (name, repr(name)))
del name
# There are a handful of variables that used to live in the
diff --git a/src/engine/SCons/Subst.py b/src/engine/SCons/Subst.py
index 98097dc..cca9bbc 100644
--- a/src/engine/SCons/Subst.py
+++ b/src/engine/SCons/Subst.py
@@ -438,7 +438,7 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={
s = eval(key, self.gvars, lvars)
except KeyboardInterrupt:
raise
- except Exception, e:
+ except Exception as e:
if e.__class__ in AllowableExceptions:
return ''
raise_exception(e, lvars['TARGETS'], s)
@@ -472,7 +472,7 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={
def func(l, conv=self.conv, substitute=self.substitute, lvars=lvars):
return conv(substitute(l, lvars))
return list(map(func, s))
- elif callable(s):
+ elif isinstance(s, collections.Callable):
try:
s = s(target=lvars['TARGETS'],
source=lvars['SOURCES'],
@@ -653,7 +653,7 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv
s = eval(key, self.gvars, lvars)
except KeyboardInterrupt:
raise
- except Exception, e:
+ except Exception as e:
if e.__class__ in AllowableExceptions:
return
raise_exception(e, lvars['TARGETS'], s)
@@ -681,7 +681,7 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv
for a in s:
self.substitute(a, lvars, 1)
self.next_word()
- elif callable(s):
+ elif isinstance(s, collections.Callable):
try:
s = s(target=lvars['TARGETS'],
source=lvars['SOURCES'],
diff --git a/src/engine/SCons/SubstTests.py b/src/engine/SCons/SubstTests.py
index 420fd73..da21020 100644
--- a/src/engine/SCons/SubstTests.py
+++ b/src/engine/SCons/SubstTests.py
@@ -241,14 +241,14 @@ class SubstTestCase(unittest.TestCase):
expect = convert(expect)
try:
result = function(input, env, **kwargs)
- except Exception, e:
+ except Exception as e:
fmt = " input %s generated %s (%s)"
- print fmt % (repr(input), e.__class__.__name__, repr(e))
+ print(fmt % (repr(input), e.__class__.__name__, repr(e)))
failed = failed + 1
else:
if result != expect:
- if failed == 0: print
- print " input %s => %s did not match %s" % (repr(input), repr(result), repr(expect))
+ if failed == 0: print()
+ print(" input %s => %s did not match %s" % (repr(input), repr(result), repr(expect)))
failed = failed + 1
del cases[:2]
fmt = "%d %s() cases failed"
@@ -460,18 +460,18 @@ class scons_subst_TestCase(SubstTestCase):
input, eraw, ecmd, esig = subst_cases[:4]
result = scons_subst(input, env, mode=SUBST_RAW, gvars=gvars)
if result != eraw:
- if failed == 0: print
- print " input %s => RAW %s did not match %s" % (repr(input), repr(result), repr(eraw))
+ if failed == 0: print()
+ print(" input %s => RAW %s did not match %s" % (repr(input), repr(result), repr(eraw)))
failed = failed + 1
result = scons_subst(input, env, mode=SUBST_CMD, gvars=gvars)
if result != ecmd:
- if failed == 0: print
- print " input %s => CMD %s did not match %s" % (repr(input), repr(result), repr(ecmd))
+ if failed == 0: print()
+ print(" input %s => CMD %s did not match %s" % (repr(input), repr(result), repr(ecmd)))
failed = failed + 1
result = scons_subst(input, env, mode=SUBST_SIG, gvars=gvars)
if result != esig:
- if failed == 0: print
- print " input %s => SIG %s did not match %s" % (repr(input), repr(result), repr(esig))
+ if failed == 0: print()
+ print(" input %s => SIG %s did not match %s" % (repr(input), repr(result), repr(esig)))
failed = failed + 1
del subst_cases[:4]
assert failed == 0, "%d subst() mode cases failed" % failed
@@ -514,7 +514,7 @@ class scons_subst_TestCase(SubstTestCase):
class Foo(object):
pass
scons_subst('${foo.bar}', env, gvars={'foo':Foo()})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
expect = [
"AttributeError `bar' trying to evaluate `${foo.bar}'",
"AttributeError `Foo instance has no attribute 'bar'' trying to evaluate `${foo.bar}'",
@@ -530,7 +530,7 @@ class scons_subst_TestCase(SubstTestCase):
env = DummyEnv(self.loc)
try:
scons_subst('$foo.bar.3.0', env)
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
expect = [
# Python 2.3, 2.4
"SyntaxError `invalid syntax (line 1)' trying to evaluate `$foo.bar.3.0'",
@@ -546,7 +546,7 @@ class scons_subst_TestCase(SubstTestCase):
env = DummyEnv(self.loc)
try:
scons_subst("${NONE[2]}", env, gvars={'NONE':None})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
expect = [
# Python 2.3, 2.4
"TypeError `unsubscriptable object' trying to evaluate `${NONE[2]}'",
@@ -565,7 +565,7 @@ class scons_subst_TestCase(SubstTestCase):
def func(a, b, c):
pass
scons_subst("${func(1)}", env, gvars={'func':func})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
expect = [
# Python 2.3, 2.4, 2.5
"TypeError `func() takes exactly 3 arguments (1 given)' trying to evaluate `${func(1)}'"
@@ -946,18 +946,18 @@ class scons_subst_list_TestCase(SubstTestCase):
input, eraw, ecmd, esig = subst_list_cases[:4]
result = scons_subst_list(input, env, mode=SUBST_RAW, gvars=gvars)
if result != eraw:
- if failed == 0: print
- print " input %s => RAW %s did not match %s" % (repr(input), repr(result), repr(eraw))
+ if failed == 0: print()
+ print(" input %s => RAW %s did not match %s" % (repr(input), repr(result), repr(eraw)))
failed = failed + 1
result = scons_subst_list(input, env, mode=SUBST_CMD, gvars=gvars)
if result != ecmd:
- if failed == 0: print
- print " input %s => CMD %s did not match %s" % (repr(input), repr(result), repr(ecmd))
+ if failed == 0: print()
+ print(" input %s => CMD %s did not match %s" % (repr(input), repr(result), repr(ecmd)))
failed = failed + 1
result = scons_subst_list(input, env, mode=SUBST_SIG, gvars=gvars)
if result != esig:
- if failed == 0: print
- print " input %s => SIG %s did not match %s" % (repr(input), repr(result), repr(esig))
+ if failed == 0: print()
+ print(" input %s => SIG %s did not match %s" % (repr(input), repr(result), repr(esig)))
failed = failed + 1
del subst_list_cases[:4]
assert failed == 0, "%d subst() mode cases failed" % failed
@@ -969,7 +969,7 @@ class scons_subst_list_TestCase(SubstTestCase):
class Foo(object):
pass
scons_subst_list('${foo.bar}', env, gvars={'foo':Foo()})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
expect = [
"AttributeError `bar' trying to evaluate `${foo.bar}'",
"AttributeError `Foo instance has no attribute 'bar'' trying to evaluate `${foo.bar}'",
@@ -985,7 +985,7 @@ class scons_subst_list_TestCase(SubstTestCase):
env = DummyEnv()
try:
scons_subst_list('$foo.bar.3.0', env)
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
expect = [
"SyntaxError `invalid syntax' trying to evaluate `$foo.bar.3.0'",
"SyntaxError `invalid syntax (line 1)' trying to evaluate `$foo.bar.3.0'",
@@ -1093,8 +1093,8 @@ class scons_subst_once_TestCase(unittest.TestCase):
input, key, expect = cases[:3]
result = scons_subst_once(input, env, key)
if result != expect:
- if failed == 0: print
- print " input %s (%s) => %s did not match %s" % (repr(input), repr(key), repr(result), repr(expect))
+ if failed == 0: print()
+ print(" input %s (%s) => %s did not match %s" % (repr(input), repr(key), repr(result), repr(expect)))
failed = failed + 1
del cases[:3]
assert failed == 0, "%d subst() cases failed" % failed
diff --git a/src/engine/SCons/Taskmaster.py b/src/engine/SCons/Taskmaster.py
index 64ab84d..54d04a8 100644
--- a/src/engine/SCons/Taskmaster.py
+++ b/src/engine/SCons/Taskmaster.py
@@ -107,7 +107,7 @@ fmt = "%(considered)3d "\
def dump_stats():
for n in sorted(StatsNodes, key=lambda a: str(a)):
- print (fmt % n.stats.__dict__) + str(n)
+ print((fmt % n.stats.__dict__) + str(n))
@@ -164,7 +164,7 @@ class Task(object):
"""
global print_prepare
T = self.tm.trace
- if T: T.write(self.trace_message(u'Task.prepare()', self.node))
+ if T: T.write(self.trace_message('Task.prepare()', self.node))
# Now that it's the appropriate time, give the TaskMaster a
# chance to raise any exceptions it encountered while preparing
@@ -189,13 +189,13 @@ class Task(object):
executor.prepare()
for t in executor.get_action_targets():
if print_prepare:
- print "Preparing target %s..."%t
+ print("Preparing target %s..."%t)
for s in t.side_effects:
- print "...with side-effect %s..."%s
+ print("...with side-effect %s..."%s)
t.prepare()
for s in t.side_effects:
if print_prepare:
- print "...Preparing side-effect %s..."%s
+ print("...Preparing side-effect %s..."%s)
s.prepare()
def get_target(self):
@@ -224,7 +224,7 @@ class Task(object):
prepare(), executed() or failed().
"""
T = self.tm.trace
- if T: T.write(self.trace_message(u'Task.execute()', self.node))
+ if T: T.write(self.trace_message('Task.execute()', self.node))
try:
cached_targets = []
@@ -254,7 +254,7 @@ class Task(object):
raise
except SCons.Errors.BuildError:
raise
- except Exception, e:
+ except Exception as e:
buildError = SCons.Errors.convert_to_BuildError(e)
buildError.node = self.targets[0]
buildError.exc_info = sys.exc_info()
@@ -383,7 +383,7 @@ class Task(object):
This is the default behavior for building only what's necessary.
"""
T = self.tm.trace
- if T: T.write(self.trace_message(u'Task.make_ready_current()',
+ if T: T.write(self.trace_message('Task.make_ready_current()',
self.node))
self.out_of_date = []
@@ -393,7 +393,7 @@ class Task(object):
t.disambiguate().make_ready()
is_up_to_date = not t.has_builder() or \
(not t.always_build and t.is_up_to_date())
- except EnvironmentError, e:
+ except EnvironmentError as e:
raise SCons.Errors.BuildError(node=t, errstr=e.strerror, filename=e.filename)
if not is_up_to_date:
@@ -428,7 +428,7 @@ class Task(object):
that can be put back on the candidates list.
"""
T = self.tm.trace
- if T: T.write(self.trace_message(u'Task.postprocess()', self.node))
+ if T: T.write(self.trace_message('Task.postprocess()', self.node))
# We may have built multiple targets, some of which may have
# common parents waiting for this build. Count up how many
@@ -445,7 +445,7 @@ class Task(object):
# A node can only be in the pending_children set if it has
# some waiting_parents.
if t.waiting_parents:
- if T: T.write(self.trace_message(u'Task.postprocess()',
+ if T: T.write(self.trace_message('Task.postprocess()',
t,
'removing'))
pending_children.discard(t)
@@ -462,9 +462,9 @@ class Task(object):
if p.ref_count == 0:
self.tm.candidates.append(p)
- for p, subtract in parents.items():
+ for p, subtract in list(parents.items()):
p.ref_count = p.ref_count - subtract
- if T: T.write(self.trace_message(u'Task.postprocess()',
+ if T: T.write(self.trace_message('Task.postprocess()',
p,
'adjusted parent ref count'))
if p.ref_count == 0:
@@ -524,7 +524,7 @@ class Task(object):
except ValueError:
exc_type, exc_value = exc
exc_traceback = None
- raise exc_type, exc_value, exc_traceback
+ raise exc_type(exc_value).with_traceback(exc_traceback)
class AlwaysTask(Task):
def needs_execute(self):
@@ -748,12 +748,12 @@ class Taskmaster(object):
self.ready_exc = None
T = self.trace
- if T: T.write(u'\n' + self.trace_message('Looking for a node to evaluate'))
+ if T: T.write('\n' + self.trace_message('Looking for a node to evaluate'))
while True:
node = self.next_candidate()
if node is None:
- if T: T.write(self.trace_message('No candidate anymore.') + u'\n')
+ if T: T.write(self.trace_message('No candidate anymore.') + '\n')
return None
node = node.disambiguate()
@@ -776,7 +776,7 @@ class Taskmaster(object):
else:
S = None
- if T: T.write(self.trace_message(u' Considering node %s and its children:' % self.trace_node(node)))
+ if T: T.write(self.trace_message(' Considering node %s and its children:' % self.trace_node(node)))
if state == NODE_NO_STATE:
# Mark this node as being on the execution stack:
@@ -784,7 +784,7 @@ class Taskmaster(object):
elif state > NODE_PENDING:
# Skip this node if it has already been evaluated:
if S: S.already_handled = S.already_handled + 1
- if T: T.write(self.trace_message(u' already handled (executed)'))
+ if T: T.write(self.trace_message(' already handled (executed)'))
continue
executor = node.get_executor()
@@ -797,7 +797,7 @@ class Taskmaster(object):
self.ready_exc = (SCons.Errors.ExplicitExit, e)
if T: T.write(self.trace_message(' SystemExit'))
return node
- except Exception, e:
+ except Exception as e:
# We had a problem just trying to figure out the
# children (like a child couldn't be linked in to a
# VariantDir, or a Scanner threw something). Arrange to
@@ -815,7 +815,7 @@ class Taskmaster(object):
for child in chain(executor.get_all_prerequisites(), children):
childstate = child.get_state()
- if T: T.write(self.trace_message(u' ' + self.trace_node(child)))
+ if T: T.write(self.trace_message(' ' + self.trace_node(child)))
if childstate == NODE_NO_STATE:
children_not_visited.append(child)
@@ -874,7 +874,7 @@ class Taskmaster(object):
# count so we can be put back on the list for
# re-evaluation when they've all finished.
node.ref_count = node.ref_count + child.add_to_waiting_parents(node)
- if T: T.write(self.trace_message(u' adjusted ref count: %s, child %s' %
+ if T: T.write(self.trace_message(' adjusted ref count: %s, child %s' %
(self.trace_node(node), repr(str(child)))))
if T:
@@ -900,7 +900,7 @@ class Taskmaster(object):
# The default when we've gotten through all of the checks above:
# this node is ready to be built.
if S: S.build = S.build + 1
- if T: T.write(self.trace_message(u'Evaluating %s\n' %
+ if T: T.write(self.trace_message('Evaluating %s\n' %
self.trace_node(node)))
# For debugging only:
diff --git a/src/engine/SCons/TaskmasterTests.py b/src/engine/SCons/TaskmasterTests.py
index 85ade8d..0140278 100644
--- a/src/engine/SCons/TaskmasterTests.py
+++ b/src/engine/SCons/TaskmasterTests.py
@@ -20,7 +20,7 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
-from __future__ import division
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -692,7 +692,7 @@ class TaskmasterTestCase(unittest.TestCase):
tm = SCons.Taskmaster.Taskmaster([n3])
try:
t = tm.next_task()
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
assert str(e) == "Dependency cycle: n3 -> n1 -> n2 -> n3", str(e)
else:
assert 'Did not catch expected UserError'
@@ -846,7 +846,7 @@ class TaskmasterTestCase(unittest.TestCase):
exc_caught = None
try:
t.prepare()
- except MyException, e:
+ except MyException as e:
exc_caught = 1
except:
pass
@@ -899,7 +899,7 @@ class TaskmasterTestCase(unittest.TestCase):
t = tm.next_task()
try:
t.prepare()
- except Exception, e:
+ except Exception as e:
assert str(e) == "Executor.prepare() exception", e
else:
raise AssertionError("did not catch expected exception")
@@ -953,7 +953,7 @@ class TaskmasterTestCase(unittest.TestCase):
t = tm.next_task()
try:
t.execute()
- except SCons.Errors.BuildError, e:
+ except SCons.Errors.BuildError as e:
assert e.node == n4, e.node
assert e.errstr == "OtherError : ", e.errstr
assert len(e.exc_info) == 3, e.exc_info
diff --git a/src/engine/SCons/Tool/FortranCommon.py b/src/engine/SCons/Tool/FortranCommon.py
index 4c5730c..c21128e 100644
--- a/src/engine/SCons/Tool/FortranCommon.py
+++ b/src/engine/SCons/Tool/FortranCommon.py
@@ -61,7 +61,7 @@ def isfortran(env, source):
def _fortranEmitter(target, source, env):
node = source[0].rfile()
if not node.exists() and not node.is_derived():
- print "Could not locate " + str(node.name)
+ print("Could not locate " + str(node.name))
return ([], [])
mod_regex = """(?i)^\s*MODULE\s+(?!PROCEDURE)(\w+)"""
cre = re.compile(mod_regex,re.M)
diff --git a/src/engine/SCons/Tool/GettextCommon.py b/src/engine/SCons/Tool/GettextCommon.py
index cd2f306..ea81f0d 100644
--- a/src/engine/SCons/Tool/GettextCommon.py
+++ b/src/engine/SCons/Tool/GettextCommon.py
@@ -196,7 +196,7 @@ class _POFileBuilder(BuilderBase):
import SCons.Util
import SCons.Node
linguas_files = None
- if env.has_key('LINGUAS_FILE') and env['LINGUAS_FILE']:
+ if 'LINGUAS_FILE' in env and env['LINGUAS_FILE']:
linguas_files = env['LINGUAS_FILE']
# This prevents endless recursion loop (we'll be invoked once for
# each target appended here, we must not extend the list again).
@@ -341,7 +341,7 @@ class RPaths(object):
def _init_po_files(target, source, env):
""" Action function for `POInit` builder. """
nop = lambda target, source, env : 0
- if env.has_key('POAUTOINIT'):
+ if 'POAUTOINIT' in env:
autoinit = env['POAUTOINIT']
else:
autoinit = False
@@ -365,7 +365,7 @@ def _init_po_files(target, source, env):
#############################################################################
def _detect_xgettext(env):
""" Detects *xgettext(1)* binary """
- if env.has_key('XGETTEXT'):
+ if 'XGETTEXT' in env:
return env['XGETTEXT']
xgettext = env.Detect('xgettext');
if xgettext:
@@ -380,7 +380,7 @@ def _xgettext_exists(env):
#############################################################################
def _detect_msginit(env):
""" Detects *msginit(1)* program. """
- if env.has_key('MSGINIT'):
+ if 'MSGINIT' in env:
return env['MSGINIT']
msginit = env.Detect('msginit');
if msginit:
@@ -395,7 +395,7 @@ def _msginit_exists(env):
#############################################################################
def _detect_msgmerge(env):
""" Detects *msgmerge(1)* program. """
- if env.has_key('MSGMERGE'):
+ if 'MSGMERGE' in env:
return env['MSGMERGE']
msgmerge = env.Detect('msgmerge');
if msgmerge:
@@ -410,7 +410,7 @@ def _msgmerge_exists(env):
#############################################################################
def _detect_msgfmt(env):
""" Detects *msgmfmt(1)* program. """
- if env.has_key('MSGFMT'):
+ if 'MSGFMT' in env:
return env['MSGFMT']
msgfmt = env.Detect('msgfmt');
if msgfmt:
diff --git a/src/engine/SCons/Tool/MSCommon/common.py b/src/engine/SCons/Tool/MSCommon/common.py
index caf2b37..dcf69c8 100644
--- a/src/engine/SCons/Tool/MSCommon/common.py
+++ b/src/engine/SCons/Tool/MSCommon/common.py
@@ -38,7 +38,7 @@ import SCons.Util
logfile = os.environ.get('SCONS_MSCOMMON_DEBUG')
if logfile == '-':
def debug(x):
- print x
+ print(x)
elif logfile:
try:
import logging
@@ -113,7 +113,7 @@ def normalize_env(env, keys, force=False):
Note: the environment is copied."""
normenv = {}
if env:
- for k in env.keys():
+ for k in list(env.keys()):
normenv[k] = copy.deepcopy(env[k]).encode('mbcs')
for k in keys:
@@ -217,7 +217,7 @@ def parse_output(output, keep = ("INCLUDE", "LIB", "LIBPATH", "PATH")):
dkeep[key].append(p)
for line in output.splitlines():
- for k,v in rdk.items():
+ for k,v in list(rdk.items()):
m = v.match(line)
if m:
add_env(m, k)
diff --git a/src/engine/SCons/Tool/MSCommon/netframework.py b/src/engine/SCons/Tool/MSCommon/netframework.py
index 6124e5b..1a6478f 100644
--- a/src/engine/SCons/Tool/MSCommon/netframework.py
+++ b/src/engine/SCons/Tool/MSCommon/netframework.py
@@ -28,7 +28,7 @@ __doc__ = """
import os
import re
-from common import read_reg, debug
+from .common import read_reg, debug
# Original value recorded by dcournapeau
_FRAMEWORKDIR_HKEY_ROOT = r'Software\Microsoft\.NETFramework\InstallRoot'
@@ -40,7 +40,7 @@ def find_framework_root():
try:
froot = read_reg(_FRAMEWORKDIR_HKEY_ROOT)
debug("Found framework install root in registry: %s" % froot)
- except WindowsError, e:
+ except WindowsError as e:
debug("Could not read reg key %s" % _FRAMEWORKDIR_HKEY_ROOT)
return None
diff --git a/src/engine/SCons/Tool/MSCommon/sdk.py b/src/engine/SCons/Tool/MSCommon/sdk.py
index 2bf5eef..f71035b 100644
--- a/src/engine/SCons/Tool/MSCommon/sdk.py
+++ b/src/engine/SCons/Tool/MSCommon/sdk.py
@@ -33,7 +33,7 @@ import os
import SCons.Errors
import SCons.Util
-import common
+from . import common
debug = common.debug
@@ -80,7 +80,7 @@ class SDKDefinition(object):
try:
sdk_dir = common.read_reg(hkey)
- except WindowsError, e:
+ except WindowsError as e:
debug('find_sdk_dir(): no SDK registry key %s' % repr(hkey))
return None
@@ -299,7 +299,7 @@ def get_cur_sdk_dir_from_reg():
try:
val = common.read_reg(_CURINSTALLED_SDK_HKEY_ROOT)
debug("Found current sdk dir in registry: %s" % val)
- except WindowsError, e:
+ except WindowsError as e:
debug("Did not find current sdk in registry")
return None
@@ -350,7 +350,7 @@ def mssdk_setup_env(env):
debug('sdk.py:mssdk_setup_env thinks msvs_version is None')
return
msvs_version = env.subst(msvs_version)
- import vs
+ from . import vs
msvs = vs.get_vs_by_version(msvs_version)
debug('sdk.py:mssdk_setup_env:msvs is :%s'%msvs)
if not msvs:
diff --git a/src/engine/SCons/Tool/MSCommon/vc.py b/src/engine/SCons/Tool/MSCommon/vc.py
index 1266ee8..35b95d5 100644
--- a/src/engine/SCons/Tool/MSCommon/vc.py
+++ b/src/engine/SCons/Tool/MSCommon/vc.py
@@ -42,11 +42,11 @@ from string import digits as string_digits
import SCons.Warnings
-import common
+from . import common
debug = common.debug
-import sdk
+from . import sdk
get_installed_sdks = sdk.get_installed_sdks
@@ -119,14 +119,14 @@ def get_host_target(env):
try:
host = _ARCH_TO_CANONICAL[host_platform.lower()]
- except KeyError, e:
+ except KeyError as e:
msg = "Unrecognized host architecture %s"
raise ValueError(msg % repr(host_platform))
try:
target = _ARCH_TO_CANONICAL[target_platform.lower()]
- except KeyError, e:
- all_archs = str(_ARCH_TO_CANONICAL.keys())
+ except KeyError as e:
+ all_archs = str(list(_ARCH_TO_CANONICAL.keys()))
raise ValueError("Unrecognized target architecture %s\n\tValid architectures: %s" % (target_platform, all_archs))
return (host, target,req_target_platform)
@@ -168,7 +168,7 @@ def msvc_version_to_maj_min(msvc_version):
maj = int(t[0])
min = int(t[1])
return maj, min
- except ValueError, e:
+ except ValueError as e:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
def is_host_target_supported(host_target, msvc_version):
@@ -217,7 +217,7 @@ def find_vc_pdir(msvc_version):
key = root + key
try:
comps = common.read_reg(key)
- except WindowsError, e:
+ except WindowsError as e:
debug('find_vc_dir(): no VC registry key %s' % repr(key))
else:
debug('find_vc_dir(): found VC in registry: %s' % comps)
@@ -289,7 +289,7 @@ def get_installed_vcs():
installed_versions.append(ver)
else:
debug('find_vc_pdir return None for ver %s' % ver)
- except VisualCException, e:
+ except VisualCException as e:
debug('did not find VC %s: caught exception %s' % (ver, str(e)))
return installed_versions
@@ -393,7 +393,7 @@ def msvc_find_valid_batch_script(env,version):
try:
(vc_script,sdk_script) = find_batch_file(env,version,host_platform,tp)
debug('vc.py:msvc_find_valid_batch_script() vc_script:%s sdk_script:%s'%(vc_script,sdk_script))
- except VisualCException, e:
+ except VisualCException as e:
msg = str(e)
debug('Caught exception while looking for batch file (%s)' % msg)
warn_msg = "VC version %s not installed. " + \
@@ -408,7 +408,7 @@ def msvc_find_valid_batch_script(env,version):
if vc_script:
try:
d = script_env(vc_script, args=arg)
- except BatchFileExecutionError, e:
+ except BatchFileExecutionError as e:
debug('vc.py:msvc_find_valid_batch_script() use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e))
vc_script=None
continue
@@ -416,7 +416,7 @@ def msvc_find_valid_batch_script(env,version):
debug('vc.py:msvc_find_valid_batch_script() use_script 4: trying sdk script: %s'%(sdk_script))
try:
d = script_env(sdk_script,args=[])
- except BatchFileExecutionError,e:
+ except BatchFileExecutionError as e:
debug('vc.py:msvc_find_valid_batch_script() use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e))
continue
elif not vc_script and not sdk_script:
@@ -468,7 +468,7 @@ def msvc_setup_env(env):
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
- for k, v in d.items():
+ for k, v in list(d.items()):
debug('vc.py:msvc_setup_env() env:%s -> %s'%(k,v))
env.PrependENVPath(k, v, delete_existing=True)
diff --git a/src/engine/SCons/Tool/MSCommon/vs.py b/src/engine/SCons/Tool/MSCommon/vs.py
index d5bf2c3..3219719 100644
--- a/src/engine/SCons/Tool/MSCommon/vs.py
+++ b/src/engine/SCons/Tool/MSCommon/vs.py
@@ -31,7 +31,7 @@ import os
import SCons.Errors
import SCons.Util
-from common import debug, \
+from .common import debug, \
get_output, \
is_win64, \
normalize_env, \
@@ -85,7 +85,7 @@ class VisualStudio(object):
key = root + key
try:
comps = read_reg(key)
- except WindowsError, e:
+ except WindowsError as e:
debug('find_vs_dir_by_reg(): no VS registry key %s' % repr(key))
else:
debug('find_vs_dir_by_reg(): found VS in registry: %s' % comps)
@@ -536,7 +536,7 @@ def msvs_setup_env(env):
env['ENV'] = save_ENV
vars = parse_output(output, vars)
- for k, v in vars.items():
+ for k, v in list(vars.items()):
env.PrependENVPath(k, v, delete_existing=1)
def query_versions():
diff --git a/src/engine/SCons/Tool/__init__.py b/src/engine/SCons/Tool/__init__.py
index b80d6e4..ac180a9 100644
--- a/src/engine/SCons/Tool/__init__.py
+++ b/src/engine/SCons/Tool/__init__.py
@@ -113,7 +113,7 @@ class Tool(object):
finally:
if file:
file.close()
- except ImportError, e:
+ except ImportError as e:
if str(e)!="No module named %s"%self.name:
raise SCons.Errors.EnvironmentError(e)
try:
@@ -125,7 +125,7 @@ class Tool(object):
try:
importer = zipimport.zipimporter(aPath)
return importer.load_module(self.name)
- except ImportError, e:
+ except ImportError as e:
pass
finally:
sys.path = oldpythonpath
@@ -143,7 +143,7 @@ class Tool(object):
if file:
file.close()
return module
- except ImportError, e:
+ except ImportError as e:
if str(e)!="No module named %s"%self.name:
raise SCons.Errors.EnvironmentError(e)
try:
@@ -152,10 +152,10 @@ class Tool(object):
module = importer.load_module(full_name)
setattr(SCons.Tool, self.name, module)
return module
- except ImportError, e:
+ except ImportError as e:
m = "No tool named '%s': %s" % (self.name, e)
raise SCons.Errors.EnvironmentError(m)
- except ImportError, e:
+ except ImportError as e:
m = "No tool named '%s': %s" % (self.name, e)
raise SCons.Errors.EnvironmentError(m)
@@ -254,7 +254,7 @@ def VersionShLibLinkNames(version, libname, env):
suffix_re = re.escape('.' + version + shlib_suffix)
linkname = re.sub(suffix_re, shlib_suffix, libname)
if Verbose:
- print "VersionShLibLinkNames: linkname = ",linkname
+ print("VersionShLibLinkNames: linkname = ",linkname)
linknames.append(linkname)
elif platform == 'posix':
# For libfoo.so.x.y.z, linknames libfoo.so libfoo.so.x.y libfoo.so.x
@@ -262,7 +262,7 @@ def VersionShLibLinkNames(version, libname, env):
# First linkname has no version number
linkname = re.sub(suffix_re, shlib_suffix, libname)
if Verbose:
- print "VersionShLibLinkNames: linkname = ",linkname
+ print("VersionShLibLinkNames: linkname = ",linkname)
linknames.append(linkname)
versionparts = version.split('.')
major_name = linkname + "." + versionparts[0]
@@ -271,7 +271,7 @@ def VersionShLibLinkNames(version, libname, env):
#for linkname in [major_name, minor_name]:
for linkname in [major_name, ]:
if Verbose:
- print "VersionShLibLinkNames: linkname ",linkname, ", target ",libname
+ print("VersionShLibLinkNames: linkname ",linkname, ", target ",libname)
linknames.append(linkname)
# note: no Windows case here (win32 or cygwin);
# MSVC doesn't support this type of versioned shared libs.
@@ -294,10 +294,10 @@ symlinks for the platform we are on"""
shlib_suffix = env.subst('$SHLIBSUFFIX')
shlink_flags = SCons.Util.CLVar(env.subst('$SHLINKFLAGS'))
if Verbose:
- print "VersionShLib: libname = ",libname
- print "VersionShLib: platform = ",platform
- print "VersionShLib: shlib_suffix = ",shlib_suffix
- print "VersionShLib: target = ",str(target[0])
+ print("VersionShLib: libname = ",libname)
+ print("VersionShLib: platform = ",platform)
+ print("VersionShLib: shlib_suffix = ",shlib_suffix)
+ print("VersionShLib: target = ",str(target[0]))
if version:
# set the shared library link flags
@@ -308,7 +308,7 @@ symlinks for the platform we are on"""
soname = re.sub(suffix_re, shlib_suffix, libname) + '.' + major
shlink_flags += [ '-Wl,-Bsymbolic', '-Wl,-soname=%s' % soname ]
if Verbose:
- print " soname ",soname,", shlink_flags ",shlink_flags
+ print(" soname ",soname,", shlink_flags ",shlink_flags)
elif platform == 'cygwin':
shlink_flags += [ '-Wl,-Bsymbolic',
'-Wl,--out-implib,${TARGET.base}.a' ]
@@ -317,7 +317,7 @@ symlinks for the platform we are on"""
'-compatibility_version', '%s' % version,
'-undefined', 'dynamic_lookup' ]
if Verbose:
- print "VersionShLib: shlink_flags = ",shlink_flags
+ print("VersionShLib: shlink_flags = ",shlink_flags)
envlink = env.Clone()
envlink['SHLINKFLAGS'] = shlink_flags
else:
@@ -330,7 +330,7 @@ symlinks for the platform we are on"""
libname = target[0].path
linknames = VersionShLibLinkNames(version, libname, env)
if Verbose:
- print "VerShLib: linknames ",linknames
+ print("VerShLib: linknames ",linknames)
# Here we just need the file name w/o path as the target of the link
lib_ver = target[0].name
# make symlink of adjacent names in linknames
@@ -343,7 +343,7 @@ symlinks for the platform we are on"""
pass
os.symlink(os.path.basename(linkname),lastlinkname)
if Verbose:
- print "VerShLib: made sym link of %s -> %s" % (lastlinkname,linkname)
+ print("VerShLib: made sym link of %s -> %s" % (lastlinkname,linkname))
lastlinkname = linkname
# finish chain of sym links with link to the actual library
if len(linknames)>0:
@@ -353,7 +353,7 @@ symlinks for the platform we are on"""
pass
os.symlink(lib_ver,lastlinkname)
if Verbose:
- print "VerShLib: made sym link of %s -> %s" % (linkname, lib_ver)
+ print("VerShLib: made sym link of %s -> %s" % (linkname, lib_ver))
return result
ShLibAction = SCons.Action.Action(VersionedSharedLibrary, None)
@@ -631,7 +631,7 @@ class ToolInitializer(object):
so we no longer copy and re-bind them when the construction
environment gets cloned.
"""
- for method in self.methods.values():
+ for method in list(self.methods.values()):
env.RemoveMethod(method)
def apply_tools(self, env):
diff --git a/src/engine/SCons/Tool/aixcc.py b/src/engine/SCons/Tool/aixcc.py
index 9668f79..b1da31e 100644
--- a/src/engine/SCons/Tool/aixcc.py
+++ b/src/engine/SCons/Tool/aixcc.py
@@ -36,7 +36,7 @@ import os.path
import SCons.Platform.aix
-import cc
+from . import cc
packages = ['vac.C', 'ibmcxx.cmp']
diff --git a/src/engine/SCons/Tool/aixf77.py b/src/engine/SCons/Tool/aixf77.py
index a667e84..21786ee 100644
--- a/src/engine/SCons/Tool/aixf77.py
+++ b/src/engine/SCons/Tool/aixf77.py
@@ -36,7 +36,7 @@ import os.path
#import SCons.Platform.aix
-import f77
+from . import f77
# It would be good to look for the AIX F77 package the same way we're now
# looking for the C and C++ packages. This should be as easy as supplying
diff --git a/src/engine/SCons/Tool/aixlink.py b/src/engine/SCons/Tool/aixlink.py
index 3512522..fc65afb 100644
--- a/src/engine/SCons/Tool/aixlink.py
+++ b/src/engine/SCons/Tool/aixlink.py
@@ -37,8 +37,8 @@ import os.path
import SCons.Util
-import aixcc
-import link
+from . import aixcc
+from . import link
cplusplus = __import__('c++', globals(), locals(), [])
diff --git a/src/engine/SCons/Tool/applelink.py b/src/engine/SCons/Tool/applelink.py
index 1939098..ba955a4 100644
--- a/src/engine/SCons/Tool/applelink.py
+++ b/src/engine/SCons/Tool/applelink.py
@@ -37,7 +37,7 @@ import SCons.Util
# Even though the Mac is based on the GNU toolchain, it doesn't understand
# the -rpath option, so we use the "link" tool instead of "gnulink".
-import link
+from . import link
def generate(env):
"""Add Builders and construction variables for applelink to an
diff --git a/src/engine/SCons/Tool/cvf.py b/src/engine/SCons/Tool/cvf.py
index 2a28e6a..da2c910 100644
--- a/src/engine/SCons/Tool/cvf.py
+++ b/src/engine/SCons/Tool/cvf.py
@@ -29,7 +29,7 @@ Tool-specific initialization for the Compaq Visual Fortran compiler.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import fortran
+from . import fortran
compilers = ['f90']
diff --git a/src/engine/SCons/Tool/cyglink.py b/src/engine/SCons/Tool/cyglink.py
index 87716cf..1685d7f 100644
--- a/src/engine/SCons/Tool/cyglink.py
+++ b/src/engine/SCons/Tool/cyglink.py
@@ -11,7 +11,7 @@ selection method.
import SCons.Action
import SCons.Util
-import gnulink
+from . import gnulink
def shlib_generator(target, source, env, for_signature):
cmd = SCons.Util.CLVar(['$SHLINK'])
diff --git a/src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/docbook.py b/src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/docbook.py
index c070602..ef03206 100644
--- a/src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/docbook.py
+++ b/src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/docbook.py
@@ -82,7 +82,7 @@ def adjustColumnWidths(ctx, nodeset):
relParts.append(relPart)
absParts.append(pixels)
- col = col.next
+ col = col.__next__
# Ok, now we have the relative widths and absolute widths in
# two parallel arrays.
@@ -116,7 +116,7 @@ def adjustColumnWidths(ctx, nodeset):
pixelWidth = convertLength(tableWidth)
if pixelWidth <= absTotal:
- print "Table is wider than table width"
+ print("Table is wider than table width")
else:
pixelWidth = pixelWidth - absTotal
@@ -151,7 +151,7 @@ def adjustColumnWidths(ctx, nodeset):
col.setProp("width", widths[count])
count = count+1
- col = col.next
+ col = col.__next__
return nodeset
@@ -163,10 +163,10 @@ def convertLength(length):
m = re.search('([+-]?[\d\.]+)(\S+)', length)
if m != None and m.lastindex > 1:
unit = pixelsPerInch
- if unitHash.has_key(m.group(2)):
+ if m.group(2) in unitHash:
unit = unitHash[m.group(2)]
else:
- print "Unrecognized length: " + m.group(2)
+ print("Unrecognized length: " + m.group(2))
pixels = unit * float(m.group(1))
else:
diff --git a/src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/xslt.py b/src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/xslt.py
index c712f65..8554dd1 100644
--- a/src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/xslt.py
+++ b/src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/xslt.py
@@ -18,7 +18,7 @@ try:
xmlfile = sys.argv[1]
xslfile = sys.argv[2]
except IndexError:
- print usage
+ print(usage)
sys.exit(1)
def quote(astring):
@@ -38,12 +38,12 @@ try:
while (sys.argv[count]):
try:
name, value = sys.argv[count].split("=", 2)
- if params.has_key(name):
- print "Warning: '%s' re-specified; replacing value" % name
+ if name in params:
+ print("Warning: '%s' re-specified; replacing value" % name)
params[name] = quote(value)
except ValueError:
- print "Invalid parameter specification: '" + sys.argv[count] + "'"
- print usage
+ print("Invalid parameter specification: '" + sys.argv[count] + "'")
+ print(usage)
sys.exit(1)
count = count+1
except IndexError:
@@ -70,7 +70,7 @@ result = style.applyStylesheet(doc, params)
if outfile:
style.saveResultToFilename(outfile, result, 0)
else:
- print result
+ print(result)
# Free things up
style.freeStylesheet()
diff --git a/src/engine/SCons/Tool/dvipdf.py b/src/engine/SCons/Tool/dvipdf.py
index 7c41e9c..374b9c5 100644
--- a/src/engine/SCons/Tool/dvipdf.py
+++ b/src/engine/SCons/Tool/dvipdf.py
@@ -100,7 +100,7 @@ def generate(env):
if DVIPDFAction is None:
DVIPDFAction = SCons.Action.Action(DviPdfFunction, strfunction = DviPdfStrFunction)
- import pdf
+ from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
diff --git a/src/engine/SCons/Tool/f03.py b/src/engine/SCons/Tool/f03.py
index 3aab1c0..6c30971 100644
--- a/src/engine/SCons/Tool/f03.py
+++ b/src/engine/SCons/Tool/f03.py
@@ -36,7 +36,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Defaults
import SCons.Tool
import SCons.Util
-import fortran
+from . import fortran
from SCons.Tool.FortranCommon import add_all_to_env, add_f03_to_env
compilers = ['f03']
diff --git a/src/engine/SCons/Tool/f95.py b/src/engine/SCons/Tool/f95.py
index 5ce5e57..5baa31e 100644
--- a/src/engine/SCons/Tool/f95.py
+++ b/src/engine/SCons/Tool/f95.py
@@ -36,7 +36,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Defaults
import SCons.Tool
import SCons.Util
-import fortran
+from . import fortran
from SCons.Tool.FortranCommon import add_all_to_env, add_f95_to_env
compilers = ['f95']
diff --git a/src/engine/SCons/Tool/filesystem.py b/src/engine/SCons/Tool/filesystem.py
index 31c8abc..3b8ee4c 100644
--- a/src/engine/SCons/Tool/filesystem.py
+++ b/src/engine/SCons/Tool/filesystem.py
@@ -66,7 +66,7 @@ def generate(env):
try:
env['BUILDERS']['CopyTo']
env['BUILDERS']['CopyAs']
- except KeyError, e:
+ except KeyError as e:
global copyToBuilder
if copyToBuilder is None:
copyToBuilder = SCons.Builder.Builder(
diff --git a/src/engine/SCons/Tool/gcc.py b/src/engine/SCons/Tool/gcc.py
index 71f60a3..4f87b24 100644
--- a/src/engine/SCons/Tool/gcc.py
+++ b/src/engine/SCons/Tool/gcc.py
@@ -33,7 +33,7 @@ selection method.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import cc
+from . import cc
import os
import re
import subprocess
diff --git a/src/engine/SCons/Tool/gfortran.py b/src/engine/SCons/Tool/gfortran.py
index 4f3e7e4..7b05e68 100644
--- a/src/engine/SCons/Tool/gfortran.py
+++ b/src/engine/SCons/Tool/gfortran.py
@@ -36,7 +36,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Util
-import fortran
+from . import fortran
def generate(env):
"""Add Builders and construction variables for gfortran to an
diff --git a/src/engine/SCons/Tool/gnulink.py b/src/engine/SCons/Tool/gnulink.py
index bf71270..ea8d7bd 100644
--- a/src/engine/SCons/Tool/gnulink.py
+++ b/src/engine/SCons/Tool/gnulink.py
@@ -35,7 +35,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Util
-import link
+from . import link
linkers = ['g++', 'gcc']
diff --git a/src/engine/SCons/Tool/gs.py b/src/engine/SCons/Tool/gs.py
index ada169a..c5506ce 100644
--- a/src/engine/SCons/Tool/gs.py
+++ b/src/engine/SCons/Tool/gs.py
@@ -57,7 +57,7 @@ def generate(env):
if GhostscriptAction is None:
GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR')
- import pdf
+ from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
diff --git a/src/engine/SCons/Tool/hpcc.py b/src/engine/SCons/Tool/hpcc.py
index 30f4964..51d2e38 100644
--- a/src/engine/SCons/Tool/hpcc.py
+++ b/src/engine/SCons/Tool/hpcc.py
@@ -34,7 +34,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Util
-import cc
+from . import cc
def generate(env):
"""Add Builders and construction variables for aCC & cc to an Environment."""
diff --git a/src/engine/SCons/Tool/hplink.py b/src/engine/SCons/Tool/hplink.py
index 17dbe05..10ef30b 100644
--- a/src/engine/SCons/Tool/hplink.py
+++ b/src/engine/SCons/Tool/hplink.py
@@ -37,7 +37,7 @@ import os.path
import SCons.Util
-import link
+from . import link
ccLinker = None
diff --git a/src/engine/SCons/Tool/icc.py b/src/engine/SCons/Tool/icc.py
index db15642..11ea075 100644
--- a/src/engine/SCons/Tool/icc.py
+++ b/src/engine/SCons/Tool/icc.py
@@ -33,7 +33,7 @@ selection method.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import cc
+from . import cc
def generate(env):
"""Add Builders and construction variables for the OS/2 to an Environment."""
diff --git a/src/engine/SCons/Tool/ifl.py b/src/engine/SCons/Tool/ifl.py
index 30b3672..865d2ba 100644
--- a/src/engine/SCons/Tool/ifl.py
+++ b/src/engine/SCons/Tool/ifl.py
@@ -35,7 +35,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Defaults
from SCons.Scanner.Fortran import FortranScan
-from FortranCommon import add_all_to_env
+from .FortranCommon import add_all_to_env
def generate(env):
"""Add Builders and construction variables for ifl to an Environment."""
diff --git a/src/engine/SCons/Tool/ifort.py b/src/engine/SCons/Tool/ifort.py
index 4b2fd65..638bd12 100644
--- a/src/engine/SCons/Tool/ifort.py
+++ b/src/engine/SCons/Tool/ifort.py
@@ -36,7 +36,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Defaults
from SCons.Scanner.Fortran import FortranScan
-from FortranCommon import add_all_to_env
+from .FortranCommon import add_all_to_env
def generate(env):
"""Add Builders and construction variables for ifort to an Environment."""
diff --git a/src/engine/SCons/Tool/install.py b/src/engine/SCons/Tool/install.py
index 0c81d05..4236e81 100644
--- a/src/engine/SCons/Tool/install.py
+++ b/src/engine/SCons/Tool/install.py
@@ -82,21 +82,21 @@ def scons_copytree(src, dst, symlinks=False):
else:
shutil.copy2(srcname, dstname)
# XXX What about devices, sockets etc.?
- except (IOError, os.error), why:
+ except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
# catch the CopytreeError from the recursive copytree so that we can
# continue with other files
- except CopytreeError, err:
+ except CopytreeError as err:
errors.extend(err.args[0])
try:
shutil.copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
- except OSError, why:
+ except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
- raise CopytreeError, errors
+ raise CopytreeError(errors)
#
@@ -174,7 +174,7 @@ def versionedLibVersion(dest, env):
version_File = version_re.findall(versioned_re.findall(libname)[-1])[-1]
if Verbose:
- print "install: version_File ", version_File
+ print("install: version_File ", version_File)
# result is False if we did not find a versioned shared library name, so return and empty list
if not result:
return (None, libname, install_dir)
@@ -188,7 +188,7 @@ def versionedLibVersion(dest, env):
if version != version_File:
#raise SCons.Errors.UserError("SHLIBVERSION '%s' does not match the version # '%s' in the filename" % (version, version_File) )
- print "SHLIBVERSION '%s' does not match the version # '%s' in the filename, proceeding based on file name" % (version, version_File)
+ print("SHLIBVERSION '%s' does not match the version # '%s' in the filename, proceeding based on file name" % (version, version_File))
version = version_File
return (version, libname, install_dir)
@@ -202,7 +202,7 @@ def versionedLibLinks(dest, source, env):
# libname includes the version number if one was given
linknames = SCons.Tool.VersionShLibLinkNames(version,libname,env)
if Verbose:
- print "versionedLibLinks: linknames ",linknames
+ print("versionedLibLinks: linknames ",linknames)
# Here we just need the file name w/o path as the target of the link
lib_ver = libname
# make symlink of adjacent names in linknames
@@ -210,7 +210,7 @@ def versionedLibLinks(dest, source, env):
linkname = linknames[count]
fulllinkname = os.path.join(install_dir, linkname)
if Verbose:
- print "full link name ",fulllinkname
+ print("full link name ",fulllinkname)
if count > 0:
try:
os.remove(lastlinkname)
@@ -218,7 +218,7 @@ def versionedLibLinks(dest, source, env):
pass
os.symlink(os.path.basename(fulllinkname),lastlinkname)
if Verbose:
- print "versionedLibLinks: made sym link of %s -> %s" % (lastlinkname,os.path.basename(fulllinkname))
+ print("versionedLibLinks: made sym link of %s -> %s" % (lastlinkname,os.path.basename(fulllinkname)))
lastlinkname = fulllinkname
# finish chain of sym links with link to the actual library
if len(linknames)>0:
@@ -228,7 +228,7 @@ def versionedLibLinks(dest, source, env):
pass
os.symlink(lib_ver,lastlinkname)
if Verbose:
- print "versionedLibLinks: made sym link of %s -> %s" % (lib_ver,lastlinkname)
+ print("versionedLibLinks: made sym link of %s -> %s" % (lib_ver,lastlinkname))
return
def installFunc(target, source, env):
@@ -298,7 +298,7 @@ def add_versioned_targets_to_INSTALLED_FILES(target, source, env):
Verbose = False
_INSTALLED_FILES.extend(target)
if Verbose:
- print "ver lib emitter ",repr(target)
+ print("ver lib emitter ",repr(target))
# see if we have a versioned shared library, if so generate side effects
version, libname, install_dir = versionedLibVersion(target[0].path, env)
@@ -307,13 +307,13 @@ def add_versioned_targets_to_INSTALLED_FILES(target, source, env):
linknames = SCons.Tool.VersionShLibLinkNames(version,libname,env)
for linkname in linknames:
if Verbose:
- print "make side effect of %s" % os.path.join(install_dir, linkname)
+ print("make side effect of %s" % os.path.join(install_dir, linkname))
fulllinkname = os.path.join(install_dir, linkname)
env.SideEffect(fulllinkname,target[0])
env.Clean(target[0],fulllinkname)
_INSTALLED_FILES.append(fulllinkname)
if Verbose:
- print "installed list ", _INSTALLED_FILES
+ print("installed list ", _INSTALLED_FILES)
_UNIQUE_INSTALLED_FILES = None
return (target, source)
diff --git a/src/engine/SCons/Tool/intelc.py b/src/engine/SCons/Tool/intelc.py
index 4201092..8b178a7 100644
--- a/src/engine/SCons/Tool/intelc.py
+++ b/src/engine/SCons/Tool/intelc.py
@@ -30,7 +30,7 @@ selection method.
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-from __future__ import division
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -206,17 +206,16 @@ def get_all_compiler_versions():
# Registry points to nonexistent dir. Ignore this
# version.
value = get_intel_registry_value('ProductDir', subkey, 'IA32')
- except MissingRegistryError, e:
+ except MissingRegistryError as e:
# Registry key is left dangling (potentially
# after uninstalling).
- print \
- "scons: *** Ignoring the registry key for the Intel compiler version %s.\n" \
+ print("scons: *** Ignoring the registry key for the Intel compiler version %s.\n" \
"scons: *** It seems that the compiler was uninstalled and that the registry\n" \
- "scons: *** was not cleaned up properly.\n" % subkey
+ "scons: *** was not cleaned up properly.\n" % subkey)
else:
- print "scons: *** Ignoring "+str(value)
+ print("scons: *** Ignoring "+str(value))
i = i + 1
except EnvironmentError:
@@ -424,8 +423,8 @@ def generate(env, version=None, abi=None, topdir=None, verbose=0):
bindir="bin"
libdir="lib"
if verbose:
- print "Intel C compiler: using version %s (%g), abi %s, in '%s/%s'"%\
- (repr(version), linux_ver_normalize(version),abi,topdir,bindir)
+ print("Intel C compiler: using version %s (%g), abi %s, in '%s/%s'"%\
+ (repr(version), linux_ver_normalize(version),abi,topdir,bindir))
if is_linux:
# Show the actual compiler version by running the compiler.
os.system('%s/%s/icc --version'%(topdir,bindir))
@@ -439,14 +438,14 @@ def generate(env, version=None, abi=None, topdir=None, verbose=0):
'LIB' : libdir,
'PATH' : bindir,
'LD_LIBRARY_PATH' : libdir}
- for p in paths.keys():
+ for p in list(paths.keys()):
env.PrependENVPath(p, os.path.join(topdir, paths[p]))
if is_mac:
paths={'INCLUDE' : 'include',
'LIB' : libdir,
'PATH' : bindir,
'LD_LIBRARY_PATH' : libdir}
- for p in paths.keys():
+ for p in list(paths.keys()):
env.PrependENVPath(p, os.path.join(topdir, paths[p]))
if is_windows:
# env key reg valname default subdir of top
diff --git a/src/engine/SCons/Tool/latex.py b/src/engine/SCons/Tool/latex.py
index 1c71743..f30356b 100644
--- a/src/engine/SCons/Tool/latex.py
+++ b/src/engine/SCons/Tool/latex.py
@@ -55,10 +55,10 @@ def generate(env):
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
- import dvi
+ from . import dvi
dvi.generate(env)
- import pdf
+ from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['DVI']
diff --git a/src/engine/SCons/Tool/link.py b/src/engine/SCons/Tool/link.py
index 3f20fe0..5539f62 100644
--- a/src/engine/SCons/Tool/link.py
+++ b/src/engine/SCons/Tool/link.py
@@ -81,7 +81,7 @@ def shlib_emitter(target, source, env):
env.SideEffect(name, target[0])
env.Clean(target[0], name)
if Verbose:
- print "shlib_emitter: add side effect - ",name
+ print("shlib_emitter: add side effect - ",name)
except KeyError:
version = None
return (target, source)
@@ -104,16 +104,16 @@ def shlib_emitter_names(target, source, env):
# generate library name with the version number
version_name = target[0].name + '.' + version
if Verbose:
- print "shlib_emitter_names: target is ", version_name
- print "shlib_emitter_names: side effect: ", name
+ print("shlib_emitter_names: target is ", version_name)
+ print("shlib_emitter_names: side effect: ", name)
# add version_name to list of names to be a Side effect
version_names.append(version_name)
if Verbose:
- print "shlib_emitter_names: versionparts ",versionparts
+ print("shlib_emitter_names: versionparts ",versionparts)
for ver in versionparts[0:-1]:
name = name + '.' + ver
if Verbose:
- print "shlib_emitter_names: side effect: ", name
+ print("shlib_emitter_names: side effect: ", name)
# add name to list of names to be a Side effect
version_names.append(name)
elif platform == 'darwin':
@@ -123,8 +123,8 @@ def shlib_emitter_names(target, source, env):
suffix_re = re.escape(shlib_suffix)
version_name = re.sub(suffix_re, '.' + version + shlib_suffix, name)
if Verbose:
- print "shlib_emitter_names: target is ", version_name
- print "shlib_emitter_names: side effect: ", name
+ print("shlib_emitter_names: target is ", version_name)
+ print("shlib_emitter_names: side effect: ", name)
# add version_name to list of names to be a Side effect
version_names.append(version_name)
elif platform == 'cygwin':
@@ -134,8 +134,8 @@ def shlib_emitter_names(target, source, env):
suffix_re = re.escape(shlib_suffix)
version_name = re.sub(suffix_re, '-' + re.sub('\.', '-', version) + shlib_suffix, name)
if Verbose:
- print "shlib_emitter_names: target is ", version_name
- print "shlib_emitter_names: side effect: ", name
+ print("shlib_emitter_names: target is ", version_name)
+ print("shlib_emitter_names: side effect: ", name)
# add version_name to list of names to be a Side effect
version_names.append(version_name)
diff --git a/src/engine/SCons/Tool/midl.py b/src/engine/SCons/Tool/midl.py
index 64b927a..7a59e33 100644
--- a/src/engine/SCons/Tool/midl.py
+++ b/src/engine/SCons/Tool/midl.py
@@ -39,7 +39,7 @@ import SCons.Defaults
import SCons.Scanner.IDL
import SCons.Util
-from MSCommon import msvc_exists
+from .MSCommon import msvc_exists
def midl_emitter(target, source, env):
"""Produces a list of outputs from the MIDL compiler"""
diff --git a/src/engine/SCons/Tool/msgfmt.py b/src/engine/SCons/Tool/msgfmt.py
index 352ba77..4fe6afd 100644
--- a/src/engine/SCons/Tool/msgfmt.py
+++ b/src/engine/SCons/Tool/msgfmt.py
@@ -41,7 +41,7 @@ class _MOFileBuilder(BuilderBase):
import SCons.Util
from SCons.Tool.GettextCommon import _read_linguas_from_files
linguas_files = None
- if env.has_key('LINGUAS_FILE') and env['LINGUAS_FILE'] is not None:
+ if 'LINGUAS_FILE' in env and env['LINGUAS_FILE'] is not None:
linguas_files = env['LINGUAS_FILE']
# This should prevent from endless recursion.
env['LINGUAS_FILE'] = None
diff --git a/src/engine/SCons/Tool/msginit.py b/src/engine/SCons/Tool/msginit.py
index 5e9c0e4..39f460d 100644
--- a/src/engine/SCons/Tool/msginit.py
+++ b/src/engine/SCons/Tool/msginit.py
@@ -35,7 +35,7 @@ def _optional_no_translator_flag(env):
""" Return '--no-translator' flag if we run *msginit(1)* in non-interactive
mode."""
import SCons.Util
- if env.has_key('POAUTOINIT'):
+ if 'POAUTOINIT' in env:
autoinit = env['POAUTOINIT']
else:
autoinit = False
@@ -66,7 +66,7 @@ def _POInitBuilderWrapper(env, target=None, source=_null, **kw):
if source is _null:
if 'POTDOMAIN' in kw:
domain = kw['POTDOMAIN']
- elif env.has_key('POTDOMAIN'):
+ elif 'POTDOMAIN' in env:
domain = env['POTDOMAIN']
else:
domain = 'messages'
diff --git a/src/engine/SCons/Tool/msgmerge.py b/src/engine/SCons/Tool/msgmerge.py
index f3710ab..11d7b48 100644
--- a/src/engine/SCons/Tool/msgmerge.py
+++ b/src/engine/SCons/Tool/msgmerge.py
@@ -58,7 +58,7 @@ def _POUpdateBuilderWrapper(env, target=None, source=_null, **kw):
if source is _null:
if 'POTDOMAIN' in kw:
domain = kw['POTDOMAIN']
- elif env.has_key('POTDOMAIN') and env['POTDOMAIN']:
+ elif 'POTDOMAIN' in env and env['POTDOMAIN']:
domain = env['POTDOMAIN']
else:
domain = 'messages'
diff --git a/src/engine/SCons/Tool/mslib.py b/src/engine/SCons/Tool/mslib.py
index 8a4af57..df8d877 100644
--- a/src/engine/SCons/Tool/mslib.py
+++ b/src/engine/SCons/Tool/mslib.py
@@ -39,7 +39,7 @@ import SCons.Tool.msvs
import SCons.Tool.msvc
import SCons.Util
-from MSCommon import msvc_exists, msvc_setup_env_once
+from .MSCommon import msvc_exists, msvc_setup_env_once
def generate(env):
"""Add Builders and construction variables for lib to an Environment."""
diff --git a/src/engine/SCons/Tool/mslink.py b/src/engine/SCons/Tool/mslink.py
index 40f112b..b56d34a 100644
--- a/src/engine/SCons/Tool/mslink.py
+++ b/src/engine/SCons/Tool/mslink.py
@@ -44,7 +44,7 @@ import SCons.Tool.msvc
import SCons.Tool.msvs
import SCons.Util
-from MSCommon import msvc_setup_env_once, msvc_exists
+from .MSCommon import msvc_setup_env_once, msvc_exists
def pdbGenerator(env, target, source, for_signature):
try:
@@ -195,7 +195,7 @@ def RegServerFunc(target, source, env):
if ret:
raise SCons.Errors.UserError("Unable to register %s" % target[0])
else:
- print "Registered %s sucessfully" % target[0]
+ print("Registered %s sucessfully" % target[0])
return ret
return 0
@@ -212,10 +212,10 @@ def embedManifestDllCheck(target, source, env):
if os.path.exists(manifestSrc):
ret = (embedManifestDllAction) ([target[0]],None,env)
if ret:
- raise SCons.Errors.UserError, "Unable to embed manifest into %s" % (target[0])
+ raise SCons.Errors.UserError("Unable to embed manifest into %s" % (target[0]))
return ret
else:
- print '(embed: no %s.manifest found; not embedding.)'%str(target[0])
+ print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))
return 0
def embedManifestExeCheck(target, source, env):
@@ -226,10 +226,10 @@ def embedManifestExeCheck(target, source, env):
if os.path.exists(manifestSrc):
ret = (embedManifestExeAction) ([target[0]],None,env)
if ret:
- raise SCons.Errors.UserError, "Unable to embed manifest into %s" % (target[0])
+ raise SCons.Errors.UserError("Unable to embed manifest into %s" % (target[0]))
return ret
else:
- print '(embed: no %s.manifest found; not embedding.)'%str(target[0])
+ print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))
return 0
embedManifestDllCheckAction = SCons.Action.Action(embedManifestDllCheck, None)
diff --git a/src/engine/SCons/Tool/mssdk.py b/src/engine/SCons/Tool/mssdk.py
index 6103f30..f373002 100644
--- a/src/engine/SCons/Tool/mssdk.py
+++ b/src/engine/SCons/Tool/mssdk.py
@@ -33,7 +33,7 @@ It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
-from MSCommon import mssdk_exists, \
+from .MSCommon import mssdk_exists, \
mssdk_setup_env
def generate(env):
diff --git a/src/engine/SCons/Tool/msvc.py b/src/engine/SCons/Tool/msvc.py
index d42c257..0bc296f 100644
--- a/src/engine/SCons/Tool/msvc.py
+++ b/src/engine/SCons/Tool/msvc.py
@@ -47,7 +47,7 @@ import SCons.Util
import SCons.Warnings
import SCons.Scanner.RC
-from MSCommon import msvc_exists, msvc_setup_env_once
+from .MSCommon import msvc_exists, msvc_setup_env_once
CSuffixes = ['.c', '.C']
CXXSuffixes = ['.cc', '.cpp', '.cxx', '.c++', '.C++']
diff --git a/src/engine/SCons/Tool/msvs.py b/src/engine/SCons/Tool/msvs.py
index 06ce486..0879a28 100644
--- a/src/engine/SCons/Tool/msvs.py
+++ b/src/engine/SCons/Tool/msvs.py
@@ -51,7 +51,7 @@ import SCons.PathList
import SCons.Util
import SCons.Warnings
-from MSCommon import msvc_exists, msvc_setup_env_once
+from .MSCommon import msvc_exists, msvc_setup_env_once
from SCons.Defaults import processDefines
##############################################################################
@@ -351,13 +351,13 @@ class _DSPGenerator(object):
config.platform = 'Win32'
self.configs[variant] = config
- print "Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dspfile) + "'"
+ print("Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dspfile) + "'")
for i in range(len(variants)):
AddConfig(self, variants[i], buildtarget[i], outdir[i], runfile[i], cmdargs)
self.platforms = []
- for key in self.configs.keys():
+ for key in list(self.configs.keys()):
platform = self.configs[key].platform
if not platform in self.platforms:
self.platforms.append(platform)
@@ -480,7 +480,7 @@ class _GenerateV6DSP(_DSPGenerator):
'Resource Files': 'r|rc|ico|cur|bmp|dlg|rc2|rct|bin|cnt|rtf|gif|jpg|jpeg|jpe',
'Other Files': ''}
- for kind in sorted(categories.keys(), key=lambda a: a.lower()):
+ for kind in sorted(list(categories.keys()), key=lambda a: a.lower()):
if not self.sources[kind]:
continue # skip empty groups
@@ -551,7 +551,7 @@ class _GenerateV6DSP(_DSPGenerator):
def Build(self):
try:
self.file = open(self.dspabs,'w')
- except IOError, detail:
+ except IOError as detail:
raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail))
else:
self.PrintHeader()
@@ -744,7 +744,7 @@ class _GenerateV7DSP(_DSPGenerator):
self.file.write(pdata + '-->\n')
def printSources(self, hierarchy, commonprefix):
- sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower())
+ sorteditems = sorted(list(hierarchy.items()), key=lambda a: a[0].lower())
# First folders, then files
for key, value in sorteditems:
@@ -774,7 +774,7 @@ class _GenerateV7DSP(_DSPGenerator):
self.file.write('\t<Files>\n')
- cats = sorted([k for k in categories.keys() if self.sources[k]],
+ cats = sorted([k for k in list(categories.keys()) if self.sources[k]],
key=lambda a: a.lower())
for kind in cats:
if len(cats) > 1:
@@ -861,7 +861,7 @@ class _GenerateV7DSP(_DSPGenerator):
def Build(self):
try:
self.file = open(self.dspabs,'w')
- except IOError, detail:
+ except IOError as detail:
raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail))
else:
self.PrintHeader()
@@ -1029,7 +1029,7 @@ class _GenerateV10DSP(_DSPGenerator):
self.filtersabs = self.dspabs + '.filters'
try:
self.filters_file = open(self.filtersabs, 'w')
- except IOError, detail:
+ except IOError as detail:
raise SCons.Errors.InternalError('Unable to open "' + self.filtersabs + '" for writing:' + str(detail))
self.filters_file.write('<?xml version="1.0" encoding="utf-8"?>\n'
@@ -1055,7 +1055,7 @@ class _GenerateV10DSP(_DSPGenerator):
self.file.write(pdata + '-->\n')
def printFilters(self, hierarchy, name):
- sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())
+ sorteditems = sorted(list(hierarchy.items()), key = lambda a: a[0].lower())
for key, value in sorteditems:
if SCons.Util.is_Dict(value):
@@ -1072,7 +1072,7 @@ class _GenerateV10DSP(_DSPGenerator):
'Resource Files': 'None',
'Other Files': 'None'}
- sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())
+ sorteditems = sorted(list(hierarchy.items()), key = lambda a: a[0].lower())
# First folders, then files
for key, value in sorteditems:
@@ -1098,7 +1098,7 @@ class _GenerateV10DSP(_DSPGenerator):
'Resource Files': 'r;rc;ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe',
'Other Files': ''}
- cats = sorted([k for k in categories.keys() if self.sources[k]],
+ cats = sorted([k for k in list(categories.keys()) if self.sources[k]],
key = lambda a: a.lower())
# print vcxproj.filters file first
@@ -1158,12 +1158,12 @@ class _GenerateV10DSP(_DSPGenerator):
'\t</ItemGroup>\n' % str(self.sconscript))
def Parse(self):
- print "_GenerateV10DSP.Parse()"
+ print("_GenerateV10DSP.Parse()")
def Build(self):
try:
self.file = open(self.dspabs, 'w')
- except IOError, detail:
+ except IOError as detail:
raise SCons.Errors.InternalError('Unable to open "' + self.dspabs + '" for writing:' + str(detail))
else:
self.PrintHeader()
@@ -1242,7 +1242,7 @@ class _GenerateV7DSW(_DSWGenerator):
config.platform = 'Win32'
self.configs[variant] = config
- print "Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dswfile) + "'"
+ print("Adding '" + self.name + ' - ' + config.variant + '|' + config.platform + "' to '" + str(dswfile) + "'")
if 'variant' not in env:
raise SCons.Errors.InternalError("You must specify a 'variant' argument (i.e. 'Debug' or " +\
@@ -1254,7 +1254,7 @@ class _GenerateV7DSW(_DSWGenerator):
AddConfig(self, variant)
self.platforms = []
- for key in self.configs.keys():
+ for key in list(self.configs.keys()):
platform = self.configs[key].platform
if not platform in self.platforms:
self.platforms.append(platform)
@@ -1424,7 +1424,7 @@ class _GenerateV7DSW(_DSWGenerator):
def Build(self):
try:
self.file = open(self.dswfile,'w')
- except IOError, detail:
+ except IOError as detail:
raise SCons.Errors.InternalError('Unable to open "' + self.dswfile + '" for writing:' + str(detail))
else:
self.PrintSolution()
@@ -1473,7 +1473,7 @@ class _GenerateV6DSW(_DSWGenerator):
def Build(self):
try:
self.file = open(self.dswfile,'w')
- except IOError, detail:
+ except IOError as detail:
raise SCons.Errors.InternalError('Unable to open "' + self.dswfile + '" for writing:' + str(detail))
else:
self.PrintWorkspace()
@@ -1530,8 +1530,8 @@ def GenerateProject(target, source, env):
if not dspfile is builddspfile:
try:
bdsp = open(str(builddspfile), "w+")
- except IOError, detail:
- print 'Unable to open "' + str(dspfile) + '" for writing:',detail,'\n'
+ except IOError as detail:
+ print('Unable to open "' + str(dspfile) + '" for writing:',detail,'\n')
raise
bdsp.write("This is just a placeholder file.\nThe real project file is here:\n%s\n" % dspfile.get_abspath())
@@ -1546,8 +1546,8 @@ def GenerateProject(target, source, env):
try:
bdsw = open(str(builddswfile), "w+")
- except IOError, detail:
- print 'Unable to open "' + str(dspfile) + '" for writing:',detail,'\n'
+ except IOError as detail:
+ print('Unable to open "' + str(dspfile) + '" for writing:',detail,'\n')
raise
bdsw.write("This is just a placeholder file.\nThe real workspace file is here:\n%s\n" % dswfile.get_abspath())
diff --git a/src/engine/SCons/Tool/msvsTests.py b/src/engine/SCons/Tool/msvsTests.py
index 7d966c1..1466db6 100644
--- a/src/engine/SCons/Tool/msvsTests.py
+++ b/src/engine/SCons/Tool/msvsTests.py
@@ -743,7 +743,7 @@ if __name__ == "__main__":
]
for test_class in test_classes:
- print "TEST: ", test_class.__doc__
+ print("TEST: ", test_class.__doc__)
back_osenv = copy.deepcopy(os.environ)
try:
# XXX: overriding the os.environ is bad, but doing it
diff --git a/src/engine/SCons/Tool/packaging/__init__.py b/src/engine/SCons/Tool/packaging/__init__.py
index 95311a2..c3de2aa 100644
--- a/src/engine/SCons/Tool/packaging/__init__.py
+++ b/src/engine/SCons/Tool/packaging/__init__.py
@@ -72,7 +72,7 @@ def Tag(env, target, source, *more_tags, **kw_tags):
target=env.Flatten(target)
for t in target:
- for (k,v) in kw_tags.items():
+ for (k,v) in list(kw_tags.items()):
# all file tags have to start with PACKAGING_, so we can later
# differentiate between "normal" object attributes and the
# packaging attributes. As the user should not be bothered with
@@ -120,7 +120,7 @@ def Package(env, target=None, source=None, **kw):
try:
file,path,desc=imp.find_module(type, __path__)
return imp.load_module(type, file, path, desc)
- except ImportError, e:
+ except ImportError as e:
raise EnvironmentError("packager %s not available: %s"%(type,str(e)))
packagers=list(map(load_packager, PACKAGETYPE))
@@ -141,7 +141,7 @@ def Package(env, target=None, source=None, **kw):
if 'PACKAGEROOT' not in kw:
kw['PACKAGEROOT'] = default_name%kw
- except KeyError, e:
+ except KeyError as e:
raise SCons.Errors.UserError( "Missing Packagetag '%s'"%e.args[0] )
# setup the source files
@@ -157,10 +157,10 @@ def Package(env, target=None, source=None, **kw):
assert( len(target) == 0 )
- except KeyError, e:
+ except KeyError as e:
raise SCons.Errors.UserError( "Missing Packagetag '%s' for %s packager"\
% (e.args[0],packager.__name__) )
- except TypeError, e:
+ except TypeError as e:
# this exception means that a needed argument for the packager is
# missing. As our packagers get their "tags" as named function
# arguments we need to find out which one is missing.
diff --git a/src/engine/SCons/Tool/packaging/ipk.py b/src/engine/SCons/Tool/packaging/ipk.py
index 6549445..ad27a62 100644
--- a/src/engine/SCons/Tool/packaging/ipk.py
+++ b/src/engine/SCons/Tool/packaging/ipk.py
@@ -169,7 +169,7 @@ Description: $X_IPK_DESCRIPTION
#
# close all opened files
- for f in opened_files.values():
+ for f in list(opened_files.values()):
f.close()
# call a user specified function
diff --git a/src/engine/SCons/Tool/packaging/msi.py b/src/engine/SCons/Tool/packaging/msi.py
index fe78c9c..70fdc48 100644
--- a/src/engine/SCons/Tool/packaging/msi.py
+++ b/src/engine/SCons/Tool/packaging/msi.py
@@ -172,7 +172,7 @@ def generate_guids(root):
# find all XMl nodes matching the key, retrieve their attribute, hash their
# subtree, convert hash to string and add as a attribute to the xml node.
- for (key,value) in needs_id.items():
+ for (key,value) in list(needs_id.items()):
node_list = root.getElementsByTagName(key)
attribute = value
for node in node_list:
@@ -216,7 +216,7 @@ def build_wxsfile(target, source, env):
if 'CHANGE_SPECFILE' in env:
env['CHANGE_SPECFILE'](target, source)
- except KeyError, e:
+ except KeyError as e:
raise SCons.Errors.UserError( '"%s" package field for MSI is missing.' % e.args[0] )
#
@@ -335,7 +335,7 @@ def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set,
}
# fill in the default tags given above.
- for k,v in [ (k, v) for (k,v) in h.items() if not hasattr(file, k) ]:
+ for k,v in [ (k, v) for (k,v) in list(h.items()) if not hasattr(file, k) ]:
setattr( file, k, v )
File = factory.createElement( 'File' )
@@ -382,7 +382,7 @@ def build_wxsfile_features_section(root, files, NAME, VERSION, SUMMARY, id_set):
Feature.attributes['Description'] = escape( SUMMARY )
Feature.attributes['Display'] = 'expand'
- for (feature, files) in create_feature_dict(files).items():
+ for (feature, files) in list(create_feature_dict(files).items()):
SubFeature = factory.createElement('Feature')
SubFeature.attributes['Level'] = '1'
diff --git a/src/engine/SCons/Tool/packaging/rpm.py b/src/engine/SCons/Tool/packaging/rpm.py
index 07857d1..4958065 100644
--- a/src/engine/SCons/Tool/packaging/rpm.py
+++ b/src/engine/SCons/Tool/packaging/rpm.py
@@ -107,7 +107,7 @@ def collectintargz(target, source, env):
try:
#tarball = env['SOURCE_URL'].split('/')[-1]
tarball = env['SOURCE_URL'].split('/')[-1]
- except KeyError, e:
+ except KeyError as e:
raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )
tarball = src_targz.package(env, source=sources, target=tarball,
@@ -143,7 +143,7 @@ def build_specfile(target, source, env):
if 'CHANGE_SPECFILE' in env:
env['CHANGE_SPECFILE'](target, source)
- except KeyError, e:
+ except KeyError as e:
raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] )
@@ -277,7 +277,7 @@ def build_specfile_filesection(spec, files):
for file in files:
# build the tagset
tags = {}
- for k in supported_tags.keys():
+ for k in list(supported_tags.keys()):
try:
tags[k]=getattr(file, k)
except AttributeError:
@@ -331,7 +331,7 @@ class SimpleTagCompiler(object):
for key, replacement in domestic:
try:
str = str + replacement % values[key]
- except KeyError, e:
+ except KeyError as e:
if self.mandatory:
raise e
@@ -340,11 +340,11 @@ class SimpleTagCompiler(object):
for key, replacement in international:
try:
#int_values_for_key = [ (get_country_code(k),v) for k,v in values.items() if strip_country_code(k) == key ]
- x = [t for t in values.items() if strip_country_code(t[0]) == key]
+ x = [t for t in list(values.items()) if strip_country_code(t[0]) == key]
int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x]
for v in int_values_for_key:
str = str + replacement % v
- except KeyError, e:
+ except KeyError as e:
if self.mandatory:
raise e
diff --git a/src/engine/SCons/Tool/pdflatex.py b/src/engine/SCons/Tool/pdflatex.py
index 922e718..fbffb23 100644
--- a/src/engine/SCons/Tool/pdflatex.py
+++ b/src/engine/SCons/Tool/pdflatex.py
@@ -62,7 +62,7 @@ def generate(env):
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
- import pdf
+ from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
diff --git a/src/engine/SCons/Tool/pdftex.py b/src/engine/SCons/Tool/pdftex.py
index 30c56af..e9a0bda 100644
--- a/src/engine/SCons/Tool/pdftex.py
+++ b/src/engine/SCons/Tool/pdftex.py
@@ -85,7 +85,7 @@ def generate(env):
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
- import pdf
+ from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
diff --git a/src/engine/SCons/Tool/qt.py b/src/engine/SCons/Tool/qt.py
index 716c7d5..fdfdd26 100644
--- a/src/engine/SCons/Tool/qt.py
+++ b/src/engine/SCons/Tool/qt.py
@@ -130,12 +130,12 @@ class _Automoc(object):
if not obj.has_builder():
# binary obj file provided
if debug:
- print "scons: qt: '%s' seems to be a binary. Discarded." % str(obj)
+ print("scons: qt: '%s' seems to be a binary. Discarded." % str(obj))
continue
cpp = obj.sources[0]
if not splitext(str(cpp))[1] in cxx_suffixes:
if debug:
- print "scons: qt: '%s' is no cxx file. Discarded." % str(cpp)
+ print("scons: qt: '%s' is no cxx file. Discarded." % str(cpp))
# c or fortran source
continue
#cpp_contents = comment.sub('', cpp.get_text_contents())
@@ -148,12 +148,12 @@ class _Automoc(object):
h = find_file(hname, (cpp.get_dir(),), env.File)
if h:
if debug:
- print "scons: qt: Scanning '%s' (header of '%s')" % (str(h), str(cpp))
+ print("scons: qt: Scanning '%s' (header of '%s')" % (str(h), str(cpp)))
#h_contents = comment.sub('', h.get_text_contents())
h_contents = h.get_text_contents()
break
if not h and debug:
- print "scons: qt: no header for '%s'." % (str(cpp))
+ print("scons: qt: no header for '%s'." % (str(cpp)))
if h and q_object_search.search(h_contents):
# h file with the Q_OBJECT macro found -> add moc_cpp
moc_cpp = env.Moc(h)
@@ -161,14 +161,14 @@ class _Automoc(object):
out_sources.append(moc_o)
#moc_cpp.target_scanner = SCons.Defaults.CScan
if debug:
- print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(h), str(moc_cpp))
+ print("scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(h), str(moc_cpp)))
if cpp and q_object_search.search(cpp_contents):
# cpp file with Q_OBJECT macro found -> add moc
# (to be included in cpp)
moc = env.Moc(cpp)
env.Ignore(moc, moc)
if debug:
- print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(cpp), str(moc))
+ print("scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(cpp), str(moc)))
#moc.source_scanner = SCons.Defaults.CScan
# restore the original env attributes (FIXME)
objBuilder.env = objBuilderEnv
diff --git a/src/engine/SCons/Tool/rpmutils.py b/src/engine/SCons/Tool/rpmutils.py
index 90e3d74..e96c54c 100644
--- a/src/engine/SCons/Tool/rpmutils.py
+++ b/src/engine/SCons/Tool/rpmutils.py
@@ -491,7 +491,7 @@ def updateRpmDicts(rpmrc, pyfile):
key = tokens[0]
if key in sections:
# Have we met this section before?
- if not data.has_key(tokens[0]):
+ if tokens[0] not in data:
# No, so insert it
data[key] = {}
# Insert data
@@ -509,7 +509,7 @@ def updateRpmDicts(rpmrc, pyfile):
if l.startswith('# Start of rpmrc dictionaries'):
pm = 1
# Write data sections to single dictionaries
- for key, entries in data.iteritems():
+ for key, entries in data.items():
out.write("%s = {\n" % key)
for arch in sorted(entries.keys()):
out.write(" '%s' : ['%s'],\n" % (arch, "','".join(entries[arch])))
@@ -519,7 +519,7 @@ def updateRpmDicts(rpmrc, pyfile):
pass
def usage():
- print "rpmutils.py rpmrc.in rpmutils.py"
+ print("rpmutils.py rpmrc.in rpmutils.py")
def main():
import sys
diff --git a/src/engine/SCons/Tool/sgicc.py b/src/engine/SCons/Tool/sgicc.py
index 662eb7d..94a0497 100644
--- a/src/engine/SCons/Tool/sgicc.py
+++ b/src/engine/SCons/Tool/sgicc.py
@@ -33,7 +33,7 @@ selection method.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-import cc
+from . import cc
def generate(env):
"""Add Builders and construction variables for gcc to an Environment."""
diff --git a/src/engine/SCons/Tool/sgilink.py b/src/engine/SCons/Tool/sgilink.py
index 6244141..b1e7921 100644
--- a/src/engine/SCons/Tool/sgilink.py
+++ b/src/engine/SCons/Tool/sgilink.py
@@ -35,7 +35,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Util
-import link
+from . import link
linkers = ['CC', 'cc']
diff --git a/src/engine/SCons/Tool/suncc.py b/src/engine/SCons/Tool/suncc.py
index 458538b..4651219 100644
--- a/src/engine/SCons/Tool/suncc.py
+++ b/src/engine/SCons/Tool/suncc.py
@@ -34,7 +34,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Util
-import cc
+from . import cc
def generate(env):
"""
diff --git a/src/engine/SCons/Tool/sunf77.py b/src/engine/SCons/Tool/sunf77.py
index d05ce54..20d1893 100644
--- a/src/engine/SCons/Tool/sunf77.py
+++ b/src/engine/SCons/Tool/sunf77.py
@@ -35,7 +35,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Util
-from FortranCommon import add_all_to_env
+from .FortranCommon import add_all_to_env
compilers = ['sunf77', 'f77']
diff --git a/src/engine/SCons/Tool/sunf90.py b/src/engine/SCons/Tool/sunf90.py
index 93b89c0..ce1697c 100644
--- a/src/engine/SCons/Tool/sunf90.py
+++ b/src/engine/SCons/Tool/sunf90.py
@@ -35,7 +35,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Util
-from FortranCommon import add_all_to_env
+from .FortranCommon import add_all_to_env
compilers = ['sunf90', 'f90']
diff --git a/src/engine/SCons/Tool/sunf95.py b/src/engine/SCons/Tool/sunf95.py
index c09026c..218569c 100644
--- a/src/engine/SCons/Tool/sunf95.py
+++ b/src/engine/SCons/Tool/sunf95.py
@@ -35,7 +35,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Util
-from FortranCommon import add_all_to_env
+from .FortranCommon import add_all_to_env
compilers = ['sunf95', 'f95']
diff --git a/src/engine/SCons/Tool/sunlink.py b/src/engine/SCons/Tool/sunlink.py
index 5996a30..af13392 100644
--- a/src/engine/SCons/Tool/sunlink.py
+++ b/src/engine/SCons/Tool/sunlink.py
@@ -37,7 +37,7 @@ import os.path
import SCons.Util
-import link
+from . import link
ccLinker = None
diff --git a/src/engine/SCons/Tool/tex.py b/src/engine/SCons/Tool/tex.py
index 5f24df0..febec35 100644
--- a/src/engine/SCons/Tool/tex.py
+++ b/src/engine/SCons/Tool/tex.py
@@ -163,15 +163,15 @@ def FindFile(name,suffixes,paths,env,requireExt=False):
if ext:
name = name + ext
if Verbose:
- print " searching for '%s' with extensions: " % name,suffixes
+ print(" searching for '%s' with extensions: " % name,suffixes)
for path in paths:
testName = os.path.join(path,name)
if Verbose:
- print " look for '%s'" % testName
+ print(" look for '%s'" % testName)
if os.path.isfile(testName):
if Verbose:
- print " found '%s'" % testName
+ print(" found '%s'" % testName)
return env.fs.File(testName)
else:
name_ext = SCons.Util.splitext(testName)[1]
@@ -182,14 +182,14 @@ def FindFile(name,suffixes,paths,env,requireExt=False):
for suffix in suffixes:
testNameExt = testName + suffix
if Verbose:
- print " look for '%s'" % testNameExt
+ print(" look for '%s'" % testNameExt)
if os.path.isfile(testNameExt):
if Verbose:
- print " found '%s'" % testNameExt
+ print(" found '%s'" % testNameExt)
return env.fs.File(testNameExt)
if Verbose:
- print " did not find '%s'" % name
+ print(" did not find '%s'" % name)
return None
def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None):
@@ -249,7 +249,7 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
saved_hashes[suffix] = theNode.get_csig()
if Verbose:
- print "hashes: ",saved_hashes
+ print("hashes: ",saved_hashes)
must_rerun_latex = True
@@ -268,12 +268,12 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
if saved_hashes[suffix] == new_md5:
if Verbose:
- print "file %s not changed" % (targetbase+suffix)
+ print("file %s not changed" % (targetbase+suffix))
return False # unchanged
saved_hashes[suffix] = new_md5
must_rerun_latex = True
if Verbose:
- print "file %s changed, rerunning Latex, new hash = " % (targetbase+suffix), new_md5
+ print("file %s changed, rerunning Latex, new hash = " % (targetbase+suffix), new_md5)
return True # changed
# generate the file name that latex will generate
@@ -322,8 +322,8 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
bcffiles = list(dups.keys())
if Verbose:
- print "auxfiles ",auxfiles
- print "bcffiles ",bcffiles
+ print("auxfiles ",auxfiles)
+ print("bcffiles ",bcffiles)
# Now decide if bibtex will need to be run.
# The information that bibtex reads from the .aux file is
@@ -339,7 +339,7 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
content = open(target_aux, "rb").read()
if content.find("bibdata") != -1:
if Verbose:
- print "Need to run bibtex on ",auxfilename
+ print("Need to run bibtex on ",auxfilename)
bibfile = env.fs.File(SCons.Util.splitext(target_aux)[0])
result = BibTeXAction(bibfile, bibfile, env)
if result != 0:
@@ -362,7 +362,7 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
content = open(target_bcf, "rb").read()
if content.find("bibdata") != -1:
if Verbose:
- print "Need to run biber on ",bcffilename
+ print("Need to run biber on ",bcffilename)
bibfile = env.fs.File(SCons.Util.splitext(target_bcf)[0])
result = BiberAction(bibfile, bibfile, env)
if result != 0:
@@ -373,7 +373,7 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
if check_MD5(suffix_nodes['.idx'],'.idx') or (count == 1 and run_makeindex):
# We must run makeindex
if Verbose:
- print "Need to run makeindex"
+ print("Need to run makeindex")
idxfile = suffix_nodes['.idx']
result = MakeIndexAction(idxfile, idxfile, env)
if result != 0:
@@ -391,7 +391,7 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
if check_MD5(suffix_nodes['.nlo'],'.nlo') or (count == 1 and run_nomenclature):
# We must run makeindex
if Verbose:
- print "Need to run makeindex for nomenclature"
+ print("Need to run makeindex for nomenclature")
nclfile = suffix_nodes['.nlo']
result = MakeNclAction(nclfile, nclfile, env)
if result != 0:
@@ -403,7 +403,7 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
if check_MD5(suffix_nodes['.glo'],'.glo') or (count == 1 and run_glossaries) or (count == 1 and run_glossary):
# We must run makeindex
if Verbose:
- print "Need to run makeindex for glossary"
+ print("Need to run makeindex for glossary")
glofile = suffix_nodes['.glo']
result = MakeGlossaryAction(glofile, glofile, env)
if result != 0:
@@ -415,7 +415,7 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
if check_MD5(suffix_nodes['.acn'],'.acn') or (count == 1 and run_acronyms):
# We must run makeindex
if Verbose:
- print "Need to run makeindex for acronyms"
+ print("Need to run makeindex for acronyms")
acrfile = suffix_nodes['.acn']
result = MakeAcronymsAction(acrfile, acrfile, env)
if result != 0:
@@ -428,7 +428,7 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
if check_MD5(suffix_nodes[newglossary_suffix[ig][2]],newglossary_suffix[ig][2]) or (count == 1):
# We must run makeindex
if Verbose:
- print "Need to run makeindex for newglossary"
+ print("Need to run makeindex for newglossary")
newglfile = suffix_nodes[newglossary_suffix[ig][2]]
MakeNewGlossaryAction = SCons.Action.Action("$MAKENEWGLOSSARY ${SOURCE.filebase}%s -s ${SOURCE.filebase}.ist -t ${SOURCE.filebase}%s -o ${SOURCE.filebase}%s" % (newglossary_suffix[ig][2],newglossary_suffix[ig][0],newglossary_suffix[ig][1]), "$MAKENEWGLOSSARYCOMSTR")
@@ -442,26 +442,26 @@ def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None
if warning_rerun_re.search(logContent):
must_rerun_latex = True
if Verbose:
- print "rerun Latex due to latex or package rerun warning"
+ print("rerun Latex due to latex or package rerun warning")
if rerun_citations_re.search(logContent):
must_rerun_latex = True
if Verbose:
- print "rerun Latex due to 'Rerun to get citations correct' warning"
+ print("rerun Latex due to 'Rerun to get citations correct' warning")
if undefined_references_re.search(logContent):
must_rerun_latex = True
if Verbose:
- print "rerun Latex due to undefined references or citations"
+ print("rerun Latex due to undefined references or citations")
if (count >= int(env.subst('$LATEXRETRIES')) and must_rerun_latex):
- print "reached max number of retries on Latex ,",int(env.subst('$LATEXRETRIES'))
+ print("reached max number of retries on Latex ,",int(env.subst('$LATEXRETRIES')))
# end of while loop
# rename Latex's output to what the target name is
if not (str(target[0]) == resultfilename and os.path.isfile(resultfilename)):
if os.path.isfile(resultfilename):
- print "move %s to %s" % (resultfilename, str(target[0]), )
+ print("move %s to %s" % (resultfilename, str(target[0]), ))
shutil.move(resultfilename,str(target[0]))
# Original comment (when TEXPICTS was not restored):
@@ -515,27 +515,27 @@ def is_LaTeX(flist,env,abspath):
else:
env['ENV']['TEXINPUTS'] = savedpath
if Verbose:
- print "is_LaTeX search path ",paths
- print "files to search :",flist
+ print("is_LaTeX search path ",paths)
+ print("files to search :",flist)
# Now that we have the search path and file list, check each one
for f in flist:
if Verbose:
- print " checking for Latex source ",str(f)
+ print(" checking for Latex source ",str(f))
content = f.get_text_contents()
if LaTeX_re.search(content):
if Verbose:
- print "file %s is a LaTeX file" % str(f)
+ print("file %s is a LaTeX file" % str(f))
return 1
if Verbose:
- print "file %s is not a LaTeX file" % str(f)
+ print("file %s is not a LaTeX file" % str(f))
# now find included files
inc_files = [ ]
inc_files.extend( include_re.findall(content) )
if Verbose:
- print "files included by '%s': "%str(f),inc_files
+ print("files included by '%s': "%str(f),inc_files)
# inc_files is list of file names as given. need to find them
# using TEXINPUTS paths.
@@ -545,7 +545,7 @@ def is_LaTeX(flist,env,abspath):
# make this a list since is_LaTeX takes a list.
fileList = [srcNode,]
if Verbose:
- print "FindFile found ",srcNode
+ print("FindFile found ",srcNode)
if srcNode is not None:
file_test = is_LaTeX(fileList, env, abspath)
@@ -554,7 +554,7 @@ def is_LaTeX(flist,env,abspath):
return file_test
if Verbose:
- print " done scanning ",str(f)
+ print(" done scanning ",str(f))
return 0
@@ -619,15 +619,15 @@ def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphi
content = theFile.get_text_contents()
if Verbose:
- print " scanning ",str(theFile)
+ print(" scanning ",str(theFile))
for i in range(len(file_tests_search)):
if file_tests[i][0] is None:
if Verbose:
- print "scan i ",i," files_tests[i] ",file_tests[i], file_tests[i][1]
+ print("scan i ",i," files_tests[i] ",file_tests[i], file_tests[i][1])
file_tests[i][0] = file_tests_search[i].search(content)
if Verbose and file_tests[i][0]:
- print " found match for ",file_tests[i][1][-1]
+ print(" found match for ",file_tests[i][1][-1])
# for newglossary insert the suffixes in file_tests[i]
if file_tests[i][0] and file_tests[i][1][-1] == 'newglossary':
findresult = file_tests_search[i].findall(content)
@@ -638,19 +638,19 @@ def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphi
suffix_list = ['.'+findresult[l][0],'.'+findresult[l][2],'.'+findresult[l][3] ]
newglossary_suffix.append(suffix_list)
if Verbose:
- print " new suffixes for newglossary ",newglossary_suffix
+ print(" new suffixes for newglossary ",newglossary_suffix)
incResult = includeOnly_re.search(content)
if incResult:
aux_files.append(os.path.join(targetdir, incResult.group(1)))
if Verbose:
- print "\include file names : ", aux_files
+ print("\include file names : ", aux_files)
# recursively call this on each of the included files
inc_files = [ ]
inc_files.extend( include_re.findall(content) )
if Verbose:
- print "files included by '%s': "%str(theFile),inc_files
+ print("files included by '%s': "%str(theFile),inc_files)
# inc_files is list of file names as given. need to find them
# using TEXINPUTS paths.
@@ -659,7 +659,7 @@ def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphi
if srcNode is not None:
file_tests = ScanFiles(srcNode, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files)
if Verbose:
- print " done scanning ",str(theFile)
+ print(" done scanning ",str(theFile))
return file_tests
def tex_emitter_core(target, source, env, graphics_extensions):
@@ -689,7 +689,7 @@ def tex_emitter_core(target, source, env, graphics_extensions):
env.SideEffect(logfilename,target[0])
env.SideEffect(flsfilename,target[0])
if Verbose:
- print "side effect :",auxfilename,logfilename,flsfilename
+ print("side effect :",auxfilename,logfilename,flsfilename)
env.Clean(target[0],auxfilename)
env.Clean(target[0],logfilename)
env.Clean(target[0],flsfilename)
@@ -765,7 +765,7 @@ def tex_emitter_core(target, source, env, graphics_extensions):
else:
env['ENV']['TEXINPUTS'] = savedpath
if Verbose:
- print "search path ",paths
+ print("search path ",paths)
# scan all sources for side effect files
aux_files = []
@@ -774,7 +774,7 @@ def tex_emitter_core(target, source, env, graphics_extensions):
for (theSearch,suffix_list) in file_tests:
# add side effects if feature is present.If file is to be generated,add all side effects
if Verbose and theSearch:
- print "check side effects for ",suffix_list[-1]
+ print("check side effects for ",suffix_list[-1])
if (theSearch != None) or (not source[0].exists() ):
file_list = [targetbase,]
# for bibunit we need a list of files
@@ -788,11 +788,11 @@ def tex_emitter_core(target, source, env, graphics_extensions):
if suffix_list[-1] == 'multibib':
for multibibmatch in multibib_re.finditer(content):
if Verbose:
- print "multibib match ",multibibmatch.group(1)
+ print("multibib match ",multibibmatch.group(1))
if multibibmatch != None:
baselist = multibibmatch.group(1).split(',')
if Verbose:
- print "multibib list ", baselist
+ print("multibib list ", baselist)
for i in range(len(baselist)):
file_list.append(os.path.join(targetdir, baselist[i]))
# now define the side effects
@@ -800,14 +800,14 @@ def tex_emitter_core(target, source, env, graphics_extensions):
for suffix in suffix_list[:-1]:
env.SideEffect(file_name + suffix,target[0])
if Verbose:
- print "side effect tst :",file_name + suffix, " target is ",str(target[0])
+ print("side effect tst :",file_name + suffix, " target is ",str(target[0]))
env.Clean(target[0],file_name + suffix)
for aFile in aux_files:
aFile_base = SCons.Util.splitext(aFile)[0]
env.SideEffect(aFile_base + '.aux',target[0])
if Verbose:
- print "side effect aux :",aFile_base + '.aux'
+ print("side effect aux :",aFile_base + '.aux')
env.Clean(target[0],aFile_base + '.aux')
# read fls file to get all other files that latex creates and will read on the next pass
# remove files from list that we explicitly dealt with above
@@ -820,7 +820,7 @@ def tex_emitter_core(target, source, env, graphics_extensions):
out_files.remove(filename)
env.SideEffect(out_files,target[0])
if Verbose:
- print "side effect fls :",out_files
+ print("side effect fls :",out_files)
env.Clean(target[0],out_files)
return (target, source)
@@ -840,7 +840,7 @@ def generate(env):
generate_common(env)
- import dvi
+ from . import dvi
dvi.generate(env)
bld = env['BUILDERS']['DVI']
diff --git a/src/engine/SCons/Tool/textfile.py b/src/engine/SCons/Tool/textfile.py
index 8dc8f4b..4897113 100644
--- a/src/engine/SCons/Tool/textfile.py
+++ b/src/engine/SCons/Tool/textfile.py
@@ -54,6 +54,7 @@ import re
from SCons.Node import Node
from SCons.Node.Python import Value
from SCons.Util import is_String, is_Sequence, is_Dict
+import collections
def _do_subst(node, subs):
"""
@@ -96,7 +97,7 @@ def _action(target, source, env):
raise SCons.Errors.UserError('SUBST_DICT must be dict or sequence')
subs = []
for (k,v) in d:
- if callable(v):
+ if isinstance(v, collections.Callable):
v = v()
if is_String(v):
v = env.subst(v)
@@ -107,7 +108,7 @@ def _action(target, source, env):
# write the file
try:
fd = open(target[0].get_path(), "wb")
- except (OSError,IOError), e:
+ except (OSError,IOError) as e:
raise SCons.Errors.UserError("Can't write target file %s" % target[0])
# separate lines by 'linesep' only if linesep is not empty
lsep = None
diff --git a/src/engine/SCons/Tool/xgettext.py b/src/engine/SCons/Tool/xgettext.py
index 64436b8..489d4d7 100644
--- a/src/engine/SCons/Tool/xgettext.py
+++ b/src/engine/SCons/Tool/xgettext.py
@@ -55,7 +55,7 @@ class _CmdRunner(object):
proc = SCons.Action._subproc(env, command, **kw)
self.out, self.err = proc.communicate()
self.status = proc.wait()
- if self.err: sys.stderr.write(unicode(self.err))
+ if self.err: sys.stderr.write(str(self.err))
return self.status
def strfunction(self, target, source, env):
@@ -153,7 +153,7 @@ from SCons.Builder import BuilderBase
class _POTBuilder(BuilderBase):
def _execute(self, env, target, source, *args):
if not target:
- if env.has_key('POTDOMAIN') and env['POTDOMAIN']:
+ if 'POTDOMAIN' in env and env['POTDOMAIN']:
domain = env['POTDOMAIN']
else:
domain = 'messages'
@@ -175,7 +175,7 @@ def _scan_xgettext_from_files(target, source, env, files = None, path = None):
files = [ files ]
if path is None:
- if env.has_key('XGETTEXTPATH'):
+ if 'XGETTEXTPATH' in env:
path = env['XGETTEXTPATH']
else:
path = []
@@ -222,7 +222,7 @@ def _pot_update_emitter(target, source, env):
import SCons.Util
import SCons.Node.FS
- if env.has_key('XGETTEXTFROM'):
+ if 'XGETTEXTFROM' in env:
xfrom = env['XGETTEXTFROM']
else:
return target, source
diff --git a/src/engine/SCons/Util.py b/src/engine/SCons/Util.py
index 822d524..f2e5325 100644
--- a/src/engine/SCons/Util.py
+++ b/src/engine/SCons/Util.py
@@ -33,15 +33,16 @@ import re
import types
from collections import UserDict, UserList, UserString
+import collections
# Don't "from types import ..." these because we need to get at the
# types module later to look for UnicodeType.
InstanceType = types.InstanceType
MethodType = types.MethodType
FunctionType = types.FunctionType
-try: unicode
+try: str
except NameError: UnicodeType = None
-else: UnicodeType = unicode
+else: UnicodeType = str
def dictify(keys, values, result={}):
for k, v in zip(keys, values):
@@ -111,7 +112,7 @@ class NodeList(UserList):
>>> someList.strip()
[ 'foo', 'bar' ]
"""
- def __nonzero__(self):
+ def __bool__(self):
return len(self.data) != 0
def __str__(self):
@@ -153,7 +154,7 @@ class DisplayEngine(object):
return
if append_newline: text = text + '\n'
try:
- sys.stdout.write(unicode(text))
+ sys.stdout.write(str(text))
except IOError:
# Stdout might be connected to a pipe that has been closed
# by now. The most likely reason for the pipe being closed
@@ -239,7 +240,7 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}):
' N = no clean\n' +
' H = no cache\n' +
'\n')
- sys.stdout.write(unicode(legend))
+ sys.stdout.write(str(legend))
tags = ['[']
tags.append(' E'[IDX(root.exists())])
@@ -264,10 +265,10 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}):
children = child_func(root)
if prune and rname in visited and children:
- sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + u'\n')
+ sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + '\n')
return
- sys.stdout.write(''.join(tags + margins + ['+-', rname]) + u'\n')
+ sys.stdout.write(''.join(tags + margins + ['+-', rname]) + '\n')
visited[rname] = 1
@@ -303,11 +304,11 @@ SequenceTypes = (list, tuple, UserList)
# Note that profiling data shows a speed-up when comparing
# explicitely with str and unicode instead of simply comparing
# with basestring. (at least on Python 2.5.1)
-StringTypes = (str, unicode, UserString)
+StringTypes = (str, str, UserString)
# Empirically, it is faster to check explicitely for str and
# unicode than for basestring.
-BaseStringTypes = (str, unicode)
+BaseStringTypes = (str, str)
def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes):
return isinstance(obj, DictTypes)
@@ -440,7 +441,7 @@ _semi_deepcopy_dispatch = d = {}
def semi_deepcopy_dict(x, exclude = [] ):
copy = {}
- for key, val in x.items():
+ for key, val in list(x.items()):
# The regular Python copy.deepcopy() also deepcopies the key,
# as follows:
#
@@ -465,7 +466,7 @@ def semi_deepcopy(x):
if copier:
return copier(x)
else:
- if hasattr(x, '__semi_deepcopy__') and callable(x.__semi_deepcopy__):
+ if hasattr(x, '__semi_deepcopy__') and isinstance(x.__semi_deepcopy__, collections.Callable):
return x.__semi_deepcopy__()
elif isinstance(x, UserDict):
return x.__class__(semi_deepcopy_dict(x))
@@ -718,7 +719,7 @@ else:
# raised so as to not mask possibly serious disk or
# network issues.
continue
- if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
+ if stat.S_IMODE(st[stat.ST_MODE]) & 0o111:
try:
reject.index(f)
except ValueError:
@@ -979,7 +980,7 @@ class OrderedDict(UserDict):
if key not in self._keys: self._keys.append(key)
def update(self, dict):
- for (key, val) in dict.items():
+ for (key, val) in list(dict.items()):
self.__setitem__(key, val)
def values(self):
@@ -1001,7 +1002,7 @@ class Selector(OrderedDict):
# Try to perform Environment substitution on the keys of
# the dictionary before giving up.
s_dict = {}
- for (k,v) in self.items():
+ for (k,v) in list(self.items()):
if k is not None:
s_k = env.subst(k)
if s_k in s_dict:
@@ -1360,7 +1361,7 @@ def AddMethod(obj, function, name=None):
print a.listIndex(5)
"""
if name is None:
- name = function.func_name
+ name = function.__name__
else:
function = RenameFunction(function, name)
@@ -1376,10 +1377,10 @@ def RenameFunction(function, name):
Returns a function identical to the specified function, but with
the specified name.
"""
- return FunctionType(function.func_code,
- function.func_globals,
+ return FunctionType(function.__code__,
+ function.__globals__,
name,
- function.func_defaults)
+ function.__defaults__)
md5 = False
@@ -1461,7 +1462,7 @@ class Null(object):
return self
def __repr__(self):
return "Null(0x%08X)" % id(self)
- def __nonzero__(self):
+ def __bool__(self):
return False
def __getattr__(self, name):
return self
diff --git a/src/engine/SCons/UtilTests.py b/src/engine/SCons/UtilTests.py
index a1e6756..a30404c 100644
--- a/src/engine/SCons/UtilTests.py
+++ b/src/engine/SCons/UtilTests.py
@@ -219,7 +219,7 @@ class UtilTestCase(unittest.TestCase):
assert not is_Dict(())
assert not is_Dict("")
if HasUnicode:
- exec "assert not is_Dict(u'')"
+ exec("assert not is_Dict(u'')")
def test_is_List(self):
assert is_List([])
@@ -235,12 +235,12 @@ class UtilTestCase(unittest.TestCase):
assert not is_List({})
assert not is_List("")
if HasUnicode:
- exec "assert not is_List(u'')"
+ exec("assert not is_List(u'')")
def test_is_String(self):
assert is_String("")
if HasUnicode:
- exec "assert is_String(u'')"
+ exec("assert is_String(u'')")
assert is_String(UserString(''))
try:
class mystr(str):
@@ -266,7 +266,7 @@ class UtilTestCase(unittest.TestCase):
assert not is_Tuple({})
assert not is_Tuple("")
if HasUnicode:
- exec "assert not is_Tuple(u'')"
+ exec("assert not is_Tuple(u'')")
def test_to_String(self):
"""Test the to_String() method."""
@@ -285,16 +285,16 @@ class UtilTestCase(unittest.TestCase):
assert to_String(s2) == 'foo', s2
if HasUnicode:
- s3=UserString(unicode('bar'))
+ s3=UserString(str('bar'))
assert to_String(s3) == s3, s3
- assert to_String(s3) == unicode('bar'), s3
- assert isinstance(to_String(s3), unicode), \
+ assert to_String(s3) == str('bar'), s3
+ assert isinstance(to_String(s3), str), \
type(to_String(s3))
if HasUnicode:
- s4 = unicode('baz')
- assert to_String(s4) == unicode('baz'), to_String(s4)
- assert isinstance(to_String(s4), unicode), \
+ s4 = str('baz')
+ assert to_String(s4) == str('baz'), to_String(s4)
+ assert isinstance(to_String(s4), str), \
type(to_String(s4))
def test_WhereIs(self):
@@ -313,10 +313,10 @@ class UtilTestCase(unittest.TestCase):
os.mkdir(sub2_xxx_exe)
test.write(sub3_xxx_exe, "\n")
- os.chmod(sub3_xxx_exe, 0777)
+ os.chmod(sub3_xxx_exe, 0o777)
test.write(sub4_xxx_exe, "\n")
- os.chmod(sub4_xxx_exe, 0777)
+ os.chmod(sub4_xxx_exe, 0o777)
env_path = os.environ['PATH']
@@ -681,7 +681,7 @@ bling
fobj = io.StringIO(content)
except TypeError:
# Python 2.7 and beyond require unicode strings.
- fobj = io.StringIO(unicode(content))
+ fobj = io.StringIO(str(content))
lines = LogicalLines(fobj).readlines()
assert lines == [
@@ -696,7 +696,7 @@ bling
s1 = silent_intern("spam")
# Python 3.x does not have a unicode() global function
if sys.version[0] == '2':
- s2 = silent_intern(unicode("unicode spam"))
+ s2 = silent_intern(str("unicode spam"))
s3 = silent_intern(42)
s4 = silent_intern("spam")
assert id(s1) == id(s4)
diff --git a/src/engine/SCons/Variables/EnumVariableTests.py b/src/engine/SCons/Variables/EnumVariableTests.py
index f4b600d..4feb712 100644
--- a/src/engine/SCons/Variables/EnumVariableTests.py
+++ b/src/engine/SCons/Variables/EnumVariableTests.py
@@ -122,7 +122,7 @@ class EnumVariableTestCase(unittest.TestCase):
'C' : ['C', 'three', 'three'],
}
- for k, l in table.items():
+ for k, l in list(table.items()):
x = o0.converter(k)
assert x == l[0], "o0 got %s, expected %s" % (x, l[0])
x = o1.converter(k)
@@ -186,7 +186,7 @@ class EnumVariableTestCase(unittest.TestCase):
'no_v' : [invalid, invalid, invalid],
}
- for v, l in table.items():
+ for v, l in list(table.items()):
l[0](o0, v)
l[1](o1, v)
l[2](o2, v)
diff --git a/src/engine/SCons/Variables/PathVariableTests.py b/src/engine/SCons/Variables/PathVariableTests.py
index 084154b..2fa46eb 100644
--- a/src/engine/SCons/Variables/PathVariableTests.py
+++ b/src/engine/SCons/Variables/PathVariableTests.py
@@ -65,7 +65,7 @@ class PathVariableTestCase(unittest.TestCase):
dne = test.workpath('does_not_exist')
try:
o.validator('X', dne, {})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
assert str(e) == 'Path for option X does not exist: %s' % dne, e
except:
raise Exception("did not catch expected UserError")
@@ -89,7 +89,7 @@ class PathVariableTestCase(unittest.TestCase):
f = test.workpath('file')
try:
o.validator('X', f, {})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
assert str(e) == 'Directory path for option X is a file: %s' % f, e
except:
raise Exception("did not catch expected UserError")
@@ -97,7 +97,7 @@ class PathVariableTestCase(unittest.TestCase):
dne = test.workpath('does_not_exist')
try:
o.validator('X', dne, {})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
assert str(e) == 'Directory path for option X does not exist: %s' % dne, e
except:
raise Exception("did not catch expected UserError")
@@ -122,7 +122,7 @@ class PathVariableTestCase(unittest.TestCase):
f = test.workpath('file')
try:
o.validator('X', f, {})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
assert str(e) == 'Path for option X is a file, not a directory: %s' % f, e
except:
raise Exception("did not catch expected UserError")
@@ -146,7 +146,7 @@ class PathVariableTestCase(unittest.TestCase):
d = test.workpath('d')
try:
o.validator('X', d, {})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
assert str(e) == 'File path for option X does not exist: %s' % d, e
except:
raise Exception("did not catch expected UserError")
@@ -154,7 +154,7 @@ class PathVariableTestCase(unittest.TestCase):
dne = test.workpath('does_not_exist')
try:
o.validator('X', dne, {})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
assert str(e) == 'File path for option X does not exist: %s' % dne, e
except:
raise Exception("did not catch expected UserError")
@@ -198,7 +198,7 @@ class PathVariableTestCase(unittest.TestCase):
dne = test.workpath('does_not_exist')
try:
o.validator('X', dne, {})
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
expect = 'Path for option X does not exist: %s' % dne
assert str(e) == expect, e
else:
@@ -217,7 +217,7 @@ class PathVariableTestCase(unittest.TestCase):
try:
o.validator('Y', 'value', {})
- except Exception, e:
+ except Exception as e:
assert str(e) == 'my_validator() got called for Y, value!', e
else:
raise Exception("did not catch expected exception from my_validator()")
diff --git a/src/engine/SCons/Variables/VariablesTests.py b/src/engine/SCons/Variables/VariablesTests.py
index ad46bd6..520c8e3 100644
--- a/src/engine/SCons/Variables/VariablesTests.py
+++ b/src/engine/SCons/Variables/VariablesTests.py
@@ -55,7 +55,7 @@ def check(key, value, env):
def checkSave(file, expected):
gdict = {}
ldict = {}
- exec open(file, 'rU').read() in gdict, ldict
+ exec(open(file, 'rU').read(), gdict, ldict)
assert expected == ldict, "%s\n...not equal to...\n%s" % (expected, ldict)
class VariablesTestCase(unittest.TestCase):
diff --git a/src/engine/SCons/Variables/__init__.py b/src/engine/SCons/Variables/__init__.py
index ede7480..8d15b8d 100644
--- a/src/engine/SCons/Variables/__init__.py
+++ b/src/engine/SCons/Variables/__init__.py
@@ -36,11 +36,11 @@ import SCons.Errors
import SCons.Util
import SCons.Warnings
-from BoolVariable import BoolVariable # okay
-from EnumVariable import EnumVariable # okay
-from ListVariable import ListVariable # naja
-from PackageVariable import PackageVariable # naja
-from PathVariable import PathVariable # okay
+from .BoolVariable import BoolVariable # okay
+from .EnumVariable import EnumVariable # okay
+from .ListVariable import ListVariable # naja
+from .PackageVariable import PackageVariable # naja
+from .PathVariable import PathVariable # okay
class Variables(object):
@@ -170,7 +170,7 @@ class Variables(object):
sys.path.insert(0, dir)
try:
values['__name__'] = filename
- exec open(filename, 'rU').read() in {}, values
+ exec(open(filename, 'rU').read(), {}, values)
finally:
if dir:
del sys.path[0]
@@ -180,7 +180,7 @@ class Variables(object):
if args is None:
args = self.args
- for arg, value in args.items():
+ for arg, value in list(args.items()):
added = False
for option in self.options:
if arg in list(option.aliases) + [ option.key ]:
@@ -206,7 +206,7 @@ class Variables(object):
env[option.key] = option.converter(value)
except TypeError:
env[option.key] = option.converter(value, env)
- except ValueError, x:
+ except ValueError as x:
raise SCons.Errors.UserError('Error converting option: %s\n%s'%(option.key, x))
@@ -268,7 +268,7 @@ class Variables(object):
finally:
fh.close()
- except IOError, x:
+ except IOError as x:
raise SCons.Errors.UserError('Error writing options to file: %s\n%s' % (filename, x))
def GenerateHelpText(self, env, sort=None):
diff --git a/src/engine/SCons/compat/__init__.py b/src/engine/SCons/compat/__init__.py
index c870fbc..6f1a7ee 100644
--- a/src/engine/SCons/compat/__init__.py
+++ b/src/engine/SCons/compat/__init__.py
@@ -87,7 +87,7 @@ def rename_module(new, old):
rename_module('builtins', '__builtin__')
-import _scons_builtins
+from . import _scons_builtins
try:
diff --git a/src/engine/SCons/compat/_scons_subprocess.py b/src/engine/SCons/compat/_scons_subprocess.py
index eebe53d..72581f7 100644
--- a/src/engine/SCons/compat/_scons_subprocess.py
+++ b/src/engine/SCons/compat/_scons_subprocess.py
@@ -439,22 +439,22 @@ except TypeError:
def is_int(obj):
return isinstance(obj, type(1))
def is_int_or_long(obj):
- return type(obj) in (type(1), type(1L))
+ return type(obj) in (type(1), type(1))
else:
def is_int(obj):
return isinstance(obj, int)
def is_int_or_long(obj):
- return isinstance(obj, (int, long))
+ return isinstance(obj, int)
try:
- types.StringTypes
+ str
except AttributeError:
try:
- types.StringTypes = (str, unicode)
+ str = (str, str)
except NameError:
- types.StringTypes = (str,)
+ str = (str,)
def is_string(obj):
- return isinstance(obj, types.StringTypes)
+ return isinstance(obj, str)
_active = []
@@ -785,7 +785,7 @@ class Popen(object):
errread, errwrite):
"""Execute program (MS Windows version)"""
- if not isinstance(args, types.StringTypes):
+ if not isinstance(args, str):
args = list2cmdline(args)
# Process startup details
@@ -802,7 +802,7 @@ class Popen(object):
startupinfo.wShowWindow = SW_HIDE
comspec = os.environ.get("COMSPEC", "cmd.exe")
args = comspec + " /c " + args
- if (GetVersion() >= 0x80000000L or
+ if (GetVersion() >= 0x80000000 or
os.path.basename(comspec).lower() == "command.com"):
# Win9x, or using command.com on NT. We need to
# use the w9xpopen intermediate program. For more
@@ -830,7 +830,7 @@ class Popen(object):
env,
cwd,
startupinfo)
- except pywintypes.error, e:
+ except pywintypes.error as e:
# Translate pywintypes.error to WindowsError, which is
# a subclass of OSError. FIXME: We should really
# translate errno using _sys_errlist (or simliar), but
@@ -1215,8 +1215,8 @@ def _demo_posix():
# Example 1: Simple redirection: Get process list
#
plist = Popen(["ps"], stdout=PIPE).communicate()[0]
- print "Process list:"
- print plist
+ print("Process list:")
+ print(plist)
#
# Example 2: Change uid before executing child
@@ -1228,25 +1228,25 @@ def _demo_posix():
#
# Example 3: Connecting several subprocesses
#
- print "Looking for 'hda'..."
+ print("Looking for 'hda'...")
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
- print repr(p2.communicate()[0])
+ print(repr(p2.communicate()[0]))
#
# Example 4: Catch execution error
#
- print
- print "Trying a weird file..."
+ print()
+ print("Trying a weird file...")
try:
- print Popen(["/this/path/does/not/exist"]).communicate()
- except OSError, e:
+ print(Popen(["/this/path/does/not/exist"]).communicate())
+ except OSError as e:
if e.errno == errno.ENOENT:
- print "The file didn't exist. I thought so..."
- print "Child traceback:"
- print e.child_traceback
+ print("The file didn't exist. I thought so...")
+ print("Child traceback:")
+ print(e.child_traceback)
else:
- print "Error", e.errno
+ print("Error", e.errno)
else:
sys.stderr.write( "Gosh. No error.\n" )
@@ -1255,15 +1255,15 @@ def _demo_windows():
#
# Example 1: Connecting several subprocesses
#
- print "Looking for 'PROMPT' in set output..."
+ print("Looking for 'PROMPT' in set output...")
p1 = Popen("set", stdout=PIPE, shell=True)
p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
- print repr(p2.communicate()[0])
+ print(repr(p2.communicate()[0]))
#
# Example 2: Simple execution of program
#
- print "Executing calc..."
+ print("Executing calc...")
p = Popen("calc")
p.wait()
diff --git a/src/engine/SCons/cpp.py b/src/engine/SCons/cpp.py
index 0ba10f5..4cc771b 100644
--- a/src/engine/SCons/cpp.py
+++ b/src/engine/SCons/cpp.py
@@ -31,6 +31,7 @@ import SCons.compat
import os
import re
+import collections
#
# First "subsystem" of regular expressions that we set up:
@@ -72,7 +73,7 @@ cpp_lines_dict = {
# the corresponding compiled regular expression that fetches the arguments
# we care about.
Table = {}
-for op_list, expr in cpp_lines_dict.items():
+for op_list, expr in list(cpp_lines_dict.items()):
e = re.compile(expr)
for op in op_list:
Table[op] = e
@@ -87,7 +88,7 @@ del op_list
override = {
'if' : 'if(?!def)',
}
-l = [override.get(x, x) for x in Table.keys()]
+l = [override.get(x, x) for x in list(Table.keys())]
# Turn the list of expressions into one big honkin' regular expression
@@ -130,7 +131,7 @@ CPP_to_Python_Ops_Sub = lambda m: CPP_to_Python_Ops_Dict[m.group(0)]
# re module, as late as version 2.2.2, empirically matches the
# "!" in "!=" first, instead of finding the longest match.
# What's up with that?
-l = sorted(CPP_to_Python_Ops_Dict.keys(), key=lambda a: len(a), reverse=True)
+l = sorted(list(CPP_to_Python_Ops_Dict.keys()), key=lambda a: len(a), reverse=True)
# Turn the list of keys into one regular expression that will allow us
# to substitute all of the operators at once.
@@ -266,7 +267,7 @@ class PreProcessor(object):
d = {
'scons_current_file' : self.scons_current_file
}
- for op in Table.keys():
+ for op in list(Table.keys()):
d[op] = getattr(self, 'do_' + op)
self.default_table = d
@@ -552,7 +553,7 @@ class PreProcessor(object):
except KeyError:
m = function_name.search(s)
s = self.cpp_namespace[m.group(1)]
- if callable(s):
+ if isinstance(s, collections.Callable):
args = function_arg_separator.split(m.group(2))
s = s(*args)
if not s:
diff --git a/src/engine/SCons/cppTests.py b/src/engine/SCons/cppTests.py
index 2f2025b..5566e53 100644
--- a/src/engine/SCons/cppTests.py
+++ b/src/engine/SCons/cppTests.py
@@ -27,7 +27,7 @@ import atexit
import sys
import unittest
-import cpp
+from . import cpp
diff --git a/src/engine/SCons/dblite.py b/src/engine/SCons/dblite.py
index f4ba90a..89b9856 100644
--- a/src/engine/SCons/dblite.py
+++ b/src/engine/SCons/dblite.py
@@ -14,20 +14,20 @@ keep_all_files = 00000
ignore_corrupt_dbfiles = 0
def corruption_warning(filename):
- print "Warning: Discarding corrupt database:", filename
+ print("Warning: Discarding corrupt database:", filename)
-try: unicode
+try: str
except NameError:
def is_string(s):
return isinstance(s, str)
else:
def is_string(s):
- return type(s) in (str, unicode)
+ return type(s) in (str, str)
try:
- unicode('a')
+ str('a')
except NameError:
- def unicode(s): return s
+ def str(s): return s
dblite_suffix = '.dblite'
tmp_suffix = '.tmp'
@@ -77,7 +77,7 @@ class dblite(object):
statinfo = os.stat(self._file_name)
self._chown_to = statinfo.st_uid
self._chgrp_to = statinfo.st_gid
- except OSError, e:
+ except OSError as e:
# db file doesn't exist yet.
# Check os.environ for SUDO_UID, use if set
self._chown_to = int(os.environ.get('SUDO_UID', -1))
@@ -90,7 +90,7 @@ class dblite(object):
else:
try:
f = self._open(self._file_name, "rb")
- except IOError, e:
+ except IOError as e:
if (self._flag != "c"):
raise e
self._open(self._file_name, "wb", self._mode)
@@ -122,7 +122,7 @@ class dblite(object):
# (e.g. from a previous run as root). We should still be able to
# unlink() the file if the directory's writable, though, so ignore
# any OSError exception thrown by the chmod() call.
- try: self._os_chmod(self._file_name, 0777)
+ try: self._os_chmod(self._file_name, 0o777)
except OSError: pass
self._os_unlink(self._file_name)
self._os_rename(self._tmp_name, self._file_name)
@@ -151,7 +151,7 @@ class dblite(object):
if (not is_string(value)):
raise TypeError("value `%s' must be a string but is %s" % (value, type(value)))
self._dict[key] = value
- self._needs_sync = 0001
+ self._needs_sync = 0o001
def keys(self):
return list(self._dict.keys())
@@ -171,7 +171,7 @@ class dblite(object):
def __len__(self):
return len(self._dict)
-def open(file, flag=None, mode=0666):
+def open(file, flag=None, mode=0o666):
return dblite(file, flag, mode)
def _exercise():
@@ -179,26 +179,26 @@ def _exercise():
assert len(db) == 0
db["foo"] = "bar"
assert db["foo"] == "bar"
- db[unicode("ufoo")] = unicode("ubar")
- assert db[unicode("ufoo")] == unicode("ubar")
+ db[str("ufoo")] = str("ubar")
+ assert db[str("ufoo")] == str("ubar")
db.sync()
db = open("tmp", "c")
assert len(db) == 2, len(db)
assert db["foo"] == "bar"
db["bar"] = "foo"
assert db["bar"] == "foo"
- db[unicode("ubar")] = unicode("ufoo")
- assert db[unicode("ubar")] == unicode("ufoo")
+ db[str("ubar")] = str("ufoo")
+ assert db[str("ubar")] == str("ufoo")
db.sync()
db = open("tmp", "r")
assert len(db) == 4, len(db)
assert db["foo"] == "bar"
assert db["bar"] == "foo"
- assert db[unicode("ufoo")] == unicode("ubar")
- assert db[unicode("ubar")] == unicode("ufoo")
+ assert db[str("ufoo")] == str("ubar")
+ assert db[str("ubar")] == str("ufoo")
try:
db.sync()
- except IOError, e:
+ except IOError as e:
assert str(e) == "Read-only database: tmp.dblite"
else:
raise RuntimeError("IOError expected.")
@@ -208,13 +208,13 @@ def _exercise():
db.sync()
try:
db[(1,2)] = "tuple"
- except TypeError, e:
+ except TypeError as e:
assert str(e) == "key `(1, 2)' must be a string but is <type 'tuple'>", str(e)
else:
raise RuntimeError("TypeError exception expected")
try:
db["list"] = [1,2]
- except TypeError, e:
+ except TypeError as e:
assert str(e) == "value `[1, 2]' must be a string but is <type 'list'>", str(e)
else:
raise RuntimeError("TypeError exception expected")
@@ -238,11 +238,11 @@ def _exercise():
os.unlink("tmp.dblite")
try:
db = open("tmp", "w")
- except IOError, e:
+ except IOError as e:
assert str(e) == "[Errno 2] No such file or directory: 'tmp.dblite'", str(e)
else:
raise RuntimeError("IOError expected.")
- print "OK"
+ print("OK")
if (__name__ == "__main__"):
_exercise()
diff --git a/src/script/scons-time.py b/src/script/scons-time.py
index 3b215f9..4296192 100644
--- a/src/script/scons-time.py
+++ b/src/script/scons-time.py
@@ -29,8 +29,8 @@
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-from __future__ import division
-from __future__ import nested_scopes
+
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -42,6 +42,7 @@ import shutil
import sys
import tempfile
import time
+import collections
try:
sorted
@@ -109,8 +110,8 @@ def HACK_for_exec(cmd, *args):
internal functions.
'''
if not args: exec(cmd)
- elif len(args) == 1: exec cmd in args[0]
- else: exec cmd in args[0], args[1]
+ elif len(args) == 1: exec(cmd, args[0])
+ else: exec(cmd, args[0], args[1])
class Plotter(object):
def increment_size(self, largest):
@@ -146,7 +147,7 @@ class Line(object):
def print_label(self, inx, x, y):
if self.label:
- print 'set label %s "%s" at %s,%s right' % (inx, self.label, x, y)
+ print('set label %s "%s" at %s,%s right' % (inx, self.label, x, y))
def plot_string(self):
if self.title:
@@ -159,15 +160,15 @@ class Line(object):
if fmt is None:
fmt = self.fmt
if self.comment:
- print '# %s' % self.comment
+ print('# %s' % self.comment)
for x, y in self.points:
# If y is None, it usually represents some kind of break
# in the line's index number. We might want to represent
# this some way rather than just drawing the line straight
# between the two points on either side.
if not y is None:
- print fmt % (x, y)
- print 'e'
+ print(fmt % (x, y))
+ print('e')
def get_x_values(self):
return [ p[0] for p in self.points ]
@@ -253,8 +254,8 @@ class Gnuplotter(Plotter):
return
if self.title:
- print 'set title "%s"' % self.title
- print 'set key %s' % self.key_location
+ print('set title "%s"' % self.title)
+ print('set key %s' % self.key_location)
min_y = self.get_min_y()
max_y = self.max_graph_value(self.get_max_y())
@@ -269,7 +270,7 @@ class Gnuplotter(Plotter):
inx += 1
plot_strings = [ self.plot_string(l) for l in self.lines ]
- print 'plot ' + ', \\\n '.join(plot_strings)
+ print('plot ' + ', \\\n '.join(plot_strings))
for line in self.lines:
line.print_points()
@@ -455,7 +456,7 @@ class SConsTimer(object):
Each message is prepended with a standard prefix of our name
plus the time.
"""
- if callable(msg):
+ if isinstance(msg, collections.Callable):
msg = msg(*args)
else:
msg = msg % args
@@ -474,7 +475,7 @@ class SConsTimer(object):
The action is called if it's a callable Python function, and
otherwise passed to os.system().
"""
- if callable(action):
+ if isinstance(action, collections.Callable):
action(*args)
else:
os.system(action % args)
@@ -540,7 +541,7 @@ class SConsTimer(object):
header_fmt = ' '.join(['%12s'] * len(columns))
line_fmt = header_fmt + ' %s'
- print header_fmt % columns
+ print(header_fmt % columns)
for file in files:
t = line_function(file, *args, **kw)
@@ -550,7 +551,7 @@ class SConsTimer(object):
if diff > 0:
t += [''] * diff
t.append(file_function(file))
- print line_fmt % tuple(t)
+ print(line_fmt % tuple(t))
def collect_results(self, files, function, *args, **kw):
results = {}
@@ -690,13 +691,13 @@ class SConsTimer(object):
"""
try:
import pstats
- except ImportError, e:
+ except ImportError as e:
sys.stderr.write('%s: func: %s\n' % (self.name, e))
sys.stderr.write('%s This version of Python is missing the profiler.\n' % self.name_spaces)
sys.stderr.write('%s Cannot use the "func" subcommand.\n' % self.name_spaces)
sys.exit(1)
statistics = pstats.Stats(file).stats
- matches = [ e for e in statistics.items() if e[0][2] == function ]
+ matches = [ e for e in list(statistics.items()) if e[0][2] == function ]
r = matches[0]
return r[0][0], r[0][1], r[0][2], r[1][3]
@@ -751,7 +752,7 @@ class SConsTimer(object):
return self.default(argv)
try:
return func(argv)
- except TypeError, e:
+ except TypeError as e:
sys.stderr.write("%s %s: %s\n" % (self.name, cmdName, e))
import traceback
traceback.print_exc(file=sys.stderr)
@@ -856,7 +857,7 @@ class SConsTimer(object):
self.title = a
if self.config_file:
- exec open(self.config_file, 'rU').read() in self.__dict__
+ exec(open(self.config_file, 'rU').read(), self.__dict__)
if self.chdir:
os.chdir(self.chdir)
@@ -889,13 +890,13 @@ class SConsTimer(object):
try:
f, line, func, time = \
self.get_function_profile(file, function_name)
- except ValueError, e:
+ except ValueError as e:
sys.stderr.write("%s: func: %s: %s\n" %
(self.name, file, e))
else:
if f.startswith(cwd_):
f = f[len(cwd_):]
- print "%.3f %s:%d(%s)" % (time, f, line, func)
+ print("%.3f %s:%d(%s)" % (time, f, line, func))
elif format == 'gnuplot':
@@ -1233,7 +1234,7 @@ class SConsTimer(object):
sys.exit(1)
if self.config_file:
- exec open(self.config_file, 'rU').read() in self.__dict__
+ exec(open(self.config_file, 'rU').read(), self.__dict__)
if args:
self.archive_list = args
@@ -1466,7 +1467,7 @@ class SConsTimer(object):
elif o in ('--title',):
self.title = a
elif o in ('--which',):
- if not a in self.time_strings.keys():
+ if not a in list(self.time_strings.keys()):
sys.stderr.write('%s: time: Unrecognized timer "%s".\n' % (self.name, a))
sys.stderr.write('%s Type "%s help time" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
diff --git a/src/script/sconsign.py b/src/script/sconsign.py
index e5e9d4f..323d1bf 100644
--- a/src/script/sconsign.py
+++ b/src/script/sconsign.py
@@ -171,7 +171,7 @@ sys.path = libs + sys.path
import SCons.compat # so pickle will import cPickle instead
-import whichdb
+import dbm
import time
import pickle
import imp
@@ -189,8 +189,8 @@ def my_whichdb(filename):
pass
return _orig_whichdb(filename)
-_orig_whichdb = whichdb.whichdb
-whichdb.whichdb = my_whichdb
+_orig_whichdb = dbm.whichdb
+dbm.whichdb = my_whichdb
def my_import(mname):
if '.' in mname:
@@ -310,14 +310,14 @@ def printfield(name, entry, prefix=""):
outlist = field("implicit", entry, 0)
if outlist:
if Verbose:
- print " implicit:"
- print " " + outlist
+ print(" implicit:")
+ print(" " + outlist)
outact = field("action", entry, 0)
if outact:
if Verbose:
- print " action: " + outact
+ print(" action: " + outact)
else:
- print " " + outact
+ print(" " + outact)
def printentries(entries, location):
if Print_Entries:
@@ -330,9 +330,9 @@ def printentries(entries, location):
try:
ninfo = entry.ninfo
except AttributeError:
- print name + ":"
+ print(name + ":")
else:
- print nodeinfo_string(name, entry.ninfo)
+ print(nodeinfo_string(name, entry.ninfo))
printfield(name, entry.binfo)
else:
for name in sorted(entries.keys()):
@@ -340,9 +340,9 @@ def printentries(entries, location):
try:
ninfo = entry.ninfo
except AttributeError:
- print name + ":"
+ print(name + ":")
else:
- print nodeinfo_string(name, entry.ninfo)
+ print(nodeinfo_string(name, entry.ninfo))
printfield(name, entry.binfo)
class Do_SConsignDB(object):
@@ -361,7 +361,7 @@ class Do_SConsignDB(object):
# .sconsign => .sconsign.dblite
# .sconsign.dblite => .sconsign.dblite.dblite
db = self.dbm.open(fname, "r")
- except (IOError, OSError), e:
+ except (IOError, OSError) as e:
print_e = e
try:
# That didn't work, so try opening the base name,
@@ -375,7 +375,7 @@ class Do_SConsignDB(object):
# suffix-mangling).
try:
open(fname, "r")
- except (IOError, OSError), e:
+ except (IOError, OSError) as e:
# Nope, that file doesn't even exist, so report that
# fact back.
print_e = e
@@ -386,7 +386,7 @@ class Do_SConsignDB(object):
except pickle.UnpicklingError:
sys.stderr.write("sconsign: ignoring invalid `%s' file `%s'\n" % (self.dbm_name, fname))
return
- except Exception, e:
+ except Exception as e:
sys.stderr.write("sconsign: ignoring invalid `%s' file `%s': %s\n" % (self.dbm_name, fname, e))
return
@@ -403,13 +403,13 @@ class Do_SConsignDB(object):
self.printentries(dir, db[dir])
def printentries(self, dir, val):
- print '=== ' + dir + ':'
+ print('=== ' + dir + ':')
printentries(pickle.loads(val), dir)
def Do_SConsignDir(name):
try:
fp = open(name, 'rb')
- except (IOError, OSError), e:
+ except (IOError, OSError) as e:
sys.stderr.write("sconsign: %s\n" % (e))
return
try:
@@ -419,7 +419,7 @@ def Do_SConsignDir(name):
except pickle.UnpicklingError:
sys.stderr.write("sconsign: ignoring invalid .sconsign file `%s'\n" % (name))
return
- except Exception, e:
+ except Exception as e:
sys.stderr.write("sconsign: ignoring invalid .sconsign file `%s': %s\n" % (name, e))
return
printentries(sconsign.entries, args[0])
@@ -471,13 +471,13 @@ for o, a in opts:
dbm = my_import(dbm_name)
except:
sys.stderr.write("sconsign: illegal file format `%s'\n" % a)
- print helpstr
+ print(helpstr)
sys.exit(2)
Do_Call = Do_SConsignDB(a, dbm)
else:
Do_Call = Do_SConsignDir
elif o in ('-h', '--help'):
- print helpstr
+ print(helpstr)
sys.exit(0)
elif o in ('-i', '--implicit'):
Print_Flags['implicit'] = 1
@@ -497,7 +497,7 @@ if Do_Call:
Do_Call(a)
else:
for a in args:
- dbm_name = whichdb.whichdb(a)
+ dbm_name = dbm.whichdb(a)
if dbm_name:
Map_Module = {'SCons.dblite' : 'dblite'}
dbm = my_import(dbm_name)
diff --git a/src/test_files.py b/src/test_files.py
index 7d8e75e..d71329b 100644
--- a/src/test_files.py
+++ b/src/test_files.py
@@ -77,7 +77,7 @@ check = {
missing = []
no_result = []
-for directory, check_list in check.items():
+for directory, check_list in list(check.items()):
if os.path.exists(directory):
for c in check_list:
f = os.path.join(directory, c)
@@ -87,13 +87,13 @@ for directory, check_list in check.items():
no_result.append(directory)
if missing:
- print "Missing the following files:\n"
- print "\t" + "\n\t".join(missing)
+ print("Missing the following files:\n")
+ print("\t" + "\n\t".join(missing))
test.fail_test(1)
if no_result:
- print "Cannot check files, the following have apparently not been built:"
- print "\t" + "\n\t".join(no_result)
+ print("Cannot check files, the following have apparently not been built:")
+ print("\t" + "\n\t".join(no_result))
test.no_result(1)
test.pass_test()
diff --git a/src/test_interrupts.py b/src/test_interrupts.py
index fb12e2a..1e027a1 100644
--- a/src/test_interrupts.py
+++ b/src/test_interrupts.py
@@ -102,7 +102,7 @@ for f in files:
indent_list.append( (line_num, match.group('try_or_except') ) )
try_except_lines[match.group('indent')] = indent_list
uncaught_this_file = []
- for indent in try_except_lines.keys():
+ for indent in list(try_except_lines.keys()):
exc_keyboardint_seen = 0
exc_all_seen = 0
for (l,statement) in try_except_lines[indent] + [(-1,indent + 'try')]:
@@ -129,9 +129,9 @@ for f in files:
if expected_num != len(uncaught_this_file):
uncaughtKeyboardInterrupt = 1
msg = "%s: expected %d uncaught interrupts, got %d:"
- print msg % (f, expected_num, len(uncaught_this_file))
+ print(msg % (f, expected_num, len(uncaught_this_file)))
for line in uncaught_this_file:
- print " File %s:%d: Uncaught KeyboardInterrupt!" % (f,line)
+ print(" File %s:%d: Uncaught KeyboardInterrupt!" % (f,line))
test.fail_test(uncaughtKeyboardInterrupt)
diff --git a/src/test_pychecker.py b/src/test_pychecker.py
index f87d303..24aa966 100644
--- a/src/test_pychecker.py
+++ b/src/test_pychecker.py
@@ -139,7 +139,7 @@ for file in files:
mismatches.append(stderr)
if mismatches:
- print ''.join(mismatches[1:])
+ print(''.join(mismatches[1:]))
test.fail_test()
test.pass_test()
diff --git a/src/test_setup.py b/src/test_setup.py
index 29d36bf..731fbe7 100644
--- a/src/test_setup.py
+++ b/src/test_setup.py
@@ -197,9 +197,9 @@ if not os.path.isdir(scons_version) and os.path.isfile(tar_gz):
os.system("gunzip -c %s | tar xf -" % tar_gz)
if not os.path.isdir(scons_version):
- print "Cannot test package installation, found none of the following packages:"
- print "\t" + tar_gz
- print "\t" + zip
+ print("Cannot test package installation, found none of the following packages:")
+ print("\t" + tar_gz)
+ print("\t" + zip)
test.no_result(1)
# Verify that a virgin installation installs the version library,
diff --git a/src/test_strings.py b/src/test_strings.py
index 3288d5f..b57c714 100644
--- a/src/test_strings.py
+++ b/src/test_strings.py
@@ -248,13 +248,13 @@ for collector in check_list:
not_built.append(collector.directory)
if missing_strings:
- print "Found the following files with missing strings:"
- print "\t" + "\n\t".join(missing_strings)
+ print("Found the following files with missing strings:")
+ print("\t" + "\n\t".join(missing_strings))
test.fail_test(1)
if not_built:
- print "Cannot check all strings, the following have apparently not been built:"
- print "\t" + "\n\t".join(not_built)
+ print("Cannot check all strings, the following have apparently not been built:")
+ print("\t" + "\n\t".join(not_built))
test.no_result(1)
test.pass_test()