diff options
author | Stefan Zimmermann <zimmermann.code@gmail.com> | 2014-03-31 15:13:02 (GMT) |
---|---|---|
committer | Stefan Zimmermann <zimmermann.code@gmail.com> | 2014-03-31 15:13:02 (GMT) |
commit | 1a1a11122ad28df19d305af879ba79a2b08ce7d4 (patch) | |
tree | 4464eb544fe0cc698ea4d1c5789e19770b83cd6f /src | |
parent | 9f36c5b899b8d2d54cae8d3da76b01308c144ed6 (diff) | |
download | SCons-1a1a11122ad28df19d305af879ba79a2b08ce7d4.zip SCons-1a1a11122ad28df19d305af879ba79a2b08ce7d4.tar.gz SCons-1a1a11122ad28df19d305af879ba79a2b08ce7d4.tar.bz2 |
Made former 2to3 changes Python 2.7 compatible (or removed unneeded changes).
Diffstat (limited to 'src')
71 files changed, 273 insertions, 219 deletions
diff --git a/src/engine/SCons/Action.py b/src/engine/SCons/Action.py index 66757a4..006e8f5 100644 --- a/src/engine/SCons/Action.py +++ b/src/engine/SCons/Action.py @@ -114,7 +114,6 @@ import SCons.Errors import SCons.Executor import SCons.Util import SCons.Subst -import collections # we use these a lot, so try to optimize them is_String = SCons.Util.is_String @@ -329,7 +328,7 @@ def _do_create_keywords(args, kw): cmdstrfunc = args[0] if cmdstrfunc is None or is_String(cmdstrfunc): kw['cmdstr'] = cmdstrfunc - elif isinstance(cmdstrfunc, collections.Callable): + elif callable(cmdstrfunc): kw['strfunction'] = cmdstrfunc else: raise SCons.Errors.UserError( @@ -360,7 +359,7 @@ def _do_create_action(act, kw): if is_List(act): return CommandAction(act, **kw) - if isinstance(act, collections.Callable): + if callable(act): try: gen = kw['generator'] del kw['generator'] @@ -494,7 +493,7 @@ class _ActionAction(ActionBase): self.targets = targets if batch_key: - if not isinstance(batch_key, collections.Callable): + if not callable(batch_key): # They have set batch_key, but not to their own # callable. The default behavior here will batch # *all* targets+sources using this action, separated @@ -514,7 +513,7 @@ class _ActionAction(ActionBase): # This code assumes s is a regular string, but should # work if it's unicode too. try: - sys.stdout.write(str(s + "\n")) + sys.stdout.write(s + u"\n") except UnicodeDecodeError: sys.stdout.write(s + "\n") @@ -555,7 +554,7 @@ class _ActionAction(ActionBase): source = executor.get_all_sources() t = ' and '.join(map(str, target)) l = '\n '.join(self.presub_lines(env)) - out = "Building %s with action:\n %s\n" % (t, l) + out = u"Building %s with action:\n %s\n" % (t, l) sys.stdout.write(out) cmd = None if show and self.strfunction: @@ -655,7 +654,7 @@ def _subproc(scons_env, cmd, error = 'ignore', **kw): # Ensure that the ENV values are all strings: new_env = {} - for key, value in list(ENV.items()): + for key, value in ENV.items(): if is_List(value): # If the value is a list, then we assume it is a path list, # because that's a pretty common list-like value to stick @@ -781,7 +780,7 @@ class CommandAction(_ActionAction): ENV = get_default_ENV(env) # Ensure that the ENV values are all strings: - for key, value in list(ENV.items()): + for key, value in ENV.items(): if not is_String(value): if is_List(value): # If the value is a list, then we assume it is a @@ -1040,7 +1039,7 @@ class FunctionAction(_ActionAction): else: if strfunc is None: return None - if isinstance(strfunc, collections.Callable): + if callable(strfunc): return strfunc(target, source, env) name = self.function_name() tstr = array(target) @@ -1216,7 +1215,7 @@ class ActionCaller(object): def subst_kw(self, target, source, env): kw = {} - for key in list(self.kw.keys()): + for key in self.kw.keys(): kw[key] = self.subst(self.kw[key], target, source, env) return kw diff --git a/src/engine/SCons/ActionTests.py b/src/engine/SCons/ActionTests.py index 6edf373..754c6e7 100644 --- a/src/engine/SCons/ActionTests.py +++ b/src/engine/SCons/ActionTests.py @@ -133,7 +133,7 @@ class Environment(object): self.d['SPAWN'] = scons_env['SPAWN'] self.d['PSPAWN'] = scons_env['PSPAWN'] self.d['ESCAPE'] = scons_env['ESCAPE'] - for k, v in list(kw.items()): + for k, v in kw.items(): self.d[k] = v # Just use the underlying scons_subst*() utility methods. def subst(self, strSubst, raw=0, target=[], source=[], conv=None): @@ -158,12 +158,12 @@ class Environment(object): def Clone(self, **kw): res = Environment() res.d = SCons.Util.semi_deepcopy(self.d) - for k, v in list(kw.items()): + for k, v in kw.items(): res.d[k] = v return res def sig_dict(self): d = {} - for k,v in list(self.items()): d[k] = v + for k,v in self.items(): d[k] = v d['TARGETS'] = ['__t1__', '__t2__', '__t3__', '__t4__', '__t5__', '__t6__'] d['TARGET'] = d['TARGETS'][0] d['SOURCES'] = ['__s1__', '__s2__', '__s3__', '__s4__', '__s5__', '__s6__'] @@ -305,7 +305,7 @@ class ActionTestCase(unittest.TestCase): # a singleton list returns the contained action test_positional_args(cmd_action, ["string"]) - try: str + try: unicode except NameError: pass else: a2 = eval("SCons.Action.Action(u'string')") diff --git a/src/engine/SCons/Builder.py b/src/engine/SCons/Builder.py index 6abcbcf..0f7aff4 100644 --- a/src/engine/SCons/Builder.py +++ b/src/engine/SCons/Builder.py @@ -179,7 +179,7 @@ class CallableSelector(SCons.Util.Selector): finds if it can.""" def __call__(self, env, source): value = SCons.Util.Selector.__call__(self, env, source) - if isinstance(value, collections.Callable): + if callable(value): value = value(env, source) return value @@ -230,7 +230,7 @@ class OverrideWarner(collections.UserDict): def warn(self): if self.already_warned: return - for k in list(self.keys()): + for k in self.keys(): if k in misleading_keywords: alt = misleading_keywords[k] msg = "Did you mean to use `%s' instead of `%s'?" % (alt, k) @@ -336,7 +336,7 @@ class EmitterProxy(object): # in strings. Maybe we should change that? while SCons.Util.is_String(emitter) and emitter in env: emitter = env[emitter] - if isinstance(emitter, collections.Callable): + if callable(emitter): target, source = emitter(target, source, env) elif SCons.Util.is_List(emitter): for e in emitter: @@ -426,9 +426,12 @@ class BuilderBase(object): src_builder = [ src_builder ] self.src_builder = src_builder - def __bool__(self): + 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. @@ -638,18 +641,18 @@ class BuilderBase(object): def get_prefix(self, env, sources=[]): prefix = self.prefix - if isinstance(prefix, collections.Callable): + if callable(prefix): prefix = prefix(env, sources) return env.subst(prefix) def set_suffix(self, suffix): - if not isinstance(suffix, collections.Callable): + if not callable(suffix): suffix = self.adjust_suffix(suffix) self.suffix = suffix def get_suffix(self, env, sources=[]): suffix = self.suffix - if isinstance(suffix, collections.Callable): + if callable(suffix): suffix = suffix(env, sources) return env.subst(suffix) @@ -658,7 +661,7 @@ class BuilderBase(object): src_suffix = [] elif not SCons.Util.is_List(src_suffix): src_suffix = [ src_suffix ] - self.src_suffix = [isinstance(suf, collections.Callable) and suf or self.adjust_suffix(suf) for suf in src_suffix] + self.src_suffix = [callable(suf) and suf or self.adjust_suffix(suf) for suf in src_suffix] def get_src_suffix(self, env): """Get the first src_suffix in the list of src_suffixes.""" @@ -868,7 +871,7 @@ def is_a_Builder(obj): """ return (isinstance(obj, BuilderBase) or isinstance(obj, CompositeBuilder) - or isinstance(obj, collections.Callable)) + or callable(obj)) # Local Variables: # tab-width:4 diff --git a/src/engine/SCons/BuilderTests.py b/src/engine/SCons/BuilderTests.py index da03a3c..41b640b 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__" @@ -77,7 +78,7 @@ class Environment(object): self.d['SHELL'] = scons_env['SHELL'] self.d['SPAWN'] = scons_env['SPAWN'] self.d['ESCAPE'] = scons_env['ESCAPE'] - for k, v in list(kw.items()): + for k, v in kw.items(): self.d[k] = v global env_arg2nodes_called env_arg2nodes_called = None @@ -138,7 +139,7 @@ class Environment(object): return list(self.d.items()) def sig_dict(self): d = {} - for k,v in list(self.items()): d[k] = v + for k,v in self.items(): d[k] = v d['TARGETS'] = ['__t1__', '__t2__', '__t3__', '__t4__', '__t5__', '__t6__'] d['TARGET'] = d['TARGETS'][0] d['SOURCES'] = ['__s1__', '__s2__', '__s3__', '__s4__', '__s5__', '__s6__'] @@ -305,11 +306,11 @@ class BuilderTestCase(unittest.TestCase): #be = target.get_build_env() #assert be['VAR'] == 'foo', be['VAR'] - try: str + try: unicode except NameError: uni = str else: - uni = str + uni = unicode target = builder(env, target = uni('n12 n13'), source = [uni('n14 n15')])[0] diff --git a/src/engine/SCons/Conftest.py b/src/engine/SCons/Conftest.py index 4e2a3e8..6212a47 100644 --- a/src/engine/SCons/Conftest.py +++ b/src/engine/SCons/Conftest.py @@ -728,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/Debug.py b/src/engine/SCons/Debug.py index 363c8b7..1c0c638 100644 --- a/src/engine/SCons/Debug.py +++ b/src/engine/SCons/Debug.py @@ -73,7 +73,7 @@ def dumpLoggedInstances(classes, file=sys.stdout): obj = ref() if obj is not None: file.write(' %s:\n' % obj) - for key, value in list(obj.__dict__.items()): + for key, value in obj.__dict__.items(): file.write(' %20s : %s\n' % (key, value)) @@ -143,7 +143,7 @@ def caller_trace(back=0): # print a single caller and its callers, if any def _dump_one_caller(key, file, level=0): leader = ' '*level - for v,c in sorted([(-v,c) for c,v in list(caller_dicts[key].items())]): + for v,c in sorted([(-v,c) for c,v in caller_dicts[key].items()]): file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:]))) if c in caller_dicts: _dump_one_caller(c, file, level+1) diff --git a/src/engine/SCons/Defaults.py b/src/engine/SCons/Defaults.py index fe1f87b..491b9f2 100644 --- a/src/engine/SCons/Defaults.py +++ b/src/engine/SCons/Defaults.py @@ -31,7 +31,7 @@ from distutils.msvccompiler. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # - +from __future__ import division __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -50,7 +50,6 @@ import SCons.Environment import SCons.PathList import SCons.Subst import SCons.Tool -import collections # A placeholder for a default Environment (for fetching source files # from source code management systems and the like). This must be @@ -326,9 +325,9 @@ def _stripixes(prefix, itms, suffix, stripprefixes, stripsuffixes, env, c=None): if not itms: return itms - if not isinstance(c, collections.Callable): + if not callable(c): env_c = env['_concat'] - if env_c != _concat and isinstance(env_c, collections.Callable): + if env_c != _concat and callable(env_c): # There's a custom _concat() method in the construction # environment, and we've allowed people to set that in # the past (see test/custom-concat.py), so preserve the diff --git a/src/engine/SCons/Environment.py b/src/engine/SCons/Environment.py index 88b0553..b5bd620 100644 --- a/src/engine/SCons/Environment.py +++ b/src/engine/SCons/Environment.py @@ -58,7 +58,6 @@ import SCons.Subst import SCons.Tool import SCons.Util import SCons.Warnings -import collections class _Null(object): pass @@ -128,7 +127,7 @@ future_reserved_construction_var_names = [ def copy_non_reserved_keywords(dict): result = semi_deepcopy(dict) - for k in list(result.keys()): + for k in 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) @@ -152,7 +151,7 @@ def _set_BUILDERS(env, key, value): except KeyError: bd = BuilderDict(kwbd, env) env._dict[key] = bd - for k, v in list(value.items()): + for k, v in value.items(): if not SCons.Builder.is_a_Builder(v): raise SCons.Errors.UserError('%s is not a Builder.' % repr(v)) bd.update(value) @@ -324,7 +323,7 @@ class BuilderDict(UserDict): delattr(self.env, item) def update(self, dict): - for i, v in list(dict.items()): + for i, v in dict.items(): self.__setitem__(i, v) @@ -518,7 +517,7 @@ class SubstitutionEnvironment(object): def subst_kw(self, kw, raw=0, target=None, source=None): nkw = {} - for k, v in list(kw.items()): + for k, v in kw.items(): k = self.subst(k, raw, target, source) if SCons.Util.is_String(v): v = self.subst(v, raw, target, source) @@ -592,7 +591,7 @@ class SubstitutionEnvironment(object): out,err = p.communicate() status = p.wait() if err: - sys.stderr.write(str(err)) + sys.stderr.write(u"" + err) if status: raise OSError("'%s' exited %d" % (command, status)) return out @@ -630,7 +629,7 @@ class SubstitutionEnvironment(object): if not o: return self overrides = {} merges = None - for key, value in list(o.items()): + for key, value in o.items(): if key == 'parse_flags': merges = value else: @@ -815,7 +814,7 @@ class SubstitutionEnvironment(object): if not unique: self.Append(**args) return self - for key, value in list(args.items()): + for key, value in args.items(): if not value: continue try: @@ -1005,7 +1004,7 @@ class Base(SubstitutionEnvironment): # Now restore the passed-in and customized variables # to the environment, since the values the user set explicitly # should override any values set by the tools. - for key, val in list(save.items()): + for key, val in save.items(): self._dict[key] = val # Finally, apply any flags to be merged in @@ -1263,7 +1262,7 @@ class Base(SubstitutionEnvironment): values move to end. """ kw = copy_non_reserved_keywords(kw) - for key, val in list(kw.items()): + for key, val in kw.items(): if SCons.Util.is_List(val): val = _delete_duplicates(val, delete_existing) if key not in self._dict or self._dict[key] in ('', None): @@ -1403,7 +1402,7 @@ class Base(SubstitutionEnvironment): # so the tools can use the new variables kw = copy_non_reserved_keywords(kw) new = {} - for key, value in list(kw.items()): + for key, value in kw.items(): new[key] = SCons.Subst.scons_subst_once(value, self, key) clone.Replace(**new) @@ -1470,7 +1469,7 @@ class Base(SubstitutionEnvironment): copy_function = self._copy_from_cache elif function == 'timestamp-match': function = self._changed_timestamp_match - elif not isinstance(function, collections.Callable): + elif not callable(function): raise UserError("Unknown Decider value %s" % repr(function)) # We don't use AddMethod because we don't want to turn the @@ -1603,7 +1602,7 @@ class Base(SubstitutionEnvironment): in an Environment. """ kw = copy_non_reserved_keywords(kw) - for key, val in list(kw.items()): + for key, val in 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" @@ -1694,7 +1693,7 @@ class Base(SubstitutionEnvironment): values move to front. """ kw = copy_non_reserved_keywords(kw) - for key, val in list(kw.items()): + for key, val in kw.items(): if SCons.Util.is_List(val): val = _delete_duplicates(val, not delete_existing) if key not in self._dict or self._dict[key] in ('', None): @@ -1769,7 +1768,7 @@ class Base(SubstitutionEnvironment): return os.path.join(dir, new_prefix+name+new_suffix) def SetDefault(self, **kw): - for k in list(kw.keys()): + for k in kw.keys(): if k in self._dict: del kw[k] self.Replace(**kw) @@ -1831,7 +1830,7 @@ class Base(SubstitutionEnvironment): uniq = {} for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 - for executor in list(uniq.keys()): + for executor in uniq.keys(): executor.add_pre_action(action) return nodes @@ -1841,7 +1840,7 @@ class Base(SubstitutionEnvironment): uniq = {} for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 - for executor in list(uniq.keys()): + for executor in uniq.keys(): executor.add_post_action(action) return nodes diff --git a/src/engine/SCons/EnvironmentTests.py b/src/engine/SCons/EnvironmentTests.py index 3af879a..22552b3 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__" @@ -160,7 +161,7 @@ class TestEnvironmentFixture(object): default_keys = { 'CC' : 'cc', 'CCFLAGS' : '-DNDEBUG', 'ENV' : { 'TMP' : '/tmp' } } - for key, value in list(default_keys.items()): + for key, value in default_keys.items(): if key not in kw: kw[key] = value if 'BUILDERS' not in kw: @@ -263,16 +264,10 @@ class SubstitutionTestCase(unittest.TestCase): assert isinstance(nodes[0], X) assert nodes[0].name == "Util.py UtilTests.py" - try: str - 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, 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 diff --git a/src/engine/SCons/Executor.py b/src/engine/SCons/Executor.py index 68419b8..6248cf1 100644 --- a/src/engine/SCons/Executor.py +++ b/src/engine/SCons/Executor.py @@ -428,8 +428,8 @@ class Executor(object): pass env = self.get_build_env() result = b"".join([action.get_contents(self.get_all_targets(), - self.get_all_sources(), - env) + 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/Memoize.py b/src/engine/SCons/Memoize.py index 9fe6851..ac728c9 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__" diff --git a/src/engine/SCons/MemoizeTests.py b/src/engine/SCons/MemoizeTests.py index b6750e0..06b4235 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 six import add_metaclass __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -29,8 +30,8 @@ import unittest import SCons.Memoize - -class FakeObject(object, metaclass=SCons.Memoize.Memoized_Metaclass): +@add_metaclass(SCons.Memoize.Memoized_Metaclass) +class FakeObject(object): memoizer_counters = [] diff --git a/src/engine/SCons/Node/FS.py b/src/engine/SCons/Node/FS.py index 22dca1f..91c6893 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__" @@ -54,7 +55,6 @@ import SCons.Util import SCons.Warnings from SCons.Debug import Trace -import collections do_store_info = True print_duplicate = 0 @@ -1509,7 +1509,7 @@ class Dir(Base): This clears any cached information that is invalidated by changing the repository.""" - for node in list(self.entries.values()): + for node in self.entries.values(): if node != self.dir: if node != self and isinstance(node, Dir): node.__clearRepositoryCache(duplicate) @@ -2056,7 +2056,7 @@ class Dir(Base): # We use the .name attribute from the Node because the keys of # the dir.entries dictionary are normalized (that is, all upper # case) on case-insensitive systems like Windows. - node_names = [ v.name for k, v in list(dir.entries.items()) + node_names = [ v.name for k, v in dir.entries.items() if k not in ('.', '..') ] names.extend(node_names) if not strings: @@ -3197,10 +3197,10 @@ class FileFinder(object): except KeyError: pass - if verbose and not isinstance(verbose, collections.Callable): + if verbose and not callable(verbose): if not SCons.Util.is_String(verbose): verbose = "find_file" - _verbose = ' %s: ' % verbose + _verbose = u' %s: ' % verbose verbose = lambda s: sys.stdout.write(_verbose + s) filedir, filename = os.path.split(filename) diff --git a/src/engine/SCons/Node/FSTests.py b/src/engine/SCons/Node/FSTests.py index e8442e9..66803f9 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, print_function __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -1305,7 +1305,7 @@ class FSTestCase(_tempdirTestCase): assert f1.get_contents() == "Foo\x1aBar", f1.get_contents() # This tests to make sure we can decode UTF-8 text files. - test_string = "Foo\x1aBar" + test_string = u"Foo\x1aBar" test.write("utf8_file", test_string.encode('utf-8')) f1 = fs.File(test.workpath("utf8_file")) assert eval('f1.get_text_contents() == u"Foo\x1aBar"'), \ diff --git a/src/engine/SCons/Node/__init__.py b/src/engine/SCons/Node/__init__.py index 8f48d86..7f5d7ff 100644 --- a/src/engine/SCons/Node/__init__.py +++ b/src/engine/SCons/Node/__init__.py @@ -1197,8 +1197,8 @@ class Node(object): new_bkids = new.bsources + new.bdepends + new.bimplicit new_bkidsigs = new.bsourcesigs + new.bdependsigs + new.bimplicitsigs - osig = dict(list(zip(old_bkids, old_bkidsigs))) - nsig = dict(list(zip(new_bkids, new_bkidsigs))) + osig = dict(zip(old_bkids, old_bkidsigs)) + nsig = dict(zip(new_bkids, new_bkidsigs)) # The sources and dependencies we'll want to report are all stored # as relative paths to this target's directory, but we want to diff --git a/src/engine/SCons/Platform/__init__.py b/src/engine/SCons/Platform/__init__.py index 6ef8b05..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__" diff --git a/src/engine/SCons/Platform/posix.py b/src/engine/SCons/Platform/posix.py index d1f6c78..908be4d 100644 --- a/src/engine/SCons/Platform/posix.py +++ b/src/engine/SCons/Platform/posix.py @@ -92,7 +92,7 @@ def _get_env_command(sh, escape, cmd, args, env): s = ' '.join(args) if env: l = ['env', '-'] + \ - [escape(t[0])+'='+escape(t[1]) for t in list(env.items())] + \ + [escape(t[0])+'='+escape(t[1]) for t in env.items()] + \ [sh, '-c', escape(s)] s = ' '.join(l) return s diff --git a/src/engine/SCons/SConf.py b/src/engine/SCons/SConf.py index e14c5e0..62f2671 100644 --- a/src/engine/SCons/SConf.py +++ b/src/engine/SCons/SConf.py @@ -25,6 +25,7 @@ Autoconf-like configuration support. # 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__" @@ -118,7 +119,7 @@ def CreateConfigHBuilder(env): _stringConfigH) sconfigHBld = SCons.Builder.Builder(action=action) env.Append( BUILDERS={'SConfigHBuilder':sconfigHBld} ) - for k in list(_ac_config_hs.keys()): + for k in _ac_config_hs.keys(): env.SConfigHBuilder(k, env.Value(_ac_config_hs[k])) class SConfWarning(SCons.Warnings.Warning): @@ -175,19 +176,13 @@ class Streamer(object): """ def __init__(self, orig): self.orig = orig - try: - import StringIO - self.s = StringIO.StringIO() - except: - self.s = io.StringIO() + self.s = io.StringIO() def write(self, str): - try: - if self.orig: - self.orig.write(str) - self.s.write(str) - except: - print ('oops') + if self.orig: + self.orig.write(str) + self.s.write(str) + def writelines(self, lines): for l in lines: self.write(l + '\n') @@ -658,7 +653,7 @@ class SConfBase(object): """Adds all the tests given in the tests dictionary to this SConf instance """ - for name in list(tests.keys()): + for name in tests.keys(): self.AddTest(name, tests[name]) def _createDir( self, node ): diff --git a/src/engine/SCons/SConfTests.py b/src/engine/SCons/SConfTests.py index ba524fd..e604886 100644 --- a/src/engine/SCons/SConfTests.py +++ b/src/engine/SCons/SConfTests.py @@ -60,7 +60,7 @@ class SConfTestCase(unittest.TestCase): # We try to reset scons' state (including all global variables) import SCons.SConsign SCons.SConsign.write() # simulate normal scons-finish - for n in list(sys.modules.keys()): + for n in 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 5ce61be..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__" @@ -172,7 +173,7 @@ class Base(object): pass def merge(self): - for key, node in list(self.to_be_merged.items()): + for key, node in self.to_be_merged.items(): entry = node.get_stored_info() try: ninfo = entry.ninfo @@ -218,7 +219,7 @@ class DB(Base): 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 list(self.entries.items()): + for key, entry in self.entries.items(): entry.convert_from_sconsign(dir, key) if mode == "r": @@ -245,7 +246,7 @@ class DB(Base): # the Repository; we only write to our own .sconsign file, # not to .sconsign files in Repositories. path = normcase(self.dir.path) - for key, entry in list(self.entries.items()): + for key, entry in self.entries.items(): entry.convert_to_sconsign() db[path] = pickle.dumps(self.entries, 1) @@ -333,7 +334,7 @@ class DirFile(Dir): fname = self.sconsign except IOError: return - for key, entry in list(self.entries.items()): + for key, entry in self.entries.items(): entry.convert_to_sconsign() pickle.dump(self.entries, file, 1) file.close() diff --git a/src/engine/SCons/Scanner/Fortran.py b/src/engine/SCons/Scanner/Fortran.py index 5339ab2..1b55130 100644 --- a/src/engine/SCons/Scanner/Fortran.py +++ b/src/engine/SCons/Scanner/Fortran.py @@ -35,7 +35,6 @@ import SCons.Node.FS import SCons.Scanner import SCons.Util import SCons.Warnings -import collections class F90Scanner(SCons.Scanner.Classic): """ @@ -110,7 +109,7 @@ class F90Scanner(SCons.Scanner.Classic): # is actually found in a Repository or locally. nodes = [] source_dir = node.get_dir() - if isinstance(path, collections.Callable): + if callable(path): path = path() for dep in mods_and_includes: n, i = self.find_include(dep, source_dir, path) diff --git a/src/engine/SCons/Scanner/LaTeX.py b/src/engine/SCons/Scanner/LaTeX.py index 1e0fea1..2cb1ed5 100644 --- a/src/engine/SCons/Scanner/LaTeX.py +++ b/src/engine/SCons/Scanner/LaTeX.py @@ -200,14 +200,14 @@ class LaTeX(SCons.Scanner.Base): """ def __init__(self, dictionary): self.dictionary = {} - for k,n in list(dictionary.items()): + for k,n in dictionary.items(): self.dictionary[k] = ( SCons.Scanner.FindPathDirs(n), FindENVPathDirs(n) ) def __call__(self, env, dir=None, target=None, source=None, argument=None): di = {} - for k,(c,cENV) in list(self.dictionary.items()): + for k,(c,cENV) in self.dictionary.items(): di[k] = ( c(env, dir=None, target=None, source=None, argument=None) , cENV(env, dir=None, target=None, source=None, diff --git a/src/engine/SCons/Scanner/Prog.py b/src/engine/SCons/Scanner/Prog.py index 6e2da21..49e93a5 100644 --- a/src/engine/SCons/Scanner/Prog.py +++ b/src/engine/SCons/Scanner/Prog.py @@ -27,7 +27,6 @@ import SCons.Node import SCons.Node.FS import SCons.Scanner import SCons.Util -import collections # global, set by --debug=findlibs print_find_libs = None @@ -77,7 +76,7 @@ def scan(node, env, libpath = ()): result = [] - if isinstance(libpath, collections.Callable): + if callable(libpath): libpath = libpath() find_file = SCons.Node.FS.find_file diff --git a/src/engine/SCons/Scanner/ProgTests.py b/src/engine/SCons/Scanner/ProgTests.py index f564c91..250838d 100644 --- a/src/engine/SCons/Scanner/ProgTests.py +++ b/src/engine/SCons/Scanner/ProgTests.py @@ -230,7 +230,7 @@ def suite(): suite.addTest(ProgramScannerTestCase6()) suite.addTest(ProgramScannerTestCase7()) suite.addTest(ProgramScannerTestCase8()) - try: str + try: unicode except NameError: pass else: code = """if 1: diff --git a/src/engine/SCons/Scanner/ScannerTests.py b/src/engine/SCons/Scanner/ScannerTests.py index 5a4639d..ee26922 100644 --- a/src/engine/SCons/Scanner/ScannerTests.py +++ b/src/engine/SCons/Scanner/ScannerTests.py @@ -569,7 +569,7 @@ class ClassicCPPTestCase(unittest.TestCase): assert n == 'path/bbb', n assert i == 'bbb', i - n, i = s.find_include(('<', 'ccc'), 'foo', ('path',)) + n, i = s.find_include(('<', u'ccc'), 'foo', ('path',)) assert n == 'path/ccc', n assert i == 'ccc', i diff --git a/src/engine/SCons/Scanner/__init__.py b/src/engine/SCons/Scanner/__init__.py index b947961..2375bc4 100644 --- a/src/engine/SCons/Scanner/__init__.py +++ b/src/engine/SCons/Scanner/__init__.py @@ -33,7 +33,6 @@ import re import SCons.Node.FS import SCons.Util -import collections class _Null(object): @@ -179,7 +178,7 @@ class Base(object): self.node_class = node_class self.node_factory = node_factory self.scan_check = scan_check - if isinstance(recursive, collections.Callable): + if callable(recursive): self.recurse_nodes = recursive elif recursive: self.recurse_nodes = self._recurse_all_nodes @@ -370,7 +369,7 @@ class Classic(Current): # is actually found in a Repository or locally. nodes = [] source_dir = node.get_dir() - if isinstance(path, collections.Callable): + if callable(path): path = path() for include in includes: n, i = self.find_include(include, source_dir, path) diff --git a/src/engine/SCons/Script/Interactive.py b/src/engine/SCons/Script/Interactive.py index 87fe1cf..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__" @@ -120,7 +121,7 @@ class SConsInteractiveCmd(cmd.Cmd): def __init__(self, **kw): cmd.Cmd.__init__(self) - for key, val in list(kw.items()): + for key, val in kw.items(): setattr(self, key, val) if sys.platform == 'win32': @@ -249,7 +250,7 @@ class SConsInteractiveCmd(cmd.Cmd): while n: n = walker.get_next() - for node in list(seen_nodes.keys()): + for node in seen_nodes.keys(): # Call node.clear() to clear most of the state node.clear() # node.clear() doesn't reset node.state, so call diff --git a/src/engine/SCons/Script/Main.py b/src/engine/SCons/Script/Main.py index 9a52937..584960b 100644 --- a/src/engine/SCons/Script/Main.py +++ b/src/engine/SCons/Script/Main.py @@ -10,6 +10,8 @@ some other module. If it's specific to the "scons" script invocation, it goes here. """ +from __future__ import print_function + unsupported_python_version = (2, 3, 0) deprecated_python_version = (2, 7, 0) @@ -68,7 +70,6 @@ import SCons.Util import SCons.Warnings import SCons.Script.Interactive -import collections def fetch_win32_parallel_msg(): # A subsidiary function that exists solely to isolate this import @@ -105,7 +106,7 @@ class Progressor(object): self.interval = interval self.overwrite = overwrite - if isinstance(obj, collections.Callable): + if callable(obj): self.func = obj elif SCons.Util.is_List(obj): self.func = self.spinner @@ -716,7 +717,7 @@ def _load_site_scons_dir(topdir, site_dir_name=None): modname = os.path.basename(pathname)[:-len(sfx)] site_m = {"__file__": pathname, "__name__": modname, "__doc__": None} re_special = re.compile("__[^_]+__") - for k in list(m.__dict__.keys()): + for k in m.__dict__.keys(): if not re_special.match(k): site_m[k] = m.__dict__[k] diff --git a/src/engine/SCons/Script/SConsOptions.py b/src/engine/SCons/Script/SConsOptions.py index 559db97..a97fc94 100644 --- a/src/engine/SCons/Script/SConsOptions.py +++ b/src/engine/SCons/Script/SConsOptions.py @@ -611,7 +611,7 @@ def Parser(version): deprecated_debug_options=deprecated_debug_options): if value in debug_options: parser.values.debug.append(value) - elif value in list(deprecated_debug_options.keys()): + elif value in deprecated_debug_options.keys(): parser.values.debug.append(value) try: parser.values.delayed_warnings diff --git a/src/engine/SCons/Script/SConscript.py b/src/engine/SCons/Script/SConscript.py index 05cb6a6..b2dc4c1 100644 --- a/src/engine/SCons/Script/SConscript.py +++ b/src/engine/SCons/Script/SConscript.py @@ -26,7 +26,7 @@ files. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - +from __future__ import division, print_function __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -529,7 +529,7 @@ class SConsEnvironment(SCons.Environment.Base): return x ls = list(map(subst_element, ls)) subst_kw = {} - for key, val in list(kw.items()): + for key, val in kw.items(): if SCons.Util.is_String(val): val = self.subst(val) elif SCons.Util.is_List(val): diff --git a/src/engine/SCons/Subst.py b/src/engine/SCons/Subst.py index cca9bbc..f1e80ac 100644 --- a/src/engine/SCons/Subst.py +++ b/src/engine/SCons/Subst.py @@ -472,7 +472,7 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ def func(l, conv=self.conv, substitute=self.substitute, lvars=lvars): return conv(substitute(l, lvars)) return list(map(func, s)) - elif isinstance(s, collections.Callable): + elif callable(s): try: s = s(target=lvars['TARGETS'], source=lvars['SOURCES'], @@ -681,7 +681,7 @@ def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gv for a in s: self.substitute(a, lvars, 1) self.next_word() - elif isinstance(s, collections.Callable): + elif callable(s): try: s = s(target=lvars['TARGETS'], source=lvars['SOURCES'], diff --git a/src/engine/SCons/SubstTests.py b/src/engine/SCons/SubstTests.py index da21020..7001899 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__" diff --git a/src/engine/SCons/Taskmaster.py b/src/engine/SCons/Taskmaster.py index 14ffe8c..86bff53 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. @@ -164,7 +165,7 @@ class Task(object): """ global print_prepare T = self.tm.trace - if T: T.write(self.trace_message('Task.prepare()', self.node)) + if T: T.write(self.trace_message(u'Task.prepare()', self.node)) # Now that it's the appropriate time, give the TaskMaster a # chance to raise any exceptions it encountered while preparing @@ -224,7 +225,7 @@ class Task(object): prepare(), executed() or failed(). """ T = self.tm.trace - if T: T.write(self.trace_message('Task.execute()', self.node)) + if T: T.write(self.trace_message(u'Task.execute()', self.node)) try: cached_targets = [] @@ -383,7 +384,7 @@ class Task(object): This is the default behavior for building only what's necessary. """ T = self.tm.trace - if T: T.write(self.trace_message('Task.make_ready_current()', + if T: T.write(self.trace_message(u'Task.make_ready_current()', self.node)) self.out_of_date = [] @@ -428,7 +429,7 @@ class Task(object): that can be put back on the candidates list. """ T = self.tm.trace - if T: T.write(self.trace_message('Task.postprocess()', self.node)) + if T: T.write(self.trace_message(u'Task.postprocess()', self.node)) # We may have built multiple targets, some of which may have # common parents waiting for this build. Count up how many @@ -445,7 +446,7 @@ class Task(object): # A node can only be in the pending_children set if it has # some waiting_parents. if t.waiting_parents: - if T: T.write(self.trace_message('Task.postprocess()', + if T: T.write(self.trace_message(u'Task.postprocess()', t, 'removing')) pending_children.discard(t) @@ -462,9 +463,9 @@ class Task(object): if p.ref_count == 0: self.tm.candidates.append(p) - for p, subtract in list(parents.items()): + for p, subtract in parents.items(): p.ref_count = p.ref_count - subtract - if T: T.write(self.trace_message('Task.postprocess()', + if T: T.write(self.trace_message(u'Task.postprocess()', p, 'adjusted parent ref count')) if p.ref_count == 0: @@ -744,12 +745,12 @@ class Taskmaster(object): self.ready_exc = None T = self.trace - if T: T.write('\n' + self.trace_message('Looking for a node to evaluate')) + if T: T.write(u'\n' + self.trace_message('Looking for a node to evaluate')) while True: node = self.next_candidate() if node is None: - if T: T.write(self.trace_message('No candidate anymore.') + '\n') + if T: T.write(self.trace_message('No candidate anymore.') + u'\n') return None node = node.disambiguate() @@ -772,7 +773,7 @@ class Taskmaster(object): else: S = None - if T: T.write(self.trace_message(' Considering node %s and its children:' % self.trace_node(node))) + if T: T.write(self.trace_message(u' Considering node %s and its children:' % self.trace_node(node))) if state == NODE_NO_STATE: # Mark this node as being on the execution stack: @@ -780,7 +781,7 @@ class Taskmaster(object): elif state > NODE_PENDING: # Skip this node if it has already been evaluated: if S: S.already_handled = S.already_handled + 1 - if T: T.write(self.trace_message(' already handled (executed)')) + if T: T.write(self.trace_message(u' already handled (executed)')) continue executor = node.get_executor() @@ -811,7 +812,7 @@ class Taskmaster(object): for child in chain(executor.get_all_prerequisites(), children): childstate = child.get_state() - if T: T.write(self.trace_message(' ' + self.trace_node(child))) + if T: T.write(self.trace_message(u' ' + self.trace_node(child))) if childstate == NODE_NO_STATE: children_not_visited.append(child) @@ -870,7 +871,7 @@ class Taskmaster(object): # count so we can be put back on the list for # re-evaluation when they've all finished. node.ref_count = node.ref_count + child.add_to_waiting_parents(node) - if T: T.write(self.trace_message(' adjusted ref count: %s, child %s' % + if T: T.write(self.trace_message(u' adjusted ref count: %s, child %s' % (self.trace_node(node), repr(str(child))))) if T: @@ -896,7 +897,7 @@ class Taskmaster(object): # The default when we've gotten through all of the checks above: # this node is ready to be built. if S: S.build = S.build + 1 - if T: T.write(self.trace_message('Evaluating %s\n' % + if T: T.write(self.trace_message(u'Evaluating %s\n' % self.trace_node(node))) # For debugging only: diff --git a/src/engine/SCons/TaskmasterTests.py b/src/engine/SCons/TaskmasterTests.py index 0140278..278b690 100644 --- a/src/engine/SCons/TaskmasterTests.py +++ b/src/engine/SCons/TaskmasterTests.py @@ -20,7 +20,7 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # - +from __future__ import division __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" diff --git a/src/engine/SCons/Tool/FortranCommon.py b/src/engine/SCons/Tool/FortranCommon.py index c21128e..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__" @@ -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/MSCommon/common.py b/src/engine/SCons/Tool/MSCommon/common.py index dcf69c8..e1b4820 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__" @@ -113,7 +114,7 @@ def normalize_env(env, keys, force=False): Note: the environment is copied.""" normenv = {} if env: - for k in list(env.keys()): + for k in env.keys(): normenv[k] = copy.deepcopy(env[k]).encode('mbcs') for k in keys: @@ -217,7 +218,7 @@ def parse_output(output, keep = ("INCLUDE", "LIB", "LIBPATH", "PATH")): dkeep[key].append(p) for line in output.splitlines(): - for k,v in list(rdk.items()): + for k,v in rdk.items(): m = v.match(line) if m: add_env(m, k) diff --git a/src/engine/SCons/Tool/MSCommon/vc.py b/src/engine/SCons/Tool/MSCommon/vc.py index 35b95d5..1a221ac 100644 --- a/src/engine/SCons/Tool/MSCommon/vc.py +++ b/src/engine/SCons/Tool/MSCommon/vc.py @@ -468,7 +468,7 @@ def msvc_setup_env(env): SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) return None - for k, v in list(d.items()): + for k, v in d.items(): debug('vc.py:msvc_setup_env() env:%s -> %s'%(k,v)) env.PrependENVPath(k, v, delete_existing=True) diff --git a/src/engine/SCons/Tool/MSCommon/vs.py b/src/engine/SCons/Tool/MSCommon/vs.py index 3219719..0a170fb 100644 --- a/src/engine/SCons/Tool/MSCommon/vs.py +++ b/src/engine/SCons/Tool/MSCommon/vs.py @@ -536,7 +536,7 @@ def msvs_setup_env(env): env['ENV'] = save_ENV vars = parse_output(output, vars) - for k, v in list(vars.items()): + for k, v in vars.items(): env.PrependENVPath(k, v, delete_existing=1) def query_versions(): diff --git a/src/engine/SCons/Tool/__init__.py b/src/engine/SCons/Tool/__init__.py index 1d5b504..517b987 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__" @@ -631,7 +632,7 @@ class ToolInitializer(object): so we no longer copy and re-bind them when the construction environment gets cloned. """ - for method in list(self.methods.values()): + for method in self.methods.values(): env.RemoveMethod(method) def apply_tools(self, env): 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 ef03206..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 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 8554dd1..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 diff --git a/src/engine/SCons/Tool/install.py b/src/engine/SCons/Tool/install.py index 4236e81..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__" diff --git a/src/engine/SCons/Tool/intelc.py b/src/engine/SCons/Tool/intelc.py index 8b178a7..86c6e12 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, print_function __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -438,14 +438,14 @@ def generate(env, version=None, abi=None, topdir=None, verbose=0): 'LIB' : libdir, 'PATH' : bindir, 'LD_LIBRARY_PATH' : libdir} - for p in list(paths.keys()): + for p in paths.keys(): env.PrependENVPath(p, os.path.join(topdir, paths[p])) if is_mac: paths={'INCLUDE' : 'include', 'LIB' : libdir, 'PATH' : bindir, 'LD_LIBRARY_PATH' : libdir} - for p in list(paths.keys()): + for p in paths.keys(): env.PrependENVPath(p, os.path.join(topdir, paths[p])) if is_windows: # env key reg valname default subdir of top diff --git a/src/engine/SCons/Tool/link.py b/src/engine/SCons/Tool/link.py index 864a018..c7c6790 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__" diff --git a/src/engine/SCons/Tool/mslink.py b/src/engine/SCons/Tool/mslink.py index b56d34a..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__" @@ -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) diff --git a/src/engine/SCons/Tool/msvs.py b/src/engine/SCons/Tool/msvs.py index 0879a28..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__" @@ -357,7 +358,7 @@ class _DSPGenerator(object): AddConfig(self, variants[i], buildtarget[i], outdir[i], runfile[i], cmdargs) self.platforms = [] - for key in list(self.configs.keys()): + for key in self.configs.keys(): platform = self.configs[key].platform if not platform in self.platforms: self.platforms.append(platform) @@ -480,7 +481,7 @@ class _GenerateV6DSP(_DSPGenerator): 'Resource Files': 'r|rc|ico|cur|bmp|dlg|rc2|rct|bin|cnt|rtf|gif|jpg|jpeg|jpe', 'Other Files': ''} - for kind in sorted(list(categories.keys()), key=lambda a: a.lower()): + for kind in sorted(categories.keys(), key=lambda a: a.lower()): if not self.sources[kind]: continue # skip empty groups @@ -744,7 +745,7 @@ class _GenerateV7DSP(_DSPGenerator): self.file.write(pdata + '-->\n') def printSources(self, hierarchy, commonprefix): - sorteditems = sorted(list(hierarchy.items()), key=lambda a: a[0].lower()) + sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower()) # First folders, then files for key, value in sorteditems: @@ -774,7 +775,7 @@ class _GenerateV7DSP(_DSPGenerator): self.file.write('\t<Files>\n') - cats = sorted([k for k in list(categories.keys()) if self.sources[k]], + cats = sorted([k for k in categories.keys() if self.sources[k]], key=lambda a: a.lower()) for kind in cats: if len(cats) > 1: @@ -1055,7 +1056,7 @@ class _GenerateV10DSP(_DSPGenerator): self.file.write(pdata + '-->\n') def printFilters(self, hierarchy, name): - sorteditems = sorted(list(hierarchy.items()), key = lambda a: a[0].lower()) + sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower()) for key, value in sorteditems: if SCons.Util.is_Dict(value): @@ -1072,7 +1073,7 @@ class _GenerateV10DSP(_DSPGenerator): 'Resource Files': 'None', 'Other Files': 'None'} - sorteditems = sorted(list(hierarchy.items()), key = lambda a: a[0].lower()) + sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower()) # First folders, then files for key, value in sorteditems: @@ -1098,7 +1099,7 @@ class _GenerateV10DSP(_DSPGenerator): 'Resource Files': 'r;rc;ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe', 'Other Files': ''} - cats = sorted([k for k in list(categories.keys()) if self.sources[k]], + cats = sorted([k for k in categories.keys() if self.sources[k]], key = lambda a: a.lower()) # print vcxproj.filters file first @@ -1254,7 +1255,7 @@ class _GenerateV7DSW(_DSWGenerator): AddConfig(self, variant) self.platforms = [] - for key in list(self.configs.keys()): + for key in self.configs.keys(): platform = self.configs[key].platform if not platform in self.platforms: self.platforms.append(platform) diff --git a/src/engine/SCons/Tool/msvsTests.py b/src/engine/SCons/Tool/msvsTests.py index 1466db6..1f5fb2b 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__" diff --git a/src/engine/SCons/Tool/packaging/__init__.py b/src/engine/SCons/Tool/packaging/__init__.py index c3de2aa..345ec87 100644 --- a/src/engine/SCons/Tool/packaging/__init__.py +++ b/src/engine/SCons/Tool/packaging/__init__.py @@ -72,7 +72,7 @@ def Tag(env, target, source, *more_tags, **kw_tags): target=env.Flatten(target) for t in target: - for (k,v) in list(kw_tags.items()): + for (k,v) in kw_tags.items(): # all file tags have to start with PACKAGING_, so we can later # differentiate between "normal" object attributes and the # packaging attributes. As the user should not be bothered with diff --git a/src/engine/SCons/Tool/packaging/ipk.py b/src/engine/SCons/Tool/packaging/ipk.py index ad27a62..6549445 100644 --- a/src/engine/SCons/Tool/packaging/ipk.py +++ b/src/engine/SCons/Tool/packaging/ipk.py @@ -169,7 +169,7 @@ Description: $X_IPK_DESCRIPTION # # close all opened files - for f in list(opened_files.values()): + for f in opened_files.values(): f.close() # call a user specified function diff --git a/src/engine/SCons/Tool/packaging/msi.py b/src/engine/SCons/Tool/packaging/msi.py index 70fdc48..49c28ca 100644 --- a/src/engine/SCons/Tool/packaging/msi.py +++ b/src/engine/SCons/Tool/packaging/msi.py @@ -172,7 +172,7 @@ def generate_guids(root): # find all XMl nodes matching the key, retrieve their attribute, hash their # subtree, convert hash to string and add as a attribute to the xml node. - for (key,value) in list(needs_id.items()): + for (key,value) in needs_id.items(): node_list = root.getElementsByTagName(key) attribute = value for node in node_list: @@ -335,7 +335,7 @@ def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, } # fill in the default tags given above. - for k,v in [ (k, v) for (k,v) in list(h.items()) if not hasattr(file, k) ]: + for k,v in [ (k, v) for (k,v) in h.items() if not hasattr(file, k) ]: setattr( file, k, v ) File = factory.createElement( 'File' ) @@ -382,7 +382,7 @@ def build_wxsfile_features_section(root, files, NAME, VERSION, SUMMARY, id_set): Feature.attributes['Description'] = escape( SUMMARY ) Feature.attributes['Display'] = 'expand' - for (feature, files) in list(create_feature_dict(files).items()): + for (feature, files) in create_feature_dict(files).items(): SubFeature = factory.createElement('Feature') SubFeature.attributes['Level'] = '1' diff --git a/src/engine/SCons/Tool/packaging/rpm.py b/src/engine/SCons/Tool/packaging/rpm.py index 4958065..a9e0fa2 100644 --- a/src/engine/SCons/Tool/packaging/rpm.py +++ b/src/engine/SCons/Tool/packaging/rpm.py @@ -277,7 +277,7 @@ def build_specfile_filesection(spec, files): for file in files: # build the tagset tags = {} - for k in list(supported_tags.keys()): + for k in supported_tags.keys(): try: tags[k]=getattr(file, k) except AttributeError: @@ -340,7 +340,7 @@ class SimpleTagCompiler(object): for key, replacement in international: try: #int_values_for_key = [ (get_country_code(k),v) for k,v in values.items() if strip_country_code(k) == key ] - x = [t for t in list(values.items()) if strip_country_code(t[0]) == key] + x = [t for t in values.items() if strip_country_code(t[0]) == key] int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x] for v in int_values_for_key: str = str + replacement % v diff --git a/src/engine/SCons/Tool/qt.py b/src/engine/SCons/Tool/qt.py index fdfdd26..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__" diff --git a/src/engine/SCons/Tool/rpmutils.py b/src/engine/SCons/Tool/rpmutils.py index e96c54c..a444508 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__" diff --git a/src/engine/SCons/Tool/tex.py b/src/engine/SCons/Tool/tex.py index febec35..dac98b7 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__" diff --git a/src/engine/SCons/Tool/textfile.py b/src/engine/SCons/Tool/textfile.py index 4897113..693b62b 100644 --- a/src/engine/SCons/Tool/textfile.py +++ b/src/engine/SCons/Tool/textfile.py @@ -54,7 +54,6 @@ import re from SCons.Node import Node from SCons.Node.Python import Value from SCons.Util import is_String, is_Sequence, is_Dict -import collections def _do_subst(node, subs): """ @@ -97,7 +96,7 @@ def _action(target, source, env): raise SCons.Errors.UserError('SUBST_DICT must be dict or sequence') subs = [] for (k,v) in d: - if isinstance(v, collections.Callable): + if callable(v): v = v() if is_String(v): v = env.subst(v) diff --git a/src/engine/SCons/Tool/xgettext.py b/src/engine/SCons/Tool/xgettext.py index 489d4d7..f9375a2 100644 --- a/src/engine/SCons/Tool/xgettext.py +++ b/src/engine/SCons/Tool/xgettext.py @@ -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 six import u __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -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(str(self.err)) + if self.err: sys.stderr.write(u(self.err)) return self.status def strfunction(self, target, source, env): diff --git a/src/engine/SCons/Util.py b/src/engine/SCons/Util.py index 0c4daff..60e5c10 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 six import PY2, PY3, u __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -32,14 +33,22 @@ import copy import re import types -from collections import UserDict, UserList, UserString -import collections +try: + from collections import UserDict, UserList, UserString +except ImportError: # Python < 3 + 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. +try: + InstanceType = types.InstanceType +except AttributeError: # Python 3 + InstanceType = None MethodType = types.MethodType FunctionType = types.FunctionType -try: str +try: unicode except NameError: UnicodeType = None else: UnicodeType = str @@ -111,9 +120,12 @@ class NodeList(UserList): >>> someList.strip() [ 'foo', 'bar' ] """ - def __bool__(self): + 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 +165,7 @@ class DisplayEngine(object): return if append_newline: text = text + '\n' try: - sys.stdout.write(str(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 +251,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(str(legend)) + sys.stdout.write(u(legend)) tags = ['['] tags.append(' E'[IDX(root.exists())]) @@ -264,10 +276,10 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}): children = child_func(root) if prune and rname in visited and children: - sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + '\n') + sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + u'\n') return - sys.stdout.write(''.join(tags + margins + ['+-', rname]) + '\n') + sys.stdout.write(''.join(tags + margins + ['+-', rname]) + u'\n') visited[rname] = 1 @@ -303,11 +315,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, str, 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, str) +try: + BaseStringTypes = (str, unicode) +except NameError: + BaseStringTypes = (str) def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes): return isinstance(obj, DictTypes) @@ -440,7 +458,7 @@ _semi_deepcopy_dispatch = d = {} def semi_deepcopy_dict(x, exclude = [] ): copy = {} - for key, val in list(x.items()): + for key, val in x.items(): # The regular Python copy.deepcopy() also deepcopies the key, # as follows: # @@ -465,7 +483,7 @@ def semi_deepcopy(x): if copier: return copier(x) else: - if hasattr(x, '__semi_deepcopy__') and isinstance(x.__semi_deepcopy__, collections.Callable): + if hasattr(x, '__semi_deepcopy__') and callable(x.__semi_deepcopy__): return x.__semi_deepcopy__() elif isinstance(x, UserDict): return x.__class__(semi_deepcopy_dict(x)) @@ -979,7 +997,7 @@ class OrderedDict(UserDict): if key not in self._keys: self._keys.append(key) def update(self, dict): - for (key, val) in list(dict.items()): + for (key, val) in dict.items(): self.__setitem__(key, val) def values(self): @@ -1001,7 +1019,7 @@ class Selector(OrderedDict): # Try to perform Environment substitution on the keys of # the dictionary before giving up. s_dict = {} - for (k,v) in list(self.items()): + for (k,v) in self.items(): if k is not None: s_k = env.subst(k) if s_k in s_dict: @@ -1346,8 +1364,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() @@ -1366,9 +1385,15 @@ def AddMethod(obj, function, name=None): 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. + if PY2: + function = MethodType(function, None, obj) setattr(obj, name, function) def RenameFunction(function, name): @@ -1461,6 +1486,8 @@ class Null(object): return self def __repr__(self): return "Null(0x%08X)" % id(self) + def __nonzero__(self): + return False def __bool__(self): return False def __getattr__(self, name): diff --git a/src/engine/SCons/UtilTests.py b/src/engine/SCons/UtilTests.py index a30404c..5666f36 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 six import u __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -285,16 +286,16 @@ class UtilTestCase(unittest.TestCase): assert to_String(s2) == 'foo', s2 if HasUnicode: - s3=UserString(str('bar')) + s3=UserString(unicode('bar')) assert to_String(s3) == s3, s3 - assert to_String(s3) == str('bar'), s3 - assert isinstance(to_String(s3), str), \ + assert to_String(s3) == unicode('bar'), s3 + assert isinstance(to_String(s3), unicode), \ type(to_String(s3)) if HasUnicode: - s4 = str('baz') - assert to_String(s4) == str('baz'), to_String(s4) - assert isinstance(to_String(s4), str), \ + s4 = unicode('baz') + assert to_String(s4) == unicode('baz'), to_String(s4) + assert isinstance(to_String(s4), unicode), \ type(to_String(s4)) def test_WhereIs(self): @@ -681,7 +682,7 @@ bling fobj = io.StringIO(content) except TypeError: # Python 2.7 and beyond require unicode strings. - fobj = io.StringIO(str(content)) + fobj = io.StringIO(u(content)) lines = LogicalLines(fobj).readlines() assert lines == [ @@ -696,7 +697,7 @@ bling s1 = silent_intern("spam") # Python 3.x does not have a unicode() global function if sys.version[0] == '2': - s2 = silent_intern(str("unicode spam")) + s2 = silent_intern(unicode("unicode spam")) s3 = silent_intern(42) s4 = silent_intern("spam") assert id(s1) == id(s4) diff --git a/src/engine/SCons/Variables/EnumVariableTests.py b/src/engine/SCons/Variables/EnumVariableTests.py index 4feb712..f4b600d 100644 --- a/src/engine/SCons/Variables/EnumVariableTests.py +++ b/src/engine/SCons/Variables/EnumVariableTests.py @@ -122,7 +122,7 @@ class EnumVariableTestCase(unittest.TestCase): 'C' : ['C', 'three', 'three'], } - for k, l in list(table.items()): + for k, l in table.items(): x = o0.converter(k) assert x == l[0], "o0 got %s, expected %s" % (x, l[0]) x = o1.converter(k) @@ -186,7 +186,7 @@ class EnumVariableTestCase(unittest.TestCase): 'no_v' : [invalid, invalid, invalid], } - for v, l in list(table.items()): + for v, l in table.items(): l[0](o0, v) l[1](o1, v) l[2](o2, v) diff --git a/src/engine/SCons/Variables/__init__.py b/src/engine/SCons/Variables/__init__.py index 8d15b8d..1c8d834 100644 --- a/src/engine/SCons/Variables/__init__.py +++ b/src/engine/SCons/Variables/__init__.py @@ -180,7 +180,7 @@ class Variables(object): if args is None: args = self.args - for arg, value in list(args.items()): + for arg, value in args.items(): added = False for option in self.options: if arg in list(option.aliases) + [ option.key ]: diff --git a/src/engine/SCons/compat/_scons_subprocess.py b/src/engine/SCons/compat/_scons_subprocess.py index 72581f7..e4ac777 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 six import integer_types import sys mswindows = (sys.platform == "win32") @@ -444,15 +446,15 @@ else: def is_int(obj): return isinstance(obj, int) def is_int_or_long(obj): - return isinstance(obj, int) + return isinstance(obj, integer_types) try: - str + types.StringTypes except AttributeError: try: - str = (str, str) + types.StringTypes = (str, unicode) except NameError: - str = (str,) + types.StringTypes = (str,) def is_string(obj): return isinstance(obj, str) @@ -785,7 +787,7 @@ class Popen(object): errread, errwrite): """Execute program (MS Windows version)""" - if not isinstance(args, str): + if not isinstance(args, types.StringTypes): args = list2cmdline(args) # Process startup details diff --git a/src/engine/SCons/cpp.py b/src/engine/SCons/cpp.py index 4cc771b..0ba10f5 100644 --- a/src/engine/SCons/cpp.py +++ b/src/engine/SCons/cpp.py @@ -31,7 +31,6 @@ import SCons.compat import os import re -import collections # # First "subsystem" of regular expressions that we set up: @@ -73,7 +72,7 @@ cpp_lines_dict = { # the corresponding compiled regular expression that fetches the arguments # we care about. Table = {} -for op_list, expr in list(cpp_lines_dict.items()): +for op_list, expr in cpp_lines_dict.items(): e = re.compile(expr) for op in op_list: Table[op] = e @@ -88,7 +87,7 @@ del op_list override = { 'if' : 'if(?!def)', } -l = [override.get(x, x) for x in list(Table.keys())] +l = [override.get(x, x) for x in Table.keys()] # Turn the list of expressions into one big honkin' regular expression @@ -131,7 +130,7 @@ CPP_to_Python_Ops_Sub = lambda m: CPP_to_Python_Ops_Dict[m.group(0)] # re module, as late as version 2.2.2, empirically matches the # "!" in "!=" first, instead of finding the longest match. # What's up with that? -l = sorted(list(CPP_to_Python_Ops_Dict.keys()), key=lambda a: len(a), reverse=True) +l = sorted(CPP_to_Python_Ops_Dict.keys(), key=lambda a: len(a), reverse=True) # Turn the list of keys into one regular expression that will allow us # to substitute all of the operators at once. @@ -267,7 +266,7 @@ class PreProcessor(object): d = { 'scons_current_file' : self.scons_current_file } - for op in list(Table.keys()): + for op in Table.keys(): d[op] = getattr(self, 'do_' + op) self.default_table = d @@ -553,7 +552,7 @@ class PreProcessor(object): except KeyError: m = function_name.search(s) s = self.cpp_namespace[m.group(1)] - if isinstance(s, collections.Callable): + if callable(s): args = function_arg_separator.split(m.group(2)) s = s(*args) if not s: diff --git a/src/engine/SCons/cppTests.py b/src/engine/SCons/cppTests.py index 5566e53..2f2025b 100644 --- a/src/engine/SCons/cppTests.py +++ b/src/engine/SCons/cppTests.py @@ -27,7 +27,7 @@ import atexit import sys import unittest -from . import cpp +import cpp diff --git a/src/engine/SCons/dblite.py b/src/engine/SCons/dblite.py index 4b02239..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 @@ -16,14 +17,19 @@ ignore_corrupt_dbfiles = 0 def corruption_warning(filename): print("Warning: Discarding corrupt database:", filename) -def is_string(s): - return isinstance(s, str) +try: unicode +except NameError: + def is_string(s): + return isinstance(s, str) +else: + def is_string(s): + return type(s) in (str, unicode) def is_bytes(s): return isinstance (s, bytes) try: - str('a') + unicode('a') except NameError: - def str(s): return s + def unicode(s): return s dblite_suffix = '.dblite' if bytes is not str: @@ -177,23 +183,23 @@ def _exercise(): assert len(db) == 0 db["foo"] = "bar" assert db["foo"] == "bar" - db[str("ufoo")] = str("ubar") - assert db[str("ufoo")] == str("ubar") + db[unicode("ufoo")] = unicode("ubar") + assert db[unicode("ufoo")] == unicode("ubar") db.sync() db = open("tmp", "c") assert len(db) == 2, len(db) assert db["foo"] == "bar" db["bar"] = "foo" assert db["bar"] == "foo" - db[str("ubar")] = str("ufoo") - assert db[str("ubar")] == str("ufoo") + db[unicode("ubar")] = unicode("ufoo") + assert db[unicode("ubar")] == unicode("ufoo") db.sync() db = open("tmp", "r") assert len(db) == 4, len(db) assert db["foo"] == "bar" assert db["bar"] == "foo" - assert db[str("ufoo")] == str("ubar") - assert db[str("ubar")] == str("ufoo") + assert db[unicode("ufoo")] == unicode("ubar") + assert db[unicode("ubar")] == unicode("ufoo") try: db.sync() except IOError as e: diff --git a/src/script/scons-time.py b/src/script/scons-time.py index 4296192..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, print_function __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -42,7 +41,6 @@ import shutil import sys import tempfile import time -import collections try: sorted @@ -456,7 +454,7 @@ class SConsTimer(object): Each message is prepended with a standard prefix of our name plus the time. """ - if isinstance(msg, collections.Callable): + if callable(msg): msg = msg(*args) else: msg = msg % args @@ -475,7 +473,7 @@ class SConsTimer(object): The action is called if it's a callable Python function, and otherwise passed to os.system(). """ - if isinstance(action, collections.Callable): + if callable(action): action(*args) else: os.system(action % args) @@ -697,7 +695,7 @@ class SConsTimer(object): sys.stderr.write('%s Cannot use the "func" subcommand.\n' % self.name_spaces) sys.exit(1) statistics = pstats.Stats(file).stats - matches = [ e for e in list(statistics.items()) if e[0][2] == function ] + matches = [ e for e in statistics.items() if e[0][2] == function ] r = matches[0] return r[0][0], r[0][1], r[0][2], r[1][3] @@ -1467,7 +1465,7 @@ class SConsTimer(object): elif o in ('--title',): self.title = a elif o in ('--which',): - if not a in list(self.time_strings.keys()): + if not a in self.time_strings.keys(): sys.stderr.write('%s: time: Unrecognized timer "%s".\n' % (self.name, a)) sys.stderr.write('%s Type "%s help time" for help.\n' % (self.name_spaces, self.name)) sys.exit(1) diff --git a/src/script/sconsign.py b/src/script/sconsign.py index 323d1bf..e99a741 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 six import PY2, PY3 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" @@ -171,6 +174,8 @@ sys.path = libs + sys.path import SCons.compat # so pickle will import cPickle instead +if PY2: + import whichdb import dbm import time import pickle @@ -189,7 +194,10 @@ def my_whichdb(filename): pass return _orig_whichdb(filename) -_orig_whichdb = dbm.whichdb +if PY3: + _orig_whichdb = dbm.whichdb +else: + _orig_whichdb = whichdb.whichdb dbm.whichdb = my_whichdb def my_import(mname): diff --git a/src/test_files.py b/src/test_files.py index d71329b..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__" @@ -77,7 +78,7 @@ check = { missing = [] no_result = [] -for directory, check_list in list(check.items()): +for directory, check_list in check.items(): if os.path.exists(directory): for c in check_list: f = os.path.join(directory, c) diff --git a/src/test_interrupts.py b/src/test_interrupts.py index 1e027a1..de3a0db 100644 --- a/src/test_interrupts.py +++ b/src/test_interrupts.py @@ -102,7 +102,7 @@ for f in files: indent_list.append( (line_num, match.group('try_or_except') ) ) try_except_lines[match.group('indent')] = indent_list uncaught_this_file = [] - for indent in list(try_except_lines.keys()): + for indent in try_except_lines.keys(): exc_keyboardint_seen = 0 exc_all_seen = 0 for (l,statement) in try_except_lines[indent] + [(-1,indent + 'try')]: diff --git a/src/test_pychecker.py b/src/test_pychecker.py index 24aa966..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__" diff --git a/src/test_setup.py b/src/test_setup.py index 731fbe7..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__" diff --git a/src/test_strings.py b/src/test_strings.py index b57c714..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__" |