summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/CHANGES.txt4
-rw-r--r--src/engine/SCons/Action.py59
-rw-r--r--src/engine/SCons/ActionTests.py78
-rw-r--r--src/engine/SCons/Builder.py16
-rw-r--r--src/engine/SCons/BuilderTests.py43
-rw-r--r--src/engine/SCons/CacheDirTests.py2
-rw-r--r--src/engine/SCons/Conftest.py3
-rw-r--r--src/engine/SCons/Defaults.py7
-rw-r--r--src/engine/SCons/DefaultsTests.py2
-rw-r--r--src/engine/SCons/Environment.py28
-rw-r--r--src/engine/SCons/EnvironmentTests.py61
-rw-r--r--src/engine/SCons/Errors.py4
-rw-r--r--src/engine/SCons/ErrorsTests.py12
-rw-r--r--src/engine/SCons/Executor.py6
-rw-r--r--src/engine/SCons/ExecutorTests.py2
-rw-r--r--src/engine/SCons/Job.py4
-rw-r--r--src/engine/SCons/Memoize.py11
-rw-r--r--src/engine/SCons/MemoizeTests.py5
-rw-r--r--src/engine/SCons/Node/FS.py17
-rw-r--r--src/engine/SCons/Node/FSTests.py32
-rw-r--r--src/engine/SCons/Node/__init__.py8
-rw-r--r--src/engine/SCons/Options/__init__.py10
-rw-r--r--src/engine/SCons/Platform/__init__.py5
-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/sunos.py2
-rw-r--r--src/engine/SCons/Platform/win32.py26
-rw-r--r--src/engine/SCons/SConf.py7
-rw-r--r--src/engine/SCons/SConfTests.py2
-rw-r--r--src/engine/SCons/SConsign.py9
-rw-r--r--src/engine/SCons/Scanner/C.py2
-rw-r--r--src/engine/SCons/Scanner/ProgTests.py2
-rw-r--r--src/engine/SCons/Scanner/ScannerTests.py2
-rw-r--r--src/engine/SCons/Scanner/__init__.py11
-rw-r--r--src/engine/SCons/Script/Interactive.py9
-rw-r--r--src/engine/SCons/Script/Main.py60
-rw-r--r--src/engine/SCons/Script/SConsOptions.py6
-rw-r--r--src/engine/SCons/Script/SConscript.py20
-rw-r--r--src/engine/SCons/Script/__init__.py8
-rw-r--r--src/engine/SCons/Subst.py4
-rw-r--r--src/engine/SCons/SubstTests.py49
-rw-r--r--src/engine/SCons/Taskmaster.py31
-rw-r--r--src/engine/SCons/TaskmasterTests.py8
-rw-r--r--src/engine/SCons/Tool/386asm.py2
-rw-r--r--src/engine/SCons/Tool/FortranCommon.py7
-rw-r--r--src/engine/SCons/Tool/GettextCommon.py12
-rw-r--r--src/engine/SCons/Tool/MSCommon/common.py8
-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.py58
-rw-r--r--src/engine/SCons/Tool/MSCommon/vs.py4
-rw-r--r--src/engine/SCons/Tool/__init__.py39
-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.py3
-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/__init__.py2
-rw-r--r--src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/docbook.py11
-rw-r--r--src/engine/SCons/Tool/docbook/docbook-xsl-1.76.1/extensions/xslt.py13
-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/g++.py5
-rw-r--r--src/engine/SCons/Tool/gas.py5
-rw-r--r--src/engine/SCons/Tool/gcc.py6
-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.py4
-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.py27
-rw-r--r--src/engine/SCons/Tool/intelc.py15
-rw-r--r--src/engine/SCons/Tool/latex.py4
-rw-r--r--src/engine/SCons/Tool/link.py22
-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.py15
-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.py29
-rw-r--r--src/engine/SCons/Tool/msvsTests.py3
-rw-r--r--src/engine/SCons/Tool/packaging/__init__.py8
-rw-r--r--src/engine/SCons/Tool/packaging/msi.py2
-rw-r--r--src/engine/SCons/Tool/packaging/rpm.py8
-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.py13
-rw-r--r--src/engine/SCons/Tool/rpmutils.py7
-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/swig.py2
-rw-r--r--src/engine/SCons/Tool/tex.py99
-rw-r--r--src/engine/SCons/Tool/textfile.py2
-rw-r--r--src/engine/SCons/Tool/xgettext.py35
-rw-r--r--src/engine/SCons/Util.py106
-rw-r--r--src/engine/SCons/UtilTests.py19
-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__.py16
-rw-r--r--src/engine/SCons/compat/__init__.py2
-rw-r--r--src/engine/SCons/compat/_scons_subprocess.py42
-rwxr-xr-xsrc/engine/SCons/compat/six.py646
-rw-r--r--src/engine/SCons/compat/sixTests.py34
-rw-r--r--src/engine/SCons/dblite.py31
-rw-r--r--src/script/scons-time.py37
-rw-r--r--src/script/scons.py12
-rw-r--r--src/script/sconsign.py50
-rw-r--r--src/setup.py8
-rw-r--r--src/test_files.py9
-rw-r--r--src/test_interrupts.py4
-rw-r--r--src/test_pychecker.py3
-rw-r--r--src/test_setup.py7
-rw-r--r--src/test_strings.py9
131 files changed, 1526 insertions, 764 deletions
diff --git a/src/CHANGES.txt b/src/CHANGES.txt
index cf4264a..aaf3bc8 100644
--- a/src/CHANGES.txt
+++ b/src/CHANGES.txt
@@ -6,6 +6,9 @@
RELEASE 2.3.2.alpha.yyyymmdd - NEW DATE WILL BE INSERTED HERE
+ From Neal Becker and Stefan Zimmermann:
+ - Python 3 port and compatibility
+
From Anatoly Techtonik:
- Do not fail on EnsureSConsVersion when running from checkout
@@ -46,6 +49,7 @@ RELEASE 2.3.2
From Paweł Tomulik:
- Fix SConf tests that write output
+>>>>>>> other
From Gary Oberbrunner:
- get default RPM architecture more robustly when building RPMs
diff --git a/src/engine/SCons/Action.py b/src/engine/SCons/Action.py
index 1c746be..415cc9a 100644
--- a/src/engine/SCons/Action.py
+++ b/src/engine/SCons/Action.py
@@ -166,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:
@@ -191,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:
@@ -237,9 +237,9 @@ def _code_contents(code):
# The code contents depends on the number of local variables
# but not their actual names.
- contents.append("%s,%s" % (code.co_argcount, len(code.co_varnames)))
+ contents.append(str.encode("%s,%s" % (code.co_argcount, len(code.co_varnames))))
try:
- contents.append(",%s,%s" % (len(code.co_cellvars), len(code.co_freevars)))
+ contents.append(str.encode(",%s,%s" % (len(code.co_cellvars), len(code.co_freevars))))
except AttributeError:
# Older versions of Python do not support closures.
contents.append(",0,0")
@@ -252,35 +252,35 @@ def _code_contents(code):
# Note that we also always ignore the first entry of co_consts
# which contains the function doc string. We assume that the
# function does not access its doc string.
- contents.append(',(' + ','.join(map(_object_contents,code.co_consts[1:])) + ')')
+ contents.append(b',(' + b','.join(map(_object_contents,code.co_consts[1:])) + b')')
# The code contents depends on the variable names used to
# accessed global variable, as changing the variable name changes
# the variable actually accessed and therefore changes the
# function result.
- contents.append(',(' + ','.join(map(_object_contents,code.co_names)) + ')')
+ contents.append(b',(' + b','.join(map(_object_contents,code.co_names)) + b')')
# The code contents depends on its actual code!!!
- contents.append(',(' + str(remove_set_lineno_codes(code.co_code)) + ')')
+ contents.append(b',(' + remove_set_lineno_codes(code.co_code) + b')')
- return ''.join(contents)
+ return b''.join(contents)
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(b',(' + b','.join(map(_object_contents,func.__defaults__)) + b')')
else:
- contents.append(',()')
+ contents.append(b',()')
# 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 = []
@@ -290,9 +290,9 @@ def _function_contents(func):
xxx = [_object_contents(x.cell_contents) for x in closure]
except AttributeError:
xxx = []
- contents.append(',(' + ','.join(xxx) + ')')
+ contents.append(b',(' + ','.join(xxx).encode('ascii') + b')')
- return ''.join(contents)
+ return b''.join(contents)
def _actionAppend(act1, act2):
@@ -421,8 +421,8 @@ class ActionBase(object):
other objects (Builders, Executors, etc.) This provides the
common methods for manipulating and combining those actions."""
- def __cmp__(self, other):
- return cmp(self.__dict__, other)
+ def __eq__(self, other):
+ return self.__dict__ == other
def no_batch_key(self, env, target, source):
return None
@@ -434,6 +434,7 @@ class ActionBase(object):
def get_contents(self, target, source, env):
result = [ self.get_presig(target, source, env) ]
+ result = [ SCons.Util.to_bytes(r) for r in result ]
# This should never happen, as the Action() factory should wrap
# the varlist, but just in case an action is created directly,
# we duplicate this check here.
@@ -441,8 +442,8 @@ class ActionBase(object):
if is_String(vl): vl = (vl,)
for v in vl:
# do the subst this way to ignore $(...$) parts:
- result.append(env.subst_target_source('${'+v+'}', SCons.Subst.SUBST_SIG, target, source))
- return ''.join(result)
+ result.append(SCons.Util.to_bytes(env.subst_target_source('${'+v+'}', SCons.Subst.SUBST_SIG, target, source)))
+ return b''.join(result)
def __add__(self, other):
return _actionAppend(self, other)
@@ -514,7 +515,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(s + u"\n")
except UnicodeDecodeError:
sys.stdout.write(s + "\n")
@@ -674,7 +675,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):
@@ -1063,11 +1064,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()
@@ -1137,7 +1138,7 @@ class ListAction(ActionBase):
Simple concatenation of the signatures of the elements.
"""
- return "".join([x.get_contents(target, source, env) for x in self.list])
+ return b"".join([x.get_contents(target, source, env) for x in self.list])
def __call__(self, target, source, env, exitstatfunc=_null, presub=_null,
show=_null, execute=_null, chdir=_null, executor=None):
@@ -1182,11 +1183,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.
diff --git a/src/engine/SCons/ActionTests.py b/src/engine/SCons/ActionTests.py
index b46347d..8038f7c 100644
--- a/src/engine/SCons/ActionTests.py
+++ b/src/engine/SCons/ActionTests.py
@@ -63,7 +63,7 @@ test = TestCmd.TestCmd(workdir = '')
test.write('act.py', """\
import os, string, sys
f = open(sys.argv[1], 'w')
-f.write("act.py: '" + string.join(sys.argv[2:], "' '") + "'\\n")
+f.write("act.py: '" + "' '".join(sys.argv[2:]) + "'\\n")
try:
if sys.argv[3]:
f.write("act.py: '" + os.environ[sys.argv[3]] + "'\\n")
@@ -273,7 +273,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
@@ -496,7 +496,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
@@ -1329,7 +1329,7 @@ class CommandActionTestCase(unittest.TestCase):
c = a.get_contents(target=[], source=[],
env=Environment(foo = 'FFF', bar = 'BBB',
baz = CmdGen))
- assert c == "| | FFF BBB 1", c
+ assert c == b"| | FFF BBB 1", c
# Make sure that CommandActions use an Environment's
# subst_target_source() method for substitution.
@@ -1340,7 +1340,7 @@ class CommandActionTestCase(unittest.TestCase):
c = a.get_contents(target=DummyNode('ttt'), source = DummyNode('sss'),
env=SpecialEnvironment(foo = 'GGG', bar = 'CCC',
baz = 'ZZZ'))
- assert c == 'subst_target_source: | $( $foo | $bar $) | $baz 1', c
+ assert c == b'subst_target_source: | $( $foo | $bar $) | $baz 1', c
# We've discussed using the real target and source names in a
# CommandAction's signature contents. This would have have the
@@ -1357,35 +1357,35 @@ class CommandActionTestCase(unittest.TestCase):
a = SCons.Action.CommandAction(["$TARGET"])
c = a.get_contents(target=t, source=s, env=env)
- assert c == "t1", c
+ assert c == b"t1", c
a = SCons.Action.CommandAction(["$TARGETS"])
c = a.get_contents(target=t, source=s, env=env)
- assert c == "t1 t2 t3 t4 t5 t6", c
+ assert c == b"t1 t2 t3 t4 t5 t6", c
a = SCons.Action.CommandAction(["${TARGETS[2]}"])
c = a.get_contents(target=t, source=s, env=env)
- assert c == "t3", c
+ assert c == b"t3", c
a = SCons.Action.CommandAction(["${TARGETS[3:5]}"])
c = a.get_contents(target=t, source=s, env=env)
- assert c == "t4 t5", c
+ assert c == b"t4 t5", c
a = SCons.Action.CommandAction(["$SOURCE"])
c = a.get_contents(target=t, source=s, env=env)
- assert c == "s1", c
+ assert c == b"s1", c
a = SCons.Action.CommandAction(["$SOURCES"])
c = a.get_contents(target=t, source=s, env=env)
- assert c == "s1 s2 s3 s4 s5 s6", c
+ assert c == b"s1 s2 s3 s4 s5 s6", c
a = SCons.Action.CommandAction(["${SOURCES[2]}"])
c = a.get_contents(target=t, source=s, env=env)
- assert c == "s3", c
+ assert c == b"s3", c
a = SCons.Action.CommandAction(["${SOURCES[3:5]}"])
c = a.get_contents(target=t, source=s, env=env)
- assert c == "s4 s5", c
+ assert c == b"s4 s5", c
class CommandGeneratorActionTestCase(unittest.TestCase):
@@ -1502,7 +1502,7 @@ class CommandGeneratorActionTestCase(unittest.TestCase):
ignore = 'foo', test=test)
a = self.factory(f)
c = a.get_contents(target=[], source=[], env=env)
- assert c == "guux FFF BBB test", c
+ assert c == b"guux FFF BBB test", c
def test_get_contents_of_function_action(self):
"""Test contents of a CommandGeneratorAction-generated FunctionAction
@@ -1512,13 +1512,13 @@ class CommandGeneratorActionTestCase(unittest.TestCase):
pass
func_matches = [
- "0,0,0,0,(),(),(d\000\000S),(),()",
- "0,0,0,0,(),(),(d\x00\x00S),(),()",
+ b"0,0,0,0,(),(),(d\000\000S),(),()",
+ b"0,0,0,0,(),(),(d\x00\x00S),(),()",
]
meth_matches = [
- "1,1,0,0,(),(),(d\000\000S),(),()",
- "1,1,0,0,(),(),(d\x00\x00S),(),()",
+ b"1,1,0,0,(),(),(d\000\000S),(),()",
+ b"1,1,0,0,(),(),(d\x00\x00S),(),()",
]
def f_global(target, source, env, for_signature):
@@ -1543,7 +1543,7 @@ class CommandGeneratorActionTestCase(unittest.TestCase):
def f_local(target, source, env, for_signature):
return SCons.Action.Action(LocalFunc, varlist=['XYZ'])
- matches_foo = [x + "foo" for x in func_matches]
+ matches_foo = [x + b"foo" for x in func_matches]
a = self.factory(f_global)
c = a.get_contents(target=[], source=[], env=env)
@@ -1671,13 +1671,13 @@ class FunctionActionTestCase(unittest.TestCase):
pass
func_matches = [
- "0,0,0,0,(),(),(d\000\000S),(),()",
- "0,0,0,0,(),(),(d\x00\x00S),(),()",
+ b"0,0,0,0,(),(),(d\000\000S),(),()",
+ b"0,0,0,0,(),(),(d\x00\x00S),(),()",
]
meth_matches = [
- "1,1,0,0,(),(),(d\000\000S),(),()",
- "1,1,0,0,(),(),(d\x00\x00S),(),()",
+ b"1,1,0,0,(),(),(d\000\000S),(),()",
+ b"1,1,0,0,(),(),(d\x00\x00S),(),()",
]
def factory(act, **kw):
@@ -1691,7 +1691,7 @@ class FunctionActionTestCase(unittest.TestCase):
c = a.get_contents(target=[], source=[], env=Environment())
assert c in func_matches, repr(c)
- matches_foo = [x + "foo" for x in func_matches]
+ matches_foo = [x + b"foo" for x in func_matches]
a = factory(GlobalFunc, varlist=['XYZ'])
c = a.get_contents(target=[], source=[], env=Environment())
@@ -1709,10 +1709,10 @@ class FunctionActionTestCase(unittest.TestCase):
class Foo(object):
def get_contents(self, target, source, env):
- return 'xyzzy'
+ return b'xyzzy'
a = factory(Foo())
c = a.get_contents(target=[], source=[], env=Environment())
- assert c == 'xyzzy', repr(c)
+ assert c == b'xyzzy', repr(c)
class LocalClass(object):
def LocalMethod(self):
@@ -1823,7 +1823,7 @@ class ListActionTestCase(unittest.TestCase):
"z"])
c = a.get_contents(target=[], source=[], env=Environment(s = self))
assert self.foo==1, self.foo
- assert c == "xyz", c
+ assert c == b"xyz", c
class LazyActionTestCase(unittest.TestCase):
def test___init__(self):
@@ -1874,7 +1874,7 @@ class LazyActionTestCase(unittest.TestCase):
a = SCons.Action.Action("${FOO}")
env = Environment(FOO = [["This", "is", "a", "test"]])
c = a.get_contents(target=[], source=[], env=env)
- assert c == "This is a test", c
+ assert c == b"This is a test", c
def test_get_contents_of_function_action(self):
"""Test fetching the contents of a lazy-evaluation FunctionAction
@@ -1884,13 +1884,13 @@ class LazyActionTestCase(unittest.TestCase):
pass
func_matches = [
- "0,0,0,0,(),(),(d\000\000S),(),()",
- "0,0,0,0,(),(),(d\x00\x00S),(),()",
+ b"0,0,0,0,(),(),(d\000\000S),(),()",
+ b"0,0,0,0,(),(),(d\x00\x00S),(),()",
]
meth_matches = [
- "1,1,0,0,(),(),(d\000\000S),(),()",
- "1,1,0,0,(),(),(d\x00\x00S),(),()",
+ b"1,1,0,0,(),(),(d\000\000S),(),()",
+ b"1,1,0,0,(),(),(d\x00\x00S),(),()",
]
def factory(act, **kw):
@@ -1907,7 +1907,7 @@ class LazyActionTestCase(unittest.TestCase):
c = a.get_contents(target=[], source=[], env=env)
assert c in func_matches, repr(c)
- matches_foo = [x + "foo" for x in func_matches]
+ matches_foo = [x + b"foo" for x in func_matches]
env = Environment(FOO = factory(GlobalFunc, varlist=['XYZ']))
c = a.get_contents(target=[], source=[], env=env)
@@ -1934,8 +1934,8 @@ class ActionCallerTestCase(unittest.TestCase):
pass
matches = [
- "d\000\000S",
- "d\x00\x00S"
+ b"d\000\000S",
+ b"d\x00\x00S"
]
af = SCons.Action.ActionFactory(GlobalFunc, strfunc)
@@ -1949,8 +1949,8 @@ class ActionCallerTestCase(unittest.TestCase):
assert c in matches, repr(c)
matches = [
- 'd\000\000S',
- "d\x00\x00S"
+ b'd\000\000S',
+ b"d\x00\x00S"
]
class LocalActFunc(object):
@@ -1968,8 +1968,8 @@ class ActionCallerTestCase(unittest.TestCase):
assert c in matches, repr(c)
matches = [
- "<built-in function str>",
- "<type 'str'>",
+ b"<built-in function str>",
+ b"<type 'str'>",
]
af = SCons.Action.ActionFactory(str, strfunc)
diff --git a/src/engine/SCons/Builder.py b/src/engine/SCons/Builder.py
index ed7650a..db249bf 100644
--- a/src/engine/SCons/Builder.py
+++ b/src/engine/SCons/Builder.py
@@ -168,7 +168,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." % \
@@ -346,8 +346,11 @@ class EmitterProxy(object):
return (target, source)
- def __cmp__(self, other):
- return cmp(self.var, other.var)
+ def __eq__(self, other):
+ return self.var == other.var
+
+ def __lt__(self, other):
+ return self.var < other.var
class BuilderBase(object):
"""Base class for Builders, objects that create output
@@ -430,6 +433,9 @@ class BuilderBase(object):
def __nonzero__(self):
raise InternalError("Do not test for the Node.builder attribute directly; use Node.has_builder() instead")
+ def __bool__(self):
+ return self.__nonzero__()
+
def get_name(self, env):
"""Attempts to get the name of the Builder.
@@ -447,8 +453,8 @@ class BuilderBase(object):
except AttributeError:
return str(self.__class__)
- def __cmp__(self, other):
- return cmp(self.__dict__, other.__dict__)
+ def __eq__(self, other):
+ return self.__dict__ == other.__dict__
def splitext(self, path, env=None):
if not env:
diff --git a/src/engine/SCons/BuilderTests.py b/src/engine/SCons/BuilderTests.py
index 70a7a3f..212872f 100644
--- a/src/engine/SCons/BuilderTests.py
+++ b/src/engine/SCons/BuilderTests.py
@@ -20,6 +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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -145,8 +146,8 @@ class Environment(object):
d['SOURCES'] = ['__s1__', '__s2__', '__s3__', '__s4__', '__s5__', '__s6__']
d['SOURCE'] = d['SOURCES'][0]
return d
- def __cmp__(self, other):
- return cmp(self.scanner, other.scanner) or cmp(self.d, other.d)
+ def __eq__(self, other):
+ return self.scanner == other.scanner or self.d == other.d
class MyAction(object):
def __init__(self, action):
@@ -326,7 +327,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."
@@ -342,7 +343,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.")
@@ -1498,11 +1499,12 @@ 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
+ err = e
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"
- assert str(e) == expect, e
+ assert str(err) == expect, err
def test_source_ext_match(self):
"""Test the CompositeBuilder source_ext_match argument"""
@@ -1529,8 +1531,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'
@@ -1582,47 +1584,52 @@ 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
+ err = e
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"
- assert str(e) == expect, e
+ assert str(err) == expect, err
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
+ err = e
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"
- assert str(e) == expect, e
+ assert str(err) == expect, err
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
+ err = e
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"
- assert str(e) == expect, e
+ assert str(err) == expect, err
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
+ err = e
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']"
- assert str(e) == expect, e
+ assert str(err) == expect, err
flag = 0
try:
builder(env, target='t8', source=['test8.unknown'])[0]
- except SCons.Errors.UserError, e:
+ except SCons.Errors.UserError as e:
flag = 1
+ err = e
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']."
- assert str(e) == expect, e
+ assert str(err) == expect, err
if __name__ == "__main__":
suite = unittest.TestSuite()
diff --git a/src/engine/SCons/CacheDirTests.py b/src/engine/SCons/CacheDirTests.py
index 7ac97ef..878a87a 100644
--- a/src/engine/SCons/CacheDirTests.py
+++ b/src/engine/SCons/CacheDirTests.py
@@ -242,7 +242,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/Conftest.py b/src/engine/SCons/Conftest.py
index e9702ff..23441f1 100644
--- a/src/engine/SCons/Conftest.py
+++ b/src/engine/SCons/Conftest.py
@@ -101,7 +101,6 @@ Autoconf-like configuration support; low level implementation of tests.
#
import re
-from types import IntType
#
# PUBLIC VARIABLES
@@ -729,7 +728,7 @@ def _Have(context, key, have, comment = None):
line = "#define %s 1\n" % key_up
elif have == 0:
line = "/* #undef %s */\n" % key_up
- elif isinstance(have, IntType):
+ elif isinstance(have, int):
line = "#define %s %d\n" % (key_up, have)
else:
line = "#define %s %s\n" % (key_up, str(have))
diff --git a/src/engine/SCons/Defaults.py b/src/engine/SCons/Defaults.py
index 3f60bc0..2eb9c86 100644
--- a/src/engine/SCons/Defaults.py
+++ b/src/engine/SCons/Defaults.py
@@ -204,7 +204,8 @@ def copy_func(dest, src, symlinks=True):
else:
return copy_func(dest, linkto, symlinks)
elif os.path.isfile(src):
- return shutil.copy2(src, dest)
+ shutil.copy2(src, dest)
+ return 0
else:
return shutil.copytree(src, dest, symlinks)
@@ -241,7 +242,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)) \
@@ -401,7 +402,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 8b9fb4e..141243b 100644
--- a/src/engine/SCons/DefaultsTests.py
+++ b/src/engine/SCons/DefaultsTests.py
@@ -70,7 +70,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 62d6809..59390f7 100644
--- a/src/engine/SCons/Environment.py
+++ b/src/engine/SCons/Environment.py
@@ -128,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)
@@ -147,7 +147,7 @@ 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)
@@ -399,8 +399,8 @@ class SubstitutionEnvironment(object):
# gotten better than dict.has_key() in Python 2.5.)
self._special_set_keys = list(self._special_set.keys())
- def __cmp__(self, other):
- return cmp(self._dict, other._dict)
+ def __eq__(self, other):
+ return self._dict == other._dict
def __delitem__(self, key):
special = self._special_del.get(key)
@@ -592,7 +592,7 @@ class SubstitutionEnvironment(object):
out,err = p.communicate()
status = p.wait()
if err:
- sys.stderr.write(unicode(err))
+ sys.stderr.write(u"" + err)
if status:
raise OSError("'%s' exited %d" % (command, status))
return out
@@ -1153,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"
@@ -1223,7 +1223,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
@@ -1352,7 +1352,7 @@ class Base(SubstitutionEnvironment):
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]
@@ -1361,7 +1361,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:
@@ -1385,7 +1385,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:
@@ -1681,7 +1681,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
@@ -1793,7 +1793,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)
@@ -2268,7 +2268,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))
@@ -2411,7 +2411,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 b9ef3f2..2a3852f 100644
--- a/src/engine/SCons/EnvironmentTests.py
+++ b/src/engine/SCons/EnvironmentTests.py
@@ -20,6 +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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -114,11 +115,11 @@ class Scanner(object):
global scanned_it
scanned_it[filename] = 1
- def __cmp__(self, other):
+ def __eq__(self, other):
try:
- return cmp(self.__dict__, other.__dict__)
+ return self.__dict__ == other.__dict__
except AttributeError:
- return 1
+ return False
def get_skeys(self, env):
return self.skeys
@@ -265,16 +266,10 @@ class SubstitutionTestCase(unittest.TestCase):
assert isinstance(nodes[0], X)
assert nodes[0].name == "Util.py UtilTests.py"
- try: unicode
- except NameError: pass
- else:
- code = """if 1:
- nodes = env.arg2nodes(u"Util.py UtilTests.py", Factory)
- assert len(nodes) == 1, nodes
- assert isinstance(nodes[0], X)
- assert nodes[0].name == u"Util.py UtilTests.py"
- \n"""
- exec code in globals(), locals()
+ nodes = env.arg2nodes(u"Util.py UtilTests.py", Factory)
+ assert len(nodes) == 1, nodes
+ assert isinstance(nodes[0], X)
+ assert nodes[0].name == u"Util.py UtilTests.py"
nodes = env.arg2nodes(["Util.py", "UtilTests.py"], Factory)
assert len(nodes) == 2, nodes
@@ -657,7 +652,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")
@@ -1588,17 +1583,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
@@ -1620,7 +1615,7 @@ def exists(env):
self.name = name
def __str__(self):
return self.name
- def __cmp__(self, other):
+ def __eq__(self, other):
raise Exception("should not compare")
ccc = C('ccc')
@@ -1948,7 +1943,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] })
@@ -1956,7 +1951,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
@@ -2271,17 +2266,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
@@ -2519,10 +2514,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/Errors.py b/src/engine/SCons/Errors.py
index 3b8c3f9..54e888c 100644
--- a/src/engine/SCons/Errors.py
+++ b/src/engine/SCons/Errors.py
@@ -32,8 +32,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Util
-import exceptions
-
class BuildError(Exception):
""" Errors occuring while building.
@@ -163,7 +161,7 @@ def convert_to_BuildError(status, exc_info=None):
status=2,
exitstatus=2,
exc_info=exc_info)
- elif isinstance(status, exceptions.EnvironmentError):
+ elif isinstance(status, EnvironmentError):
# If an IOError/OSError happens, raise a BuildError.
# Report the name of the file or directory that caused the
# error, which might be different from the target being built
diff --git a/src/engine/SCons/ErrorsTests.py b/src/engine/SCons/ErrorsTests.py
index d57faa5..c38158d 100644
--- a/src/engine/SCons/ErrorsTests.py
+++ b/src/engine/SCons/ErrorsTests.py
@@ -38,7 +38,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
@@ -53,7 +53,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
@@ -67,7 +67,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
@@ -83,21 +83,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/Executor.py b/src/engine/SCons/Executor.py
index 051d275..2c53f21 100644
--- a/src/engine/SCons/Executor.py
+++ b/src/engine/SCons/Executor.py
@@ -431,9 +431,9 @@ class Executor(object):
except KeyError:
pass
env = self.get_build_env()
- result = "".join([action.get_contents(self.get_all_targets(),
- self.get_all_sources(),
- env)
+ result = b"".join([action.get_contents(self.get_all_targets(),
+ self.get_all_sources(),
+ env)
for action in self.get_action_list()])
self._memo['get_contents'] = result
return result
diff --git a/src/engine/SCons/ExecutorTests.py b/src/engine/SCons/ExecutorTests.py
index 9df0b2d..c649f0e 100644
--- a/src/engine/SCons/ExecutorTests.py
+++ b/src/engine/SCons/ExecutorTests.py
@@ -309,7 +309,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..d2938c7 100644
--- a/src/engine/SCons/Memoize.py
+++ b/src/engine/SCons/Memoize.py
@@ -20,6 +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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -143,12 +144,12 @@ class Counter(object):
CounterList.append(self)
def display(self):
fmt = " %7d hits %7d misses %s()"
- print fmt % (self.hit, self.miss, self.name)
- def __cmp__(self, other):
+ print(fmt % (self.hit, self.miss, self.name))
+ def __eq__(self, other):
try:
- return cmp(self.name, other.name)
+ return self.name == other.name
except AttributeError:
- return 0
+ return True
class CountValue(Counter):
"""
@@ -215,7 +216,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 3606d57..8476349 100644
--- a/src/engine/SCons/MemoizeTests.py
+++ b/src/engine/SCons/MemoizeTests.py
@@ -20,6 +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 SCons.compat.six import add_metaclass
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -31,11 +32,9 @@ import TestUnit
import SCons.Memoize
-
+@add_metaclass(SCons.Memoize.Memoized_Metaclass)
class FakeObject(object):
- __metaclass__ = SCons.Memoize.Memoized_Metaclass
-
memoizer_counters = []
def __init__(self):
diff --git a/src/engine/SCons/Node/FS.py b/src/engine/SCons/Node/FS.py
index 219718c..efca0c7 100644
--- a/src/engine/SCons/Node/FS.py
+++ b/src/engine/SCons/Node/FS.py
@@ -31,6 +31,7 @@ that can be used by scripts or modules looking for the canonical default.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -551,7 +552,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.
@@ -2419,11 +2420,11 @@ class File(Base):
def get_contents(self):
if not self.rexists():
- return ''
+ return b'' # Should always be bytes
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
@@ -2458,7 +2459,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
@@ -2848,7 +2849,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
@@ -2872,7 +2873,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)
@@ -2890,7 +2891,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):
@@ -2925,7 +2926,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
diff --git a/src/engine/SCons/Node/FSTests.py b/src/engine/SCons/Node/FSTests.py
index c4dc2ce..9a8763a 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
+from __future__ import division, print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -569,13 +569,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:
@@ -587,14 +587,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)
@@ -1090,7 +1090,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:
@@ -1098,7 +1098,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:
@@ -1106,7 +1106,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:
@@ -1647,7 +1647,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)
@@ -1913,9 +1913,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
@@ -2522,9 +2522,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()
@@ -3623,7 +3623,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"
@@ -3631,7 +3631,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
@@ -3640,7 +3640,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 1f62971..f13fd03 100644
--- a/src/engine/SCons/Node/__init__.py
+++ b/src/engine/SCons/Node/__init__.py
@@ -384,7 +384,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
@@ -868,7 +868,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))
@@ -887,7 +887,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))
@@ -901,7 +901,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))
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..dba3606 100644
--- a/src/engine/SCons/Platform/__init__.py
+++ b/src/engine/SCons/Platform/__init__.py
@@ -41,6 +41,7 @@ their own platform definition.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -223,8 +224,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 b6933a4..0266dc6 100644
--- a/src/engine/SCons/Platform/aix.py
+++ b/src/engine/SCons/Platform/aix.py
@@ -35,7 +35,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os
import subprocess
-import posix
+from . import posix
import SCons.Util
import SCons.Action
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/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..1e4fb2a 100644
--- a/src/engine/SCons/Platform/win32.py
+++ b/src/engine/SCons/Platform/win32.py
@@ -61,16 +61,21 @@ else:
parallel_msg = None
import builtins
-
- _builtin_file = builtins.file
+ builtin_file = getattr(builtins, 'file', None) is not None
+
+ if builtin_file:
+ _builtin_file = builtins.file
+
+ class _scons_file(_builtin_file):
+ def __init__(self, *args, **kw):
+ _builtin_file.__init__(self, *args, **kw)
+ win32api.SetHandleInformation(msvcrt.get_osfhandle(self.fileno()),
+ win32con.HANDLE_FLAG_INHERIT, 0)
+
+ builtins.file = _scons_file
+
_builtin_open = builtins.open
- class _scons_file(_builtin_file):
- def __init__(self, *args, **kw):
- _builtin_file.__init__(self, *args, **kw)
- win32api.SetHandleInformation(msvcrt.get_osfhandle(self.fileno()),
- win32con.HANDLE_FLAG_INHERIT, 0)
-
def _scons_open(*args, **kw):
fp = _builtin_open(*args, **kw)
win32api.SetHandleInformation(msvcrt.get_osfhandle(fp.fileno()),
@@ -78,7 +83,6 @@ else:
0)
return fp
- builtins.file = _scons_file
builtins.open = _scons_open
try:
@@ -155,7 +159,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 +187,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 d6a70ec..0e6967f 100644
--- a/src/engine/SCons/SConf.py
+++ b/src/engine/SCons/SConf.py
@@ -33,6 +33,7 @@ libraries are installed, if some command line options are supported etc.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -259,7 +260,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)
@@ -338,7 +339,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:
@@ -352,7 +353,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
diff --git a/src/engine/SCons/SConfTests.py b/src/engine/SCons/SConfTests.py
index 1c4b401..4ce5f5c 100644
--- a/src/engine/SCons/SConfTests.py
+++ b/src/engine/SCons/SConfTests.py
@@ -62,7 +62,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..ab8e297 100644
--- a/src/engine/SCons/SConsign.py
+++ b/src/engine/SCons/SConsign.py
@@ -26,6 +26,7 @@ Writing and reading information to the .sconsign file or files.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -84,7 +85,7 @@ def Get_DataBase(dir):
DB_sync_list.append(db)
return db, "c"
except TypeError:
- print "DataBase =", DataBase
+ print("DataBase =", DataBase)
raise
def Reset():
@@ -215,7 +216,7 @@ 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():
@@ -274,7 +275,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):
@@ -340,7 +341,7 @@ class DirFile(Dir):
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/ProgTests.py b/src/engine/SCons/Scanner/ProgTests.py
index 144addb..a5c8956 100644
--- a/src/engine/SCons/Scanner/ProgTests.py
+++ b/src/engine/SCons/Scanner/ProgTests.py
@@ -247,7 +247,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 2496534..e34dcad 100644
--- a/src/engine/SCons/Scanner/ScannerTests.py
+++ b/src/engine/SCons/Scanner/ScannerTests.py
@@ -236,7 +236,7 @@ class BaseTestCase(unittest.TestCase):
def test___cmp__(self):
"""Test the Scanner.Base class __cmp__() method"""
s = SCons.Scanner.Base(self.func, "Cmp")
- assert cmp(s, None)
+ assert s != None
def test_hash(self):
"""Test the Scanner.Base class __hash__() method"""
diff --git a/src/engine/SCons/Scanner/__init__.py b/src/engine/SCons/Scanner/__init__.py
index 562a361..5700fe9 100644
--- a/src/engine/SCons/Scanner/__init__.py
+++ b/src/engine/SCons/Scanner/__init__.py
@@ -221,12 +221,12 @@ class Base(object):
nodes.append(l)
return nodes
- def __cmp__(self, other):
+ def __eq__(self, other):
try:
- return cmp(self.__dict__, other.__dict__)
+ return self.__dict__ == other.__dict__
except AttributeError:
# other probably doesn't have a __dict__
- return cmp(self.__dict__, other)
+ return self.__dict__ == other
def __hash__(self):
return id(self)
@@ -324,7 +324,7 @@ class Classic(Current):
def __init__(self, name, suffixes, path_variable, regex, *args, **kw):
- self.cre = re.compile(regex, re.M)
+ self.cre = re.compile(SCons.Util.to_bytes(regex), re.M)
def _scan(node, env, path=(), self=self):
node = node.rfile()
@@ -393,6 +393,7 @@ class ClassicCPP(Classic):
the contained filename in group 1.
"""
def find_include(self, include, source_dir, path):
+ include = list (map (SCons.Util.to_str, include))
if include[0] == '"':
paths = (source_dir,) + tuple(path)
else:
@@ -404,7 +405,7 @@ class ClassicCPP(Classic):
return n, i
def sort_key(self, include):
- return SCons.Node.FS._my_normcase(' '.join(include))
+ return SCons.Node.FS._my_normcase(b' '.join(include))
# Local Variables:
# tab-width:4
diff --git a/src/engine/SCons/Script/Interactive.py b/src/engine/SCons/Script/Interactive.py
index ffb5096..0b28f1a 100644
--- a/src/engine/SCons/Script/Interactive.py
+++ b/src/engine/SCons/Script/Interactive.py
@@ -19,6 +19,7 @@
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -129,12 +130,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] == '!':
@@ -274,7 +275,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 +358,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 439b869..3ef88c7 100644
--- a/src/engine/SCons/Script/Main.py
+++ b/src/engine/SCons/Script/Main.py
@@ -10,6 +10,10 @@ some other module. If it's specific to the "scons" script invocation,
it goes here.
"""
+# Would affect exec()'d site_init.py:
+## from __future__ import print_function
+from SCons.compat.six import print_
+
unsupported_python_version = (2, 3, 0)
deprecated_python_version = (2, 7, 0)
@@ -229,7 +233,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)
@@ -298,8 +302,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):
@@ -334,10 +338,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 _get_files_to_clean(self):
result = []
@@ -369,7 +373,7 @@ class CleanTask(SCons.Taskmaster.AlwaysTask):
# 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))
@@ -607,7 +611,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)
@@ -722,7 +726,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:
@@ -735,10 +739,10 @@ def _load_site_scons_dir(topdir, site_dir_name=None):
site_m[k] = m.__dict__[k]
# This is the magic.
- exec fp in site_m
+ exec(compile(fp.read(), fp.name, 'exec'), 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
@@ -748,7 +752,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
@@ -800,7 +804,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):
@@ -992,7 +996,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
@@ -1053,8 +1057,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
@@ -1092,7 +1096,7 @@ def _main(parser):
nodes = _build_targets(fs, options, targets, target_top)
if not nodes:
revert_io()
- print 'Found nothing to build'
+ print('Found nothing to build')
exit_status = 2
def _build_targets(fs, options, targets, target_top):
@@ -1354,7 +1358,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())
@@ -1365,23 +1369,23 @@ def main():
_exec_main(parser, values)
finally:
revert_io()
- 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:
- print e
+ except SCons.Errors.BuildError as e:
+ print(e)
exit_status = e.exitstatus
except:
# An exception here is likely a builtin Python exception Python
@@ -1417,10 +1421,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 d7262a9..1250e6b 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.
@@ -709,7 +709,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)
@@ -876,7 +876,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 111d091..d50951d 100644
--- a/src/engine/SCons/Script/SConscript.py
+++ b/src/engine/SCons/Script/SConscript.py
@@ -26,7 +26,6 @@ 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 +112,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 +144,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 +173,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 +256,8 @@ def _SConscript(fs, *files, **kw):
pass
try:
try:
- exec _file_ in call_stack[-1].globals
+ exec(compile(_file_.read(), _file_.name, 'exec'),
+ 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.
#
@@ -471,15 +471,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):
@@ -518,7 +518,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):
diff --git a/src/engine/SCons/Script/__init__.py b/src/engine/SCons/Script/__init__.py
index bb7b632..e9e8b71 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 318d7d9..43f2e1f 100644
--- a/src/engine/SCons/Subst.py
+++ b/src/engine/SCons/Subst.py
@@ -446,7 +446,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)
@@ -661,7 +661,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)
diff --git a/src/engine/SCons/SubstTests.py b/src/engine/SCons/SubstTests.py
index 6f2eb3f..2b93e88 100644
--- a/src/engine/SCons/SubstTests.py
+++ b/src/engine/SCons/SubstTests.py
@@ -20,6 +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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -243,14 +244,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"
@@ -462,18 +463,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
@@ -516,7 +517,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}'",
@@ -532,7 +533,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'",
@@ -548,7 +549,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]}'",
@@ -567,7 +568,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)}'"
@@ -948,18 +949,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
@@ -971,7 +972,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}'",
@@ -987,7 +988,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'",
@@ -1095,8 +1096,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 5de1cda..4a06654 100644
--- a/src/engine/SCons/Taskmaster.py
+++ b/src/engine/SCons/Taskmaster.py
@@ -19,6 +19,7 @@
# 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 print_function
__doc__ = """
Generic Taskmaster module for the SCons build engine.
@@ -107,7 +108,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))
@@ -191,13 +192,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):
@@ -256,7 +257,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()
@@ -305,7 +306,7 @@ class Task(object):
t.push_to_cache()
t.built()
t.visited()
- if (not print_prepare and
+ if (not print_prepare and
(not hasattr(self, 'options') or not self.options.debug_includes)):
t.release_target_info()
else:
@@ -402,7 +403,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:
@@ -423,7 +424,7 @@ class Task(object):
# parallel build...)
t.visited()
t.set_state(NODE_UP_TO_DATE)
- if (not print_prepare and
+ if (not print_prepare and
(not hasattr(self, 'options') or not self.options.debug_includes)):
t.release_target_info()
@@ -531,13 +532,9 @@ class Task(object):
Raises a pending exception that was recorded while getting a
Task ready for execution.
"""
- exc = self.exc_info()[:]
- try:
- exc_type, exc_value, exc_traceback = exc
- except ValueError:
- exc_type, exc_value = exc
- exc_traceback = None
- raise exc_type, exc_value, exc_traceback
+
+ import SCons.compat.six
+ SCons.compat.six.reraise(*self.exc_info())
class AlwaysTask(Task):
def needs_execute(self):
@@ -810,7 +807,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
@@ -943,7 +940,7 @@ class Taskmaster(object):
executor = node.get_executor()
if executor is None:
return None
-
+
tlist = executor.get_all_targets()
task = self.tasker(self, tlist, node in self.original_top, node)
diff --git a/src/engine/SCons/TaskmasterTests.py b/src/engine/SCons/TaskmasterTests.py
index 1d81992..e795f5c 100644
--- a/src/engine/SCons/TaskmasterTests.py
+++ b/src/engine/SCons/TaskmasterTests.py
@@ -697,7 +697,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'
@@ -851,7 +851,7 @@ class TaskmasterTestCase(unittest.TestCase):
exc_caught = None
try:
t.prepare()
- except MyException, e:
+ except MyException as e:
exc_caught = 1
except:
pass
@@ -904,7 +904,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")
@@ -958,7 +958,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/386asm.py b/src/engine/SCons/Tool/386asm.py
index 8acc55f..51738eb 100644
--- a/src/engine/SCons/Tool/386asm.py
+++ b/src/engine/SCons/Tool/386asm.py
@@ -37,7 +37,7 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
from SCons.Tool.PharLapCommon import addPharLapPaths
import SCons.Util
-as_module = __import__('as', globals(), locals(), [])
+as_module = __import__('as', globals(), locals(), [], 1)
def generate(env):
"""Add Builders and construction variables for ar to an Environment."""
diff --git a/src/engine/SCons/Tool/FortranCommon.py b/src/engine/SCons/Tool/FortranCommon.py
index 4c5730c..088c717 100644
--- a/src/engine/SCons/Tool/FortranCommon.py
+++ b/src/engine/SCons/Tool/FortranCommon.py
@@ -26,6 +26,7 @@ Stuff for processing Fortran, common to all fortran dialects.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -61,7 +62,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)
@@ -167,7 +168,7 @@ def add_fortran_to_env(env):
except KeyError:
FortranSuffixes = ['.f', '.for', '.ftn']
- #print "Adding %s to fortran suffixes" % FortranSuffixes
+ #print("Adding %s to fortran suffixes" % FortranSuffixes)
try:
FortranPPSuffixes = env['FORTRANPPFILESUFFIXES']
except KeyError:
@@ -191,7 +192,7 @@ def add_f77_to_env(env):
except KeyError:
F77Suffixes = ['.f77']
- #print "Adding %s to f77 suffixes" % F77Suffixes
+ #print("Adding %s to f77 suffixes" % F77Suffixes)
try:
F77PPSuffixes = env['F77PPFILESUFFIXES']
except KeyError:
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 ccfe739..4a91310 100644
--- a/src/engine/SCons/Tool/MSCommon/common.py
+++ b/src/engine/SCons/Tool/MSCommon/common.py
@@ -20,6 +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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -38,7 +39,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
@@ -114,11 +115,11 @@ def normalize_env(env, keys, force=False):
normenv = {}
if env:
for k in env.keys():
- normenv[k] = copy.deepcopy(env[k]).encode('mbcs')
+ normenv[k] = copy.deepcopy(env[k])
for k in keys:
if k in os.environ and (force or not k in normenv):
- normenv[k] = os.environ[k].encode('mbcs')
+ normenv[k] = os.environ[k]
# This shouldn't be necessary, since the default environment should include system32,
# but keep this here to be safe, since it's needed to find reg.exe which the MSVC
@@ -211,7 +212,6 @@ def parse_output(output, keep = ("INCLUDE", "LIB", "LIBPATH", "PATH")):
for p in plist:
# Do not add empty paths (when a var ends with ;)
if p:
- p = p.encode('mbcs')
# XXX: For some reason, VC98 .bat file adds "" around the PATH
# values, and it screws up the environment later, so we strip
# it.
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 97cb349..bd7bbd0 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
@@ -107,7 +107,7 @@ def get_host_target(env):
# PROCESSOR_ARCHITECTURE.
if not host_platform:
host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '')
-
+
# Retain user requested TARGET_ARCH
req_target_platform = env.get('TARGET_ARCH')
debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform)
@@ -117,17 +117,17 @@ def get_host_target(env):
target_platform = req_target_platform
else:
target_platform = host_platform
-
+
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)
@@ -164,7 +164,7 @@ _VCVER_TO_PRODUCT_DIR = {
'6.0': [
r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir']
}
-
+
def msvc_version_to_maj_min(msvc_version):
msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.'])
@@ -175,7 +175,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):
@@ -224,7 +224,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)
@@ -244,7 +244,7 @@ def find_batch_file(env,msvc_version,host_arch,target_arch):
pdir = find_vc_pdir(msvc_version)
if pdir is None:
raise NoVersionFound("No version of Visual Studio found")
-
+
debug('vc.py: find_batch_file() pdir:%s'%pdir)
# filter out e.g. "Exp" from the version name
@@ -262,7 +262,7 @@ def find_batch_file(env,msvc_version,host_arch,target_arch):
if not os.path.exists(batfilename):
debug("Not found: %s" % batfilename)
batfilename = None
-
+
installed_sdks=get_installed_sdks()
for _sdk in installed_sdks:
sdk_bat_file = _sdk.get_sdk_vc_script(host_arch,target_arch)
@@ -270,7 +270,7 @@ def find_batch_file(env,msvc_version,host_arch,target_arch):
debug("vc.py:find_batch_file() not found:%s"%_sdk)
else:
sdk_bat_file_path = os.path.join(pdir,sdk_bat_file)
- if os.path.exists(sdk_bat_file_path):
+ if os.path.exists(sdk_bat_file_path):
debug('vc.py:find_batch_file() sdk_bat_file_path:%s'%sdk_bat_file_path)
return (batfilename,sdk_bat_file_path)
return (batfilename,None)
@@ -297,7 +297,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
@@ -333,7 +333,7 @@ def get_default_version(env):
msvc_version = env.get('MSVC_VERSION')
msvs_version = env.get('MSVS_VERSION')
-
+
debug('get_default_version(): msvc_version:%s msvs_version:%s'%(msvc_version,msvs_version))
if msvs_version and not msvc_version:
@@ -383,7 +383,7 @@ def msvc_find_valid_batch_script(env,version):
try_target_archs = [target_platform]
debug("msvs_find_valid_batch_script(): req_target_platform %s target_platform:%s"%(req_target_platform,target_platform))
- # VS2012 has a "cross compile" environment to build 64 bit
+ # VS2012 has a "cross compile" environment to build 64 bit
# with x86_amd64 as the argument to the batch setup script
if req_target_platform in ('amd64','x86_64'):
try_target_archs.append('x86_amd64')
@@ -401,7 +401,7 @@ def msvc_find_valid_batch_script(env,version):
for tp in try_target_archs:
# Set to current arch.
env['TARGET_ARCH']=tp
-
+
debug("vc.py:msvc_find_valid_batch_script() trying target_platform:%s"%tp)
host_target = (host_platform, tp)
if not is_host_target_supported(host_target, version):
@@ -409,12 +409,12 @@ def msvc_find_valid_batch_script(env,version):
(host_target, version)
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target]
-
+
# Try to locate a batch file for this host/target platform combo
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. " + \
@@ -423,13 +423,13 @@ def msvc_find_valid_batch_script(env,version):
warn_msg = warn_msg % (version, cached_get_installed_vcs())
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
continue
-
+
# Try to use the located batch file for this host/target platform combo
debug('vc.py:msvc_find_valid_batch_script() use_script 2 %s, args:%s\n' % (repr(vc_script), arg))
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
@@ -437,23 +437,23 @@ 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)
- 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:
debug('vc.py:msvc_find_valid_batch_script() use_script 6: Neither VC script nor SDK script found')
continue
-
+
debug("vc.py:msvc_find_valid_batch_script() Found a working script/target: %s %s"%(repr(sdk_script),arg))
break # We've found a working target_platform, so stop looking
-
+
# If we cannot find a viable installed compiler, reset the TARGET_ARCH
# To it's initial value
if not d:
env['TARGET_ARCH']=req_target_platform
-
+
return d
-
+
def msvc_setup_env(env):
debug('msvc_setup_env()')
@@ -472,12 +472,12 @@ def msvc_setup_env(env):
env['MSVS_VERSION'] = version
env['MSVS'] = {}
-
+
use_script = env.get('MSVC_USE_SCRIPT', True)
if SCons.Util.is_String(use_script):
debug('vc.py:msvc_setup_env() use_script 1 %s\n' % repr(use_script))
d = script_env(use_script)
- elif use_script:
+ elif use_script:
d = msvc_find_valid_batch_script(env,version)
debug('vc.py:msvc_setup_env() use_script 2 %s\n' % d)
if not d:
@@ -498,4 +498,4 @@ def msvc_exists(version=None):
if version is None:
return len(vcs) > 0
return version in vcs
-
+
diff --git a/src/engine/SCons/Tool/MSCommon/vs.py b/src/engine/SCons/Tool/MSCommon/vs.py
index 2ec403b..68e108a 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)
diff --git a/src/engine/SCons/Tool/__init__.py b/src/engine/SCons/Tool/__init__.py
index 55eb1d3..396807f 100644
--- a/src/engine/SCons/Tool/__init__.py
+++ b/src/engine/SCons/Tool/__init__.py
@@ -34,6 +34,7 @@ tool definition.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -113,8 +114,8 @@ class Tool(object):
finally:
if file:
file.close()
- except ImportError, e:
- if str(e)!="No module named %s"%self.name:
+ except ImportError as e:
+ if not str(e).startswith ("No module"):
raise SCons.Errors.EnvironmentError(e)
try:
import zipimport
@@ -125,7 +126,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,8 +144,8 @@ class Tool(object):
if file:
file.close()
return module
- except ImportError, e:
- if str(e)!="No module named %s"%self.name:
+ except ImportError as e:
+ if not str(e).startswith("No module"):
raise SCons.Errors.EnvironmentError(e)
try:
import zipimport
@@ -152,10 +153,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 +255,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':
if sys.platform.startswith('openbsd'):
@@ -266,7 +267,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]
@@ -275,7 +276,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.
@@ -298,10 +299,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
@@ -316,7 +317,7 @@ symlinks for the platform we are on"""
soname = re.sub(suffix_re, shlib_suffix, libname) + '.' + major
shlink_flags += [ '-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' ]
@@ -325,7 +326,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:
@@ -338,7 +339,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
@@ -351,7 +352,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:
@@ -361,7 +362,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
# Fix http://scons.tigris.org/issues/show_bug.cgi?id=2903 :
diff --git a/src/engine/SCons/Tool/aixcc.py b/src/engine/SCons/Tool/aixcc.py
index a89a97e..09365b1 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 4e9db21..bfddf0a 100644
--- a/src/engine/SCons/Tool/aixlink.py
+++ b/src/engine/SCons/Tool/aixlink.py
@@ -37,7 +37,8 @@ import os.path
import SCons.Util
-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/__init__.py b/src/engine/SCons/Tool/docbook/__init__.py
index 26a1a95..77ed388 100644
--- a/src/engine/SCons/Tool/docbook/__init__.py
+++ b/src/engine/SCons/Tool/docbook/__init__.py
@@ -335,7 +335,7 @@ def __build_lxml(target, source, env):
result = transform(doc)
try:
- of = open(str(target[0]), "w")
+ of = open(str(target[0]), "wb")
of.write(of.write(etree.tostring(result, pretty_print=True)))
of.close()
except:
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..e7b8cfa 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
@@ -1,5 +1,6 @@
# docbook.py: extension module
# $Id: docbook.py 8353 2009-03-17 16:57:50Z mzjn $
+from __future__ import print_function
import sys
import string
@@ -82,7 +83,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 +117,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 +152,7 @@ def adjustColumnWidths(ctx, nodeset):
col.setProp("width", widths[count])
count = count+1
- col = col.next
+ col = col.__next__
return nodeset
@@ -163,10 +164,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..77ca0de 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
@@ -1,5 +1,6 @@
#!/usr/bin/python -u
# $Id: xslt.py 8353 2009-03-17 16:57:50Z mzjn $
+from __future__ import print_function
import sys
import libxml2
@@ -18,7 +19,7 @@ try:
xmlfile = sys.argv[1]
xslfile = sys.argv[2]
except IndexError:
- print usage
+ print(usage)
sys.exit(1)
def quote(astring):
@@ -38,12 +39,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 +71,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/g++.py b/src/engine/SCons/Tool/g++.py
index 5cf3827..c5eb579 100644
--- a/src/engine/SCons/Tool/g++.py
+++ b/src/engine/SCons/Tool/g++.py
@@ -40,9 +40,8 @@ import subprocess
import SCons.Tool
import SCons.Util
-import gcc
-
-cplusplus = __import__('c++', globals(), locals(), [])
+from . import gcc
+cplusplus = __import__(__package__+'.c++', globals(), locals(), ['*'])
compilers = ['g++']
diff --git a/src/engine/SCons/Tool/gas.py b/src/engine/SCons/Tool/gas.py
index 28f84db..d01bd60 100644
--- a/src/engine/SCons/Tool/gas.py
+++ b/src/engine/SCons/Tool/gas.py
@@ -33,7 +33,10 @@ selection method.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-as_module = __import__('as', globals(), locals(), [])
+try:
+ as_module = __import__('as', globals(), locals(), [])
+except:
+ as_module = __import__(__package__+'.as', globals(), locals(), ['*'])
assemblers = ['as', 'gas']
diff --git a/src/engine/SCons/Tool/gcc.py b/src/engine/SCons/Tool/gcc.py
index df65647..998e35b 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
@@ -80,13 +80,13 @@ def detect_version(env, cc):
#line = pipe.stdout.read().strip()
#if line:
# version = line
- line = pipe.stdout.readline()
+ line = SCons.Util.to_str(pipe.stdout.readline())
match = re.search(r'[0-9]+(\.[0-9]+)+', line)
if match:
version = match.group(0)
# Non-GNU compiler's output (like AIX xlc's) may exceed the stdout buffer:
# So continue with reading to let the child process actually terminate.
- while pipe.stdout.readline():
+ while SCons.Util.to_str(pipe.stdout.readline()):
pass
ret = pipe.wait()
if ret != 0:
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 3dc8f51..6bd9471 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
def generate(env):
"""Add Builders and construction variables for gnulink to an Environment."""
diff --git a/src/engine/SCons/Tool/gs.py b/src/engine/SCons/Tool/gs.py
index 6e31ee2..25359a8 100644
--- a/src/engine/SCons/Tool/gs.py
+++ b/src/engine/SCons/Tool/gs.py
@@ -62,12 +62,12 @@ def generate(env):
if GhostscriptAction is None:
GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR')
- import pdf
+ from SCons.Tool import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.ps', GhostscriptAction)
- except ImportError, e:
+ except ImportError as e:
pass
gsbuilder = SCons.Builder.Builder(action = SCons.Action.Action('$GSCOM', '$GSCOMSTR'))
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..0d75765 100644
--- a/src/engine/SCons/Tool/install.py
+++ b/src/engine/SCons/Tool/install.py
@@ -29,6 +29,7 @@ selection method.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -82,21 +83,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 +175,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 +189,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 +203,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 +211,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 +219,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 +229,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 +299,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 +308,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 57258f3..7cc2376 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
+from __future__ import division, print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -254,17 +254,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:
@@ -480,8 +479,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))
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 baa7407..1b03075 100644
--- a/src/engine/SCons/Tool/link.py
+++ b/src/engine/SCons/Tool/link.py
@@ -30,6 +30,7 @@ selection method.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -43,8 +44,7 @@ import SCons.Warnings
from SCons.Tool.FortranCommon import isfortran
from SCons.Tool.DCommon import isD
-
-cplusplus = __import__('c++', globals(), locals(), [])
+cplusplus = __import__(__package__+'.c++', globals(), locals(), ['*'])
issued_mixed_link_warning = False
@@ -88,7 +88,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)
@@ -111,16 +111,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':
@@ -130,8 +130,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':
@@ -141,8 +141,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..f30c1d3 100644
--- a/src/engine/SCons/Tool/mslink.py
+++ b/src/engine/SCons/Tool/mslink.py
@@ -30,6 +30,7 @@ selection method.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -44,7 +45,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:
@@ -183,7 +184,7 @@ def prog_emitter(target, source, env):
# MSVC 11 and above need the PCH object file to be added to the link line,
# otherwise you get link error LNK2011.
pchobj = SCons.Util.splitext(str(env['PCH']))[0] + '.obj'
- # print "prog_emitter, version %s, appending pchobj %s"%(version_num, pchobj)
+ # print("prog_emitter, version %s, appending pchobj %s"%(version_num, pchobj))
if pchobj not in extrasources:
extrasources.append(pchobj)
@@ -195,7 +196,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 +213,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 +227,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..370af9a 100644
--- a/src/engine/SCons/Tool/msvs.py
+++ b/src/engine/SCons/Tool/msvs.py
@@ -29,6 +29,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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -51,7 +52,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,7 +352,7 @@ 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)
@@ -551,7 +552,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()
@@ -861,7 +862,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 +1030,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'
@@ -1158,12 +1159,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 +1243,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 " +\
@@ -1424,7 +1425,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 +1474,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 +1531,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 +1547,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 2f4f302..9334bac 100644
--- a/src/engine/SCons/Tool/msvsTests.py
+++ b/src/engine/SCons/Tool/msvsTests.py
@@ -20,6 +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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -748,7 +749,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..345ec87 100644
--- a/src/engine/SCons/Tool/packaging/__init__.py
+++ b/src/engine/SCons/Tool/packaging/__init__.py
@@ -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/msi.py b/src/engine/SCons/Tool/packaging/msi.py
index fe78c9c..49c28ca 100644
--- a/src/engine/SCons/Tool/packaging/msi.py
+++ b/src/engine/SCons/Tool/packaging/msi.py
@@ -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] )
#
diff --git a/src/engine/SCons/Tool/packaging/rpm.py b/src/engine/SCons/Tool/packaging/rpm.py
index 2bc3063..9bd7dbb 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] )
@@ -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
@@ -344,7 +344,7 @@ class SimpleTagCompiler(object):
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..723c39c 100644
--- a/src/engine/SCons/Tool/qt.py
+++ b/src/engine/SCons/Tool/qt.py
@@ -31,6 +31,7 @@ selection method.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -130,12 +131,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 +149,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 +162,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 e20d53b..3eeed1d 100644
--- a/src/engine/SCons/Tool/rpmutils.py
+++ b/src/engine/SCons/Tool/rpmutils.py
@@ -34,6 +34,7 @@ exact syntax.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -501,7 +502,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
@@ -519,7 +520,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])))
@@ -529,7 +530,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/swig.py b/src/engine/SCons/Tool/swig.py
index f166174..f669f83 100644
--- a/src/engine/SCons/Tool/swig.py
+++ b/src/engine/SCons/Tool/swig.py
@@ -131,7 +131,7 @@ def _get_swig_version(env):
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
- out = pipe.stdout.read()
+ out = SCons.Util.to_str (pipe.stdout.read())
match = re.search(r'SWIG Version\s+(\S+)$', out, re.MULTILINE)
if match:
return match.group(1)
diff --git a/src/engine/SCons/Tool/tex.py b/src/engine/SCons/Tool/tex.py
index 053d85d..0bf3792 100644
--- a/src/engine/SCons/Tool/tex.py
+++ b/src/engine/SCons/Tool/tex.py
@@ -31,6 +31,7 @@ selection method.
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -164,15 +165,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]
@@ -183,14 +184,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):
@@ -250,7 +251,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
@@ -269,12 +270,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
@@ -323,8 +324,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
@@ -340,7 +341,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:
@@ -363,7 +364,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:
@@ -374,7 +375,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:
@@ -392,7 +393,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:
@@ -404,7 +405,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:
@@ -416,7 +417,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:
@@ -429,7 +430,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("$MAKENEWGLOSSARYCOM ${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")
@@ -443,26 +444,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):
@@ -516,27 +517,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.
@@ -546,7 +547,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)
@@ -555,7 +556,7 @@ def is_LaTeX(flist,env,abspath):
return file_test
if Verbose:
- print " done scanning ",str(f)
+ print(" done scanning ",str(f))
return 0
@@ -620,15 +621,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)
@@ -639,19 +640,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.
@@ -660,7 +661,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):
@@ -692,7 +693,7 @@ def tex_emitter_core(target, source, env, graphics_extensions):
env.SideEffect(flsfilename,target[0])
env.SideEffect(syncfilename,target[0])
if Verbose:
- print "side effect :",auxfilename,logfilename,flsfilename,syncfilename
+ print("side effect :",auxfilename,logfilename,flsfilename,syncfilename)
env.Clean(target[0],auxfilename)
env.Clean(target[0],logfilename)
env.Clean(target[0],flsfilename)
@@ -771,7 +772,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 = []
@@ -780,7 +781,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
@@ -794,11 +795,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
@@ -806,14 +807,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
@@ -826,7 +827,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)
@@ -846,7 +847,7 @@ def generate(env):
generate_common(env)
- import dvi
+ from . import dvi
dvi.generate(env)
bld = env['BUILDERS']['DVI']
@@ -859,7 +860,7 @@ def generate_darwin(env):
except KeyError:
environ = {}
env['ENV'] = environ
-
+
if (platform.system() == 'Darwin'):
try:
ospath = env['ENV']['PATHOSX']
diff --git a/src/engine/SCons/Tool/textfile.py b/src/engine/SCons/Tool/textfile.py
index 8dc8f4b..693b62b 100644
--- a/src/engine/SCons/Tool/textfile.py
+++ b/src/engine/SCons/Tool/textfile.py
@@ -107,7 +107,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..923fd17 100644
--- a/src/engine/SCons/Tool/xgettext.py
+++ b/src/engine/SCons/Tool/xgettext.py
@@ -1,10 +1,10 @@
-""" xgettext tool
+""" xgettext tool
Tool specific initialization of `xgettext` tool.
"""
# __COPYRIGHT__
-#
+#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
@@ -12,10 +12,10 @@ Tool specific initialization of `xgettext` tool.
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
-#
+#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
-#
+#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@@ -23,6 +23,7 @@ Tool specific initialization of `xgettext` tool.
# 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 SCons.compat.six import u
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -39,12 +40,12 @@ class _CmdRunner(object):
self.command = command
self.commandstr = commandstr
- def __call__(self, target, source, env):
+ def __call__(self, target, source, env):
import SCons.Action
import subprocess
import os
import sys
- kw = {
+ kw = {
'stdin' : 'devnull',
'stdout' : subprocess.PIPE,
'stderr' : subprocess.PIPE,
@@ -55,7 +56,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(u(self.err))
return self.status
def strfunction(self, target, source, env):
@@ -104,9 +105,9 @@ def _update_pot_file(target, source, env):
os.chdir(save_os_cwd)
# If the command was not successfull, return error code.
if status: return status
-
+
new_content = cmd.out
-
+
if not new_content:
# When xgettext finds no internationalized messages, no *.pot is created
# (because we don't want to bother translators with empty POT files).
@@ -144,7 +145,7 @@ def _update_pot_file(target, source, env):
# Print message employing SCons.Action.Action for that.
msg = "Not writting " + repr(str(target[0])) + " (" + explain + ")"
env.Execute(SCons.Action.Action(nop, msg))
- return 0
+ return 0
#############################################################################
#############################################################################
@@ -153,7 +154,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 +176,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 = []
@@ -207,7 +208,7 @@ def _scan_xgettext_from_files(target, source, env, files = None, path = None):
contents = re_emptyln.sub("", contents)
contents = re_trailws.sub("", contents)
depnames = contents.splitlines()
- for depname in depnames:
+ for depname in depnames:
depfile = SCons.Node.FS.find_file(depname, dirs)
if not depfile:
depfile = env.arg2nodes(depname, dirs[0].File)
@@ -222,7 +223,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
@@ -230,13 +231,13 @@ def _pot_update_emitter(target, source, env):
xfrom = [ xfrom ]
xfrom = SCons.Util.flatten(xfrom)
-
+
# Prepare list of 'POTFILE.in' files.
files = []
for xf in xfrom:
if not isinstance(xf, SCons.Node.FS.Base):
if SCons.Util.is_String(xf):
- # Interpolate variables in strings
+ # Interpolate variables in strings
xf = env.subst(xf, source = source, target = target)
xf = env.arg2nodes(xf)
files.extend(xf)
@@ -274,7 +275,7 @@ def generate(env,**kw):
try:
env['XGETTEXT'] = _detect_xgettext(env)
except:
- env['XGETTEXT'] = 'xgettext'
+ env['XGETTEXT'] = 'xgettext'
# NOTE: sources="$SOURCES" would work as well. However, we use following
# construction to convert absolute paths provided by scons onto paths
# relative to current working dir. Note, that scons expands $SOURCE(S) to
diff --git a/src/engine/SCons/Util.py b/src/engine/SCons/Util.py
index 822d524..3a368cb 100644
--- a/src/engine/SCons/Util.py
+++ b/src/engine/SCons/Util.py
@@ -23,6 +23,7 @@ Various utility functions go here.
# 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 SCons.compat.six import PY2, PY3, u
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -32,11 +33,16 @@ import copy
import re
import types
-from collections import UserDict, UserList, UserString
+if PY3:
+ from collections import UserDict, UserList, UserString
+else:
+ from UserDict import UserDict
+ from UserList import UserList
+ from UserString import UserString
# Don't "from types import ..." these because we need to get at the
# types module later to look for UnicodeType.
-InstanceType = types.InstanceType
+InstanceType = types.InstanceType if PY2 else None
MethodType = types.MethodType
FunctionType = types.FunctionType
try: unicode
@@ -114,6 +120,9 @@ class NodeList(UserList):
def __nonzero__(self):
return len(self.data) != 0
+ def __bool__(self):
+ return self.__nonzero__()
+
def __str__(self):
return ' '.join(map(str, self.data))
@@ -153,7 +162,7 @@ class DisplayEngine(object):
return
if append_newline: text = text + '\n'
try:
- sys.stdout.write(unicode(text))
+ sys.stdout.write(u(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 +248,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(u(legend))
tags = ['[']
tags.append(' E'[IDX(root.exists())])
@@ -303,11 +312,17 @@ 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)
+try:
+ StringTypes = (str, unicode, UserString)
+except NameError:
+ StringTypes = (str, UserString)
# Empirically, it is faster to check explicitely for str and
# unicode than for basestring.
-BaseStringTypes = (str, unicode)
+try:
+ BaseStringTypes = (str, unicode)
+except NameError:
+ BaseStringTypes = (str)
def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes):
return isinstance(obj, DictTypes)
@@ -333,7 +348,7 @@ def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes
# assumes that the obj argument is a string must of the time.
return isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes)
-def do_flatten(sequence, result, isinstance=isinstance,
+def do_flatten(sequence, result, isinstance=isinstance,
StringTypes=StringTypes, SequenceTypes=SequenceTypes):
for item in sequence:
if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
@@ -341,7 +356,7 @@ def do_flatten(sequence, result, isinstance=isinstance,
else:
do_flatten(item, result)
-def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
+def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
SequenceTypes=SequenceTypes, do_flatten=do_flatten):
"""Flatten a sequence to a non-nested list.
@@ -359,7 +374,7 @@ def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
do_flatten(item, result)
return result
-def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes,
+def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes,
SequenceTypes=SequenceTypes, do_flatten=do_flatten):
"""Flatten a sequence to a non-nested list.
@@ -380,7 +395,7 @@ def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes,
# to_String_for_signature() will use a for_signature() method if the
# specified object has one.
#
-def to_String(s,
+def to_String(s,
isinstance=isinstance, str=str,
UserString=UserString, BaseStringTypes=BaseStringTypes):
if isinstance(s,BaseStringTypes):
@@ -393,11 +408,11 @@ def to_String(s,
else:
return str(s)
-def to_String_for_subst(s,
+def to_String_for_subst(s,
isinstance=isinstance, str=str, to_String=to_String,
BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes,
UserString=UserString):
-
+
# Note that the test cases are sorted by order of probability.
if isinstance(s, BaseStringTypes):
return s
@@ -413,7 +428,7 @@ def to_String_for_subst(s,
else:
return str(s)
-def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst,
+def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst,
AttributeError=AttributeError):
try:
f = obj.for_signature
@@ -471,7 +486,7 @@ def semi_deepcopy(x):
return x.__class__(semi_deepcopy_dict(x))
elif isinstance(x, UserList):
return x.__class__(_semi_deepcopy_list(x))
-
+
return x
@@ -519,10 +534,10 @@ class Proxy(object):
"""Retrieve the entire wrapped object"""
return self._subject
- def __cmp__(self, other):
+ def __eq__(self, other):
if issubclass(other.__class__, self._subject.__class__):
- return cmp(self._subject, other)
- return cmp(self.__dict__, other.__dict__)
+ return self._subject == other
+ return self.__dict__ == other.__dict__
class Delegate(object):
"""A Python Descriptor class that delegates attribute fetches
@@ -617,7 +632,7 @@ else:
builtins.WindowsError = WindowsError
else:
del e
-
+
HKEY_CLASSES_ROOT = None
HKEY_LOCAL_MACHINE = None
HKEY_CURRENT_USER = None
@@ -718,7 +733,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:
@@ -726,7 +741,7 @@ else:
continue
return None
-def PrependPath(oldpath, newpath, sep = os.pathsep,
+def PrependPath(oldpath, newpath, sep = os.pathsep,
delete_existing=1, canonicalize=None):
"""This prepends newpath elements to the given oldpath. Will only
add any particular path once (leaving the first one it encounters
@@ -745,7 +760,7 @@ def PrependPath(oldpath, newpath, sep = os.pathsep,
not move it to the beginning; it will stay where it is in the
list.
- If canonicalize is not None, it is applied to each element of
+ If canonicalize is not None, it is applied to each element of
newpath before use.
"""
@@ -767,7 +782,7 @@ def PrependPath(oldpath, newpath, sep = os.pathsep,
newpaths=list(map(canonicalize, newpaths))
if not delete_existing:
- # First uniquify the old paths, making sure to
+ # First uniquify the old paths, making sure to
# preserve the first instance (in Unix/Linux,
# the first one wins), and remembering them in normpaths.
# Then insert the new paths at the head of the list
@@ -808,7 +823,7 @@ def PrependPath(oldpath, newpath, sep = os.pathsep,
else:
return sep.join(paths)
-def AppendPath(oldpath, newpath, sep = os.pathsep,
+def AppendPath(oldpath, newpath, sep = os.pathsep,
delete_existing=1, canonicalize=None):
"""This appends new path elements to the given old path. Will
only add any particular path once (leaving the last one it
@@ -826,7 +841,7 @@ def AppendPath(oldpath, newpath, sep = os.pathsep,
If delete_existing is 0, then adding a path that exists
will not move it to the end; it will stay where it is in the list.
- If canonicalize is not None, it is applied to each element of
+ If canonicalize is not None, it is applied to each element of
newpath before use.
"""
@@ -1346,8 +1361,9 @@ def make_path_relative(path):
def AddMethod(obj, function, name=None):
"""
- Adds either a bound method to an instance or an unbound method to
- a class. If name is ommited the name of the specified function
+ Adds either a bound method to an instance or the function itself
+ (or an unbound method in Python 2) to a class.
+ If name is ommited the name of the specified function
is used by default.
Example:
a = A()
@@ -1360,26 +1376,32 @@ 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)
if hasattr(obj, '__class__') and obj.__class__ is not type:
# "obj" is an instance, so it gets a bound method.
- setattr(obj, name, MethodType(function, obj, obj.__class__))
+ if PY3:
+ method = MethodType(function, obj)
+ else:
+ method = MethodType(function, obj, obj.__class__)
+ setattr(obj, name, method)
else:
# "obj" is a class, so it gets an unbound method.
- setattr(obj, name, MethodType(function, None, obj))
+ if PY2:
+ function = MethodType(function, None, obj)
+ setattr(obj, name, function)
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
@@ -1401,7 +1423,7 @@ else:
md5 = True
def MD5signature(s):
m = hashlib.md5()
- m.update(str(s))
+ m.update(to_bytes(str(s)))
return m.hexdigest()
def MD5filesignature(fname, chunksize=65536):
@@ -1411,10 +1433,10 @@ else:
blck = f.read(chunksize)
if not blck:
break
- m.update(str(blck))
+ m.update(to_bytes (str(blck)))
f.close()
return m.hexdigest()
-
+
def MD5collect(signatures):
"""
Collects a list of signatures into an aggregate signature.
@@ -1463,6 +1485,8 @@ class Null(object):
return "Null(0x%08X)" % id(self)
def __nonzero__(self):
return False
+ def __bool__(self):
+ return False
def __getattr__(self, name):
return self
def __setattr__(self, name, value):
@@ -1485,6 +1509,18 @@ class NullSeq(Null):
del __revision__
+def to_bytes (s):
+ if isinstance (s, bytes) or bytes is str:
+ return s
+ else:
+ return bytes (s, 'utf-8')
+
+def to_str (s):
+ if bytes is str:
+ return s
+ else:
+ return str (s, 'utf-8')
+
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
diff --git a/src/engine/SCons/UtilTests.py b/src/engine/SCons/UtilTests.py
index b0c15c5..c52c910 100644
--- a/src/engine/SCons/UtilTests.py
+++ b/src/engine/SCons/UtilTests.py
@@ -20,6 +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 SCons.compat.six import u
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -220,7 +221,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([])
@@ -236,12 +237,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):
@@ -267,7 +268,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."""
@@ -314,10 +315,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']
@@ -682,7 +683,7 @@ bling
fobj = io.StringIO(content)
except TypeError:
# Python 2.7 and beyond require unicode strings.
- fobj = io.StringIO(unicode(content))
+ fobj = io.StringIO(u(content))
lines = LogicalLines(fobj).readlines()
assert lines == [
@@ -696,7 +697,7 @@ bling
def test_intern(self):
s1 = silent_intern("spam")
# Python 3.x does not have a unicode() global function
- if sys.version[0] == '2':
+ if sys.version[0] == '2':
s2 = silent_intern(unicode("unicode spam"))
s3 = silent_intern(42)
s4 = silent_intern("spam")
@@ -709,7 +710,7 @@ class MD5TestCase(unittest.TestCase):
"""Test collecting a list of signatures into a new signature value
"""
s = list(map(MD5signature, ('111', '222', '333')))
-
+
assert '698d51a19d8a121ce581499d7b701668' == MD5collect(s[0:1])
assert '8980c988edc2c78cc43ccb718c06efd5' == MD5collect(s[0:2])
assert '53fd88c84ff8a285eb6e0a687e55b8c7' == MD5collect(s)
diff --git a/src/engine/SCons/Variables/PathVariableTests.py b/src/engine/SCons/Variables/PathVariableTests.py
index 4266759..3d9d25c 100644
--- a/src/engine/SCons/Variables/PathVariableTests.py
+++ b/src/engine/SCons/Variables/PathVariableTests.py
@@ -67,7 +67,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")
@@ -91,7 +91,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")
@@ -99,7 +99,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")
@@ -124,7 +124,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")
@@ -148,7 +148,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")
@@ -156,7 +156,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")
@@ -200,7 +200,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:
@@ -219,7 +219,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 d2110c1..3888d19 100644
--- a/src/engine/SCons/Variables/VariablesTests.py
+++ b/src/engine/SCons/Variables/VariablesTests.py
@@ -57,7 +57,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..1c8d834 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]
@@ -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..a58539d 100644
--- a/src/engine/SCons/compat/_scons_subprocess.py
+++ b/src/engine/SCons/compat/_scons_subprocess.py
@@ -351,6 +351,8 @@ except that:
"""
+from __future__ import print_function
+from SCons.compat.six import integer_types
import sys
mswindows = (sys.platform == "win32")
@@ -439,12 +441,12 @@ 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, integer_types)
try:
types.StringTypes
@@ -454,7 +456,7 @@ except AttributeError:
except NameError:
types.StringTypes = (str,)
def is_string(obj):
- return isinstance(obj, types.StringTypes)
+ return isinstance(obj, str)
_active = []
@@ -802,7 +804,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 +832,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 +1217,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 +1230,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 +1257,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/compat/six.py b/src/engine/SCons/compat/six.py
new file mode 100755
index 0000000..019130f
--- /dev/null
+++ b/src/engine/SCons/compat/six.py
@@ -0,0 +1,646 @@
+"""Utilities for writing code that runs on Python 2 and 3"""
+
+# Copyright (c) 2010-2014 Benjamin Peterson
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE 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.
+
+import operator
+import sys
+import types
+
+__author__ = "Benjamin Peterson <benjamin@python.org>"
+__version__ = "1.6.1"
+
+
+# Useful for very coarse version differentiation.
+PY2 = sys.version_info[0] == 2
+PY3 = sys.version_info[0] == 3
+
+if PY3:
+ string_types = str,
+ integer_types = int,
+ class_types = type,
+ text_type = str
+ binary_type = bytes
+
+ MAXSIZE = sys.maxsize
+else:
+ string_types = basestring,
+ integer_types = (int, long)
+ class_types = (type, types.ClassType)
+ text_type = unicode
+ binary_type = str
+
+ if sys.platform.startswith("java"):
+ # Jython always uses 32 bits.
+ MAXSIZE = int((1 << 31) - 1)
+ else:
+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
+ class X(object):
+ def __len__(self):
+ return 1 << 31
+ try:
+ len(X())
+ except OverflowError:
+ # 32-bit
+ MAXSIZE = int((1 << 31) - 1)
+ else:
+ # 64-bit
+ MAXSIZE = int((1 << 63) - 1)
+ del X
+
+
+def _add_doc(func, doc):
+ """Add documentation to a function."""
+ func.__doc__ = doc
+
+
+def _import_module(name):
+ """Import module, returning the module after the last dot."""
+ __import__(name)
+ return sys.modules[name]
+
+
+class _LazyDescr(object):
+
+ def __init__(self, name):
+ self.name = name
+
+ def __get__(self, obj, tp):
+ try:
+ result = self._resolve()
+ except ImportError:
+ # See the nice big comment in MovedModule.__getattr__.
+ raise AttributeError("%s could not be imported " % self.name)
+ setattr(obj, self.name, result) # Invokes __set__.
+ # This is a bit ugly, but it avoids running this again.
+ delattr(obj.__class__, self.name)
+ return result
+
+
+class MovedModule(_LazyDescr):
+
+ def __init__(self, name, old, new=None):
+ super(MovedModule, self).__init__(name)
+ if PY3:
+ if new is None:
+ new = name
+ self.mod = new
+ else:
+ self.mod = old
+
+ def _resolve(self):
+ return _import_module(self.mod)
+
+ def __getattr__(self, attr):
+ # It turns out many Python frameworks like to traverse sys.modules and
+ # try to load various attributes. This causes problems if this is a
+ # platform-specific module on the wrong platform, like _winreg on
+ # Unixes. Therefore, we silently pretend unimportable modules do not
+ # have any attributes. See issues #51, #53, #56, and #63 for the full
+ # tales of woe.
+ #
+ # First, if possible, avoid loading the module just to look at __file__,
+ # __name__, or __path__.
+ if (attr in ("__file__", "__name__", "__path__") and
+ self.mod not in sys.modules):
+ raise AttributeError(attr)
+ try:
+ _module = self._resolve()
+ except ImportError:
+ raise AttributeError(attr)
+ value = getattr(_module, attr)
+ setattr(self, attr, value)
+ return value
+
+
+class _LazyModule(types.ModuleType):
+
+ def __init__(self, name):
+ super(_LazyModule, self).__init__(name)
+ self.__doc__ = self.__class__.__doc__
+
+ def __dir__(self):
+ attrs = ["__doc__", "__name__"]
+ attrs += [attr.name for attr in self._moved_attributes]
+ return attrs
+
+ # Subclasses should override this
+ _moved_attributes = []
+
+
+class MovedAttribute(_LazyDescr):
+
+ def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
+ super(MovedAttribute, self).__init__(name)
+ if PY3:
+ if new_mod is None:
+ new_mod = name
+ self.mod = new_mod
+ if new_attr is None:
+ if old_attr is None:
+ new_attr = name
+ else:
+ new_attr = old_attr
+ self.attr = new_attr
+ else:
+ self.mod = old_mod
+ if old_attr is None:
+ old_attr = name
+ self.attr = old_attr
+
+ def _resolve(self):
+ module = _import_module(self.mod)
+ return getattr(module, self.attr)
+
+
+
+class _MovedItems(_LazyModule):
+ """Lazy loading of moved objects"""
+
+
+_moved_attributes = [
+ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
+ MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
+ MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
+ MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
+ MovedAttribute("map", "itertools", "builtins", "imap", "map"),
+ MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
+ MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
+ MovedAttribute("reduce", "__builtin__", "functools"),
+ MovedAttribute("StringIO", "StringIO", "io"),
+ MovedAttribute("UserString", "UserString", "collections"),
+ MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
+ MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
+ MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
+
+ MovedModule("builtins", "__builtin__"),
+ MovedModule("configparser", "ConfigParser"),
+ MovedModule("copyreg", "copy_reg"),
+ MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
+ MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
+ MovedModule("http_cookies", "Cookie", "http.cookies"),
+ MovedModule("html_entities", "htmlentitydefs", "html.entities"),
+ MovedModule("html_parser", "HTMLParser", "html.parser"),
+ MovedModule("http_client", "httplib", "http.client"),
+ MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
+ MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
+ MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
+ MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
+ MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
+ MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
+ MovedModule("cPickle", "cPickle", "pickle"),
+ MovedModule("queue", "Queue"),
+ MovedModule("reprlib", "repr"),
+ MovedModule("socketserver", "SocketServer"),
+ MovedModule("_thread", "thread", "_thread"),
+ MovedModule("tkinter", "Tkinter"),
+ MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
+ MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
+ MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
+ MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
+ MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
+ MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
+ MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
+ MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
+ MovedModule("tkinter_colorchooser", "tkColorChooser",
+ "tkinter.colorchooser"),
+ MovedModule("tkinter_commondialog", "tkCommonDialog",
+ "tkinter.commondialog"),
+ MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
+ MovedModule("tkinter_font", "tkFont", "tkinter.font"),
+ MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
+ MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
+ "tkinter.simpledialog"),
+ MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
+ MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
+ MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
+ MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
+ MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
+ MovedModule("xmlrpc_server", "xmlrpclib", "xmlrpc.server"),
+ MovedModule("winreg", "_winreg"),
+]
+for attr in _moved_attributes:
+ setattr(_MovedItems, attr.name, attr)
+ if isinstance(attr, MovedModule):
+ sys.modules[__name__ + ".moves." + attr.name] = attr
+del attr
+
+_MovedItems._moved_attributes = _moved_attributes
+
+moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves")
+
+
+class Module_six_moves_urllib_parse(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_parse"""
+
+
+_urllib_parse_moved_attributes = [
+ MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
+ MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
+ MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
+ MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
+ MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
+ MovedAttribute("urljoin", "urlparse", "urllib.parse"),
+ MovedAttribute("urlparse", "urlparse", "urllib.parse"),
+ MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
+ MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
+ MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
+ MovedAttribute("quote", "urllib", "urllib.parse"),
+ MovedAttribute("quote_plus", "urllib", "urllib.parse"),
+ MovedAttribute("unquote", "urllib", "urllib.parse"),
+ MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
+ MovedAttribute("urlencode", "urllib", "urllib.parse"),
+ MovedAttribute("splitquery", "urllib", "urllib.parse"),
+]
+for attr in _urllib_parse_moved_attributes:
+ setattr(Module_six_moves_urllib_parse, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
+
+sys.modules[__name__ + ".moves.urllib_parse"] = sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse")
+
+
+class Module_six_moves_urllib_error(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_error"""
+
+
+_urllib_error_moved_attributes = [
+ MovedAttribute("URLError", "urllib2", "urllib.error"),
+ MovedAttribute("HTTPError", "urllib2", "urllib.error"),
+ MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
+]
+for attr in _urllib_error_moved_attributes:
+ setattr(Module_six_moves_urllib_error, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
+
+sys.modules[__name__ + ".moves.urllib_error"] = sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error")
+
+
+class Module_six_moves_urllib_request(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_request"""
+
+
+_urllib_request_moved_attributes = [
+ MovedAttribute("urlopen", "urllib2", "urllib.request"),
+ MovedAttribute("install_opener", "urllib2", "urllib.request"),
+ MovedAttribute("build_opener", "urllib2", "urllib.request"),
+ MovedAttribute("pathname2url", "urllib", "urllib.request"),
+ MovedAttribute("url2pathname", "urllib", "urllib.request"),
+ MovedAttribute("getproxies", "urllib", "urllib.request"),
+ MovedAttribute("Request", "urllib2", "urllib.request"),
+ MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
+ MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
+ MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
+ MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
+ MovedAttribute("FileHandler", "urllib2", "urllib.request"),
+ MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
+ MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
+ MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
+ MovedAttribute("urlretrieve", "urllib", "urllib.request"),
+ MovedAttribute("urlcleanup", "urllib", "urllib.request"),
+ MovedAttribute("URLopener", "urllib", "urllib.request"),
+ MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
+ MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
+]
+for attr in _urllib_request_moved_attributes:
+ setattr(Module_six_moves_urllib_request, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
+
+sys.modules[__name__ + ".moves.urllib_request"] = sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request")
+
+
+class Module_six_moves_urllib_response(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_response"""
+
+
+_urllib_response_moved_attributes = [
+ MovedAttribute("addbase", "urllib", "urllib.response"),
+ MovedAttribute("addclosehook", "urllib", "urllib.response"),
+ MovedAttribute("addinfo", "urllib", "urllib.response"),
+ MovedAttribute("addinfourl", "urllib", "urllib.response"),
+]
+for attr in _urllib_response_moved_attributes:
+ setattr(Module_six_moves_urllib_response, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
+
+sys.modules[__name__ + ".moves.urllib_response"] = sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response")
+
+
+class Module_six_moves_urllib_robotparser(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_robotparser"""
+
+
+_urllib_robotparser_moved_attributes = [
+ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
+]
+for attr in _urllib_robotparser_moved_attributes:
+ setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
+
+sys.modules[__name__ + ".moves.urllib_robotparser"] = sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser")
+
+
+class Module_six_moves_urllib(types.ModuleType):
+ """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
+ parse = sys.modules[__name__ + ".moves.urllib_parse"]
+ error = sys.modules[__name__ + ".moves.urllib_error"]
+ request = sys.modules[__name__ + ".moves.urllib_request"]
+ response = sys.modules[__name__ + ".moves.urllib_response"]
+ robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"]
+
+ def __dir__(self):
+ return ['parse', 'error', 'request', 'response', 'robotparser']
+
+
+sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib")
+
+
+def add_move(move):
+ """Add an item to six.moves."""
+ setattr(_MovedItems, move.name, move)
+
+
+def remove_move(name):
+ """Remove item from six.moves."""
+ try:
+ delattr(_MovedItems, name)
+ except AttributeError:
+ try:
+ del moves.__dict__[name]
+ except KeyError:
+ raise AttributeError("no such move, %r" % (name,))
+
+
+if PY3:
+ _meth_func = "__func__"
+ _meth_self = "__self__"
+
+ _func_closure = "__closure__"
+ _func_code = "__code__"
+ _func_defaults = "__defaults__"
+ _func_globals = "__globals__"
+
+ _iterkeys = "keys"
+ _itervalues = "values"
+ _iteritems = "items"
+ _iterlists = "lists"
+else:
+ _meth_func = "im_func"
+ _meth_self = "im_self"
+
+ _func_closure = "func_closure"
+ _func_code = "func_code"
+ _func_defaults = "func_defaults"
+ _func_globals = "func_globals"
+
+ _iterkeys = "iterkeys"
+ _itervalues = "itervalues"
+ _iteritems = "iteritems"
+ _iterlists = "iterlists"
+
+
+try:
+ advance_iterator = next
+except NameError:
+ def advance_iterator(it):
+ return it.next()
+next = advance_iterator
+
+
+try:
+ callable = callable
+except NameError:
+ def callable(obj):
+ return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
+
+
+if PY3:
+ def get_unbound_function(unbound):
+ return unbound
+
+ create_bound_method = types.MethodType
+
+ Iterator = object
+else:
+ def get_unbound_function(unbound):
+ return unbound.im_func
+
+ def create_bound_method(func, obj):
+ return types.MethodType(func, obj, obj.__class__)
+
+ class Iterator(object):
+
+ def next(self):
+ return type(self).__next__(self)
+
+ callable = callable
+_add_doc(get_unbound_function,
+ """Get the function out of a possibly unbound function""")
+
+
+get_method_function = operator.attrgetter(_meth_func)
+get_method_self = operator.attrgetter(_meth_self)
+get_function_closure = operator.attrgetter(_func_closure)
+get_function_code = operator.attrgetter(_func_code)
+get_function_defaults = operator.attrgetter(_func_defaults)
+get_function_globals = operator.attrgetter(_func_globals)
+
+
+def iterkeys(d, **kw):
+ """Return an iterator over the keys of a dictionary."""
+ return iter(getattr(d, _iterkeys)(**kw))
+
+def itervalues(d, **kw):
+ """Return an iterator over the values of a dictionary."""
+ return iter(getattr(d, _itervalues)(**kw))
+
+def iteritems(d, **kw):
+ """Return an iterator over the (key, value) pairs of a dictionary."""
+ return iter(getattr(d, _iteritems)(**kw))
+
+def iterlists(d, **kw):
+ """Return an iterator over the (key, [values]) pairs of a dictionary."""
+ return iter(getattr(d, _iterlists)(**kw))
+
+
+if PY3:
+ def b(s):
+ return s.encode("latin-1")
+ def u(s):
+ return s
+ unichr = chr
+ if sys.version_info[1] <= 1:
+ def int2byte(i):
+ return bytes((i,))
+ else:
+ # This is about 2x faster than the implementation above on 3.2+
+ int2byte = operator.methodcaller("to_bytes", 1, "big")
+ byte2int = operator.itemgetter(0)
+ indexbytes = operator.getitem
+ iterbytes = iter
+ import io
+ StringIO = io.StringIO
+ BytesIO = io.BytesIO
+else:
+ def b(s):
+ return s
+ # Workaround for standalone backslash
+ def u(s):
+ return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
+ unichr = unichr
+ int2byte = chr
+ def byte2int(bs):
+ return ord(bs[0])
+ def indexbytes(buf, i):
+ return ord(buf[i])
+ def iterbytes(buf):
+ return (ord(byte) for byte in buf)
+ import StringIO
+ StringIO = BytesIO = StringIO.StringIO
+_add_doc(b, """Byte literal""")
+_add_doc(u, """Text literal""")
+
+
+if PY3:
+ exec_ = getattr(moves.builtins, "exec")
+
+
+ def reraise(tp, value, tb=None):
+ if value.__traceback__ is not tb:
+ raise value.with_traceback(tb)
+ raise value
+
+else:
+ def exec_(_code_, _globs_=None, _locs_=None):
+ """Execute code in a namespace."""
+ if _globs_ is None:
+ frame = sys._getframe(1)
+ _globs_ = frame.f_globals
+ if _locs_ is None:
+ _locs_ = frame.f_locals
+ del frame
+ elif _locs_ is None:
+ _locs_ = _globs_
+ exec("""exec _code_ in _globs_, _locs_""")
+
+
+ exec_("""def reraise(tp, value, tb=None):
+ raise tp, value, tb
+""")
+
+
+print_ = getattr(moves.builtins, "print", None)
+if print_ is None:
+ def print_(*args, **kwargs):
+ """The new-style print function for Python 2.4 and 2.5."""
+ fp = kwargs.pop("file", sys.stdout)
+ if fp is None:
+ return
+ def write(data):
+ if not isinstance(data, basestring):
+ data = str(data)
+ # If the file has an encoding, encode unicode with it.
+ if (isinstance(fp, file) and
+ isinstance(data, unicode) and
+ fp.encoding is not None):
+ errors = getattr(fp, "errors", None)
+ if errors is None:
+ errors = "strict"
+ data = data.encode(fp.encoding, errors)
+ fp.write(data)
+ want_unicode = False
+ sep = kwargs.pop("sep", None)
+ if sep is not None:
+ if isinstance(sep, unicode):
+ want_unicode = True
+ elif not isinstance(sep, str):
+ raise TypeError("sep must be None or a string")
+ end = kwargs.pop("end", None)
+ if end is not None:
+ if isinstance(end, unicode):
+ want_unicode = True
+ elif not isinstance(end, str):
+ raise TypeError("end must be None or a string")
+ if kwargs:
+ raise TypeError("invalid keyword arguments to print()")
+ if not want_unicode:
+ for arg in args:
+ if isinstance(arg, unicode):
+ want_unicode = True
+ break
+ if want_unicode:
+ newline = unicode("\n")
+ space = unicode(" ")
+ else:
+ newline = "\n"
+ space = " "
+ if sep is None:
+ sep = space
+ if end is None:
+ end = newline
+ for i, arg in enumerate(args):
+ if i:
+ write(sep)
+ write(arg)
+ write(end)
+
+_add_doc(reraise, """Reraise an exception.""")
+
+
+def with_metaclass(meta, *bases):
+ """Create a base class with a metaclass."""
+ return meta("NewBase", bases, {})
+
+def add_metaclass(metaclass):
+ """Class decorator for creating a class with a metaclass."""
+ def wrapper(cls):
+ orig_vars = cls.__dict__.copy()
+ orig_vars.pop('__dict__', None)
+ orig_vars.pop('__weakref__', None)
+ slots = orig_vars.get('__slots__')
+ if slots is not None:
+ if isinstance(slots, str):
+ slots = [slots]
+ for slots_var in slots:
+ orig_vars.pop(slots_var)
+ return metaclass(cls.__name__, cls.__bases__, orig_vars)
+ return wrapper
diff --git a/src/engine/SCons/compat/sixTests.py b/src/engine/SCons/compat/sixTests.py
new file mode 100644
index 0000000..f8c1979
--- /dev/null
+++ b/src/engine/SCons/compat/sixTests.py
@@ -0,0 +1,34 @@
+#
+# __COPYRIGHT__
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# 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.
+#
+
+import unittest
+
+class sixTestCase(unittest.TestCase):
+
+ def test_import(self):
+ """Test that six imports correctly."""
+ import sys
+ print sys.path
+ from SCons.compat.six import PY2, PY3
+ self.assertTrue(PY2 or PY3)
+
diff --git a/src/engine/SCons/dblite.py b/src/engine/SCons/dblite.py
index f4ba90a..dbbd65d 100644
--- a/src/engine/SCons/dblite.py
+++ b/src/engine/SCons/dblite.py
@@ -1,5 +1,6 @@
# dblite.py module contributed by Ralf W. Grosse-Kunstleve.
# Extended for Unicode by Steven Knight.
+from __future__ import print_function
import SCons.compat
@@ -14,7 +15,7 @@ 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
except NameError:
@@ -23,13 +24,16 @@ except NameError:
else:
def is_string(s):
return type(s) in (str, unicode)
-
+def is_bytes(s):
+ return isinstance (s, bytes)
try:
unicode('a')
except NameError:
def unicode(s): return s
dblite_suffix = '.dblite'
+if bytes is not str:
+ dblite_suffix += '.p3'
tmp_suffix = '.tmp'
class dblite(object):
@@ -77,7 +81,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 +94,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 +126,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)
@@ -148,10 +152,10 @@ class dblite(object):
self._check_writable()
if (not is_string(key)):
raise TypeError("key `%s' must be a string but is %s" % (key, type(key)))
- if (not is_string(value)):
- raise TypeError("value `%s' must be a string but is %s" % (value, type(value)))
+ if (not is_bytes(value)):
+ raise TypeError("value `%s' must be a bytes 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 +175,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():
@@ -198,7 +202,7 @@ def _exercise():
assert db[unicode("ubar")] == unicode("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 +212,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 +242,10 @@ 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"
if (__name__ == "__main__"):
_exercise()
diff --git a/src/script/scons-time.py b/src/script/scons-time.py
index 3b215f9..9737dfe 100644
--- a/src/script/scons-time.py
+++ b/src/script/scons-time.py
@@ -29,8 +29,7 @@
# 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
+from __future__ import division, print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -109,8 +108,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 +145,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 +158,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 +252,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 +268,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()
@@ -540,7 +539,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 +549,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,7 +689,7 @@ 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)
@@ -751,7 +750,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 +855,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 +888,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 +1232,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
diff --git a/src/script/scons.py b/src/script/scons.py
index 0c7b44c..25ae644 100644
--- a/src/script/scons.py
+++ b/src/script/scons.py
@@ -56,11 +56,11 @@ import sys
# engine modules if they're in either directory.
-if sys.version_info >= (3,0,0):
- msg = "scons: *** SCons version %s does not run under Python version %s.\n\
-Python 3 is not yet supported.\n"
- sys.stderr.write(msg % (__version__, sys.version.split()[0]))
- sys.exit(1)
+## if sys.version_info >= (3,0,0):
+## msg = "scons: *** SCons version %s does not run under Python version %s.\n\
+## Python 3 is not yet supported.\n"
+## sys.stderr.write(msg % (__version__, sys.version.split()[0]))
+## sys.exit(1)
script_dir = sys.path[0]
@@ -191,7 +191,7 @@ if __name__ == "__main__":
except:
print("Import failed. Unable to find SCons files in:")
for path in libs:
- print " %s" % path
+ print(" %s" % path)
raise
# this does all the work, and calls sys.exit
diff --git a/src/script/sconsign.py b/src/script/sconsign.py
index e5e9d4f..9f75e3a 100644
--- a/src/script/sconsign.py
+++ b/src/script/sconsign.py
@@ -22,6 +22,9 @@
# 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 print_function
+
+from SCons.compat.six import PY2, PY3
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -82,7 +85,7 @@ try:
except ImportError:
pass
else:
- # when running from an egg add the egg's directory
+ # when running from an egg add the egg's directory
try:
d = pkg_resources.get_distribution('scons')
except pkg_resources.DistributionNotFound:
@@ -171,7 +174,9 @@ sys.path = libs + sys.path
import SCons.compat # so pickle will import cPickle instead
-import whichdb
+if PY2:
+ import whichdb
+import dbm
import time
import pickle
import imp
@@ -189,8 +194,11 @@ def my_whichdb(filename):
pass
return _orig_whichdb(filename)
-_orig_whichdb = whichdb.whichdb
-whichdb.whichdb = my_whichdb
+if PY3:
+ _orig_whichdb = dbm.whichdb
+else:
+ _orig_whichdb = whichdb.whichdb
+dbm.whichdb = my_whichdb
def my_import(mname):
if '.' in mname:
@@ -310,14 +318,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 +338,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 +348,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 +369,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 +383,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 +394,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 +411,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 +427,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 +479,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 +505,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/setup.py b/src/setup.py
index a8b59a3..2c75c60 100644
--- a/src/setup.py
+++ b/src/setup.py
@@ -46,14 +46,6 @@ man_pages = [
'scons-time.1',
]
-# Exit with error if trying to install with Python >= 3.0
-if sys.version_info >= (3,0,0):
- msg = "scons: *** SCons does not run under Python version %s.\n\
-Python 3 and above are not yet supported.\n"
- sys.stderr.write(msg % (sys.version.split()[0]))
- sys.exit(1)
-
-
# change to setup.py directory if it was executed from other dir
(head, tail) = os.path.split(sys.argv[0])
if head:
diff --git a/src/test_files.py b/src/test_files.py
index 7d8e75e..1eee11d 100644
--- a/src/test_files.py
+++ b/src/test_files.py
@@ -21,6 +21,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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -87,13 +88,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..de3a0db 100644
--- a/src/test_interrupts.py
+++ b/src/test_interrupts.py
@@ -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..54d78fb 100644
--- a/src/test_pychecker.py
+++ b/src/test_pychecker.py
@@ -20,6 +20,7 @@
# 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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -139,7 +140,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..edf0de5 100644
--- a/src/test_setup.py
+++ b/src/test_setup.py
@@ -21,6 +21,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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -197,9 +198,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..297d59d 100644
--- a/src/test_strings.py
+++ b/src/test_strings.py
@@ -21,6 +21,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 print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -248,13 +249,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()