summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorWilliam Deegan <bill@baddogconsulting.com>2016-05-23 23:21:26 (GMT)
committerWilliam Deegan <bill@baddogconsulting.com>2016-05-23 23:21:26 (GMT)
commitaa5a0468340338cc3423a06d6d55e1b52a713bc5 (patch)
tree71ff4e88b1e418ff32ba89ae0f4cf0b3f0d180a1
parent15bd909b178ba5271125fca6846fa8c069be79f1 (diff)
parentb387e34357c968d0855c525c7e838657a957ff01 (diff)
downloadSCons-aa5a0468340338cc3423a06d6d55e1b52a713bc5.zip
SCons-aa5a0468340338cc3423a06d6d55e1b52a713bc5.tar.gz
SCons-aa5a0468340338cc3423a06d6d55e1b52a713bc5.tar.bz2
merge python3 branch to default
-rw-r--r--QMTest/SConscript4
-rw-r--r--QMTest/TestCmd.py40
-rw-r--r--QMTest/TestCmdTests.py205
-rw-r--r--QMTest/TestCommon.py76
-rw-r--r--QMTest/TestSCons.py58
-rw-r--r--QMTest/TestSConsMSVS.py6
-rw-r--r--QMTest/TestSCons_time.py4
-rw-r--r--QMTest/TestSConsign.py3
-rw-r--r--QMTest/scons_tdb.py16
-rw-r--r--SConstruct46
-rw-r--r--bench/bench.py6
-rw-r--r--bench/env.__setitem__.py12
-rw-r--r--bench/timeit.py24
-rw-r--r--bin/Command.py7
-rw-r--r--bin/SConsDoc.py43
-rw-r--r--bin/SConsExamples.py148
-rw-r--r--bin/calibrate.py8
-rw-r--r--bin/caller-tree.py9
-rw-r--r--bin/docs-create-example-outputs.py9
-rw-r--r--bin/docs-update-generated.py3
-rw-r--r--bin/docs-validate.py9
-rw-r--r--bin/install_python.py7
-rw-r--r--bin/install_scons.py12
-rw-r--r--bin/linecount.py30
-rw-r--r--bin/memlogs.py10
-rw-r--r--bin/memoicmp.py22
-rw-r--r--bin/objcounts.py10
-rw-r--r--bin/scons-diff.py13
-rw-r--r--bin/scons-proc.py25
-rw-r--r--bin/scons-test.py65
-rw-r--r--bin/scons-unzip.py3
-rw-r--r--bin/scons_dev_master.py13
-rw-r--r--bin/sfsum11
-rwxr-xr-xbin/svn-bisect.py14
-rw-r--r--bin/update-release-info.py29
-rwxr-xr-xbin/xmlagenda.py3
-rw-r--r--doc/SConscript107
-rwxr-xr-xruntest.py33
-rw-r--r--shippable.yml7
-rw-r--r--src/CHANGES.txt4
-rw-r--r--src/engine/SCons/Action.py62
-rw-r--r--src/engine/SCons/ActionTests.py96
-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.py64
-rw-r--r--src/engine/SCons/Errors.py12
-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.py12
-rw-r--r--src/engine/SCons/MemoizeTests.py1
-rw-r--r--src/engine/SCons/Node/FS.py122
-rw-r--r--src/engine/SCons/Node/FSTests.py32
-rw-r--r--src/engine/SCons/Node/__init__.py46
-rw-r--r--src/engine/SCons/Options/__init__.py10
-rw-r--r--src/engine/SCons/Platform/__init__.py18
-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.py19
-rw-r--r--src/engine/SCons/SConf.py27
-rw-r--r--src/engine/SCons/SConfTests.py2
-rw-r--r--src/engine/SCons/SConsign.py19
-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.py63
-rw-r--r--src/engine/SCons/Script/SConsOptions.py6
-rw-r--r--src/engine/SCons/Script/SConscript.py24
-rw-r--r--src/engine/SCons/Script/__init__.py17
-rw-r--r--src/engine/SCons/Subst.py4
-rw-r--r--src/engine/SCons/SubstTests.py49
-rw-r--r--src/engine/SCons/Taskmaster.py33
-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.py10
-rw-r--r--src/engine/SCons/Tool/MSCommon/sdk.py31
-rw-r--r--src/engine/SCons/Tool/MSCommon/vc.py70
-rw-r--r--src/engine/SCons/Tool/MSCommon/vs.py14
-rw-r--r--src/engine/SCons/Tool/__init__.py145
-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.py50
-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/f08.py4
-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.py18
-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.py61
-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.py155
-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.py6
-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.py37
-rw-r--r--src/engine/SCons/Util.py124
-rw-r--r--src/engine/SCons/UtilTests.py26
-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__.py6
-rw-r--r--src/engine/SCons/cppTests.py2
-rw-r--r--src/engine/SCons/dblite.py32
-rw-r--r--src/script/scons-time.py37
-rw-r--r--src/script/scons.py16
-rw-r--r--src/script/sconsign.py49
-rw-r--r--src/setup.py10
-rw-r--r--src/test_files.py9
-rw-r--r--src/test_interrupts.py6
-rw-r--r--src/test_pychecker.py3
-rw-r--r--src/test_setup.py7
-rw-r--r--src/test_strings.py9
-rw-r--r--test/ARGLIST.py2
-rw-r--r--test/Actions/actions.py10
-rw-r--r--test/Actions/pre-post.py22
-rw-r--r--test/Actions/unicode-signature.py12
-rw-r--r--test/AddMethod.py8
-rw-r--r--test/AddOption/basic.py4
-rw-r--r--test/AddOption/help.py17
-rw-r--r--test/AddOption/optional-arg.py2
-rw-r--r--test/Batch/action-changed.py4
-rw-r--r--test/CC/CFLAGS.py10
-rw-r--r--test/CPPDEFINES/append.py52
-rw-r--r--test/CPPDEFINES/basic.py6
-rw-r--r--test/CPPDEFINES/pkg-config.py12
-rw-r--r--test/CPPDEFINES/undefined.py4
-rw-r--r--test/CacheDir/scanner-target.py2
-rw-r--r--test/CacheDir/source-scanner.py2
-rw-r--r--test/Chmod.py115
-rw-r--r--test/Clean/mkfifo.py37
-rw-r--r--test/Climb/filename--D.py4
-rw-r--r--test/Climb/filename--U.py4
-rw-r--r--test/Climb/filename-u.py4
-rw-r--r--test/Clone-compatibility.py4
-rw-r--r--test/Configure/ConfigureDryRunError.py3
-rw-r--r--test/Configure/Streamer1.py2
-rw-r--r--test/Configure/cache-not-ok.py2
-rw-r--r--test/Configure/config-h.py53
-rw-r--r--test/Configure/implicit-cache.py11
-rw-r--r--test/ConstructionEnvironment.py2
-rw-r--r--test/Copy-Action.py4
-rw-r--r--test/D/SharedObjects/Common/common.py2
-rw-r--r--test/Deprecated/Options/BoolOption.py4
-rw-r--r--test/Deprecated/Options/EnumOption.py7
-rw-r--r--test/Deprecated/Options/ListOption.py21
-rw-r--r--test/Deprecated/Options/Options.py28
-rw-r--r--test/Deprecated/Options/PackageOption.py2
-rw-r--r--test/Deprecated/Options/PathOption.py16
-rw-r--r--test/Deprecated/Options/chdir.py2
-rw-r--r--test/Deprecated/Options/help.py6
-rw-r--r--test/Deprecated/Options/import.py2
-rw-r--r--test/Deprecated/SourceCode/BitKeeper/BitKeeper.py7
-rw-r--r--test/Deprecated/SourceCode/Subversion.py3
-rw-r--r--test/Dir/Dir.py12
-rw-r--r--test/Entry.py12
-rw-r--r--test/Environment.py4
-rw-r--r--test/Errors/Exception.py2
-rw-r--r--test/ExecuteInvalidateCache.py4
-rw-r--r--test/Exit.py12
-rw-r--r--test/File.py16
-rw-r--r--test/FindFile.py8
-rw-r--r--test/Flatten.py8
-rw-r--r--test/Fortran/F77FLAGS.py5
-rw-r--r--test/Fortran/FORTRANFLAGS.py5
-rw-r--r--test/Fortran/SHF77FLAGS.py5
-rw-r--r--test/Fortran/SHFORTRANFLAGS.py5
-rw-r--r--test/GetBuildFailures/option-k.py2
-rw-r--r--test/GetBuildFailures/parallel.py15
-rw-r--r--test/GetBuildFailures/serial.py8
-rw-r--r--test/GetOption/help.py4
-rw-r--r--test/Glob/glob-libpath.py5
-rw-r--r--test/Install/Install.py2
-rw-r--r--test/Interactive/version.py3
-rw-r--r--test/Java/multi-step.py3
-rw-r--r--test/LINK/VersionedLib.py574
-rw-r--r--test/Libs/SharedLibraryIxes.py16
-rw-r--r--test/MSVC/batch-longlines.py122
-rw-r--r--test/MSVC/msvc.py7
-rw-r--r--test/MSVC/query_vcbat.py2
-rw-r--r--test/MSVS/vs-10.0-exec.py2
-rw-r--r--test/MSVS/vs-8.0-exec.py2
-rw-r--r--test/Mkdir.py2
-rw-r--r--test/NodeOps.py4
-rw-r--r--test/ParseConfig.py32
-rw-r--r--test/Platform.py16
-rw-r--r--test/QT/QTFLAGS.py8
-rw-r--r--test/QT/copied-env.py5
-rw-r--r--test/QT/manual.py6
-rw-r--r--test/QT/warnings.py5
-rw-r--r--test/Repository/Default.py2
-rw-r--r--test/Repository/Local.py4
-rw-r--r--test/Repository/VariantDir.py2
-rw-r--r--test/Repository/option-c.py2
-rw-r--r--test/Repository/option-n.py2
-rw-r--r--test/Repository/targets.py2
-rw-r--r--test/SConscript/Return.py32
-rw-r--r--test/SConscript/SConscript.py6
-rw-r--r--test/SConscript/env.py10
-rw-r--r--test/SConscript/white-space.py2
-rw-r--r--test/SConsignFile/use-dbhash.py2
-rw-r--r--test/SConsignFile/use-dbm.py2
-rw-r--r--test/SConsignFile/use-dumbdbm.py2
-rw-r--r--test/SConsignFile/use-gdbm.py2
-rw-r--r--test/SConstruct.py6
-rw-r--r--test/SHELL.py2
-rw-r--r--test/SWIG/SWIG.py18
-rw-r--r--test/Scanner/CrossLanguageNoExtension.py4
-rw-r--r--test/Scanner/empty-implicit.py4
-rw-r--r--test/Scanner/generated.py4
-rw-r--r--test/Scanner/scan-once.py4
-rw-r--r--test/Scanner/unicode.py20
-rw-r--r--test/Split.py16
-rw-r--r--test/Subst/AllowSubstExceptions.py16
-rw-r--r--test/TARGETS.py28
-rw-r--r--test/TEMPFILEPREFIX.py2
-rw-r--r--test/TEX/TEX.py9
-rw-r--r--test/Value.py3
-rw-r--r--test/Variables/BoolVariable.py4
-rw-r--r--test/Variables/EnumVariable.py6
-rw-r--r--test/Variables/ListVariable.py21
-rw-r--r--test/Variables/PackageVariable.py2
-rw-r--r--test/Variables/PathVariable.py14
-rw-r--r--test/Variables/Variables.py28
-rw-r--r--test/Variables/chdir.py2
-rw-r--r--test/Variables/help.py4
-rw-r--r--test/Variables/import.py2
-rw-r--r--test/WhereIs.py28
-rw-r--r--test/Win32/bad-drive.py7
-rw-r--r--test/Win32/default-drive.py3
-rw-r--r--test/Win32/mingw.py2
-rw-r--r--test/ZIP/ZIP.py2
-rw-r--r--test/ZIP/ZIPROOT.py196
-rw-r--r--test/_CPPINCFLAGS.py6
-rw-r--r--test/custom-concat.py2
-rw-r--r--test/exitfns.py6
-rw-r--r--test/gnutools.py3
-rw-r--r--test/import.py10
-rw-r--r--test/long-lines/signature.py2
-rw-r--r--test/no-arguments.py2
-rw-r--r--test/option--C.py6
-rw-r--r--test/option--I.py4
-rw-r--r--test/option--random.py5
-rw-r--r--test/option-f.py8
-rw-r--r--test/option-v.py5
-rw-r--r--test/option/debug-count.py9
-rw-r--r--test/option/debug-multiple.py16
-rw-r--r--test/option/debug-time.py10
-rw-r--r--test/option/help-options.py5
-rw-r--r--test/option/profile.py3
-rw-r--r--test/overrides.py6
-rw-r--r--test/packaging/convenience-functions/image/SConstruct5
-rw-r--r--test/preserve-source.py2
-rw-r--r--test/scons-time/run/config/python.py2
-rw-r--r--test/scons-time/run/option/python.py2
-rw-r--r--test/sconsign/nonwritable.py4
-rw-r--r--test/sconsign/script/SConsignFile.py4
-rw-r--r--test/sconsign/script/Signatures.py4
-rw-r--r--test/sconsign/script/no-SConsignFile.py4
-rw-r--r--test/site_scons/basic.py4
-rw-r--r--test/site_scons/no-site-dir.py4
-rw-r--r--test/site_scons/override.py2
-rw-r--r--test/site_scons/site-dir.py4
-rw-r--r--test/site_scons/site_init.py10
-rw-r--r--test/site_scons/sysdirs.py144
-rw-r--r--test/spaces.py2
-rw-r--r--test/subdivide.py4
-rw-r--r--test/tool_args.py8
-rw-r--r--test/toolpath/basic.py62
-rw-r--r--timings/ElectricCloud/TimeSCons-run.py3
-rwxr-xr-xwww/gen_sched_table.py13
327 files changed, 3003 insertions, 2732 deletions
diff --git a/QMTest/SConscript b/QMTest/SConscript
index 33fe903..5469d29 100644
--- a/QMTest/SConscript
+++ b/QMTest/SConscript
@@ -44,12 +44,12 @@ files = [
def copy(target, source, env):
t = str(target[0])
s = str(source[0])
- c = open(s, 'rb').read()
+ c = open(s, 'r').read()
# Note: We construct the __ VERSION __ substitution string at
# run-time so it doesn't get replaced when this file gets copied
# into the tree for packaging.
c = c.replace('__' + 'VERSION' + '__', env['VERSION'])
- open(t, 'wb').write(c)
+ open(t, 'w').write(c)
for file in files:
# Guarantee that real copies of these files always exist in
diff --git a/QMTest/TestCmd.py b/QMTest/TestCmd.py
index cd559b7..2fba0a0 100644
--- a/QMTest/TestCmd.py
+++ b/QMTest/TestCmd.py
@@ -285,7 +285,7 @@ version.
# PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
# AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
-from __future__ import division
+from __future__ import division, print_function
__author__ = "Steven Knight <knight at baldmt dot com>"
__revision__ = "TestCmd.py 1.3.D001 2010/06/03 12:58:27 knight"
@@ -477,17 +477,17 @@ def match_re(lines = None, res = None):
if not is_List(res):
res = res.split("\n")
if len(lines) != len(res):
- print "match_re: expected %d lines, found %d"%(len(res), len(lines))
+ print("match_re: expected %d lines, found %d"%(len(res), len(lines)))
return
for i in range(len(lines)):
s = "^" + res[i] + "$"
try:
expr = re.compile(s)
- except re.error, e:
+ except re.error as e:
msg = "Regular expression error in %s: %s"
raise re.error(msg % (repr(s), e.args[0]))
if not expr.search(lines[i]):
- print "match_re: mismatch at line %d:\n search re='%s'\n line='%s'"%(i,s,lines[i])
+ print("match_re: mismatch at line %d:\n search re='%s'\n line='%s'"%(i,s,lines[i]))
return
return 1
@@ -501,7 +501,7 @@ def match_re_dotall(lines = None, res = None):
s = "^" + res + "$"
try:
expr = re.compile(s, re.DOTALL)
- except re.error, e:
+ except re.error as e:
msg = "Regular expression error in %s: %s"
raise re.error(msg % (repr(s), e.args[0]))
return expr.match(lines)
@@ -551,7 +551,7 @@ def diff_re(a, b, fromfile='', tofile='',
s = "^" + aline + "$"
try:
expr = re.compile(s)
- except re.error, e:
+ except re.error as e:
msg = "Regular expression error in %s: %s"
raise re.error(msg % (repr(s), e.args[0]))
if not expr.search(bline):
@@ -627,7 +627,7 @@ else:
st = os.stat(f)
except OSError:
continue
- if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
+ if stat.S_IMODE(st[stat.ST_MODE]) & 0o111:
return f
return None
@@ -658,7 +658,7 @@ except AttributeError:
PIPE = subprocess.PIPE
-if subprocess.mswindows:
+if sys.platform == 'win32' and subprocess.mswindows:
try:
from win32file import ReadFile, WriteFile
from win32pipe import PeekNamedPipe
@@ -720,7 +720,7 @@ class Popen(subprocess.Popen):
getattr(self, which).close()
setattr(self, which, None)
- if subprocess.mswindows:
+ if sys.platform == 'win32' and subprocess.mswindows:
def send(self, input):
if not self.stdin:
return None
@@ -730,7 +730,7 @@ class Popen(subprocess.Popen):
(errCode, written) = WriteFile(x, input)
except ValueError:
return self._close('stdin')
- except (subprocess.pywintypes.error, Exception), why:
+ except (subprocess.pywintypes.error, Exception) as why:
if why.args[0] in (109, errno.ESHUTDOWN):
return self._close('stdin')
raise
@@ -751,7 +751,7 @@ class Popen(subprocess.Popen):
(errCode, read) = ReadFile(x, nAvail, None)
except ValueError:
return self._close(which)
- except (subprocess.pywintypes.error, Exception), why:
+ except (subprocess.pywintypes.error, Exception) as why:
if why.args[0] in (109, errno.ESHUTDOWN):
return self._close(which)
raise
@@ -770,7 +770,7 @@ class Popen(subprocess.Popen):
try:
written = os.write(self.stdin.fileno(), input)
- except OSError, why:
+ except OSError as why:
if why.args[0] == errno.EPIPE: #broken pipe
return self._close('stdin')
raise
@@ -964,7 +964,7 @@ class TestCmd(object):
condition = self.condition
if self._preserve[condition]:
for dir in self._dirlist:
- print unicode("Preserved directory " + dir + "\n"),
+ print("Preserved directory " + dir + "\n")
else:
list = self._dirlist[:]
list.reverse()
@@ -1030,10 +1030,10 @@ class TestCmd(object):
if diff_function is None:
diff_function = self.simple_diff
if name is not None:
- print self.banner(name)
+ print(self.banner(name))
args = (a.splitlines(), b.splitlines()) + args
for line in diff_function(*args, **kw):
- print line
+ print(line)
def diff_stderr(self, a, b, *args, **kw):
"""Compare actual and expected file contents.
@@ -1659,12 +1659,12 @@ class TestCmd(object):
def do_chmod(fname):
try: st = os.stat(fname)
except OSError: pass
- else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|0200))
+ else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|0o200))
else:
def do_chmod(fname):
try: st = os.stat(fname)
except OSError: pass
- else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~0200))
+ else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~0o200))
if os.path.isfile(top):
do_chmod(top)
@@ -1731,7 +1731,11 @@ class TestCmd(object):
file = self.canonicalize(file)
if mode[0] != 'w':
raise ValueError("mode must begin with 'w'")
- open(file, mode).write(content)
+ try:
+ open(file, mode).write(content)
+ except TypeError as e:
+ # python 3 default strings are not bytes, but unicode
+ open(file, mode).write(bytes(content,'utf-8'))
# Local Variables:
# tab-width:4
diff --git a/QMTest/TestCmdTests.py b/QMTest/TestCmdTests.py
index 1044ed1..cd62d9f 100644
--- a/QMTest/TestCmdTests.py
+++ b/QMTest/TestCmdTests.py
@@ -26,13 +26,14 @@ import os
import shutil
import signal
import stat
-import StringIO
+from StringIO import StringIO
import sys
import tempfile
import time
import types
import unittest
-import UserList
+from UserList import UserList
+
# Strip the current directory so we get the right TestCmd.py module.
sys.path = sys.path[1:]
@@ -131,11 +132,11 @@ class TestCmdTestCase(unittest.TestCase):
run_env.write(t.scriptout_path, textout)
run_env.write(t.scripterr_path, texterr)
- os.chmod(t.script_path, 0644) # XXX UNIX-specific
- os.chmod(t.scriptx_path, 0755) # XXX UNIX-specific
- os.chmod(t.script1_path, 0644) # XXX UNIX-specific
- os.chmod(t.scriptout_path, 0644) # XXX UNIX-specific
- os.chmod(t.scripterr_path, 0644) # XXX UNIX-specific
+ os.chmod(t.script_path, 0o644) # XXX UNIX-specific
+ os.chmod(t.scriptx_path, 0o755) # XXX UNIX-specific
+ os.chmod(t.script1_path, 0o644) # XXX UNIX-specific
+ os.chmod(t.scriptout_path, 0o644) # XXX UNIX-specific
+ os.chmod(t.scripterr_path, 0o644) # XXX UNIX-specific
t.orig_cwd = os.getcwd()
@@ -220,8 +221,8 @@ class cleanup_TestCase(TestCmdTestCase):
test = TestCmd.TestCmd(workdir = '')
wdir = test.workdir
test.write('file2', "Test file #2\n")
- os.chmod(test.workpath('file2'), 0400)
- os.chmod(wdir, 0500)
+ os.chmod(test.workpath('file2'), 0o400)
+ os.chmod(wdir, 0o500)
test.cleanup()
assert not os.path.exists(wdir)
@@ -286,35 +287,35 @@ class chmod_TestCase(TestCmdTestCase):
test.chmod(['sub', 'file2'], stat.S_IWRITE)
file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
- assert file1_mode == 0444, '0%o' % file1_mode
+ assert file1_mode == 0o444, '0%o' % file1_mode
file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
- assert file2_mode == 0666, '0%o' % file2_mode
+ assert file2_mode == 0o666, '0%o' % file2_mode
test.chmod('file1', stat.S_IWRITE)
test.chmod(wdir_sub_file2, stat.S_IREAD)
file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
- assert file1_mode == 0666, '0%o' % file1_mode
+ assert file1_mode == 0o666, '0%o' % file1_mode
file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
- assert file2_mode == 0444, '0%o' % file2_mode
+ assert file2_mode == 0o444, '0%o' % file2_mode
else:
- test.chmod(wdir_file1, 0700)
- test.chmod(['sub', 'file2'], 0760)
+ test.chmod(wdir_file1, 0o700)
+ test.chmod(['sub', 'file2'], 0o760)
file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
- assert file1_mode == 0700, '0%o' % file1_mode
+ assert file1_mode == 0o700, '0%o' % file1_mode
file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
- assert file2_mode == 0760, '0%o' % file2_mode
+ assert file2_mode == 0o760, '0%o' % file2_mode
- test.chmod('file1', 0765)
- test.chmod(wdir_sub_file2, 0567)
+ test.chmod('file1', 0o765)
+ test.chmod(wdir_sub_file2, 0o567)
file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
- assert file1_mode == 0765, '0%o' % file1_mode
+ assert file1_mode == 0o765, '0%o' % file1_mode
file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
- assert file2_mode == 0567, '0%o' % file2_mode
+ assert file2_mode == 0o567, '0%o' % file2_mode
@@ -1032,14 +1033,14 @@ class match_exact_TestCase(TestCmdTestCase):
assert test.match_exact("abcde\n", "abcde\n")
assert not test.match_exact(["12345\n", "abcde\n"], ["1[0-9]*5\n", "a.*e\n"])
assert test.match_exact(["12345\n", "abcde\n"], ["12345\n", "abcde\n"])
- assert not test.match_exact(UserList.UserList(["12345\n", "abcde\n"]),
+ assert not test.match_exact(UserList(["12345\n", "abcde\n"]),
["1[0-9]*5\n", "a.*e\n"])
- assert test.match_exact(UserList.UserList(["12345\n", "abcde\n"]),
+ assert test.match_exact(UserList(["12345\n", "abcde\n"]),
["12345\n", "abcde\n"])
assert not test.match_exact(["12345\n", "abcde\n"],
- UserList.UserList(["1[0-9]*5\n", "a.*e\n"]))
+ UserList(["1[0-9]*5\n", "a.*e\n"]))
assert test.match_exact(["12345\n", "abcde\n"],
- UserList.UserList(["12345\n", "abcde\n"]))
+ UserList(["12345\n", "abcde\n"]))
assert not test.match_exact("12345\nabcde\n", "1[0-9]*5\na.*e\n")
assert test.match_exact("12345\nabcde\n", "12345\nabcde\n")
lines = ["vwxyz\n", "67890\n"]
@@ -1098,28 +1099,28 @@ sys.exit(0)
["1.*j\n"])
assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
["12345\n", "abcde\n", "fghij\n"])
- assert test.match_re_dotall(UserList.UserList(["12345\n",
- "abcde\n",
- "fghij\n"]),
+ assert test.match_re_dotall(UserList(["12345\n",
+ "abcde\n",
+ "fghij\n"]),
["1[0-9]*5\n", "a.*e\n", "f.*j\n"])
- assert test.match_re_dotall(UserList.UserList(["12345\n",
- "abcde\n",
- "fghij\n"]),
+ assert test.match_re_dotall(UserList(["12345\n",
+ "abcde\n",
+ "fghij\n"]),
["1.*j\n"])
- assert test.match_re_dotall(UserList.UserList(["12345\n",
- "abcde\n",
- "fghij\n"]),
+ assert test.match_re_dotall(UserList(["12345\n",
+ "abcde\n",
+ "fghij\n"]),
["12345\n", "abcde\n", "fghij\n"])
assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
- UserList.UserList(["1[0-9]*5\n",
- "a.*e\n",
- "f.*j\n"]))
+ UserList(["1[0-9]*5\n",
+ "a.*e\n",
+ "f.*j\n"]))
assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
- UserList.UserList(["1.*j\n"]))
+ UserList(["1.*j\n"]))
assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
- UserList.UserList(["12345\n",
- "abcde\n",
- "fghij\n"]))
+ UserList(["12345\n",
+ "abcde\n",
+ "fghij\n"]))
assert test.match_re_dotall("12345\nabcde\nfghij\n",
"1[0-9]*5\na.*e\nf.*j\n")
assert test.match_re_dotall("12345\nabcde\nfghij\n", "1.*j\n")
@@ -1176,14 +1177,14 @@ sys.exit(0)
assert test.match_re("abcde\n", "abcde\n")
assert test.match_re(["12345\n", "abcde\n"], ["1[0-9]*5\n", "a.*e\n"])
assert test.match_re(["12345\n", "abcde\n"], ["12345\n", "abcde\n"])
- assert test.match_re(UserList.UserList(["12345\n", "abcde\n"]),
+ assert test.match_re(UserList(["12345\n", "abcde\n"]),
["1[0-9]*5\n", "a.*e\n"])
- assert test.match_re(UserList.UserList(["12345\n", "abcde\n"]),
+ assert test.match_re(UserList(["12345\n", "abcde\n"]),
["12345\n", "abcde\n"])
assert test.match_re(["12345\n", "abcde\n"],
- UserList.UserList(["1[0-9]*5\n", "a.*e\n"]))
+ UserList(["1[0-9]*5\n", "a.*e\n"]))
assert test.match_re(["12345\n", "abcde\n"],
- UserList.UserList(["12345\n", "abcde\n"]))
+ UserList(["12345\n", "abcde\n"]))
assert test.match_re("12345\nabcde\n", "1[0-9]*5\na.*e\n")
assert test.match_re("12345\nabcde\n", "12345\nabcde\n")
lines = ["vwxyz\n", "67890\n"]
@@ -1463,7 +1464,7 @@ class preserve_TestCase(TestCmdTestCase):
def test_preserve(self):
"""Test preserve()"""
def cleanup_test(test, cond=None, stdout=""):
- io = StringIO.StringIO()
+ io = StringIO()
save = sys.stdout
sys.stdout = io
try:
@@ -1603,7 +1604,7 @@ class read_TestCase(TestCmdTestCase):
_file_matches(wdir_foo_file3, test.read(['foo', 'file3']),
"Test\nfile\n#3.\n")
_file_matches(wdir_foo_file3,
- test.read(UserList.UserList(['foo', 'file3'])),
+ test.read(UserList(['foo', 'file3'])),
"Test\nfile\n#3.\n")
_file_matches(wdir_file4, test.read('file4', mode = 'r'),
"Test\nfile\n#4.\n")
@@ -1861,24 +1862,24 @@ class run_verbose_TestCase(TestCmdTestCase):
interpreter = 'python',
workdir = '',
verbose = 1)
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
test.run(arguments = ['arg1 arg2'])
o = sys.stdout.getvalue()
assert o == '', o
e = sys.stderr.getvalue()
expect = 'python "%s" "arg1 arg2"\n' % t.script_path
assert expect == e, (expect, e)
-
+
testx = TestCmd.TestCmd(program = t.scriptx,
workdir = '',
verbose = 1)
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
testx.run(arguments = ['arg1 arg2'])
expect = '"%s" "arg1 arg2"\n' % t.scriptx_path
o = sys.stdout.getvalue()
@@ -1912,10 +1913,10 @@ class run_verbose_TestCase(TestCmdTestCase):
interpreter = 'python',
workdir = '',
verbose = 2)
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
test.run(arguments = ['arg1 arg2'])
line_fmt = "script: %s: %s: ['arg1 arg2']\n"
@@ -1929,14 +1930,14 @@ class run_verbose_TestCase(TestCmdTestCase):
expect = 'python "%s" "arg1 arg2"\n' % t.script_path
e = sys.stderr.getvalue()
assert e == expect, (e, expect)
-
+
testx = TestCmd.TestCmd(program = t.scriptx,
workdir = '',
verbose = 2)
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
testx.run(arguments = ['arg1 arg2'])
line_fmt = "scriptx.bat: %s: %s: ['arg1 arg2']\n"
@@ -1957,10 +1958,10 @@ class run_verbose_TestCase(TestCmdTestCase):
interpreter = 'python',
workdir = '',
verbose = 2)
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
test.run(arguments = ['arg1 arg2'])
line_fmt = "scriptout: %s: %s: ['arg1 arg2']\n"
@@ -1977,10 +1978,10 @@ class run_verbose_TestCase(TestCmdTestCase):
interpreter = 'python',
workdir = '',
verbose = 3)
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
test.run(arguments = ['arg1 arg2'])
line_fmt = "scriptout: %s: %s: ['arg1 arg2']\n"
@@ -2001,10 +2002,10 @@ class run_verbose_TestCase(TestCmdTestCase):
test = TestCmd.TestCmd(program = t.script,
interpreter = 'python',
workdir = '')
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
test.run(arguments = ['arg1 arg2'])
line_fmt = "script: %s: %s: ['arg1 arg2']\n"
@@ -2018,13 +2019,13 @@ class run_verbose_TestCase(TestCmdTestCase):
expect = 'python "%s" "arg1 arg2"\n' % t.script_path
e = sys.stderr.getvalue()
assert e == expect, (e, expect)
-
+
testx = TestCmd.TestCmd(program = t.scriptx,
workdir = '')
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
testx.run(arguments = ['arg1 arg2'])
line_fmt = "scriptx.bat: %s: %s: ['arg1 arg2']\n"
@@ -2047,24 +2048,24 @@ class run_verbose_TestCase(TestCmdTestCase):
interpreter = 'python',
workdir = '',
verbose = 1)
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
test.run(arguments = ['arg1 arg2'])
o = sys.stdout.getvalue()
assert o == '', o
e = sys.stderr.getvalue()
expect = 'python "%s" "arg1 arg2"\n' % t.script_path
assert expect == e, (expect, e)
-
+
testx = TestCmd.TestCmd(program = t.scriptx,
workdir = '',
verbose = 1)
-
- sys.stdout = StringIO.StringIO()
- sys.stderr = StringIO.StringIO()
-
+
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
testx.run(arguments = ['arg1 arg2'])
expect = '"%s" "arg1 arg2"\n' % t.scriptx_path
o = sys.stdout.getvalue()
@@ -2347,7 +2348,7 @@ while 1:
logfp.close()
""" % t.recv_out_path
t.run_env.write(t.recv_script_path, text)
- os.chmod(t.recv_script_path, 0644) # XXX UNIX-specific
+ os.chmod(t.recv_script_path, 0o644) # XXX UNIX-specific
return t
def test_start(self):
@@ -2765,11 +2766,11 @@ class subdir_TestCase(TestCmdTestCase):
assert test.subdir('bar') == 1
assert test.subdir(['foo', 'succeed']) == 1
if os.name != "nt":
- os.chmod(test.workpath('foo'), 0500)
+ os.chmod(test.workpath('foo'), 0o500)
assert test.subdir(['foo', 'fail']) == 0
assert test.subdir(['sub', 'dir', 'ectory'], 'sub') == 1
assert test.subdir('one',
- UserList.UserList(['one', 'two']),
+ UserList(['one', 'two']),
['one', 'two', 'three']) == 3
assert os.path.isdir(test.workpath('foo'))
assert os.path.isdir(test.workpath('bar'))
@@ -2962,7 +2963,7 @@ class unlink_TestCase(TestCmdTestCase):
test.unlink(['foo', 'file3a'])
assert not os.path.exists(wdir_foo_file3a)
- test.unlink(UserList.UserList(['foo', 'file3b']))
+ test.unlink(UserList(['foo', 'file3b']))
assert not os.path.exists(wdir_foo_file3b)
test.unlink([test.workdir, 'foo', 'file4'])
@@ -2971,8 +2972,8 @@ class unlink_TestCase(TestCmdTestCase):
# Make it so we can't unlink file5.
# For UNIX, remove write permission from the dir and the file.
# For Windows, open the file.
- os.chmod(test.workdir, 0500)
- os.chmod(wdir_file5, 0400)
+ os.chmod(test.workdir, 0o500)
+ os.chmod(wdir_file5, 0o400)
f = open(wdir_file5, 'r')
try:
@@ -2983,8 +2984,8 @@ class unlink_TestCase(TestCmdTestCase):
except:
raise
finally:
- os.chmod(test.workdir, 0700)
- os.chmod(wdir_file5, 0600)
+ os.chmod(test.workdir, 0o700)
+ os.chmod(wdir_file5, 0o600)
f.close()
@@ -3208,11 +3209,11 @@ class executable_TestCase(TestCmdTestCase):
def make_executable(fname):
st = os.stat(fname)
- os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|0100))
+ os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|0o100))
def make_non_executable(fname):
st = os.stat(fname)
- os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~0100))
+ os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~0o100))
test.executable(test.workdir, 0)
# XXX skip these tests if euid == 0?
@@ -3282,7 +3283,7 @@ class write_TestCase(TestCmdTestCase):
test.write('file9', "Test file #9.\r\n", mode = 'wb')
if os.name != "nt":
- os.chmod(test.workdir, 0500)
+ os.chmod(test.workdir, 0o500)
try:
test.write('file10', "Test file #10 (should not get created).\n")
except IOError: # expect "Permission denied"
diff --git a/QMTest/TestCommon.py b/QMTest/TestCommon.py
index dc4c97c..f878636 100644
--- a/QMTest/TestCommon.py
+++ b/QMTest/TestCommon.py
@@ -93,6 +93,8 @@ The TestCommon module also provides the following variables
# AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+from __future__ import print_function
+
__author__ = "Steven Knight <knight at baldmt dot com>"
__revision__ = "TestCommon.py 1.3.D001 2010/06/03 12:58:27 knight"
__version__ = "1.3"
@@ -258,9 +260,9 @@ class TestCommon(TestCmd):
existing, missing = separate_files(files)
unwritable = [x for x in existing if not is_writable(x)]
if missing:
- print "Missing files: `%s'" % "', `".join(missing)
+ print("Missing files: `%s'" % "', `".join(missing))
if unwritable:
- print "Unwritable files: `%s'" % "', `".join(unwritable)
+ print("Unwritable files: `%s'" % "', `".join(unwritable))
self.fail_test(missing + unwritable)
def must_contain(self, file, required, mode = 'rb', find = None):
@@ -275,11 +277,11 @@ class TestCommon(TestCmd):
return None
contains = find(file_contents, required)
if not contains:
- print "File `%s' does not contain required string." % file
- print self.banner('Required string ')
- print required
- print self.banner('%s contents ' % file)
- print file_contents
+ print("File `%s' does not contain required string." % file)
+ print(self.banner('Required string '))
+ print(required)
+ print(self.banner('%s contents ' % file))
+ print(file_contents)
self.fail_test(not contains)
def must_contain_all(self, output, input, title=None, find=None):
@@ -306,10 +308,10 @@ class TestCommon(TestCmd):
if find(output, input) is None:
if title is None:
title = 'output'
- print 'Missing expected input from %s:' % title
- print input
- print self.banner(title + ' ')
- print output
+ print('Missing expected input from {}:'.format(title))
+ print(input)
+ print(self.banner(title + ' '))
+ print(output)
self.fail_test()
def must_contain_all_lines(self, output, lines, title=None, find=None):
@@ -444,7 +446,7 @@ class TestCommon(TestCmd):
files = [is_List(x) and os.path.join(*x) or x for x in files]
missing = [x for x in files if not os.path.exists(x) and not os.path.islink(x) ]
if missing:
- print "Missing files: `%s'" % "', `".join(missing)
+ print("Missing files: `%s'" % "', `".join(missing))
self.fail_test(missing)
def must_exist_one_of(self, files):
@@ -464,7 +466,7 @@ class TestCommon(TestCmd):
if glob.glob(xpath):
return
missing.append(xpath)
- print "Missing one of: `%s'" % "', `".join(missing)
+ print("Missing one of: `%s'" % "', `".join(missing))
self.fail_test(missing)
def must_match(self, file, expect, mode = 'rb', match=None):
@@ -481,7 +483,7 @@ class TestCommon(TestCmd):
except KeyboardInterrupt:
raise
except:
- print "Unexpected contents of `%s'" % file
+ print("Unexpected contents of `%s'" % file)
self.diff(expect, file_contents, 'contents ')
raise
@@ -497,11 +499,11 @@ class TestCommon(TestCmd):
return None
contains = find(file_contents, banned)
if contains:
- print "File `%s' contains banned string." % file
- print self.banner('Banned string ')
- print banned
- print self.banner('%s contents ' % file)
- print file_contents
+ print("File `%s' contains banned string." % file)
+ print(self.banner('Banned string '))
+ print(banned)
+ print(self.banner('%s contents ' % file))
+ print(file_contents)
self.fail_test(contains)
def must_not_contain_any_line(self, output, lines, title=None, find=None):
@@ -548,7 +550,7 @@ class TestCommon(TestCmd):
files = [is_List(x) and os.path.join(*x) or x for x in files]
existing = [x for x in files if os.path.exists(x) or os.path.islink(x)]
if existing:
- print "Unexpected files exist: `%s'" % "', `".join(existing)
+ print("Unexpected files exist: `%s'" % "', `".join(existing))
self.fail_test(existing)
def must_not_exist_any_of(self, files):
@@ -568,7 +570,7 @@ class TestCommon(TestCmd):
if glob.glob(xpath):
existing.append(xpath)
if existing:
- print "Unexpected files exist: `%s'" % "', `".join(existing)
+ print("Unexpected files exist: `%s'" % "', `".join(existing))
self.fail_test(existing)
def must_not_be_writable(self, *files):
@@ -582,9 +584,9 @@ class TestCommon(TestCmd):
existing, missing = separate_files(files)
writable = list(filter(is_writable, existing))
if missing:
- print "Missing files: `%s'" % "', `".join(missing)
+ print("Missing files: `%s'" % "', `".join(missing))
if writable:
- print "Writable files: `%s'" % "', `".join(writable)
+ print("Writable files: `%s'" % "', `".join(writable))
self.fail_test(missing + writable)
def _complete(self, actual_stdout, expected_stdout,
@@ -597,23 +599,23 @@ class TestCommon(TestCmd):
expect = ''
if status != 0:
expect = " (expected %s)" % str(status)
- print "%s returned %s%s" % (self.program, _status(self), expect)
- print self.banner('STDOUT ')
- print actual_stdout
- print self.banner('STDERR ')
- print actual_stderr
+ print("%s returned %s%s" % (self.program, _status(self), expect))
+ print(self.banner('STDOUT '))
+ print(actual_stdout)
+ print(self.banner('STDERR '))
+ print(actual_stderr)
self.fail_test()
if (expected_stdout is not None
and not match(actual_stdout, expected_stdout)):
self.diff(expected_stdout, actual_stdout, 'STDOUT ')
if actual_stderr:
- print self.banner('STDERR ')
- print actual_stderr
+ print(self.banner('STDERR '))
+ print(actual_stderr)
self.fail_test()
if (expected_stderr is not None
and not match(actual_stderr, expected_stderr)):
- print self.banner('STDOUT ')
- print actual_stdout
+ print(self.banner('STDOUT '))
+ print(actual_stdout)
self.diff(expected_stderr, actual_stderr, 'STDERR ')
self.fail_test()
@@ -633,15 +635,15 @@ class TestCommon(TestCmd):
universal_newlines, **kw)
except KeyboardInterrupt:
raise
- except Exception, e:
- print self.banner('STDOUT ')
+ except Exception as e:
+ print(self.banner('STDOUT '))
try:
- print self.stdout()
+ print(self.stdout())
except IndexError:
pass
- print self.banner('STDERR ')
+ print(self.banner('STDERR '))
try:
- print self.stderr()
+ print(self.stderr())
except IndexError:
pass
cmd_args = self.command_args(program, interpreter, arguments)
diff --git a/QMTest/TestSCons.py b/QMTest/TestSCons.py
index b71ee62..a515684 100644
--- a/QMTest/TestSCons.py
+++ b/QMTest/TestSCons.py
@@ -13,7 +13,7 @@ attributes defined in this subclass.
"""
# __COPYRIGHT__
-from __future__ import division
+from __future__ import division, print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -355,7 +355,7 @@ class TestSCons(TestCommon):
# 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:
return os.path.normpath(f)
else:
import SCons.Environment
@@ -502,9 +502,9 @@ class TestSCons(TestCommon):
self.pass_test()
else:
# test failed; have to do this by hand...
- print self.banner('STDOUT ')
- print self.stdout()
- print self.diff(warning, stderr, 'STDERR ')
+ print(self.banner('STDOUT '))
+ print(self.stdout())
+ print(self.diff(warning, stderr, 'STDERR '))
self.fail_test()
return warning
@@ -573,7 +573,7 @@ class TestSCons(TestCommon):
We stick the requested file name and line number in the right
places, abstracting out the version difference.
"""
- exec 'import traceback; x = traceback.format_stack()[-1]'
+ exec('import traceback; x = traceback.format_stack()[-1]')
x = x.lstrip()
x = x.replace('<string>', file)
x = x.replace('line 1,', 'line %s,' % line)
@@ -936,7 +936,7 @@ if ARGUMENTS.get('variant_dir', 0):
else:
builddir = 'build'
VariantDir(builddir, '.', duplicate=dup)
- print builddir, dup
+ print(builddir, dup)
sconscript = Dir(builddir).File('SConscript')
else:
sconscript = File('SConscript')
@@ -1021,7 +1021,7 @@ SConscript( sconscript )
raise NoMatch(lastEnd)
return m.end() + lastEnd
try:
- #print len(os.linesep)
+ #print(len(os.linesep))
ls = os.linesep
nols = "("
for i in range(len(ls)):
@@ -1095,27 +1095,27 @@ SConscript( sconscript )
if doCheckLog and lastEnd != len(logfile):
raise NoMatch(lastEnd)
- except NoMatch, m:
- print "Cannot match log file against log regexp."
- print "log file: "
- print "------------------------------------------------------"
- print logfile[m.pos:]
- print "------------------------------------------------------"
- print "log regexp: "
- print "------------------------------------------------------"
- print log
- print "------------------------------------------------------"
+ except NoMatch as m:
+ print("Cannot match log file against log regexp.")
+ print("log file: ")
+ print("------------------------------------------------------")
+ print(logfile[m.pos:])
+ print("------------------------------------------------------")
+ print("log regexp: ")
+ print("------------------------------------------------------")
+ print(log)
+ print("------------------------------------------------------")
self.fail_test()
if doCheckStdout:
exp_stdout = self.wrap_stdout(".*", rdstr)
if not self.match_re_dotall(self.stdout(), exp_stdout):
- print "Unexpected stdout: "
- print "-----------------------------------------------------"
- print repr(self.stdout())
- print "-----------------------------------------------------"
- print repr(exp_stdout)
- print "-----------------------------------------------------"
+ print("Unexpected stdout: ")
+ print("-----------------------------------------------------")
+ print(repr(self.stdout()))
+ print("-----------------------------------------------------")
+ print(repr(exp_stdout))
+ print("-----------------------------------------------------")
self.fail_test()
def get_python_version(self):
@@ -1149,12 +1149,12 @@ except AttributeError:
try:
import distutils.sysconfig
exec_prefix = distutils.sysconfig.EXEC_PREFIX
- print distutils.sysconfig.get_python_inc()
- print os.path.join(exec_prefix, 'libs')
+ print(distutils.sysconfig.get_python_inc())
+ print(os.path.join(exec_prefix, 'libs'))
except:
- print os.path.join(sys.prefix, 'include', py_ver)
- print os.path.join(sys.prefix, 'lib', py_ver, 'config')
-print py_ver
+ print(os.path.join(sys.prefix, 'include', py_ver))
+ print(os.path.join(sys.prefix, 'lib', py_ver, 'config'))
+print(py_ver)
""")
return [python] + self.stdout().strip().split('\n')
diff --git a/QMTest/TestSConsMSVS.py b/QMTest/TestSConsMSVS.py
index 65a09eb..39dbb5e 100644
--- a/QMTest/TestSConsMSVS.py
+++ b/QMTest/TestSConsMSVS.py
@@ -1037,8 +1037,8 @@ class TestSConsMSVS(TestSCons):
input = """\
import SCons
import SCons.Tool.MSCommon
-print "self.scons_version =", repr(SCons.__%s__)
-print "self._msvs_versions =", str(SCons.Tool.MSCommon.query_versions())
+print("self.scons_version =", repr(SCons.__%s__))
+print("self._msvs_versions =", str(SCons.Tool.MSCommon.query_versions()))
""" % 'version'
self.run(arguments = '-n -q -Q -f -', stdin = input)
@@ -1149,7 +1149,7 @@ print "self._msvs_versions =", str(SCons.Tool.MSCommon.query_versions())
try:
host = _ARCH_TO_CANONICAL[host_platform]
- except KeyError, e:
+ except KeyError as e:
# Default to x86 for all other platforms
host = 'x86'
diff --git a/QMTest/TestSCons_time.py b/QMTest/TestSCons_time.py
index abe8ccf..ba7fbd8 100644
--- a/QMTest/TestSCons_time.py
+++ b/QMTest/TestSCons_time.py
@@ -225,7 +225,7 @@ class TestSCons_time(TestCommon):
def write_fake_aegis_py(self, name):
name = self.workpath(name)
self.write(name, aegis_py)
- os.chmod(name, 0755)
+ os.chmod(name, 0o755)
return name
def write_fake_scons_py(self):
@@ -235,7 +235,7 @@ class TestSCons_time(TestCommon):
def write_fake_svn_py(self, name):
name = self.workpath(name)
self.write(name, svn_py)
- os.chmod(name, 0755)
+ os.chmod(name, 0o755)
return name
def write_sample_directory(self, archive, dir, files):
diff --git a/QMTest/TestSConsign.py b/QMTest/TestSConsign.py
index 700c242..a48b648 100644
--- a/QMTest/TestSConsign.py
+++ b/QMTest/TestSConsign.py
@@ -1,4 +1,5 @@
# __COPYRIGHT__
+from __future__ import print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -68,7 +69,7 @@ class TestSConsign(TestSCons):
elif os.path.exists(self.script_path('sconsign')):
sconsign = 'sconsign'
else:
- print "Can find neither 'sconsign.py' nor 'sconsign' scripts."
+ print("Can find neither 'sconsign.py' nor 'sconsign' scripts.")
self.no_result()
self.set_sconsign(sconsign)
diff --git a/QMTest/scons_tdb.py b/QMTest/scons_tdb.py
index 6be4696..76c7fe1 100644
--- a/QMTest/scons_tdb.py
+++ b/QMTest/scons_tdb.py
@@ -20,7 +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 division
+from __future__ import division, print_function
"""
QMTest classes to support SCons' testing and Aegis-inspired workflow.
@@ -337,14 +337,14 @@ class AegisChangeStream(AegisStream):
# We'd like to use the _FormatStatistics() method to do
# this, but it's wrapped around the list in Result.outcomes,
# so it's simpler to just do it ourselves.
- print " %6d tests total\n" % self._num_tests
+ print(" %6d tests total\n" % self._num_tests)
for outcome in AegisTest.aegis_outcomes:
if self._outcome_counts[outcome] != 0:
- print " %6d (%3.0f%%) tests %s" % (
+ print(" %6d (%3.0f%%) tests %s" % (
self._outcome_counts[outcome],
self._percent(outcome),
outcome
- )
+ ))
class AegisBaselineStream(AegisStream):
def WriteResult(self, result):
@@ -368,19 +368,19 @@ class AegisBaselineStream(AegisStream):
# this, but it's wrapped around the list in Result.outcomes,
# so it's simpler to just do it ourselves.
if self._outcome_counts[AegisTest.FAIL]:
- print " %6d (%3.0f%%) tests as expected" % (
+ print(" %6d (%3.0f%%) tests as expected" % (
self._outcome_counts[AegisTest.FAIL],
self._percent(AegisTest.FAIL),
- )
+ ))
non_fail_outcomes = list(AegisTest.aegis_outcomes[:])
non_fail_outcomes.remove(AegisTest.FAIL)
for outcome in non_fail_outcomes:
if self._outcome_counts[outcome] != 0:
- print " %6d (%3.0f%%) tests unexpected %s" % (
+ print(" %6d (%3.0f%%) tests unexpected %s" % (
self._outcome_counts[outcome],
self._percent(outcome),
outcome,
- )
+ ))
class AegisBatchStream(FileResultStream):
def __init__(self, arguments):
diff --git a/SConstruct b/SConstruct
index 33a8680..5eded92 100644
--- a/SConstruct
+++ b/SConstruct
@@ -3,6 +3,8 @@
#
# See the README.rst file for an overview of how SCons is built and tested.
+from __future__ import print_function
+
copyright_years = '2001 - 2016'
# This gets inserted into the man pages to reflect the month of release.
@@ -53,7 +55,7 @@ def is_windows():
return True
else:
return False
-
+
SConsignFile()
#
@@ -73,7 +75,7 @@ def whereis(file):
st = os.stat(f_ext)
except:
continue
- if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
+ if stat.S_IMODE(st[stat.ST_MODE]) & 0o111:
return f_ext
return None
@@ -161,7 +163,7 @@ import distutils.command
no_winpack_templates = not os.path.exists(os.path.join(os.path.split(distutils.command.__file__)[0],'wininst-9.0.exe'))
skip_win_packages = ARGUMENTS.get('SKIP_WIN_PACKAGES',False) or no_winpack_templates
if skip_win_packages:
- print "Skipping the build of Windows packages..."
+ print("Skipping the build of Windows packages...")
python_ver = sys.version[0:3]
@@ -324,7 +326,7 @@ try:
import zipfile
def zipit(env, target, source):
- print "Zipping %s:" % str(target[0])
+ print("Zipping %s:" % str(target[0]))
def visit(arg, dirname, names):
for name in names:
path = os.path.join(dirname, name)
@@ -339,7 +341,7 @@ try:
zf.close()
def unzipit(env, target, source):
- print "Unzipping %s:" % str(source[0])
+ print("Unzipping %s:" % str(source[0]))
zf = zipfile.ZipFile(str(source[0]), 'r')
for name in zf.namelist():
dest = os.path.join(env['UNPACK_ZIP_DIR'], name)
@@ -348,7 +350,7 @@ try:
os.makedirs(dir)
except:
pass
- print dest,name
+ print(dest,name)
# if the file exists, then delete it before writing
# to it so that we don't end up trying to write to a symlink:
if os.path.isfile(dest) or os.path.islink(dest):
@@ -417,7 +419,7 @@ def soelim(target, source, env):
def soscan(node, env, path):
c = node.get_text_contents()
- return re.compile(r"^[\.']so\s+(\S+)", re.M).findall(c)
+ return re.compile(br"^[\.']so\s+(\S+)", re.M).findall(c)
soelimbuilder = Builder(action = Action(soelim),
source_scanner = Scanner(soscan))
@@ -559,7 +561,7 @@ else:
i = install_egg_info(dist)
i.finalize_options()
import os.path
- print os.path.split(i.outputs[0])[1]
+ print(os.path.split(i.outputs[0])[1])
""" % version
try:
@@ -732,7 +734,7 @@ for p in [ scons ]:
platform_zip = os.path.join(build,
'dist',
"%s.%s.zip" % (pkg_version, platform))
-
+
#
# Update the environment with the relevant information
@@ -854,11 +856,11 @@ for p in [ scons ]:
for target in distutils_targets:
dist_target = env.Install('$DISTDIR', target)
- AddPostAction(dist_target, Chmod(dist_target, 0644))
+ AddPostAction(dist_target, Chmod(dist_target, 0o644))
dist_distutils_targets += dist_target
if not gzip:
- print "gzip not found in %s; skipping .tar.gz package for %s." % (os.environ['PATH'], pkg)
+ print("gzip not found in %s; skipping .tar.gz package for %s." % (os.environ['PATH'], pkg))
else:
distutils_formats.append('gztar')
@@ -870,8 +872,8 @@ for p in [ scons ]:
dist_tar_gz = env.Install('$DISTDIR', tar_gz)
dist_platform_tar_gz = env.Install('$DISTDIR', platform_tar_gz)
Local(dist_tar_gz, dist_platform_tar_gz)
- AddPostAction(dist_tar_gz, Chmod(dist_tar_gz, 0644))
- AddPostAction(dist_platform_tar_gz, Chmod(dist_platform_tar_gz, 0644))
+ AddPostAction(dist_tar_gz, Chmod(dist_tar_gz, 0o644))
+ AddPostAction(dist_platform_tar_gz, Chmod(dist_platform_tar_gz, 0o644))
#
# Unpack the tar.gz archive created by the distutils into
@@ -933,7 +935,7 @@ for p in [ scons ]:
env.Command(digest, tar_gz, Digestify)
if not zipit:
- print "zip not found; skipping .zip package for %s." % pkg
+ print("zip not found; skipping .zip package for %s." % pkg)
else:
distutils_formats.append('zip')
@@ -945,8 +947,8 @@ for p in [ scons ]:
dist_zip = env.Install('$DISTDIR', zip)
dist_platform_zip = env.Install('$DISTDIR', platform_zip)
Local(dist_zip, dist_platform_zip)
- AddPostAction(dist_zip, Chmod(dist_zip, 0644))
- AddPostAction(dist_platform_zip, Chmod(dist_platform_zip, 0644))
+ AddPostAction(dist_zip, Chmod(dist_zip, 0o644))
+ AddPostAction(dist_platform_zip, Chmod(dist_platform_zip, 0o644))
#
# Unpack the zip archive created by the distutils into
@@ -1033,8 +1035,8 @@ for p in [ scons ]:
dist_noarch_rpm = env.Install('$DISTDIR', noarch_rpm)
dist_src_rpm = env.Install('$DISTDIR', src_rpm)
Local(dist_noarch_rpm, dist_src_rpm)
- AddPostAction(dist_noarch_rpm, Chmod(dist_noarch_rpm, 0644))
- AddPostAction(dist_src_rpm, Chmod(dist_src_rpm, 0644))
+ AddPostAction(dist_noarch_rpm, Chmod(dist_noarch_rpm, 0o644))
+ AddPostAction(dist_src_rpm, Chmod(dist_src_rpm, 0o644))
dfiles = [os.path.join(test_rpm_dir, 'usr', x) for x in dst_files]
env.Command(dfiles,
@@ -1047,7 +1049,7 @@ for p in [ scons ]:
# The built deb is called just x.y.z, not x.y.z.final.0 so strip those off:
deb_version = '.'.join(version.split('.')[0:3])
deb = os.path.join(build_dir, 'dist', "%s_%s_all.deb" % (pkg, deb_version))
- # print "Building deb into %s (version=%s)"%(deb, deb_version)
+ # print("Building deb into %s (version=%s)"%(deb, deb_version))
for d in p['debian_deps']:
b = env.SCons_revision(os.path.join(build, d), d)
env.Depends(deb, b)
@@ -1107,8 +1109,8 @@ for p in [ scons ]:
dist_local_tar_gz = os.path.join("$DISTDIR/%s.tar.gz" % s_l_v)
dist_local_zip = os.path.join("$DISTDIR/%s.zip" % s_l_v)
- AddPostAction(dist_local_tar_gz, Chmod(dist_local_tar_gz, 0644))
- AddPostAction(dist_local_zip, Chmod(dist_local_zip, 0644))
+ AddPostAction(dist_local_tar_gz, Chmod(dist_local_tar_gz, 0o644))
+ AddPostAction(dist_local_zip, Chmod(dist_local_zip, 0o644))
commands = [
Delete(build_dir_local),
@@ -1218,7 +1220,7 @@ if hg_status_lines:
slines = [l for l in hg_status_lines if l[0] in 'ACM']
sfiles = [l.split()[-1] for l in slines]
else:
- print "Not building in a Mercurial tree; skipping building src package."
+ print("Not building in a Mercurial tree; skipping building src package.")
if sfiles:
remove_patterns = [
diff --git a/bench/bench.py b/bench/bench.py
index 74dbf12..f1d18c6 100644
--- a/bench/bench.py
+++ b/bench/bench.py
@@ -23,7 +23,7 @@
#
# This will allow (as much as possible) us to time just the code itself,
# not Python function call overhead.
-from __future__ import division
+from __future__ import division, print_function
import getopt
import sys
@@ -113,12 +113,12 @@ def display(label, results):
total = 0.0
for r in results:
total += r
- print " %8.3f" % ((total * 1e6) / len(results)), ':', label
+ print(" %8.3f" % ((total * 1e6) / len(results)), ':', label)
for func in FunctionList:
if func.__doc__: d = ' (' + func.__doc__ + ')'
else: d = ''
- print func.__name__ + d + ':'
+ print(func.__name__ + d + ':')
for label, args, kw in Data:
r = timer(func, *args, **kw)
diff --git a/bench/env.__setitem__.py b/bench/env.__setitem__.py
index b17b59e..9c27b6d 100644
--- a/bench/env.__setitem__.py
+++ b/bench/env.__setitem__.py
@@ -38,10 +38,10 @@ def times(num=1000000, init='', title='Results:', **statements):
t.timeit()
timings.append(t)
- print
- print title
+ print()
+ print(title)
for i in sorted([(i.getResult(),i.name) for i in timings]):
- print " %9.3f s %s" % i
+ print(" %9.3f s %s" % i)
# Import the necessary local SCons.* modules used by some of our
# alternative implementations below, first manipulating sys.path so
@@ -339,9 +339,9 @@ def run_it(title, init):
s['init'] = init
times(**s)
-print 'Environment __setitem__ benchmark using',
-print 'Python', sys.version.split()[0],
-print 'on', sys.platform, os.name
+print('Environment __setitem__ benchmark using', end=' ')
+print('Python', sys.version.split()[0], end=' ')
+print('on', sys.platform, os.name)
run_it('Results for re-adding an existing variable name 100 times:',
common_imports + """
diff --git a/bench/timeit.py b/bench/timeit.py
index c5fef12..7db0dd4 100644
--- a/bench/timeit.py
+++ b/bench/timeit.py
@@ -46,7 +46,7 @@ be aware of it. The baseline overhead can be measured by invoking the
program without arguments. The baseline overhead differs between
Python versions!
"""
-from __future__ import division
+from __future__ import division, print_function
try:
import gc
@@ -122,7 +122,7 @@ class Timer(object):
self.src = src # Save for traceback display
code = compile(src, dummy_src_name, "exec")
ns = {}
- exec code in globals(), ns
+ exec(code, globals(), ns)
self.inner = ns["inner"]
def print_exc(self, file=None):
@@ -216,9 +216,9 @@ def main(args=None):
opts, args = getopt.getopt(args, "n:s:r:tcvh",
["number=", "setup=", "repeat=",
"time", "clock", "verbose", "help"])
- except getopt.error, err:
- print err
- print "use -h/--help for command line help"
+ except getopt.error as err:
+ print(err)
+ print("use -h/--help for command line help")
return 2
timer = default_timer
stmt = "\n".join(args) or "pass"
@@ -245,7 +245,7 @@ def main(args=None):
precision = precision + 1
verbose = precision + 1
if o in ("-h", "--help"):
- print __doc__,
+ print(__doc__)
return 0
setup = "\n".join(setup) or "pass"
# Include the current directory, so that local imports work (sys.path
@@ -264,7 +264,7 @@ def main(args=None):
t.print_exc()
return 1
if verbose:
- print "%d loops -> %.*g secs" % (number, precision, x)
+ print("%d loops -> %.*g secs" % (number, precision, x))
if x >= 0.2:
break
try:
@@ -274,18 +274,18 @@ def main(args=None):
return 1
best = min(r)
if verbose:
- print "raw times:", ' '.join(["%.*g" % (precision, x) for x in r])
- print "%d loops," % number,
+ print("raw times:", ' '.join(["%.*g" % (precision, x) for x in r]))
+ print("%d loops," % number, end=' ')
usec = best * 1e6 / number
if usec < 1000:
- print "best of %d: %.*g usec per loop" % (repeat, precision, usec)
+ print("best of %d: %.*g usec per loop" % (repeat, precision, usec))
else:
msec = usec / 1000
if msec < 1000:
- print "best of %d: %.*g msec per loop" % (repeat, precision, msec)
+ print("best of %d: %.*g msec per loop" % (repeat, precision, msec))
else:
sec = msec / 1000
- print "best of %d: %.*g sec per loop" % (repeat, precision, sec)
+ print("best of %d: %.*g sec per loop" % (repeat, precision, sec))
return None
if __name__ == "__main__":
diff --git a/bin/Command.py b/bin/Command.py
index 8702f51..dadd7a9 100644
--- a/bin/Command.py
+++ b/bin/Command.py
@@ -4,6 +4,7 @@
#
# XXX Describe what the script does here.
#
+from __future__ import print_function
import getopt
import os
@@ -109,18 +110,18 @@ Usage: script-template.py [-hnq]
try:
try:
opts, args = getopt.getopt(argv[1:], short_options, long_options)
- except getopt.error, msg:
+ except getopt.error as msg:
raise Usage(msg)
for o, a in opts:
if o in ('-h', '--help'):
- print helpstr
+ print(helpstr)
sys.exit(0)
elif o in ('-n', '--no-exec'):
Command.execute = Command.do_not_execute
elif o in ('-q', '--quiet'):
Command.display = Command.do_not_display
- except Usage, err:
+ except Usage as err:
sys.stderr.write(err.msg)
sys.stderr.write('use -h to get help')
return 2
diff --git a/bin/SConsDoc.py b/bin/SConsDoc.py
index e435b4a..d566644 100644
--- a/bin/SConsDoc.py
+++ b/bin/SConsDoc.py
@@ -24,6 +24,7 @@
#
# Module for handling SCons documentation processing.
#
+from __future__ import print_function
__doc__ = """
This module parses home-brew XML files that document various things
@@ -51,7 +52,7 @@ Builder example:
to indicate a new paragraph.
<example>
- print "this is example code, it will be offset and indented"
+ print("this is example code, it will be offset and indented")
</example>
</summary>
</builder>
@@ -71,7 +72,7 @@ Function example:
&f-FUNCTION; element. It need not be on a line by itself.</para>
<example>
- print "this is example code, it will be offset and indented"
+ print("this is example code, it will be offset and indented")
</example>
</summary>
</scons_function>
@@ -88,7 +89,7 @@ Construction variable example:
&t-VARIABLE; element. It need not be on a line by itself.</para>
<example>
- print "this is example code, it will be offset and indented"
+ print("this is example code, it will be offset and indented")
</example>
</summary>
</cvar>
@@ -105,7 +106,7 @@ Tool example:
&t-TOOL; element. It need not be on a line by itself.</para>
<example>
- print "this is example code, it will be offset and indented"
+ print("this is example code, it will be offset and indented")
</example>
</summary>
</tool>
@@ -208,12 +209,12 @@ class Libxml2ValidityHandler:
def error(self, msg, data):
if data != ARG:
- raise Exception, "Error handler did not receive correct argument"
+ raise Exception("Error handler did not receive correct argument")
self.errors.append(msg)
def warning(self, msg, data):
if data != ARG:
- raise Exception, "Warning handler did not receive correct argument"
+ raise Exception("Warning handler did not receive correct argument")
self.warnings.append(msg)
@@ -330,16 +331,16 @@ if not has_libxml2:
xmlschema = etree.XMLSchema(xmlschema_context)
try:
doc = etree.parse(fpath)
- except Exception, e:
- print "ERROR: %s fails to parse:"%fpath
- print e
+ except Exception as e:
+ print("ERROR: %s fails to parse:"%fpath)
+ print(e)
return False
doc.xinclude()
try:
xmlschema.assertValid(doc)
- except Exception, e:
- print "ERROR: %s fails to validate:" % fpath
- print e
+ except Exception as e:
+ print("ERROR: %s fails to validate:" % fpath)
+ print(e)
return False
return True
@@ -475,8 +476,8 @@ else:
if err or eh.errors:
for e in eh.errors:
- print e.rstrip("\n")
- print "%s fails to validate" % fpath
+ print(e.rstrip("\n"))
+ print("%s fails to validate" % fpath)
return False
return True
@@ -597,7 +598,7 @@ class SConsDocTree:
# Create xpath context
self.xpath_context = self.doc.xpathNewContext()
# Register namespaces
- for key, val in self.nsmap.iteritems():
+ for key, val in self.nsmap.items():
self.xpath_context.xpathRegisterNs(key, val)
def __del__(self):
@@ -635,8 +636,8 @@ def validate_all_xml(dpaths, xsdfile=default_xsd):
fails = []
for idx, fp in enumerate(fpaths):
fpath = os.path.join(path, fp)
- print "%.2f%s (%d/%d) %s" % (float(idx+1)*100.0/float(len(fpaths)),
- perc, idx+1, len(fpaths),fp)
+ print("%.2f%s (%d/%d) %s" % (float(idx+1)*100.0/float(len(fpaths)),
+ perc, idx+1, len(fpaths),fp))
if not tf.validateXml(fp, xmlschema_context):
fails.append(fp)
@@ -665,8 +666,10 @@ class Item(object):
if name[0] == '_':
name = name[1:]
return name.lower()
- def __cmp__(self, other):
- return cmp(self.sort_name, other.sort_name)
+ def __eq__(self, other):
+ return self.sort_name == other.sort_name
+ def __lt__(self, other):
+ return self.sort_name < other.sort_name
class Builder(Item):
pass
@@ -808,7 +811,7 @@ def importfile(path):
file = open(path, 'r')
try:
module = imp.load_module(name, file, path, (ext, 'r', kind))
- except ImportError, e:
+ except ImportError as e:
sys.stderr.write("Could not import %s: %s\n" % (path, e))
return None
file.close()
diff --git a/bin/SConsExamples.py b/bin/SConsExamples.py
index 9823a05..dd9bfaf 100644
--- a/bin/SConsExamples.py
+++ b/bin/SConsExamples.py
@@ -1,7 +1,7 @@
# !/usr/bin/env python
-#
+#
# Copyright (c) 2010 The SCons Foundation
-#
+#
# 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
@@ -9,10 +9,10 @@
# 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
@@ -21,18 +21,18 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-#
+#
+#
# This script looks for some XML tags that describe SCons example
# configurations and commands to execute in those configurations, and
# uses TestCmd.py to execute the commands and insert the output from
# those commands into the XML that we output. This way, we can run a
# script and update all of our example documentation output without
# a lot of laborious by-hand checking.
-#
+#
# An "SCons example" looks like this, and essentially describes a set of
# input files (program source files as well as SConscript files):
-#
+#
# <scons_example name="ex1">
# <file name="SConstruct" printme="1">
# env = Environment()
@@ -42,7 +42,7 @@
# int main() { printf("foo.c\n"); }
# </file>
# </scons_example>
-#
+#
# The <file> contents within the <scons_example> tag will get written
# into a temporary directory whenever example output needs to be
# generated. By default, the <file> contents are not inserted into text
@@ -50,41 +50,43 @@
# in which case they will get inserted within a <programlisting> tag.
# This makes it easy to define the example at the appropriate
# point in the text where you intend to show the SConstruct file.
-#
+#
# Note that you should usually give the <scons_example> a "name"
# attribute so that you can refer to the example configuration later to
# run SCons and generate output.
-#
+#
# If you just want to show a file's contents without worry about running
# SCons, there's a shorter <sconstruct> tag:
-#
+#
# <sconstruct>
# env = Environment()
# env.Program('foo')
# </sconstruct>
-#
+#
# This is essentially equivalent to <scons_example><file printme="1">,
# but it's more straightforward.
-#
+#
# SCons output is generated from the following sort of tag:
-#
+#
# <scons_output example="ex1" os="posix">
# <scons_output_command suffix="1">scons -Q foo</scons_output_command>
# <scons_output_command suffix="2">scons -Q foo</scons_output_command>
# </scons_output>
-#
+#
# You tell it which example to use with the "example" attribute, and then
# give it a list of <scons_output_command> tags to execute. You can also
# supply an "os" tag, which specifies the type of operating system this
# example is intended to show; if you omit this, default value is "posix".
-#
+#
# The generated XML will show the command line (with the appropriate
# command-line prompt for the operating system), execute the command in
# a temporary directory with the example files, capture the standard
# output from SCons, and insert it into the text as appropriate.
# Error output gets passed through to your error output so you
# can see if there are any problems executing the command.
-#
+#
+
+from __future__ import print_function
import os
import re
@@ -94,9 +96,9 @@ import time
import SConsDoc
from SConsDoc import tf as stf
-#
+#
# The available types for ExampleFile entries
-#
+#
FT_FILE = 0 # a physical file (=<file>)
FT_FILEREF = 1 # a reference (=<scons_example_file>)
@@ -106,7 +108,7 @@ class ExampleFile:
self.name = ''
self.content = ''
self.chmod = ''
-
+
def isFileRef(self):
return self.type == FT_FILEREF
@@ -130,19 +132,19 @@ class ExampleOutput:
self.preserve = None
self.suffix = ''
self.commands = []
-
+
class ExampleInfo:
def __init__(self):
self.name = ''
self.files = []
self.folders = []
self.outputs = []
-
+
def getFileContents(self, fname):
for f in self.files:
if fname == f.name and not f.isFileRef():
return f.content
-
+
return ''
def readExampleInfos(fpath, examples):
@@ -150,10 +152,10 @@ def readExampleInfos(fpath, examples):
global dictionary examples.
"""
- # Create doctree
+ # Create doctree
t = SConsDoc.SConsDocTree()
t.parseXmlFile(fpath)
-
+
# Parse scons_examples
for e in stf.findAll(t.root, "scons_example", SConsDoc.dbxid,
t.xpath_context, t.nsmap):
@@ -164,7 +166,7 @@ def readExampleInfos(fpath, examples):
i = ExampleInfo()
i.name = n
examples[n] = i
-
+
# Parse file and directory entries
for f in stf.findAll(e, "file", SConsDoc.dbxid,
t.xpath_context, t.nsmap):
@@ -199,8 +201,8 @@ def readExampleInfos(fpath, examples):
fi.chmod = stf.getAttribute(f, 'chmod')
fi.content = stf.getText(f)
examples[e].files.append(fi)
-
-
+
+
# Parse scons_output
for o in stf.findAll(t.root, "scons_output", SConsDoc.dbxid,
t.xpath_context, t.nsmap):
@@ -238,7 +240,7 @@ def readExampleInfos(fpath, examples):
examples[n].outputs.append(eout)
def readAllExampleInfos(dpath):
- """ Scan for XML files in the given directory and
+ """ Scan for XML files in the given directory and
collect together all relevant infos (files/folders,
output commands) in a map, which gets returned.
"""
@@ -249,13 +251,13 @@ def readAllExampleInfos(dpath):
fpath = os.path.join(path, f)
if SConsDoc.isSConsXml(fpath):
readExampleInfos(fpath, examples)
-
+
return examples
generated_examples = os.path.join('doc', 'generated', 'examples')
def ensureExampleOutputsExist(dpath):
- """ Scan for XML files in the given directory and
+ """ Scan for XML files in the given directory and
ensure that for every example output we have a
corresponding output file in the 'generated/examples'
folder.
@@ -263,9 +265,9 @@ def ensureExampleOutputsExist(dpath):
# Ensure that the output folder exists
if not os.path.isdir(generated_examples):
os.mkdir(generated_examples)
-
+
examples = readAllExampleInfos(dpath)
- for key, value in examples.iteritems():
+ for key, value in examples.items():
# Process all scons_output tags
for o in value.outputs:
cpath = os.path.join(generated_examples,
@@ -276,7 +278,7 @@ def ensureExampleOutputsExist(dpath):
stf.setText(s, "NO OUTPUT YET! Run the script to generate/update all examples.")
# Write file
stf.writeTree(s, cpath)
-
+
# Process all scons_example_file tags
for r in value.files:
if r.isFileRef():
@@ -292,22 +294,22 @@ def ensureExampleOutputsExist(dpath):
perc = "%"
def createAllExampleOutputs(dpath):
- """ Scan for XML files in the given directory and
+ """ Scan for XML files in the given directory and
creates all output files for every example in
the 'generated/examples' folder.
"""
# Ensure that the output folder exists
if not os.path.isdir(generated_examples):
os.mkdir(generated_examples)
-
+
examples = readAllExampleInfos(dpath)
total = len(examples)
idx = 0
- for key, value in examples.iteritems():
+ for key, value in examples.items():
# Process all scons_output tags
- print "%.2f%s (%d/%d) %s" % (float(idx + 1) * 100.0 / float(total),
- perc, idx + 1, total, key)
-
+ print("%.2f%s (%d/%d) %s" % (float(idx + 1) * 100.0 / float(total),
+ perc, idx + 1, total, key))
+
create_scons_output(value)
# Process all scons_example_file tags
for r in value.files:
@@ -329,10 +331,10 @@ def collectSConsExampleNames(fpath):
suffixes = {}
failed_suffixes = False
- # Create doctree
+ # Create doctree
t = SConsDoc.SConsDocTree()
t.parseXmlFile(fpath)
-
+
# Parse it
for e in stf.findAll(t.root, "scons_example", SConsDoc.dbxid,
t.xpath_context, t.nsmap):
@@ -344,40 +346,40 @@ def collectSConsExampleNames(fpath):
if n not in suffixes:
suffixes[n] = []
else:
- print "Error: Example in file '%s' is missing a name!" % fpath
+ print("Error: Example in file '%s' is missing a name!" % fpath)
failed_suffixes = True
-
+
for o in stf.findAll(t.root, "scons_output", SConsDoc.dbxid,
t.xpath_context, t.nsmap):
n = ''
if stf.hasAttribute(o, 'example'):
n = stf.getAttribute(o, 'example')
else:
- print "Error: scons_output in file '%s' is missing an example name!" % fpath
+ print("Error: scons_output in file '%s' is missing an example name!" % fpath)
failed_suffixes = True
-
+
if n not in suffixes:
- print "Error: scons_output in file '%s' is referencing non-existent example '%s'!" % (fpath, n)
+ print("Error: scons_output in file '%s' is referencing non-existent example '%s'!" % (fpath, n))
failed_suffixes = True
continue
-
+
s = ''
if stf.hasAttribute(o, 'suffix'):
s = stf.getAttribute(o, 'suffix')
else:
- print "Error: scons_output in file '%s' (example '%s') is missing a suffix!" % (fpath, n)
+ print("Error: scons_output in file '%s' (example '%s') is missing a suffix!" % (fpath, n))
failed_suffixes = True
-
+
if s not in suffixes[n]:
suffixes[n].append(s)
else:
- print "Error: scons_output in file '%s' (example '%s') is using a duplicate suffix '%s'!" % (fpath, n, s)
+ print("Error: scons_output in file '%s' (example '%s') is using a duplicate suffix '%s'!" % (fpath, n, s))
failed_suffixes = True
-
+
return names, failed_suffixes
def exampleNamesAreUnique(dpath):
- """ Scan for XML files in the given directory and
+ """ Scan for XML files in the given directory and
check whether the scons_example names are unique.
"""
unique = True
@@ -392,21 +394,21 @@ def exampleNamesAreUnique(dpath):
unique = False
i = allnames.intersection(names)
if i:
- print "Not unique in %s are: %s" % (fpath, ', '.join(i))
+ print("Not unique in %s are: %s" % (fpath, ', '.join(i)))
unique = False
-
+
allnames |= names
-
+
return unique
# ###############################################################
-#
+#
# In the second half of this module (starting here)
# we define the variables and functions that are required
# to actually run the examples, collect their output and
# write it into the files in doc/generated/examples...
# which then get included by our UserGuide.
-#
+#
# ###############################################################
sys.path.append(os.path.join(os.getcwd(), 'QMTest'))
@@ -430,7 +432,7 @@ Prompt = {
}
# The magick SCons hackery that makes this work.
-#
+#
# So that our examples can still use the default SConstruct file, we
# actually feed the following into SCons via stdin and then have it
# SConscript() the SConstruct file. This stdin wrapper creates a set
@@ -438,7 +440,7 @@ Prompt = {
# Surrogates print output like the real tools and behave like them
# without actually having to be on the right platform or have the right
# tool installed.
-#
+#
# The upshot: The wrapper transparently changes the world out from
# under the top-level SConstruct file in an example just so we can get
# the command output.
@@ -765,7 +767,7 @@ def ExecuteCommand(args, c, t, dict):
def create_scons_output(e):
# The real raison d'etre for this script, this is where we
# actually execute SCons to fetch the output.
-
+
# Loop over all outputs for the example
for o in e.outputs:
# Create new test directory
@@ -774,19 +776,19 @@ def create_scons_output(e):
t.preserve()
t.subdir('ROOT', 'WORK')
t.rootpath = t.workpath('ROOT').replace('\\', '\\\\')
-
+
for d in e.folders:
dir = t.workpath('WORK', d.name)
if not os.path.exists(dir):
os.makedirs(dir)
-
+
for f in e.files:
if f.isFileRef():
continue
- #
+ #
# Left-align file's contents, starting on the first
# non-empty line
- #
+ #
data = f.content.split('\n')
i = 0
# Skip empty lines
@@ -813,26 +815,26 @@ def create_scons_output(e):
if hasattr(f, 'chmod'):
if len(f.chmod):
os.chmod(path, int(f.chmod, 0))
-
+
# Regular expressions for making the doc output consistent,
# regardless of reported addresses or Python version.
-
+
# Massage addresses in object repr strings to a constant.
address_re = re.compile(r' at 0x[0-9a-fA-F]*\>')
-
+
# Massage file names in stack traces (sometimes reported as absolute
# paths) to a consistent relative path.
engine_re = re.compile(r' File ".*/src/engine/SCons/')
-
+
# Python 2.5 changed the stack trace when the module is read
# from standard input from read "... line 7, in ?" to
# "... line 7, in <module>".
file_re = re.compile(r'^( *File ".*", line \d+, in) \?$', re.M)
-
+
# Python 2.6 made UserList a new-style class, which changes the
# AttributeError message generated by our NodeList subclass.
nodelist_re = re.compile(r'(AttributeError:) NodeList instance (has no attribute \S+)')
-
+
# Root element for our subtree
sroot = stf.newEtreeNode("screen", True)
curchild = None
@@ -881,7 +883,7 @@ def create_scons_output(e):
curchild.tail = content
else:
sroot.text = content
-
+
# Construct filename
fpath = os.path.join(generated_examples,
e.name + '_' + o.suffix + '.xml')
diff --git a/bin/calibrate.py b/bin/calibrate.py
index 8ed2ece..3f9104e 100644
--- a/bin/calibrate.py
+++ b/bin/calibrate.py
@@ -20,7 +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 division
+from __future__ import division, print_function
import optparse
import os
@@ -48,7 +48,7 @@ def main(argv=None):
for arg in args:
if len(args) > 1:
- print arg + ':'
+ print(arg + ':')
command = [sys.executable, 'runtest.py']
if opts.package:
@@ -67,9 +67,9 @@ def main(argv=None):
try:
elapsed = float(em.group(1))
except AttributeError:
- print output
+ print(output)
raise
- print "run %3d: %7.3f: %s" % (run, elapsed, ' '.join(vm.groups()))
+ print("run %3d: %7.3f: %s" % (run, elapsed, ' '.join(vm.groups())))
if opts.min < elapsed and elapsed < opts.max:
good += 1
else:
diff --git a/bin/caller-tree.py b/bin/caller-tree.py
index 03c1616..21cda4b 100644
--- a/bin/caller-tree.py
+++ b/bin/caller-tree.py
@@ -39,6 +39,7 @@
# function at the same time, for example, their counts will intermix.
# So use this to get a *general* idea of who's calling what, not for
# fine-grained performance tuning.
+from __future__ import print_function
import sys
@@ -74,17 +75,17 @@ for line in sys.stdin.readlines():
stack = []
def print_entry(e, level, calls):
- print '%-72s%6s' % ((' '*2*level) + e.file_line_func, calls)
+ print('%-72s%6s' % ((' '*2*level) + e.file_line_func, calls))
if e in stack:
- print (' '*2*(level+1))+'RECURSION'
- print
+ print((' '*2*(level+1))+'RECURSION')
+ print()
elif e.called_by:
stack.append(e)
for c in e.called_by:
print_entry(c[0], level+1, c[1])
stack.pop()
else:
- print
+ print()
for e in [ e for e in AllCalls.values() if not e.calls ]:
print_entry(e, 0, '')
diff --git a/bin/docs-create-example-outputs.py b/bin/docs-create-example-outputs.py
index 6e59d9f..73aa31a 100644
--- a/bin/docs-create-example-outputs.py
+++ b/bin/docs-create-example-outputs.py
@@ -3,17 +3,18 @@
# Searches through the whole doc/user tree and creates
# all output files for the single examples.
#
+from __future__ import print_function
import os
import sys
import SConsExamples
if __name__ == "__main__":
- print "Checking whether all example names are unique..."
+ print("Checking whether all example names are unique...")
if SConsExamples.exampleNamesAreUnique(os.path.join('doc','user')):
- print "OK"
+ print("OK")
else:
- print "Not all example names and suffixes are unique! Please correct the errors listed above and try again."
+ print("Not all example names and suffixes are unique! Please correct the errors listed above and try again.")
sys.exit(1)
-
+
SConsExamples.createAllExampleOutputs(os.path.join('doc','user'))
diff --git a/bin/docs-update-generated.py b/bin/docs-update-generated.py
index 55f0035..c164baf 100644
--- a/bin/docs-update-generated.py
+++ b/bin/docs-update-generated.py
@@ -6,6 +6,7 @@
# as well as the entity declarations for them.
# Uses scons-proc.py under the hood...
#
+from __future__ import print_function
import os
import sys
@@ -39,7 +40,7 @@ def generate_all():
try:
os.makedirs(gen_folder)
except:
- print "Couldn't create destination folder %s! Exiting..." % gen_folder
+ print("Couldn't create destination folder %s! Exiting..." % gen_folder)
return
# Call scons-proc.py
os.system('%s %s -b %s -f %s -t %s -v %s %s' %
diff --git a/bin/docs-validate.py b/bin/docs-validate.py
index f888c21..342ed43 100644
--- a/bin/docs-validate.py
+++ b/bin/docs-validate.py
@@ -3,6 +3,7 @@
# Searches through the whole source tree and validates all
# documentation files against our own XSD in docs/xsd.
#
+from __future__ import print_function
import sys,os
import SConsDoc
@@ -10,9 +11,9 @@ import SConsDoc
if __name__ == "__main__":
if len(sys.argv)>1:
if SConsDoc.validate_all_xml((sys.argv[1],)):
- print "OK"
+ print("OK")
else:
- print "Validation failed! Please correct the errors above and try again."
+ print("Validation failed! Please correct the errors above and try again.")
else:
if SConsDoc.validate_all_xml(['src',
os.path.join('doc','design'),
@@ -22,7 +23,7 @@ if __name__ == "__main__":
os.path.join('doc','reference'),
os.path.join('doc','user')
]):
- print "OK"
+ print("OK")
else:
- print "Validation failed! Please correct the errors above and try again."
+ print("Validation failed! Please correct the errors above and try again.")
sys.exit(1)
diff --git a/bin/install_python.py b/bin/install_python.py
index 86807af..5c947ac 100644
--- a/bin/install_python.py
+++ b/bin/install_python.py
@@ -6,6 +6,7 @@
# This was written for a Linux system (specifically Ubuntu) but should
# be reasonably generic to any POSIX-style system with a /usr/local
# hierarchy.
+from __future__ import print_function
import getopt
import os
@@ -48,7 +49,7 @@ Usage: install_python.py [-ahnq] [-d DIR] [-p PREFIX] [VERSION ...]
try:
try:
opts, args = getopt.getopt(argv[1:], short_options, long_options)
- except getopt.error, msg:
+ except getopt.error as msg:
raise Usage(msg)
for o, a in opts:
@@ -57,7 +58,7 @@ Usage: install_python.py [-ahnq] [-d DIR] [-p PREFIX] [VERSION ...]
elif o in ('-d', '--downloads'):
downloads_dir = a
elif o in ('-h', '--help'):
- print helpstr
+ print(helpstr)
sys.exit(0)
elif o in ('-n', '--no-exec'):
CommandRunner.execute = CommandRunner.do_not_execute
@@ -65,7 +66,7 @@ Usage: install_python.py [-ahnq] [-d DIR] [-p PREFIX] [VERSION ...]
prefix = a
elif o in ('-q', '--quiet'):
CommandRunner.display = CommandRunner.do_not_display
- except Usage, err:
+ except Usage as err:
sys.stderr.write(str(err.msg) + '\n')
sys.stderr.write('use -h to get help\n')
return 2
diff --git a/bin/install_scons.py b/bin/install_scons.py
index 00129f6..ac79fd3 100644
--- a/bin/install_scons.py
+++ b/bin/install_scons.py
@@ -18,12 +18,14 @@
# be reasonably generic to any POSIX-style system with a /usr/local
# hierarchy.
+from __future__ import print_function
+
import getopt
import os
import shutil
import sys
import tarfile
-import urllib
+from urllib import urlretrieve
from Command import CommandRunner, Usage
@@ -129,7 +131,7 @@ Usage: install_scons.py [-ahnq] [-d DIR] [-p PREFIX] [VERSION ...]
try:
try:
opts, args = getopt.getopt(argv[1:], short_options, long_options)
- except getopt.error, msg:
+ except getopt.error as msg:
raise Usage(msg)
for o, a in opts:
@@ -138,7 +140,7 @@ Usage: install_scons.py [-ahnq] [-d DIR] [-p PREFIX] [VERSION ...]
elif o in ('-d', '--downloads'):
downloads_dir = a
elif o in ('-h', '--help'):
- print helpstr
+ print(helpstr)
sys.exit(0)
elif o in ('-n', '--no-exec'):
CommandRunner.execute = CommandRunner.do_not_execute
@@ -146,7 +148,7 @@ Usage: install_scons.py [-ahnq] [-d DIR] [-p PREFIX] [VERSION ...]
prefix = a
elif o in ('-q', '--quiet'):
CommandRunner.display = CommandRunner.do_not_display
- except Usage, err:
+ except Usage as err:
sys.stderr.write(str(err.msg) + '\n')
sys.stderr.write('use -h to get help\n')
return 2
@@ -171,7 +173,7 @@ Usage: install_scons.py [-ahnq] [-d DIR] [-p PREFIX] [VERSION ...]
if not os.path.exists(tar_gz):
if not os.path.exists(downloads_dir):
cmd.run('mkdir %(downloads_dir)s')
- cmd.run((urllib.urlretrieve, tar_gz_url, tar_gz),
+ cmd.run((urlretrieve, tar_gz_url, tar_gz),
'wget -O %(tar_gz)s %(tar_gz_url)s')
def extract(tar_gz):
diff --git a/bin/linecount.py b/bin/linecount.py
index 6f49dca..897f1e8 100644
--- a/bin/linecount.py
+++ b/bin/linecount.py
@@ -21,7 +21,7 @@
# in each category, the number of non-blank lines, and the number of
# non-comment lines. The last figure (non-comment) lines is the most
# interesting one for most purposes.
-from __future__ import division
+from __future__ import division, print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -98,23 +98,23 @@ all_tests = Collection('all tests', src_tests.files + test_tests.files)
def ratio(over, under):
return "%.2f" % (float(len(over)) / float(len(under)))
-print fmt % ('', '', '', '', '', 'non-blank')
-print fmt % ('', 'files', 'lines', 'non-blank', 'non-comment', 'non-comment')
-print
-print fmt % src_Tests_py_tests.printables()
-print fmt % src_test_tests.printables()
-print
-print fmt % src_tests.printables()
-print fmt % test_tests.printables()
-print
-print fmt % all_tests.printables()
-print fmt % sources.printables()
-print
-print fmt % ('ratio:',
+print(fmt % ('', '', '', '', '', 'non-blank'))
+print(fmt % ('', 'files', 'lines', 'non-blank', 'non-comment', 'non-comment'))
+print()
+print(fmt % src_Tests_py_tests.printables())
+print(fmt % src_test_tests.printables())
+print()
+print(fmt % src_tests.printables())
+print(fmt % test_tests.printables())
+print()
+print(fmt % all_tests.printables())
+print(fmt % sources.printables())
+print()
+print(fmt % ('ratio:',
ratio(all_tests, sources),
ratio(all_tests.lines(), sources.lines()),
ratio(all_tests.non_blank(), sources.non_blank()),
ratio(all_tests.non_comment(), sources.non_comment()),
ratio(all_tests.non_blank_non_comment(),
sources.non_blank_non_comment())
- )
+ ))
diff --git a/bin/memlogs.py b/bin/memlogs.py
index 9d957c9..b450939 100644
--- a/bin/memlogs.py
+++ b/bin/memlogs.py
@@ -21,26 +21,28 @@
# 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
+
import getopt
import sys
filenames = sys.argv[1:]
if not filenames:
- print """Usage: memlogs.py file [...]
+ print("""Usage: memlogs.py file [...]
Summarizes the --debug=memory numbers from one or more build logs.
-"""
+""")
sys.exit(0)
fmt = "%12s %12s %12s %12s %s"
-print fmt % ("pre-read", "post-read", "pre-build", "post-build", "")
+print(fmt % ("pre-read", "post-read", "pre-build", "post-build", ""))
for fname in sys.argv[1:]:
lines = [l for l in open(fname).readlines() if l[:7] == 'Memory ']
t = tuple([l.split()[-1] for l in lines]) + (fname,)
- print fmt % t
+ print(fmt % t)
# Local Variables:
# tab-width:4
diff --git a/bin/memoicmp.py b/bin/memoicmp.py
index 812af66..7f0369e 100644
--- a/bin/memoicmp.py
+++ b/bin/memoicmp.py
@@ -3,6 +3,8 @@
# A script to compare the --debug=memoizer output found in
# two different files.
+from __future__ import print_function
+
import sys
def memoize_output(fname):
@@ -23,8 +25,8 @@ def memoize_cmp(filea, fileb):
ma = memoize_output(filea)
mb = memoize_output(fileb)
- print 'All output: %s / %s [delta]'%(filea, fileb)
- print '----------HITS---------- ---------MISSES---------'
+ print('All output: %s / %s [delta]'%(filea, fileb))
+ print('----------HITS---------- ---------MISSES---------')
cfmt='%7d/%-7d [%d]'
ma_o = []
mb_o = []
@@ -45,30 +47,30 @@ def memoize_cmp(filea, fileb):
mab.sort()
ma_o.sort()
mb_o.sort()
-
+
for k in mab:
hits = cfmt%(ma[k][0], mb[k][0], mb[k][0]-ma[k][0])
miss = cfmt%(ma[k][1], mb[k][1], mb[k][1]-ma[k][1])
- print '%-24s %-24s %s'%(hits, miss, k)
+ print('%-24s %-24s %s'%(hits, miss, k))
for k in ma_o:
hits = '%7d/ --'%(ma[k][0])
miss = '%7d/ --'%(ma[k][1])
- print '%-24s %-24s %s'%(hits, miss, k)
+ print('%-24s %-24s %s'%(hits, miss, k))
for k in mb_o:
hits = ' -- /%-7d'%(mb[k][0])
miss = ' -- /%-7d'%(mb[k][1])
- print '%-24s %-24s %s'%(hits, miss, k)
+ print('%-24s %-24s %s'%(hits, miss, k))
+
+ print('-'*(24+24+1+20))
- print '-'*(24+24+1+20)
-
if __name__ == "__main__":
if len(sys.argv) != 3:
- print """Usage: %s file1 file2
+ print("""Usage: %s file1 file2
-Compares --debug=memomize output from file1 against file2."""%sys.argv[0]
+Compares --debug=memomize output from file1 against file2."""%sys.argv[0])
sys.exit(1)
memoize_cmp(sys.argv[1], sys.argv[2])
diff --git a/bin/objcounts.py b/bin/objcounts.py
index 0662012..2bd8923 100644
--- a/bin/objcounts.py
+++ b/bin/objcounts.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
import re
import sys
@@ -27,10 +28,10 @@ import sys
filenames = sys.argv[1:]
if len(sys.argv) != 3:
- print """Usage: objcounts.py file1 file2
+ print("""Usage: objcounts.py file1 file2
Compare the --debug=object counts from two build logs.
-"""
+""")
sys.exit(0)
def fetch_counts(fname):
@@ -81,10 +82,9 @@ def diffstr(c1, c2):
return " %5s/%-5s %-8s" % (c1, c2, d)
def printline(c1, c2, classname):
- print \
- diffstr(c1[2], c2[2]) + \
+ print(diffstr(c1[2], c2[2]) + \
diffstr(c1[3], c2[3]) + \
- ' ' + classname
+ ' ' + classname)
for k in sorted(common.keys()):
c = common[k]
diff --git a/bin/scons-diff.py b/bin/scons-diff.py
index 52bd51b..8597501 100644
--- a/bin/scons-diff.py
+++ b/bin/scons-diff.py
@@ -8,6 +8,7 @@
# etc. so that you can diff trees without having to ignore changes in
# version lines.
#
+from __future__ import print_function
import difflib
import getopt
@@ -43,7 +44,7 @@ def diff_line(left, right):
opts = ' ' + ' '.join(diff_options)
else:
opts = ''
- print 'diff%s %s %s' % (opts, left, right)
+ print('diff%s %s %s' % (opts, left, right))
for o, a in opts:
if o in ('-c', '-u'):
@@ -51,7 +52,7 @@ for o, a in opts:
context = int(a)
diff_options.append(o)
elif o in ('-h', '--help'):
- print Usage
+ print(Usage)
sys.exit(0)
elif o in ('-n'):
diff_options.append(o)
@@ -161,9 +162,9 @@ def diff_file(left, right):
else:
if text:
diff_line(left, right)
- print text,
+ print(text)
elif report_same:
- print 'Files %s and %s are identical' % (left, right)
+ print('Files %s and %s are identical' % (left, right))
def diff_dir(left, right):
llist = os.listdir(left)
@@ -180,9 +181,9 @@ def diff_dir(left, right):
os.path.join(right, x),
recursive)
else:
- print 'Only in %s: %s' % (left, x)
+ print('Only in %s: %s' % (left, x))
else:
- print 'Only in %s: %s' % (right, x)
+ print('Only in %s: %s' % (right, x))
do_diff(left, right, True)
diff --git a/bin/scons-proc.py b/bin/scons-proc.py
index d6a770b..e09c853 100644
--- a/bin/scons-proc.py
+++ b/bin/scons-proc.py
@@ -9,6 +9,8 @@
# DocBook-formatted generated XML files containing the summary text
# and/or .mod files containing the ENTITY definitions for each item.
#
+from __future__ import print_function
+
import getopt
import os
import re
@@ -225,10 +227,15 @@ 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__
+
+ ## def __lt__(self, other):
+ ## if issubclass(other.__class__, self.__subject.__class__):
+ ## return self.__subject < other
+ ## return self.__dict__ < other.__dict__
class SConsThing(Proxy):
def idfunc(self):
@@ -340,25 +347,25 @@ def write_output_files(h, buildersfiles, functionsfiles,
processor_class = SCons_XML
# Step 1: Creating entity files for builders, functions,...
-print "Generating entity files..."
+print("Generating entity files...")
h = parse_docs(args, False)
write_output_files(h, buildersfiles, functionsfiles, toolsfiles,
variablesfiles, SCons_XML.write_mod)
# Step 2: Validating all input files
-print "Validating files against SCons XSD..."
+print("Validating files against SCons XSD...")
if SConsDoc.validate_all_xml(['src']):
- print "OK"
+ print("OK")
else:
- print "Validation failed! Please correct the errors above and try again."
+ print("Validation failed! Please correct the errors above and try again.")
# Step 3: Creating actual documentation snippets, using the
# fully resolved and updated entities from the *.mod files.
-print "Updating documentation for builders, tools and functions..."
+print("Updating documentation for builders, tools and functions...")
h = parse_docs(args, True)
write_output_files(h, buildersfiles, functionsfiles, toolsfiles,
variablesfiles, SCons_XML.write)
-print "Done"
+print("Done")
# Local Variables:
# tab-width:4
diff --git a/bin/scons-test.py b/bin/scons-test.py
index 046cf4b..dd54dd1 100644
--- a/bin/scons-test.py
+++ b/bin/scons-test.py
@@ -14,6 +14,7 @@
# relevant information about the system, the Python version, etc.,
# so that problems on different platforms can be identified sooner.
#
+from __future__ import print_function
import atexit
import getopt
@@ -60,7 +61,7 @@ for o, a in opts:
outdir = a
elif o == '-v' or o == '--verbose':
def printname(x):
- print x
+ print(x)
elif o == '--xml':
format = o
@@ -148,34 +149,34 @@ else:
if format == '--xml':
- print "<scons_test_run>"
- print " <sys>"
+ print("<scons_test_run>")
+ print(" <sys>")
sys_keys = ['byteorder', 'exec_prefix', 'executable', 'maxint', 'maxunicode', 'platform', 'prefix', 'version', 'version_info']
for k in sys_keys:
- print " <%s>%s</%s>" % (k, sys.__dict__[k], k)
- print " </sys>"
+ print(" <%s>%s</%s>" % (k, sys.__dict__[k], k))
+ print(" </sys>")
fmt = '%a %b %d %H:%M:%S %Y'
- print " <time>"
- print " <gmtime>%s</gmtime>" % time.strftime(fmt, time.gmtime())
- print " <localtime>%s</localtime>" % time.strftime(fmt, time.localtime())
- print " </time>"
+ print(" <time>")
+ print(" <gmtime>%s</gmtime>" % time.strftime(fmt, time.gmtime()))
+ print(" <localtime>%s</localtime>" % time.strftime(fmt, time.localtime()))
+ print(" </time>")
- print " <tempdir>%s</tempdir>" % tempdir
+ print(" <tempdir>%s</tempdir>" % tempdir)
def print_version_info(tag, module):
- print " <%s>" % tag
- print " <version>%s</version>" % module.__version__
- print " <build>%s</build>" % module.__build__
- print " <buildsys>%s</buildsys>" % module.__buildsys__
- print " <date>%s</date>" % module.__date__
- print " <developer>%s</developer>" % module.__developer__
- print " </%s>" % tag
-
- print " <scons>"
+ print(" <%s>" % tag)
+ print(" <version>%s</version>" % module.__version__)
+ print(" <build>%s</build>" % module.__build__)
+ print(" <buildsys>%s</buildsys>" % module.__buildsys__)
+ print(" <date>%s</date>" % module.__date__)
+ print(" <developer>%s</developer>" % module.__developer__)
+ print(" </%s>" % tag)
+
+ print(" <scons>")
print_version_info("script", scons)
print_version_info("engine", SCons)
- print " </scons>"
+ print(" </scons>")
environ_keys = [
'PATH',
@@ -213,37 +214,37 @@ if format == '--xml':
'USER',
]
- print " <environment>"
+ print(" <environment>")
for key in sorted(environ_keys):
value = os.environ.get(key)
if value:
- print " <variable>"
- print " <name>%s</name>" % key
- print " <value>%s</value>" % value
- print " </variable>"
- print " </environment>"
+ print(" <variable>")
+ print(" <name>%s</name>" % key)
+ print(" <value>%s</value>" % value)
+ print(" </variable>")
+ print(" </environment>")
command = '"%s" runtest.py -q -o - --xml %s' % (sys.executable, runtest_args)
- #print command
+ #print(command)
os.system(command)
- print "</scons_test_run>"
+ print("</scons_test_run>")
else:
def print_version_info(tag, module):
- print "\t%s: v%s.%s, %s, by %s on %s" % (tag,
+ print("\t%s: v%s.%s, %s, by %s on %s" % (tag,
module.__version__,
module.__build__,
module.__date__,
module.__developer__,
- module.__buildsys__)
+ module.__buildsys__))
- print "SCons by Steven Knight et al.:"
+ print("SCons by Steven Knight et al.:")
print_version_info("script", scons)
print_version_info("engine", SCons)
command = '"%s" runtest.py %s' % (sys.executable, runtest_args)
- #print command
+ #print(command)
os.system(command)
# Local Variables:
diff --git a/bin/scons-unzip.py b/bin/scons-unzip.py
index d4ec4bf..a64179f 100644
--- a/bin/scons-unzip.py
+++ b/bin/scons-unzip.py
@@ -7,6 +7,7 @@
# I'm using this to make it more convenient to manage working on multiple
# changes on Windows, where I don't have access to my Aegis tools.
#
+from __future__ import print_function
import getopt
import os.path
@@ -32,7 +33,7 @@ for o, a in opts:
outdir = a
elif o == '-v' or o == '--verbose':
def printname(x):
- print x
+ print(x)
if len(args) != 1:
sys.stderr.write("scons-unzip.py: \n")
diff --git a/bin/scons_dev_master.py b/bin/scons_dev_master.py
index 3c41ac0..71842aa 100644
--- a/bin/scons_dev_master.py
+++ b/bin/scons_dev_master.py
@@ -3,6 +3,7 @@
# A script for turning a generic Ubuntu system into a master for
# SCons development.
+from __future__ import print_function
import getopt
import sys
@@ -10,7 +11,7 @@ import sys
from Command import CommandRunner, Usage
INITIAL_PACKAGES = [
- 'subversion',
+ 'mercurial',
]
INSTALL_PACKAGES = [
@@ -122,7 +123,7 @@ Usage: scons_dev_master.py [-hnqy] [--password PASSWORD] [--username USER]
buildbot Install packages for running BuildBot
"""
- scons_url = 'http://scons.tigris.org/svn/scons/trunk'
+ scons_url = 'https://bdbaddog@bitbucket.org/scons/scons'
sudo = 'sudo'
password = '""'
username = 'guest'
@@ -131,12 +132,12 @@ Usage: scons_dev_master.py [-hnqy] [--password PASSWORD] [--username USER]
try:
try:
opts, args = getopt.getopt(argv[1:], short_options, long_options)
- except getopt.error, msg:
+ except getopt.error as msg:
raise Usage(msg)
for o, a in opts:
if o in ('-h', '--help'):
- print helpstr
+ print(helpstr)
sys.exit(0)
elif o in ('-n', '--no-exec'):
CommandRunner.execute = CommandRunner.do_not_execute
@@ -148,7 +149,7 @@ Usage: scons_dev_master.py [-hnqy] [--password PASSWORD] [--username USER]
username = a
elif o in ('-y', '--yes', '--assume-yes'):
yesflag = o
- except Usage, err:
+ except Usage as err:
sys.stderr.write(str(err.msg) + '\n')
sys.stderr.write('use -h to get help\n')
return 2
@@ -170,7 +171,7 @@ Usage: scons_dev_master.py [-hnqy] [--password PASSWORD] [--username USER]
cmd.run('%(sudo)s apt-get %(yesflag)s upgrade')
elif arg == 'checkout':
cmd.run('%(sudo)s apt-get %(yesflag)s install %(initial_packages)s')
- cmd.run('svn co --username guest --password "" %(scons_url)s')
+ cmd.run('hg clone" %(scons_url)s')
elif arg == 'building':
cmd.run('%(sudo)s apt-get %(yesflag)s install %(building_packages)s')
elif arg == 'testing':
diff --git a/bin/sfsum b/bin/sfsum
index 2dfa422..142793a 100644
--- a/bin/sfsum
+++ b/bin/sfsum
@@ -22,6 +22,7 @@
#
# https://sourceforge.net/projects/sitedocs/
#
+from __future__ import print_function
import xml.sax
import xml.sax.saxutils
@@ -121,9 +122,9 @@ if __name__ == '__main__':
# generalized once we figure out other things for this script to do.
bugs = [x for x in Artifacts['Bugs'] if x.status == 'Open']
- print list(Artifacts.keys())
+ print(list(Artifacts.keys()))
- print "%d open bugs" % len(bugs)
+ print("%d open bugs" % len(bugs))
# Sort them into a separate list for each assignee.
Assigned = {}
@@ -141,7 +142,7 @@ if __name__ == '__main__':
except KeyError:
pass
else:
- print " %s" % a
- b.sort(lambda x, y: cmp(x.artifact_id, y.artifact_id))
+ print(" %s" % a)
+ b.sort(key=lambda x, y: (x.artifact_id, y.artifact_id))
for bug in b:
- print " %-6s %s" % (bug.artifact_id, bug.summary)
+ print(" %-6s %s" % (bug.artifact_id, bug.summary))
diff --git a/bin/svn-bisect.py b/bin/svn-bisect.py
index 77bda58..dbf8dd9 100755
--- a/bin/svn-bisect.py
+++ b/bin/svn-bisect.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
# -*- Python -*-
-from __future__ import division
+from __future__ import division, print_function
import sys
from math import log, ceil
@@ -28,22 +28,22 @@ script = script_args[2:]
# print an error message and quit
def error(s):
- print >>sys.stderr, "******", s, "******"
+ print("******", s, "******", file=sys.stderr)
sys.exit(1)
# update to the specified version and run test
def testfail(revision):
"Return true if test fails"
- print "Updating to revision", revision
+ print("Updating to revision", revision)
if subprocess.call(["svn","up","-qr",str(revision)]) != 0:
m = "SVN did not update properly to revision %d"
raise RuntimeError(m % revision)
return subprocess.call(script,shell=False) != 0
# confirm that the endpoints are different
-print "****** Checking upper bracket", upper
+print("****** Checking upper bracket", upper)
upperfails = testfail(upper)
-print "****** Checking lower bracket", lower
+print("****** Checking lower bracket", lower)
lowerfails = testfail(lower)
if upperfails == lowerfails:
error("Upper and lower revisions must bracket the failure")
@@ -51,7 +51,7 @@ if upperfails == lowerfails:
# binary search for transition
msg = "****** max %d revisions to test (bug bracketed by [%d,%d])"
while upper-lower > 1:
- print msg % (ceil(log(upper-lower,2)), lower, upper)
+ print(msg % (ceil(log(upper-lower,2)), lower, upper))
mid = (lower + upper)//2
midfails = testfail(mid)
@@ -64,7 +64,7 @@ while upper-lower > 1:
# show which revision was first to fail
if upperfails != lowerfails: lower = upper
-print "The error was caused by revision", lower
+print("The error was caused by revision", lower)
# Local Variables:
# tab-width:4
diff --git a/bin/update-release-info.py b/bin/update-release-info.py
index 896f54a..49f2788 100644
--- a/bin/update-release-info.py
+++ b/bin/update-release-info.py
@@ -56,6 +56,7 @@ In 'post' mode, files are prepared for the next release cycle:
# 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__"
@@ -73,14 +74,14 @@ if len(sys.argv) < 2:
else:
mode = sys.argv[1]
if mode not in ['develop', 'release', 'post']:
- print("""ERROR: `%s' as a parameter is invalid; it must be one of
-\tdevelop, release, or post. The default is develop.""" % mode)
+ print(("""ERROR: `%s' as a parameter is invalid; it must be one of
+\tdevelop, release, or post. The default is develop.""" % mode))
sys.exit(1)
# Get configuration information
config = dict()
-exec open('ReleaseConfig').read() in globals(), config
+exec(open('ReleaseConfig').read(), globals(), config)
try:
version_tuple = config['version_tuple']
@@ -90,9 +91,9 @@ except KeyError:
print('''ERROR: Config file must contain at least version_tuple,
\tunsupported_python_version, and deprecated_python_version.''')
sys.exit(1)
-if DEBUG: print 'version tuple', version_tuple
-if DEBUG: print 'unsupported Python version', unsupported_version
-if DEBUG: print 'deprecated Python version', deprecated_version
+if DEBUG: print('version tuple', version_tuple)
+if DEBUG: print('unsupported Python version', unsupported_version)
+if DEBUG: print('deprecated Python version', deprecated_version)
try:
release_date = config['release_date']
@@ -102,9 +103,9 @@ else:
if len(release_date) == 3:
release_date = release_date + time.localtime()[3:6]
if len(release_date) != 6:
- print '''ERROR: Invalid release date''', release_date
+ print('''ERROR: Invalid release date''', release_date)
sys.exit(1)
-if DEBUG: print 'release date', release_date
+if DEBUG: print('release date', release_date)
if mode == 'develop' and version_tuple[3] != 'alpha':
version_tuple == version_tuple[:3] + ('alpha', 0)
@@ -119,11 +120,11 @@ if len(version_tuple) > 3:
version_type = version_tuple[3]
else:
version_type = 'final'
-if DEBUG: print 'version string', version_string
+if DEBUG: print('version string', version_string)
if version_type not in ['alpha', 'beta', 'candidate', 'final']:
- print("""ERROR: `%s' is not a valid release type in version tuple;
-\tit must be one of alpha, beta, candidate, or final""" % version_type)
+ print(("""ERROR: `%s' is not a valid release type in version tuple;
+\tit must be one of alpha, beta, candidate, or final""" % version_type))
sys.exit(1)
try:
@@ -133,13 +134,13 @@ except KeyError:
month_year = 'MONTH YEAR'
else:
month_year = time.strftime('%B %Y', release_date + (0,0,0))
-if DEBUG: print 'month year', month_year
+if DEBUG: print('month year', month_year)
try:
copyright_years = config['copyright_years']
except KeyError:
copyright_years = '2001 - %d'%(release_date[0] + 1)
-if DEBUG: print 'copyright years', copyright_years
+if DEBUG: print('copyright years', copyright_years)
class UpdateFile(object):
"""
@@ -218,7 +219,7 @@ class UpdateFile(object):
XXX
'''
if self.file is not None and self.content != self.orig:
- print 'Updating ' + self.file + '...'
+ print('Updating ' + self.file + '...')
open(self.file, 'w').write(self.content)
if mode == 'post':
diff --git a/bin/xmlagenda.py b/bin/xmlagenda.py
index b3cd520..fcfe53e 100755
--- a/bin/xmlagenda.py
+++ b/bin/xmlagenda.py
@@ -18,6 +18,7 @@
# Grab the sort bar on the far left (just above the "1" for row one)
# and move it down one row. (Row one becomes a floating header)
# Voila!
+from __future__ import print_function
# The team members
# FIXME: These names really should be external to this script
@@ -89,7 +90,7 @@ for issue in issues:
writer.writerow(['','','','','','',''])
for member in team: writer.writerow(['','',member,'','','',''])
-print "Exported %d issues to editlist.csv. Ready to upload to Google."%len(issues)
+print("Exported %d issues to editlist.csv. Ready to upload to Google."%len(issues))
# Local Variables:
# tab-width:4
diff --git a/doc/SConscript b/doc/SConscript
index 35eb380..7e6aaeb 100644
--- a/doc/SConscript
+++ b/doc/SConscript
@@ -24,6 +24,8 @@
# 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
+
import os.path
import re
import sys
@@ -51,7 +53,7 @@ fop = whereis('fop')
xep = whereis('xep')
if not fop and not xep:
- print "doc: No PDF renderer found (fop|xep)!"
+ print("doc: No PDF renderer found (fop|xep)!")
skip_doc = True
#
@@ -109,16 +111,17 @@ man_replace_tpl = """.TH "%(uctitle)s" "1" "%(today)s" "SCons %(version)s" "SCon
.ad l
.SH "NOTE"
%(title)s \- This is a replacement file, stemming from an incomplete
-packaging process without the required doc modules installed. Please
+packaging process without the required doc modules installed. Please
update the system and try running bootstrap.py again.
"""
#
# --- Processing ---
#
+
if skip_doc:
- print "doc: ...skipping building User Guide."
- print " ...creating fake MAN pages."
+ print("doc: ...skipping building User Guide.")
+ print(" ...creating fake MAN pages.")
# Since the top-level SConstruct requires the MAN
# pages to exist for the basic packaging, we create simple
@@ -126,7 +129,7 @@ if skip_doc:
scdir = os.path.join(build, 'man')
if not os.path.isdir(scdir):
os.makedirs(scdir)
-
+
import datetime
today = datetime.date.today().strftime("%m/%d/%Y")
version = env.subst('$VERSION')
@@ -140,8 +143,8 @@ if skip_doc:
fman.close()
else:
if not lynx:
- print "doc: Warning, lynx is not installed...created release packages won't be complete!"
-
+ print("doc: Warning, lynx is not installed...created release packages won't be complete!")
+
#
# Always create a version.xml file containing the version information
# for this run. Ignore it for dependency purposes so we don't
@@ -157,7 +160,7 @@ else:
#
# Builder for copying files to an Install dir, based
# on their extension (better: glob matching pattern)...
- #
+ #
def _glob_install_action(target, source, env):
if not SCons.Util.is_List(target):
target = [target]
@@ -170,7 +173,7 @@ else:
target = [target]
if not SCons.Util.is_List(source):
source = [source]
-
+
res = []
res_src = []
tdir = env.Dir(target[0])
@@ -185,7 +188,7 @@ else:
#
# Builder for copying ChunkedHTML files to an Install dir...
- #
+ #
def _chunked_install_action(target, source, env):
if not SCons.Util.is_List(target):
target = [target]
@@ -195,13 +198,13 @@ else:
spattern = os.path.join(os.path.split(str(source[0]))[0], '*.html')
for g in glob.glob(spattern):
shutil.copy(g, tdir)
-
+
def _chunked_install_emitter(target, source, env):
if not SCons.Util.is_List(target):
target = [target]
if not SCons.Util.is_List(source):
source = [source]
-
+
tdir = env.Dir(target[0])
head, tail = os.path.split(str(source[0]))
return os.path.join(str(tdir), tail), source
@@ -214,23 +217,23 @@ else:
# Ensure that all XML files are valid against our XSD, and
# that all example names and example output suffixes are unique
#
- print "Validating files against SCons XSD..."
+ print("Validating files against SCons XSD...")
if SConsDoc.validate_all_xml(['src'], xsdfile='xsd/scons.xsd'):
- print "OK"
+ print("OK")
else:
- print "Validation failed! Please correct the errors above and try again."
- sys.exit(0)
-
- print "Checking whether all example names are unique..."
+ print("Validation failed! Please correct the errors above and try again.")
+ sys.exit(1)
+
+ print("Checking whether all example names are unique...")
if SConsExamples.exampleNamesAreUnique(os.path.join('doc','user')):
- print "OK"
+ print("OK")
else:
- print "Not all example names and suffixes are unique! Please correct the errors listed above and try again."
- sys.exit(0)
-
+ print("Not all example names and suffixes are unique! Please correct the errors listed above and try again.")
+ sys.exit(1)
+
# List of prerequisite files in the build/doc folder
buildsuite = []
-
+
def copy_dbfiles(env, toolpath, paths, fpattern, use_builddir=True):
""" Helper function, copies a bunch of files matching
the given fpattern to a target directory.
@@ -251,7 +254,7 @@ else:
target_dir = env.Dir(os.path.join(*(toolpath+paths)))
buildsuite.extend(env.GlobInstall(target_dir,
os.path.join(*(paths + fpattern))))
-
+
#
# Copy generated files (.gen/.mod/.xml) to the build folder
#
@@ -300,7 +303,7 @@ else:
# installing/copying them to the build directory. It basically
# links the original sources to the respective build folder,
# such that a simple 'python bootstrap.py' rebuilds the
- # documentation when a file, like 'doc/user/depends.xml'
+ # documentation when a file, like 'doc/user/depends.xml'
# for example, changes.
# Finally, in DOCNODES we store the created PDF and HTML files,
# such that we can then install them in the proper places for
@@ -315,7 +318,7 @@ else:
'user' : (['chunked','html','pdf','epub','text'], [], []),
'man' : (['man','epub','text'], [], [])
}
-
+
#
# We have to tell SCons to scan the top-level XML files which
# get included by the document XML files in the subdirectories.
@@ -327,15 +330,15 @@ else:
continue
base, ext = os.path.splitext(s)
if ext in ['.fig', '.jpg']:
- buildsuite.extend(env.Command(os.path.join(build, s),
- s,
+ buildsuite.extend(env.Command(os.path.join(build, s),
+ s,
Copy("$TARGET", "$SOURCE")))
else:
revaction([env.File(os.path.join(build, s))],
[env.File(s)], env)
for doc in docs:
-
+
#
# Read MANIFEST file and copy the listed files to the
# build directory, while branding them with the
@@ -359,7 +362,7 @@ else:
else:
target_dir = os.path.join(build, doc)
if ext in ['.fig', '.jpg', '.svg']:
- docs[doc][DOCDEPENDS].extend(env.Command(build_s, doc_s,
+ docs[doc][DOCDEPENDS].extend(env.Command(build_s, doc_s,
Copy("$TARGET", "$SOURCE")))
else:
btarget = env.File(build_s)
@@ -389,18 +392,18 @@ else:
sctargets.append(env.File(os.path.join(scdir, 'scons-%s.pdf' % doc)))
if 'epub' in docs[doc][DOCTARGETS]:
sctargets.append(env.File(os.path.join(scdir, 'scons-%s.epub' % doc)))
-
+
if 'man' in docs[doc][DOCTARGETS]:
for m in man_page_list:
sctargets.append(os.path.join(scdir, m))
man, _1 = os.path.splitext(m)
-
+
sctargets.append(os.path.join(scdir, 'scons-%s.pdf' % man))
sctargets.append(os.path.join(scdir, 'scons-%s.html' % man))
-
- docs[doc][DOCNODES].extend(env.Command(sctargets, buildsuite + docs[doc][DOCDEPENDS],
+
+ docs[doc][DOCNODES].extend(env.Command(sctargets, buildsuite + docs[doc][DOCDEPENDS],
"cd %s && $PYTHON ${SCONS_PY.abspath}%s" % (scdir, cleanopt)))
-
+
install_css = False
for doc in docs:
@@ -412,13 +415,13 @@ else:
epub = os.path.join(build, 'EPUB', 'scons-%s.epub' % doc)
text = os.path.join(build, 'TEXT', 'scons-%s.txt' % doc)
if 'chunked' in docs[doc][DOCTARGETS]:
- installed_chtml = env.ChunkedInstall(env.Dir(htmldir),
+ installed_chtml = env.ChunkedInstall(env.Dir(htmldir),
os.path.join(build, doc,'scons-%s' % doc, 'index.html'))
installed_chtml_css = env.Install(env.Dir(htmldir),
os.path.join(build, doc, 'scons.css'))
env.Depends(installed_chtml, docs[doc][DOCNODES])
env.Depends(installed_chtml_css, docs[doc][DOCNODES])
-
+
tar_deps.extend([htmlindex, installed_chtml_css])
tar_list.extend([htmldir])
Local(htmlindex)
@@ -431,7 +434,7 @@ else:
Local(html)
env.Ignore(html, version_xml)
install_css = True
-
+
if 'pdf' in docs[doc][DOCTARGETS]:
env.InstallAs(env.File(pdf), env.File(os.path.join(build, doc,'scons-%s.pdf' % doc)))
Local(pdf)
@@ -447,14 +450,14 @@ else:
tar_deps.append(epub)
tar_list.append(epub)
-
- if ('text' in docs[doc][DOCTARGETS] and lynx and
+
+ if ('text' in docs[doc][DOCTARGETS] and lynx and
(('html' in docs[doc][DOCTARGETS]) or (doc == 'man'))):
texthtml = os.path.join(build, doc,'index.html')
if doc == 'man':
# Special handling for single MAN file
texthtml = os.path.join(build, doc, 'scons-scons.html')
-
+
env.Command(text, env.File(texthtml), "lynx -dump ${SOURCE.abspath} > $TARGET")
Local(text)
@@ -462,21 +465,21 @@ else:
tar_deps.append(text)
tar_list.append(text)
-
-
+
+
if 'man' in docs[doc][DOCTARGETS]:
#
# Man page(s)
#
for m in man_page_list:
man, _1 = os.path.splitext(m)
-
+
pdf = os.path.join(build, 'PDF', '%s-man.pdf' % man)
html = os.path.join(build, 'HTML' , '%s-man.html' % man)
-
+
env.InstallAs(env.File(pdf), env.File(os.path.join(build, 'man','scons-%s.pdf' % man)))
env.InstallAs(env.File(html), env.File(os.path.join(build, 'man','scons-%s.html' % man)))
-
+
tar_deps.extend([pdf, html])
tar_list.extend([pdf, html])
@@ -484,7 +487,7 @@ else:
# Install CSS file, common to all single HTMLs
if install_css:
css_file = os.path.join(build, 'HTML', 'scons.css')
- env.InstallAs(env.File(css_file),
+ env.InstallAs(env.File(css_file),
env.File(os.path.join(build, 'user','scons.css')))
tar_deps.extend([css_file])
tar_list.extend([css_file])
@@ -540,7 +543,7 @@ if not epydoc_cli:
# http://epydoc.svn.sourceforge.net/viewvc/epydoc/trunk/epydoc/src/epydoc/cli.py
elif env['EPYDOCFLAGS'] == '--pdf':
- pdf_writer = LatexWriter(docindex,
+ pdf_writer = LatexWriter(docindex,
docformat='restructuredText',
prj_name='SCons',
prj_url='http://www.scons.org/')
@@ -560,9 +563,9 @@ else: # epydoc_cli is found
Touch('$TARGET'),
]
-
+
if not epydoc_cli and not epydoc:
- print "doc: epydoc not found, skipping building API documentation."
+ print("doc: epydoc not found, skipping building API documentation.")
else:
# XXX Should be in common with reading the same thing in
# the SConstruct file.
@@ -584,7 +587,7 @@ else:
tar_list.append(htmldir)
if not epydoc_cli:
- print "doc: command line epydoc is not found, skipping PDF/PS/Tex output"
+ print("doc: command line epydoc is not found, skipping PDF/PS/Tex output")
else:
# PDF and PostScript and TeX are built from the
# same invocation.
@@ -617,7 +620,7 @@ if tar_deps:
tar_list = ' '.join([x.replace(build+'/', '') for x in tar_list])
t = env.Command(dist_doc_tar_gz, tar_deps,
"tar cf${TAR_HFLAG} - -C %s %s | gzip > $TARGET" % (build, tar_list))
- AddPostAction(dist_doc_tar_gz, Chmod(dist_doc_tar_gz, 0644))
+ AddPostAction(dist_doc_tar_gz, Chmod(dist_doc_tar_gz, 0o644))
Local(t)
Alias('doc', t)
else:
diff --git a/runtest.py b/runtest.py
index 1b5c7dd..0950bbe 100755
--- a/runtest.py
+++ b/runtest.py
@@ -77,6 +77,8 @@
# library directory. If we ever resurrect that as the default, then
# you can find the appropriate code in the 0.04 version of this script,
# rather than reinventing that wheel.)
+from __future__ import print_function
+
import getopt
import glob
@@ -88,10 +90,13 @@ import time
try:
import threading
- import Queue # 2to3: rename to queue
+ try: # python3
+ from queue import Queue
+ except ImportError as e: # python2
+ from Queue import Queue
threading_ok = True
except ImportError:
- print "Can't import threading or queue"
+ print("Can't import threading or queue")
threading_ok = False
cwd = os.getcwd()
@@ -183,12 +188,12 @@ class PassThroughOptionParser(OptionParser):
def _process_long_opt(self, rargs, values):
try:
OptionParser._process_long_opt(self, rargs, values)
- except BadOptionError, err:
+ except BadOptionError as err:
self.largs.append(err.opt_str)
def _process_short_opts(self, rargs, values):
try:
OptionParser._process_short_opts(self, rargs, values)
- except BadOptionError, err:
+ except BadOptionError as err:
self.largs.append(err.opt_str)
parser = PassThroughOptionParser(add_help_option=False)
@@ -238,7 +243,7 @@ for o, a in opts:
a = os.path.join(cwd, a)
testlistfile = a
elif o in ['-h', '--help']:
- print helpstr
+ print(helpstr)
sys.exit(0)
elif o in ['-j', '--jobs']:
jobs = int(a)
@@ -328,7 +333,7 @@ else:
st = os.stat(f)
except OSError:
continue
- if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
+ if stat.S_IMODE(st[stat.ST_MODE]) & 0o111:
return f
return None
@@ -566,7 +571,7 @@ else:
base = os.path.join(base, os.path.split(url)[1])
if printcommand:
- print command
+ print(command)
if execute_tests:
os.system(command)
else:
@@ -795,15 +800,15 @@ def run_test(t, io_lock, async=True):
if suppress_stdout or suppress_stderr:
sys.stdout.write(header)
if not suppress_stdout and t.stdout:
- print t.stdout
+ print(t.stdout)
if not suppress_stderr and t.stderr:
- print t.stderr
+ print(t.stderr)
print_time_func("Test execution time: %.1f seconds\n", t.test_time)
if io_lock:
io_lock.release()
if quit_on_failure and t.status == 1:
- print "Exiting due to error"
- print t.status
+ print("Exiting due to error")
+ print(t.status)
sys.exit(1)
class RunTest(threading.Thread):
@@ -819,9 +824,9 @@ class RunTest(threading.Thread):
self.queue.task_done()
if jobs > 1 and threading_ok:
- print "Running tests using %d jobs"%jobs
+ print("Running tests using %d jobs"%jobs)
# Start worker threads
- queue = Queue.Queue()
+ queue = Queue()
io_lock = threading.Lock()
for i in range(1, jobs):
t = RunTest(queue, io_lock)
@@ -834,7 +839,7 @@ if jobs > 1 and threading_ok:
else:
# Run tests serially
if jobs > 1:
- print "Ignoring -j%d option; no python threading module available."%jobs
+ print("Ignoring -j%d option; no python threading module available."%jobs)
for t in tests:
run_test(t, None, False)
diff --git a/shippable.yml b/shippable.yml
new file mode 100644
index 0000000..b7e363a
--- /dev/null
+++ b/shippable.yml
@@ -0,0 +1,7 @@
+language: python
+
+python:
+ - "2.7"
+ - "3.4"
+
+script: python runtest.py -a
diff --git a/src/CHANGES.txt b/src/CHANGES.txt
index 25f982a..aab73b4 100644
--- a/src/CHANGES.txt
+++ b/src/CHANGES.txt
@@ -221,6 +221,9 @@ RELEASE 2.3.3 - Sun, 24 Aug 2014 21:08:33 -0400
From Russel Winder:
- Fix regression on Windows in D language update
+ From Neal Becker and Stefan Zimmermann:
+ - Python 3 port and compatibility
+
From Anatoly Techtonik:
- Do not fail on EnsureSConsVersion when running from checkout
@@ -261,6 +264,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 4dfde31..7e1f8f1 100644
--- a/src/engine/SCons/Action.py
+++ b/src/engine/SCons/Action.py
@@ -101,7 +101,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import dis
import os
-# compat layer imports "cPickle" for us if it's available.
import pickle
import re
import sys
@@ -163,12 +162,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:
@@ -188,12 +187,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:
@@ -234,8 +233,8 @@ 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(",%s,%s" % (len(code.co_cellvars), len(code.co_freevars)))
+ contents.append(b"{}, {}".format(code.co_argcount, len(code.co_varnames)))
+ contents.append(b", {}, {}".format(len(code.co_cellvars), len(code.co_freevars)))
# The code contents depends on any constants accessed by the
# function. Note that we have to call _object_contents on each
@@ -245,43 +244,43 @@ 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.
- closure = func.func_closure or []
+ closure = func.__closure__ or []
#xxx = [_object_contents(x.cell_contents) for x in closure]
try:
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):
@@ -362,7 +361,7 @@ def _do_create_action(act, kw):
# The list of string commands may include a LazyAction, so we
# reprocess them via _do_create_list_action.
return _do_create_list_action(commands, kw)
-
+
if is_List(act):
return CommandAction(act, **kw)
@@ -411,8 +410,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
@@ -424,6 +423,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.
@@ -431,8 +431,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)
@@ -504,7 +504,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")
@@ -664,7 +664,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):
@@ -1052,11 +1052,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()
@@ -1126,7 +1126,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):
@@ -1171,11 +1171,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 631d7c1..3eee4b6 100644
--- a/src/engine/SCons/ActionTests.py
+++ b/src/engine/SCons/ActionTests.py
@@ -61,7 +61,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")
@@ -265,7 +265,7 @@ def test_positional_args(pos_callback, cmd, **kw):
"""Test handling of bad cmdstrfunc arguments """
try:
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
@@ -488,7 +488,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
@@ -556,7 +556,7 @@ class _ActionActionTestCase(unittest.TestCase):
assert isinstance(source, list), type(source)
return 9
b = SCons.Action.Action([firstfunc, execfunc, lastfunc])
-
+
sio = io.StringIO()
sys.stdout = sio
result = a("out", "in", env)
@@ -699,7 +699,7 @@ class _ActionActionTestCase(unittest.TestCase):
env['PRINT_CMD_LINE_FUNC'] = my_print_cmd_line
a("output", "input", env)
assert result == ["execfunc(['output'], ['input'])"], result
-
+
finally:
sys.stdout = save_stdout
@@ -942,7 +942,7 @@ class CommandActionTestCase(unittest.TestCase):
act = SCons.Action.CommandAction('xyzzy $TARGETS $SOURCES',
cmdstr='cmdstr\t$TARGETS\n$SOURCES ')
-
+
s = act.strfunction([], [], env)
assert s == 'cmdstr\t\n ', s
s = act.strfunction([t1], [s1], env)
@@ -1246,7 +1246,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.
@@ -1257,7 +1257,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
@@ -1274,35 +1274,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):
@@ -1419,7 +1419,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
@@ -1429,13 +1429,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):
@@ -1460,7 +1460,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)
@@ -1588,13 +1588,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):
@@ -1608,7 +1608,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())
@@ -1626,10 +1626,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):
@@ -1740,7 +1740,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):
@@ -1791,7 +1791,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
@@ -1801,13 +1801,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):
@@ -1824,7 +1824,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)
@@ -1851,8 +1851,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)
@@ -1866,8 +1866,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):
@@ -1885,8 +1885,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)
@@ -1999,16 +1999,16 @@ class ActionCompareTestCase(unittest.TestCase):
especially two builders that can generate the same suffix,
where one of the builders has a suffix dictionary with a None
key."""
-
+
foo = SCons.Builder.Builder(action = '$FOO', suffix = '.foo')
bar = SCons.Builder.Builder(action = {}, suffix={None:'.bar'})
bar.add_action('.cow', "$MOO")
dog = SCons.Builder.Builder(suffix = '.bar')
-
+
env = Environment( BUILDERS = {'FOO' : foo,
'BAR' : bar,
'DOG' : dog} )
-
+
assert foo.get_name(env) == 'FOO', foo.get_name(env)
assert bar.get_name(env) == 'BAR', bar.get_name(env)
assert dog.get_name(env) == 'DOG', dog.get_name(env)
diff --git a/src/engine/SCons/Builder.py b/src/engine/SCons/Builder.py
index 80dcaca..50e85ec 100644
--- a/src/engine/SCons/Builder.py
+++ b/src/engine/SCons/Builder.py
@@ -166,7 +166,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." % \
@@ -344,8 +344,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
@@ -423,6 +426,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.
@@ -440,8 +446,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 3eca588..1e544a1 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):
@@ -327,7 +328,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."
@@ -343,7 +344,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.")
@@ -1499,11 +1500,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"""
@@ -1530,8 +1532,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'
@@ -1583,47 +1585,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 82fba8f..8a52928 100644
--- a/src/engine/SCons/CacheDirTests.py
+++ b/src/engine/SCons/CacheDirTests.py
@@ -249,7 +249,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 87a3022..4db7e06 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
@@ -745,7 +744,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 37cbc99..f1d5bca 100644
--- a/src/engine/SCons/Defaults.py
+++ b/src/engine/SCons/Defaults.py
@@ -261,7 +261,8 @@ def copy_func(dest, src, symlinks=True):
else:
return copy_func(dest, os.path.realpath(src))
elif os.path.isfile(src):
- return shutil.copy2(src, dest)
+ shutil.copy2(src, dest)
+ return 0
else:
return shutil.copytree(src, dest, symlinks)
@@ -298,7 +299,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)) \
@@ -458,7 +459,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 45b24c5..d979005 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)
@@ -396,8 +396,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)
@@ -589,7 +589,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
@@ -1131,7 +1131,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"
@@ -1201,7 +1201,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
@@ -1330,7 +1330,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]
@@ -1339,7 +1339,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:
@@ -1363,7 +1363,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:
@@ -1659,7 +1659,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
@@ -1771,7 +1771,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)
@@ -2246,7 +2246,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))
@@ -2389,7 +2389,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 0567906..4b57763 100644
--- a/src/engine/SCons/EnvironmentTests.py
+++ b/src/engine/SCons/EnvironmentTests.py
@@ -21,6 +21,8 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
+from __future__ import print_function
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.compat
@@ -114,11 +116,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 +267,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 +653,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")
@@ -1566,17 +1562,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
@@ -1598,7 +1594,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')
@@ -1873,7 +1869,7 @@ def generate(env):
# test for pull request #150
env = self.TestEnvironment()
env._dict.pop('BUILDERS')
- assert env.has_key('BUILDERS') is False
+ assert ('BUILDERS' in env) is False
env2 = env.Clone()
def test_Copy(self):
@@ -1926,7 +1922,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] })
@@ -1934,7 +1930,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
@@ -2252,17 +2248,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
@@ -2500,10 +2496,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..3cc9c6d 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.
@@ -146,6 +144,7 @@ def convert_to_BuildError(status, exc_info=None):
if not exc_info and isinstance(status, Exception):
exc_info = (status.__class__, status, None)
+
if isinstance(status, BuildError):
buildError = status
buildError.exitstatus = 2 # always exit with 2 on build errors
@@ -163,14 +162,17 @@ 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, OSError, IOError)):
# 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
# (for example, failure to create the directory in which the
# target file will appear).
- try: filename = status.filename
- except AttributeError: filename = None
+ try:
+ filename = status.filename
+ except AttributeError:
+ filename = None
+
buildError = BuildError(
errstr=status.strerror,
status=status.errno,
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 b6d4cb6..7107fde 100644
--- a/src/engine/SCons/Executor.py
+++ b/src/engine/SCons/Executor.py
@@ -455,9 +455,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 f390319..99c6226 100644
--- a/src/engine/SCons/ExecutorTests.py
+++ b/src/engine/SCons/ExecutorTests.py
@@ -311,7 +311,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 42b009e..c0e80b1 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 5144f83..9774bdd 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__"
@@ -123,13 +124,12 @@ class Counter(object):
def key(self):
return self.cls_name+'.'+self.method_name
def display(self):
- fmt = " %7d hits %7d misses %s()"
- print fmt % (self.hit, self.miss, self.key())
- def __cmp__(self, other):
+ print(" {:7d} hits {:7d} misses {}()".format(self.hit, self.miss, self.key()))
+ def __eq__(self, other):
try:
- return cmp(self.key(), other.key())
+ return self.key() == other.key()
except AttributeError:
- return 0
+ return True
class CountValue(Counter):
"""
@@ -185,7 +185,7 @@ def Dump(title=None):
collected so far.
"""
if title:
- print title
+ print(title)
for counter in sorted(CounterList):
CounterList[counter].display()
diff --git a/src/engine/SCons/MemoizeTests.py b/src/engine/SCons/MemoizeTests.py
index 77ff6bc..3ce9a11 100644
--- a/src/engine/SCons/MemoizeTests.py
+++ b/src/engine/SCons/MemoizeTests.py
@@ -34,7 +34,6 @@ import SCons.Memoize
SCons.Memoize.EnableMemoization()
class FakeObject(object):
-
def __init__(self):
self._memo = {}
diff --git a/src/engine/SCons/Node/FS.py b/src/engine/SCons/Node/FS.py
index 4a4942b..d19afa9 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__"
@@ -122,7 +123,7 @@ def save_strings(val):
# tells us whether or not os.path.splitdrive() actually does anything
# on this system, and therefore whether we need to bother calling it
# when looking up path names in various methods below.
-#
+#
do_splitdrive = None
_my_splitdrive =None
@@ -157,7 +158,7 @@ def initialize_do_splitdrive():
global OS_SEP
global UNC_PREFIX
global os_sep_is_slash
-
+
OS_SEP = os.sep
UNC_PREFIX = OS_SEP + OS_SEP
os_sep_is_slash = OS_SEP == '/'
@@ -178,7 +179,7 @@ needs_normpath_check = re.compile(
# b) The path starts with '..'. E.g. '../' or '../moredirs'
# but we not match '..abc/'.
# c) The path ends with '..'. E.g. '/..' or 'dirs/..'
- # d) The path contains a '..' in the middle.
+ # d) The path contains a '..' in the middle.
# E.g. dirs/../moredirs
(.*/)?\.\.(?:/|$) |
@@ -200,7 +201,7 @@ needs_normpath_check = re.compile(
\./|.*/\.(?:/|$)
- ''',
+ ''',
re.VERBOSE
)
needs_normpath_match = needs_normpath_check.match
@@ -564,7 +565,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.
@@ -670,14 +671,14 @@ class Base(SCons.Node.Node):
single variables lazily when required, in order to save memory.
The redirection to the getters lets older Tools and
SConstruct continue to work without any additional changes,
- fully transparent to the user.
+ fully transparent to the user.
Note, that __getattr__ is only called as fallback when the
requested attribute can't be found, so there should be no
speed performance penalty involved for standard builds.
"""
if attr in node_bwcomp:
return node_bwcomp[attr](self)
-
+
raise AttributeError("%r object has no attribute %r" %
(self.__class__, attr))
@@ -799,7 +800,7 @@ class Base(SCons.Node.Node):
path_elems = self.get_path_elements()
pathname = ''
try: i = path_elems.index(dir)
- except ValueError:
+ except ValueError:
for p in path_elems[:-1]:
pathname += p.dirname
else:
@@ -840,13 +841,13 @@ class Base(SCons.Node.Node):
return self.name
else:
return self.dir.entry_path(self.name)
-
+
def get_tpath(self):
if self.dir._tpath == '.':
return self.name
else:
return self.dir.entry_tpath(self.name)
-
+
def get_path_elements(self):
return self.dir._path_elements + [self]
@@ -939,7 +940,7 @@ class Base(SCons.Node.Node):
def _glob1(self, pattern, ondisk=True, source=False, strings=False):
return []
-
+
# Dict that provides a simple backward compatibility
# layer for the Node attributes 'abspath', 'labspath',
# 'path', 'tpath' and 'path_elements'.
@@ -979,7 +980,7 @@ class Entry(Base):
def __init__(self, name, directory, fs):
Base.__init__(self, name, directory, fs)
self._func_exists = 3
- self._func_get_contents = 1
+ self._func_get_contents = 1
def diskcheck_match(self):
pass
@@ -1198,7 +1199,7 @@ class FS(LocalFS):
DirNodeInfo.fs = self
FileNodeInfo.fs = self
-
+
def set_SConstruct_dir(self, dir):
self.SConstruct_dir = dir
@@ -1310,7 +1311,7 @@ class FS(LocalFS):
p = p.strip('/')
needs_normpath = needs_normpath_match(p)
-
+
# The path is relative to the top-level SCons directory.
if p in ('', '.'):
p = directory.get_labspath()
@@ -1469,7 +1470,7 @@ class FS(LocalFS):
"""
Globs
- This is mainly a shim layer
+ This is mainly a shim layer
"""
if cwd is None:
cwd = self.getcwd()
@@ -1555,7 +1556,7 @@ class Dir(Base):
self._func_sconsign = 1
self._func_exists = 2
self._func_get_contents = 2
-
+
self._abspath = SCons.Util.silent_intern(self.dir.entry_abspath(self.name))
self._labspath = SCons.Util.silent_intern(self.dir.entry_labspath(self.name))
if self.dir._path == '.':
@@ -1594,7 +1595,7 @@ class Dir(Base):
# Prepend MkdirBuilder action to existing action list
l = self.get_executor().action_list
a = get_MkdirBuilder().action
- l.insert(0, a)
+ l.insert(0, a)
self.get_executor().set_action_list(l)
def diskcheck_match(self):
@@ -1742,7 +1743,7 @@ class Dir(Base):
path_elems = ['..'] * (len(self._path_elements) - i) \
+ [n.name for n in other._path_elements[i:]]
-
+
result = OS_SEP.join(path_elems)
memo_dict[other] = result
@@ -1913,10 +1914,10 @@ class Dir(Base):
def get_internal_path(self):
return self._path
-
+
def get_tpath(self):
return self._tpath
-
+
def get_path_elements(self):
return self._path_elements
@@ -1936,7 +1937,7 @@ class Dir(Base):
""" Searches through the file/dir entries of the current
directory, and returns True if a physical entry with the given
name could be found.
-
+
@see rentry_exists_on_disk
"""
try:
@@ -1970,10 +1971,10 @@ class Dir(Base):
The local directory (self) gets searched first, so
repositories take a lower precedence regarding the
searching order.
-
+
@see entry_exists_on_disk
"""
-
+
rentry_exists = self.entry_exists_on_disk(name)
if not rentry_exists:
# Search through the repository folders
@@ -2256,9 +2257,9 @@ class RootDir(Dir):
add a separator when creating the path names of entries within
this directory.
"""
-
+
__slots__ = ['_lookupDict']
-
+
def __init__(self, drive, fs):
if SCons.Debug.track_instances: logInstanceCreation(self, 'Node.FS.RootDir')
SCons.Node.Node.__init__(self)
@@ -2266,7 +2267,7 @@ class RootDir(Dir):
# Handle all the types of drives:
if drive == '':
# No drive, regular UNIX root or Windows default drive.
- name = OS_SEP
+ name = OS_SEP
dirname = OS_SEP
elif drive == '//':
# UNC path
@@ -2336,7 +2337,7 @@ class RootDir(Dir):
self._func_sconsign = 1
self._func_exists = 2
self._func_get_contents = 2
-
+
# Don't just reset the executor, replace its action list,
# because it might have some pre-or post-actions that need to
# be preserved.
@@ -2352,9 +2353,9 @@ class RootDir(Dir):
# Prepend MkdirBuilder action to existing action list
l = self.get_executor().action_list
a = get_MkdirBuilder().action
- l.insert(0, a)
+ l.insert(0, a)
self.get_executor().set_action_list(l)
-
+
def must_be_same(self, klass):
if klass is Dir:
@@ -2628,11 +2629,11 @@ class File(Base):
self.store_info = 1
self._func_exists = 4
self._func_get_contents = 3
-
+
# Initialize this Node's decider function to decide_source() because
# every file is a source file until it has a Builder attached...
self.changed_since_last_build = 4
-
+
# If there was already a Builder set on this entry, then
# we need to make sure we call the target-decider function,
# not the source-decider. Reaching in and doing this by hand
@@ -2681,12 +2682,12 @@ 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
return cs
-
+
@SCons.Memoize.CountMethodCall
def get_size(self):
try:
@@ -2960,11 +2961,11 @@ class File(Base):
def release_target_info(self):
"""Called just after this node has been marked
up-to-date or was built completely.
-
+
This is where we try to release as many target node infos
as possible for clean builds and update runs, in order
to minimize the overall memory consumption.
-
+
We'd like to remove a lot more attributes like self.sources
and self.sources_set, but they might get used
in a next build step. For example, during configuration
@@ -2972,18 +2973,18 @@ class File(Base):
which linker to use for the resulting Program (gcc vs. g++)!
That's why we check for the 'keep_targetinfo' attribute,
config Nodes and the Interactive mode just don't allow
- an early release of most variables.
+ an early release of most variables.
In the same manner, we can't simply remove the self.attributes
here. The smart linking relies on the shared flag, and some
parts of the java Tool use it to transport information
about nodes...
-
+
@see: built() and Node.release_target_info()
"""
if (self.released_target_info or SCons.Node.interactive):
return
-
+
if not hasattr(self.attributes, 'keep_targetinfo'):
# Cache some required values, before releasing
# stuff like env, executor and builder...
@@ -3056,7 +3057,7 @@ class File(Base):
def _rmv_existing(self):
self.clear_memoized_values()
if SCons.Node.print_duplicate:
- print "dup: removing existing target %s"%self
+ print("dup: removing existing target {}".format(self))
e = Unlink(self, [], None)
if isinstance(e, SCons.Errors.BuildError):
raise e
@@ -3080,9 +3081,8 @@ class File(Base):
else:
try:
self._createDir()
- except SCons.Errors.StopError, drive:
- desc = "No drive `%s' for target `%s'." % (drive, self)
- raise SCons.Errors.StopError(desc)
+ except SCons.Errors.StopError as drive:
+ raise SCons.Errors.StopError("No drive `{}' for target `{}'.".format(drive, self))
#
#
@@ -3098,12 +3098,11 @@ class File(Base):
def do_duplicate(self, src):
self._createDir()
if SCons.Node.print_duplicate:
- print "dup: relinking variant '%s' from '%s'"%(self, src)
+ print("dup: relinking variant '{}' from '{}'".format(self, src))
Unlink(self, None, None)
e = Link(self, src, None)
if isinstance(e, SCons.Errors.BuildError):
- desc = "Cannot duplicate `%s' in `%s': %s." % (src.get_internal_path(), self.dir._path, e.errstr)
- raise SCons.Errors.StopError(desc)
+ raise SCons.Errors.StopError("Cannot duplicate `{}' in `{}': {}.".format(src.get_internal_path(), self.dir._path, e.errstr))
self.linked = 1
# The Link() action may or may not have actually
# created the file, depending on whether the -n
@@ -3117,7 +3116,6 @@ class File(Base):
return self._memo['exists']
except KeyError:
pass
-
result = SCons.Node._exists_map[self._func_exists](self)
self._memo['exists'] = result
return result
@@ -3199,37 +3197,37 @@ class File(Base):
def built(self):
"""Called just after this File node is successfully built.
-
+
Just like for 'release_target_info' we try to release
some more target node attributes in order to minimize the
overall memory consumption.
-
+
@see: release_target_info
"""
SCons.Node.Node.built(self)
- if (not SCons.Node.interactive and
+ if (not SCons.Node.interactive and
not hasattr(self.attributes, 'keep_targetinfo')):
- # Ensure that the build infos get computed and cached...
+ # Ensure that the build infos get computed and cached...
SCons.Node.store_info_map[self.store_info](self)
# ... then release some more variables.
self._specific_sources = False
self._labspath = None
self._save_str()
self.cwd = None
-
+
self.scanner_paths = None
def changed(self, node=None, allowcache=False):
"""
Returns if the node is up-to-date with respect to the BuildInfo
- stored last time it was built.
-
+ stored last time it was built.
+
For File nodes this is basically a wrapper around Node.changed(),
but we allow the return value to get cached after the reference
to the Executor got released in release_target_info().
-
+
@see: Node.changed()
"""
if node is None:
@@ -3237,7 +3235,7 @@ class File(Base):
return self._memo['changed']
except KeyError:
pass
-
+
has_changed = SCons.Node.Node.changed(self, node)
if allowcache:
self._memo['changed'] = has_changed
@@ -3290,7 +3288,7 @@ class File(Base):
# ...and they'd like a local copy.
e = LocalCopy(self, r, None)
if isinstance(e, SCons.Errors.BuildError):
- raise
+ raise
SCons.Node.store_info_map[self.store_info](self)
if T: Trace(' 1\n')
return 1
@@ -3372,12 +3370,12 @@ class File(Base):
It computes and returns the signature for this
node's contents.
"""
-
+
try:
return self.contentsig
except AttributeError:
pass
-
+
executor = self.get_executor()
result = self.contentsig = SCons.Util.MD5signature(executor.get_contents())
@@ -3397,7 +3395,7 @@ class File(Base):
return self.cachesig
except AttributeError:
pass
-
+
# Collect signatures for all children
children = self.children()
sigs = [n.get_cachedir_csig() for n in children]
@@ -3461,7 +3459,7 @@ class FileFinder(object):
def _find_file_key(self, filename, paths, verbose=None):
return (filename, paths)
-
+
@SCons.Memoize.CountDictCall(_find_file_key)
def find_file(self, filename, paths, verbose=None):
"""
@@ -3547,7 +3545,7 @@ def invalidate_node_memos(targets):
if not SCons.Util.is_List(targets):
targets = [targets]
-
+
for entry in targets:
# If the target is a Node object, clear the cache. If it is a
# filename, look up potentially existing Node object first.
@@ -3559,7 +3557,7 @@ def invalidate_node_memos(targets):
# do not correspond to an existing Node object.
node = get_default_fs().Entry(entry)
if node:
- node.clear_memoized_values()
+ node.clear_memoized_values()
# Local Variables:
# tab-width:4
diff --git a/src/engine/SCons/Node/FSTests.py b/src/engine/SCons/Node/FSTests.py
index fc27859..b9c19bc 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().get_internal_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().get_internal_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].get_internal_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].get_internal_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)
@@ -1084,7 +1084,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:
@@ -1092,7 +1092,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:
@@ -1100,7 +1100,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:
@@ -1641,7 +1641,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)
@@ -1907,9 +1907,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
@@ -2546,9 +2546,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()
@@ -3663,7 +3663,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"
@@ -3671,7 +3671,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
@@ -3680,7 +3680,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 86a5c1d..1a76b60 100644
--- a/src/engine/SCons/Node/__init__.py
+++ b/src/engine/SCons/Node/__init__.py
@@ -19,6 +19,8 @@ be able to depend on any other type of "thing."
"""
+from __future__ import print_function
+
#
# __COPYRIGHT__
#
@@ -151,7 +153,7 @@ def exists_file(node):
# 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 exists_base(node) or node.islink():
node.fs.unlink(node.get_internal_path())
# Return None explicitly because the Base.exists() call
@@ -205,13 +207,13 @@ def get_contents_dir(node):
contents.append('%s %s\n' % (n.get_csig(), n.name))
return ''.join(contents)
-def get_contents_file(node):
+def get_contents_file(node):
if not node.rexists():
return ''
fname = node.rfile().get_abspath()
try:
contents = open(fname, "rb").read()
- except EnvironmentError, e:
+ except EnvironmentError as e:
if not e.filename:
e.filename = fname
raise
@@ -407,21 +409,21 @@ class NodeInfoBase(object):
for name in getattr(obj,'__slots__',()):
if hasattr(self, name):
state[name] = getattr(self, name)
-
+
state['_version_id'] = self.current_version_id
try:
del state['__weakref__']
except KeyError:
pass
return state
-
+
def __setstate__(self, state):
"""
Restore the attributes from a pickled state. The version is discarded.
"""
# TODO check or discard version
del state['_version_id']
-
+
for key, value in state.items():
if key not in ('__weakref__',):
setattr(self, key, value)
@@ -456,7 +458,7 @@ class BuildInfoBase(object):
"""
state = other.__getstate__()
self.__setstate__(state)
-
+
def __getstate__(self):
"""
Return all fields that shall be pickled. Walk the slots in the class
@@ -536,7 +538,7 @@ class Node(object):
class Attrs(object):
__slots__ = ('shared', '__dict__')
-
+
def __init__(self):
if SCons.Debug.track_instances: logInstanceCreation(self, 'Node.Node')
@@ -588,7 +590,7 @@ class Node(object):
self._func_rexists = 1
self._func_get_contents = 0
self._func_target_from_source = 0
-
+
self.clear_memoized_values()
# Let the interface in which the build engine is embedded
@@ -737,7 +739,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
@@ -776,16 +778,16 @@ class Node(object):
def release_target_info(self):
"""Called just after this node has been marked
up-to-date or was built completely.
-
+
This is where we try to release as many target node infos
as possible for clean builds and update runs, in order
to minimize the overall memory consumption.
-
+
By purging attributes that aren't needed any longer after
a Node (=File) got built, we don't have to care that much how
many KBytes a Node actually requires...as long as we free
the memory shortly afterwards.
-
+
@see: built() and File.release_target_info()
"""
pass
@@ -934,7 +936,7 @@ class Node(object):
node = nodes.pop(0)
scanner = node._get_scanner(env, initial_scanner, root_node_scanner, kw)
-
+
if not scanner:
continue
@@ -958,14 +960,14 @@ class Node(object):
else:
# handle explicit scanner case
scanner = initial_scanner.select(self)
-
+
if not scanner:
# no scanner could be found for the given node's scanner key;
# thus, make an attempt at using a default.
scanner = root_node_scanner
-
+
return scanner
-
+
def get_env_scanner(self, env, kw={}):
return env.get_scanner(self.scanner_key())
@@ -1237,7 +1239,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))
@@ -1256,7 +1258,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))
@@ -1270,7 +1272,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))
@@ -1422,14 +1424,14 @@ class Node(object):
any difference, but we now rely on checking every dependency
to make sure that any necessary Node information (for example,
the content signature of an #included .h file) is updated.
-
+
The allowcache option was added for supporting the early
release of the executor/builder structures, right after
a File target was built. When set to true, the return
value of this changed method gets cached for File nodes.
Like this, the executor isn't needed any longer for subsequent
calls to changed().
-
+
@see: FS.File.changed(), FS.File.release_target_info()
"""
t = 0
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 7f3e90b..7f4639f 100644
--- a/src/engine/SCons/Platform/__init__.py
+++ b/src/engine/SCons/Platform/__init__.py
@@ -21,7 +21,7 @@ their own platform definition.
#
# __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
@@ -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__"
@@ -130,7 +131,7 @@ class PlatformSpec(object):
def __str__(self):
return self.name
-
+
class TempFileMunge(object):
"""A callable class. You can set an Environment variable to this,
then call it with a string argument, then it will perform temporary
@@ -183,9 +184,9 @@ class TempFileMunge(object):
node = target[0] if SCons.Util.is_List(target) else target
cmdlist = getattr(node.attributes, 'tempfile_cmdlist', None) \
if node is not None else None
- if cmdlist is not None :
+ if cmdlist is not None :
return cmdlist
-
+
# We do a normpath because mktemp() has what appears to be
# a bug in Windows that will use a forward slash as a path
# delimiter. Windows's link mistakes that for a command line
@@ -233,14 +234,14 @@ 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:
- cmdstr = env.subst(self.cmdstr, SCons.Subst.SUBST_RAW, target,
+ cmdstr = env.subst(self.cmdstr, SCons.Subst.SUBST_RAW, target,
source) if self.cmdstr is not None else ''
# Print our message only if XXXCOMSTR returns an empty string
if len(cmdstr) == 0 :
print("Using tempfile "+native_tmp+" for command line:\n"+
str(cmd[0]) + " " + " ".join(args))
-
- # Store the temporary file command list into the target Node.attributes
+
+ # Store the temporary file command list into the target Node.attributes
# to avoid creating two temporary files one for print and one for execute.
cmdlist = [ cmd[0], prefix + native_tmp + '\n' + rm, native_tmp ]
if node is not None:
@@ -249,7 +250,8 @@ class TempFileMunge(object):
except AttributeError:
pass
return cmdlist
-
+
+
def Platform(name = platform_default()):
"""Select a canned Platform specification.
"""
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 34c79ff..8b4669c 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 4cfabea..269007d 100644
--- a/src/engine/SCons/Platform/win32.py
+++ b/src/engine/SCons/Platform/win32.py
@@ -69,6 +69,7 @@ else:
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()),
@@ -82,7 +83,7 @@ else:
try:
import threading
spawn_lock = threading.Lock()
-
+
# This locked version of spawnve works around a Windows
# MSVCRT bug, because its spawnve is not thread-safe.
# Without this, python can randomly crash while using -jN.
@@ -111,7 +112,7 @@ except ImportError:
# simulating a non-existent package.
def spawnve(mode, file, args, env):
return os.spawnve(mode, file, args, env)
-
+
# The upshot of all this is that, if you are using Python 1.5.2,
# you had better have cmd or command.com in your PATH when you run
# scons.
@@ -153,7 +154,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]]
@@ -181,7 +182,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]))
@@ -261,7 +262,7 @@ def get_program_files_dir():
# A reasonable default if we can't read the registry
# (Actually, it's pretty reasonable even if we can :-)
val = os.path.join(os.path.dirname(get_system_root()),"Program Files")
-
+
return val
@@ -346,7 +347,7 @@ def generate(env):
os.path.join(systemroot,'System32')
tmp_pathext = '.com;.exe;.bat;.cmd'
if 'PATHEXT' in os.environ:
- tmp_pathext = os.environ['PATHEXT']
+ tmp_pathext = os.environ['PATHEXT']
cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext)
if not cmd_interp:
cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext)
@@ -356,7 +357,7 @@ def generate(env):
if not cmd_interp:
cmd_interp = env.Detect('command')
-
+
if 'ENV' not in env:
env['ENV'] = {}
@@ -401,10 +402,10 @@ def generate(env):
env['TEMPFILEPREFIX'] = '@'
env['MAXLINELENGTH'] = 2048
env['ESCAPE'] = escape
-
+
env['HOST_OS'] = 'win32'
env['HOST_ARCH'] = get_architecture().arch
-
+
# Local Variables:
# tab-width:4
diff --git a/src/engine/SCons/SConf.py b/src/engine/SCons/SConf.py
index 94027ec..d56b333 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__"
@@ -134,7 +135,7 @@ def CreateConfigHBuilder(env):
for k in _ac_config_hs.keys():
env.SConfigHBuilder(k, env.Value(_ac_config_hs[k]))
-
+
class SConfWarning(SCons.Warnings.Warning):
pass
SCons.Warnings.enableWarningClass(SConfWarning)
@@ -176,7 +177,7 @@ class SConfBuildInfo(SCons.Node.FS.FileBuildInfo):
contains messages of the original build phase.
"""
__slots__ = ('result', 'string')
-
+
def __init__(self):
self.result = None # -> 0/None -> no error, != 0 error
self.string = None # the stdout / stderr output when building the target
@@ -217,7 +218,7 @@ class Streamer(object):
if self.orig:
self.orig.flush()
self.s.flush()
-
+
class SConfBuildTask(SCons.Taskmaster.AlwaysTask):
"""
@@ -311,7 +312,7 @@ class SConfBuildTask(SCons.Taskmaster.AlwaysTask):
binfo = self.targets[0].get_stored_info().binfo
self.display_cached_string(binfo)
raise SCons.Errors.BuildError # will be 'caught' in self.failed
- elif is_up_to_date:
+ elif is_up_to_date:
self.display("\"%s\" is up to date." % str(self.targets[0]))
binfo = self.targets[0].get_stored_info().binfo
self.display_cached_string(binfo)
@@ -332,7 +333,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:
@@ -346,7 +347,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 = SConfBuildInfo()
binfo.merge(t.get_binfo())
@@ -396,7 +397,7 @@ class SConfBase(object):
"""
def __init__(self, env, custom_tests = {}, conf_dir='$CONFIGUREDIR',
- log_file='$CONFIGURELOG', config_h = None, _depth = 0):
+ log_file='$CONFIGURELOG', config_h = None, _depth = 0):
"""Constructor. Pass additional tests in the custom_tests-dictionary,
e.g. custom_tests={'CheckPrivate':MyPrivateTest}, where MyPrivateTest
defines a custom test.
@@ -457,7 +458,7 @@ class SConfBase(object):
If value is None (default), then #define name is written. If value is not
none, then #define name value is written.
-
+
comment is a string which will be put as a C comment in the
header, to explain the meaning of the value (appropriate C comments /* and
*/ will be put automatically."""
@@ -689,7 +690,7 @@ class SConfBase(object):
global _ac_config_logs
global sconf_global
global SConfFS
-
+
self.lastEnvFs = self.env.fs
self.env.fs = SConfFS
self._createDir(self.confdir)
@@ -716,7 +717,7 @@ class SConfBase(object):
self.logstream.write('file %s,line %d:\n\tConfigure(confdir = %s)\n' %
(tb[0], tb[1], str(self.confdir)) )
SConfFS.chdir(old_fs_dir)
- else:
+ else:
self.logstream = None
# we use a special builder to create source files from TEXT
action = SCons.Action.Action(_createSource,
@@ -913,14 +914,14 @@ def CheckType(context, type_name, includes = "", language = None):
def CheckTypeSize(context, type_name, includes = "", language = None, expect = None):
res = SCons.Conftest.CheckTypeSize(context, type_name,
- header = includes, language = language,
+ header = includes, language = language,
expect = expect)
context.did_show_result = 1
return res
def CheckDeclaration(context, declaration, includes = "", language = None):
res = SCons.Conftest.CheckDeclaration(context, declaration,
- includes = includes,
+ includes = includes,
language = language)
context.did_show_result = 1
return not res
@@ -1004,7 +1005,7 @@ def CheckLib(context, library = None, symbol = "main",
if not SCons.Util.is_List(library):
library = [library]
-
+
# ToDo: accept path for the library
res = SCons.Conftest.CheckLib(context, library, symbol, header = header,
language = language, autoadd = autoadd)
diff --git a/src/engine/SCons/SConfTests.py b/src/engine/SCons/SConfTests.py
index f9ee0d0..15499ed 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 74ee804..cb089aa 100644
--- a/src/engine/SCons/SConsign.py
+++ b/src/engine/SCons/SConsign.py
@@ -27,12 +27,13 @@ Writing and reading information to the .sconsign file or files.
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
+from __future__ import print_function
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.compat
import os
-# compat layer imports "cPickle" for us if it's available.
import pickle
import SCons.dblite
@@ -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():
@@ -124,16 +125,16 @@ class SConsignEntry(object):
"""
__slots__ = ("binfo", "ninfo", "__weakref__")
current_version_id = 2
-
+
def __init__(self):
# Create an object attribute from the class attribute so it ends up
# in the pickled data in the .sconsign file.
#_version_id = self.current_version_id
pass
-
+
def convert_to_sconsign(self):
self.binfo.convert_to_sconsign()
-
+
def convert_from_sconsign(self, dir, name):
self.binfo.convert_from_sconsign(dir, name)
@@ -155,7 +156,7 @@ class SConsignEntry(object):
for key, value in state.items():
if key not in ('_version_id','__weakref__'):
setattr(self, key, value)
-
+
class Base(object):
"""
This is the controlling class for the signatures for the collection of
@@ -239,7 +240,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.get_tpath(), e))
for key, entry in self.entries.items():
@@ -298,7 +299,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):
@@ -364,7 +365,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 e6ac720..3b34b88 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 ace3ff4..e7c791c 100644
--- a/src/engine/SCons/Scanner/ProgTests.py
+++ b/src/engine/SCons/Scanner/ProgTests.py
@@ -270,7 +270,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 5450ff5..e7a0658 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):
@@ -351,7 +352,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 05c0d75..c0b22a7 100644
--- a/src/engine/SCons/Script/Main.py
+++ b/src/engine/SCons/Script/Main.py
@@ -10,9 +10,13 @@ some other module. If it's specific to the "scons" script invocation,
it goes here.
"""
+from __future__ import print_function
+
+
unsupported_python_version = (2, 6, 0)
deprecated_python_version = (2, 7, 0)
+
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
@@ -36,6 +40,7 @@ deprecated_python_version = (2, 7, 0)
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
+
import SCons.compat
import os
@@ -220,7 +225,7 @@ class BuildTask(SCons.Taskmaster.OutOfDateTask):
self.exception_set()
self.do_failed()
else:
- print "scons: Nothing to be done for `%s'." % t
+ print("scons: Nothing to be done for `%s'." % t)
SCons.Taskmaster.OutOfDateTask.executed(self)
else:
SCons.Taskmaster.OutOfDateTask.executed(self)
@@ -289,8 +294,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):
@@ -325,10 +330,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 = []
@@ -354,13 +359,13 @@ class CleanTask(SCons.Taskmaster.AlwaysTask):
for t in self._get_files_to_clean():
try:
removed = t.remove()
- except OSError, e:
+ except OSError as e:
# An OSError may indicate something like a permissions
# issue, an IOError would indicate something like
# the file not existing. In either case, print a
# message and keep going to try to remove as many
# targets as possible.
- print "scons: Could not remove '%s':" % str(t), e.strerror
+ print("scons: Could not remove '{0}'".format(str(t)), e.strerror)
else:
if removed:
display("Removed " + str(t))
@@ -600,7 +605,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)
@@ -714,7 +719,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:
@@ -727,10 +732,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
@@ -740,7 +745,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
@@ -792,7 +797,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 +997,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 +1058,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
@@ -1091,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):
@@ -1335,7 +1340,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())
@@ -1346,23 +1351,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
@@ -1398,10 +1403,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 f56504a..b2f2858 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.
@@ -663,7 +663,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)
@@ -830,7 +830,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 e696cfa..6480ace 100644
--- a/src/engine/SCons/Script/SConscript.py
+++ b/src/engine/SCons/Script/SConscript.py
@@ -5,6 +5,8 @@ files.
"""
+from __future__ import print_function
+
#
# __COPYRIGHT__
#
@@ -26,7 +28,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__"
@@ -69,7 +70,7 @@ def get_calling_namespaces():
"""Return the locals and globals for the function that called
into this module in the current call stack."""
try: 1//0
- except ZeroDivisionError:
+ except ZeroDivisionError:
# Don't start iterating with the current stack-frame to
# prevent creating reference cycles (f_back is safe).
frame = sys.exc_info()[2].tb_frame.f_back
@@ -103,7 +104,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
@@ -135,7 +136,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:
@@ -164,7 +165,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
@@ -247,7 +248,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:
@@ -272,7 +274,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.
#
@@ -462,15 +464,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):
@@ -509,7 +511,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 be6e5ce..3fa3a48 100644
--- a/src/engine/SCons/Script/__init__.py
+++ b/src/engine/SCons/Script/__init__.py
@@ -41,7 +41,12 @@ start_time = time.time()
import collections
import os
-import StringIO
+
+try:
+ from StringIO import StringIO
+except ImportError:
+ from io import StringIO
+
import sys
# Special chicken-and-egg handling of the "--debug=memoizer" flag:
@@ -67,7 +72,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
@@ -86,7 +91,7 @@ import SCons.Util
import SCons.Variables
import SCons.Defaults
-import Main
+from . import Main
main = Main.main
@@ -130,7 +135,7 @@ GetBuildFailures = Main.GetBuildFailures
#repositories = Main.repositories
#
-import SConscript
+from . import SConscript
_SConscript = SConscript
call_stack = _SConscript.call_stack
@@ -264,7 +269,7 @@ def HelpFunction(text, append=False):
global help_text
if help_text is None:
if append:
- s = StringIO.StringIO()
+ s = StringIO()
PrintHelp(s)
help_text = s.getvalue()
s.close()
@@ -375,7 +380,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 236b08e..3c9b390 100644
--- a/src/engine/SCons/Subst.py
+++ b/src/engine/SCons/Subst.py
@@ -445,7 +445,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)
@@ -652,7 +652,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 e625cc7..8eda845 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)}'"
@@ -937,18 +938,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
@@ -960,7 +961,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}'",
@@ -976,7 +977,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'",
@@ -1084,8 +1085,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 86cae42..0f4fd21 100644
--- a/src/engine/SCons/Taskmaster.py
+++ b/src/engine/SCons/Taskmaster.py
@@ -20,6 +20,10 @@
# 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
+
+import sys
+
__doc__ = """
Generic Taskmaster module for the SCons build engine.
@@ -107,7 +111,7 @@ fmt = "%(considered)3d "\
def dump_stats():
for n in sorted(StatsNodes, key=lambda a: str(a)):
- print (fmt % n.attributes.stats.__dict__) + str(n)
+ print((fmt % n.attributes.stats.__dict__) + str(n))
@@ -191,13 +195,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 +260,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 +309,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 +406,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 +427,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()
@@ -537,7 +541,14 @@ class Task(object):
except ValueError:
exc_type, exc_value = exc
exc_traceback = None
- raise exc_type, exc_value, exc_traceback
+
+ if sys.version_info[0] == 2:
+ exec("raise exc_type, exc_value, exc_traceback")
+ else: # sys.version_info[0] == 3:
+ exec("raise exc_type(exc_value).with_traceback(exc_traceback)")
+
+ # raise e.__class__, e.__class__(e), sys.exc_info()[2]
+
class AlwaysTask(Task):
def needs_execute(self):
@@ -810,7 +821,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 +954,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 2df2a32..e450730 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 f01371a..e23a2d7 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).
@@ -324,7 +324,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
@@ -348,7 +348,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:
@@ -363,7 +363,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:
@@ -378,7 +378,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:
@@ -393,7 +393,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 be890e2..bcfee2b 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 8fa3c43..787d008 100644
--- a/src/engine/SCons/Tool/MSCommon/netframework.py
+++ b/src/engine/SCons/Tool/MSCommon/netframework.py
@@ -29,7 +29,7 @@ import os
import re
import SCons.Util
-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,13 +40,13 @@ def find_framework_root():
# XXX: find it from environment (FrameworkDir)
try:
froot = read_reg(_FRAMEWORKDIR_HKEY_ROOT)
- debug("Found framework install root in registry: %s" % froot)
- except SCons.Util.WinError, e:
- debug("Could not read reg key %s" % _FRAMEWORKDIR_HKEY_ROOT)
+ debug("Found framework install root in registry: {}".format(froot))
+ except SCons.Util.WinError as e:
+ debug("Could not read reg key {}".format(_FRAMEWORKDIR_HKEY_ROOT))
return None
if not os.path.exists(froot):
- debug("%s not found on fs" % froot)
+ debug("{} not found on fs".format(froot))
return None
return froot
diff --git a/src/engine/SCons/Tool/MSCommon/sdk.py b/src/engine/SCons/Tool/MSCommon/sdk.py
index b8b71a6..1845599 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
@@ -76,23 +76,23 @@ class SDKDefinition(object):
return None
hkey = self.HKEY_FMT % self.hkey_data
- debug('find_sdk_dir(): checking registry:%s'%hkey)
+ debug('find_sdk_dir(): checking registry:{}'.format(hkey))
try:
sdk_dir = common.read_reg(hkey)
- except SCons.Util.WinError, e:
- debug('find_sdk_dir(): no SDK registry key %s' % repr(hkey))
+ except SCons.Util.WinError as e:
+ debug('find_sdk_dir(): no SDK registry key {}'.format(repr(hkey)))
return None
- debug('find_sdk_dir(): Trying SDK Dir: %s'%sdk_dir)
+ debug('find_sdk_dir(): Trying SDK Dir: {}'.format(sdk_dir))
if not os.path.exists(sdk_dir):
- debug('find_sdk_dir(): %s not on file system' % sdk_dir)
+ debug('find_sdk_dir(): {} not on file system'.format(sdk_dir))
return None
ftc = os.path.join(sdk_dir, self.sanity_check_file)
if not os.path.exists(ftc):
- debug("find_sdk_dir(): sanity check %s not found" % ftc)
+ debug("find_sdk_dir(): sanity check {} not found".format(ftc))
return None
return sdk_dir
@@ -105,7 +105,7 @@ class SDKDefinition(object):
sdk_dir = self.find_sdk_dir()
self._sdk_dir = sdk_dir
return sdk_dir
-
+
def get_sdk_vc_script(self,host_arch, target_arch):
""" Return the script to initialize the VC compiler installed by SDK
"""
@@ -113,11 +113,11 @@ class SDKDefinition(object):
if (host_arch == 'amd64' and target_arch == 'x86'):
# No cross tools needed compiling 32 bits on 64 bit machine
host_arch=target_arch
-
+
arch_string=target_arch
if (host_arch != target_arch):
arch_string='%s_%s'%(host_arch,target_arch)
-
+
debug("sdk.py: get_sdk_vc_script():arch_string:%s host_arch:%s target_arch:%s"%(arch_string,
host_arch,
target_arch))
@@ -308,8 +308,7 @@ def set_sdk_by_directory(env, sdk_dir):
def get_sdk_by_version(mssdk):
if mssdk not in SupportedSDKMap:
- msg = "SDK version %s is not supported" % repr(mssdk)
- raise SCons.Errors.UserError(msg)
+ raise SCons.Errors.UserError("SDK version {} is not supported".format(repr(mssdk)))
get_installed_sdks()
return InstalledSDKMap.get(mssdk)
@@ -327,16 +326,16 @@ def mssdk_setup_env(env):
if sdk_dir is None:
return
sdk_dir = env.subst(sdk_dir)
- debug('sdk.py:mssdk_setup_env: Using MSSDK_DIR:%s'%sdk_dir)
+ debug('sdk.py:mssdk_setup_env: Using MSSDK_DIR:{}'.format(sdk_dir))
elif 'MSSDK_VERSION' in env:
sdk_version = env['MSSDK_VERSION']
if sdk_version is None:
- msg = "SDK version is specified as None"
+ msg = "SDK version is specified as None"
raise SCons.Errors.UserError(msg)
sdk_version = env.subst(sdk_version)
mssdk = get_sdk_by_version(sdk_version)
if mssdk is None:
- msg = "SDK version %s is not installed" % sdk_version
+ msg = "SDK version %s is not installed" % sdk_version
raise SCons.Errors.UserError(msg)
sdk_dir = mssdk.get_sdk_dir()
debug('sdk.py:mssdk_setup_env: Using MSSDK_VERSION:%s'%sdk_dir)
@@ -347,7 +346,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 97e2ffc..f96b8ca 100644
--- a/src/engine/SCons/Tool/MSCommon/vc.py
+++ b/src/engine/SCons/Tool/MSCommon/vc.py
@@ -43,11 +43,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
@@ -108,7 +108,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)
@@ -118,17 +118,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)
@@ -183,7 +183,7 @@ _VCVER_TO_PRODUCT_DIR = {
(SCons.Util.HKEY_LOCAL_MACHINE, 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 + '.'])
@@ -194,7 +194,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):
@@ -244,22 +244,21 @@ def find_vc_pdir(msvc_version):
try:
# ordinally at win64, try Wow6432Node first.
comps = common.read_reg(root + 'Wow6432Node\\' + key, hkroot)
- except SCons.Util.WinError, e:
+ except SCons.Util.WinError as e:
# at Microsoft Visual Studio for Python 2.7, value is not in Wow6432Node
pass
if not comps:
# not Win64, or Microsoft Visual Studio for Python 2.7
comps = common.read_reg(root + key, hkroot)
- except SCons.Util.WinError, e:
- debug('find_vc_dir(): no VC registry key %s' % repr(key))
+ except SCons.Util.WinError as e:
+ debug('find_vc_dir(): no VC registry key {}'.format(repr(key)))
else:
- debug('find_vc_dir(): found VC in registry: %s' % comps)
+ debug('find_vc_dir(): found VC in registry: {}'.format(comps))
if os.path.exists(comps):
return comps
else:
- debug('find_vc_dir(): reg says dir is %s, but it does not exist. (ignoring)'\
- % comps)
- raise MissingConfiguration("registry dir %s not found on the filesystem" % comps)
+ debug('find_vc_dir(): reg says dir is {}, but it does not exist. (ignoring)'.format(comps))
+ raise MissingConfiguration("registry dir {} not found on the filesystem".format(comps))
return None
def find_batch_file(env,msvc_version,host_arch,target_arch):
@@ -270,8 +269,8 @@ 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)
+
+ debug('vc.py: find_batch_file() pdir:{}'.format(pdir))
# filter out e.g. "Exp" from the version name
msvc_ver_numeric = ''.join([x for x in msvc_version if x in string_digits + "."])
@@ -288,7 +287,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)
@@ -296,7 +295,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)
@@ -323,7 +322,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
@@ -359,7 +358,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:
@@ -409,7 +408,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')
@@ -427,7 +426,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):
@@ -435,12 +434,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. " + \
@@ -449,13 +448,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
@@ -463,23 +462,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()')
@@ -498,12 +497,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:
@@ -524,4 +523,3 @@ 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 0bdbf0c..31197ef 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, \
@@ -83,10 +83,10 @@ class VisualStudio(object):
key = root + key
try:
comps = read_reg(key)
- except SCons.Util.WinError, e:
- debug('find_vs_dir_by_reg(): no VS registry key %s' % repr(key))
+ except SCons.Util.WinError as e:
+ debug('find_vs_dir_by_reg(): no VS registry key {}'.format(repr(key)))
else:
- debug('find_vs_dir_by_reg(): found VS in registry: %s' % comps)
+ debug('find_vs_dir_by_reg(): found VS in registry: {}'.format(comps))
return comps
return None
@@ -105,12 +105,12 @@ class VisualStudio(object):
def find_executable(self):
vs_dir = self.get_vs_dir()
if not vs_dir:
- debug('find_executable(): no vs_dir (%s)'%vs_dir)
+ debug('find_executable(): no vs_dir ({})'.format(vs_dir))
return None
executable = os.path.join(vs_dir, self.executable_path)
executable = os.path.normpath(executable)
if not os.path.isfile(executable):
- debug('find_executable(): %s not on file system' % executable)
+ debug('find_executable(): {} not on file system'.format(executable))
return None
return executable
@@ -209,7 +209,7 @@ SupportedVSList = [
batch_file_path=r'Common7\Tools\vsvars32.bat',
supported_arch=['x86', 'amd64', "arm"],
),
-
+
# Visual C++ 2015 Express Edition (for Desktop)
VisualStudio('14.0Exp',
vc_version='14.0',
diff --git a/src/engine/SCons/Tool/__init__.py b/src/engine/SCons/Tool/__init__.py
index f16e9e2..45d0aa1 100644
--- a/src/engine/SCons/Tool/__init__.py
+++ b/src/engine/SCons/Tool/__init__.py
@@ -38,11 +38,13 @@ tool definition.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import imp
+import importlib
import sys
import re
import os
import shutil
+
import SCons.Builder
import SCons.Errors
import SCons.Node.FS
@@ -52,6 +54,7 @@ import SCons.Scanner.D
import SCons.Scanner.LaTeX
import SCons.Scanner.Prog
import SCons.Scanner.SWIG
+import collections
DefaultToolpath=[]
@@ -112,30 +115,62 @@ class Tool(object):
oldpythonpath = sys.path
sys.path = self.toolpath + sys.path
- try:
+
+ if sys.version_info[0] < 3:
+ # Py 2 code
try:
- file, path, desc = imp.find_module(self.name, self.toolpath)
try:
- return imp.load_module(self.name, file, path, desc)
- finally:
- if file:
- file.close()
- except ImportError, e:
- if str(e)!="No module named %s"%self.name:
- raise SCons.Errors.EnvironmentError(e)
+ file, path, desc = imp.find_module(self.name, self.toolpath)
+ try:
+ return imp.load_module(self.name, file, path, desc)
+
+ finally:
+ if file:
+ file.close()
+ except ImportError as e:
+ if str(e)!="No module named %s"%self.name:
+ raise SCons.Errors.EnvironmentError(e)
+ try:
+ import zipimport
+ except ImportError:
+ pass
+ else:
+ for aPath in self.toolpath:
+ try:
+ importer = zipimport.zipimporter(aPath)
+ return importer.load_module(self.name)
+ except ImportError as e:
+ pass
+ finally:
+ sys.path = oldpythonpath
+ else:
+ # Py 3 code
+ try:
+ # Try site_tools first
+ return importlib.import_module(self.name)
+ except ImportError as e:
+ # Then try modules in main distribution
try:
- import zipimport
- except ImportError:
- pass
- else:
- for aPath in self.toolpath:
- try:
- importer = zipimport.zipimporter(aPath)
- return importer.load_module(self.name)
- except ImportError, e:
- pass
- finally:
- sys.path = oldpythonpath
+ return importlib.import_module('SCons.Tool.'+self.name)
+ except ImportError as e:
+ if str(e) != "No module named %s" % self.name:
+ raise SCons.Errors.EnvironmentError(e)
+ try:
+ import zipimport
+ except ImportError:
+ pass
+ else:
+ for aPath in self.toolpath:
+ try:
+ importer = zipimport.zipimporter(aPath)
+ return importer.load_module(self.name)
+ except ImportError as e:
+ pass
+
+ finally:
+ sys.path = oldpythonpath
+
+
full_name = 'SCons.Tool.' + self.name
try:
@@ -150,7 +185,7 @@ class Tool(object):
if file:
file.close()
return module
- except ImportError, e:
+ except ImportError as e:
if str(e)!="No module named %s"%self.name:
raise SCons.Errors.EnvironmentError(e)
try:
@@ -159,10 +194,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,22 +289,22 @@ def _call_linker_cb(env, callback, args, result = None):
Verbose = False
if Verbose:
- print '_call_linker_cb: args=%r' % args
- print '_call_linker_cb: callback=%r' % callback
+ print('_call_linker_cb: args=%r' % args)
+ print('_call_linker_cb: callback=%r' % callback)
try:
cbfun = env['LINKCALLBACKS'][callback]
except (KeyError, TypeError):
if Verbose:
- print '_call_linker_cb: env["LINKCALLBACKS"][%r] not found or can not be used' % callback
+ print('_call_linker_cb: env["LINKCALLBACKS"][%r] not found or can not be used' % callback)
pass
else:
if Verbose:
- print '_call_linker_cb: env["LINKCALLBACKS"][%r] found' % callback
- print '_call_linker_cb: env["LINKCALLBACKS"][%r]=%r' % (callback, cbfun)
- if(callable(cbfun)):
+ print('_call_linker_cb: env["LINKCALLBACKS"][%r] found' % callback)
+ print('_call_linker_cb: env["LINKCALLBACKS"][%r]=%r' % (callback, cbfun))
+ if(isinstance(cbfun, collections.Callable)):
if Verbose:
- print '_call_linker_cb: env["LINKCALLBACKS"][%r] is callable' % callback
+ print('_call_linker_cb: env["LINKCALLBACKS"][%r] is callable' % callback)
result = cbfun(env, *args)
return result
@@ -407,17 +442,17 @@ class _LibPrefixGenerator(_LibInfoGeneratorBase):
prefix = self.get_lib_prefix(env,**kw2)
if Verbose:
- print "_LibPrefixGenerator: input prefix=%r" % prefix
+ print("_LibPrefixGenerator: input prefix=%r" % prefix)
version = self.get_lib_version(env, **kw2)
if Verbose:
- print "_LibPrefixGenerator: version=%r" % version
+ print("_LibPrefixGenerator: version=%r" % version)
if version:
prefix = self.generate_versioned_lib_info(env, [prefix, version], prefix, **kw2)
if Verbose:
- print "_LibPrefixGenerator: return prefix=%r" % prefix
+ print("_LibPrefixGenerator: return prefix=%r" % prefix)
return prefix
ShLibPrefixGenerator = _LibPrefixGenerator('ShLib')
@@ -441,17 +476,17 @@ class _LibSuffixGenerator(_LibInfoGeneratorBase):
suffix = self.get_lib_suffix(env, **kw2)
if Verbose:
- print "_LibSuffixGenerator: input suffix=%r" % suffix
+ print("_LibSuffixGenerator: input suffix=%r" % suffix)
version = self.get_lib_version(env, **kw2)
if Verbose:
- print "_LibSuffixGenerator: version=%r" % version
+ print("_LibSuffixGenerator: version=%r" % version)
if version:
suffix = self.generate_versioned_lib_info(env, [suffix, version], suffix, **kw2)
if Verbose:
- print "_LibSuffixGenerator: return suffix=%r" % suffix
+ print("_LibSuffixGenerator: return suffix=%r" % suffix)
return suffix
ShLibSuffixGenerator = _LibSuffixGenerator('ShLib')
@@ -474,15 +509,15 @@ class _LibSymlinkGenerator(_LibInfoGeneratorBase):
kw2 = kw
if Verbose:
- print "_LibSymLinkGenerator: libnode=%r" % libnode.get_path()
+ print("_LibSymLinkGenerator: libnode=%r" % libnode.get_path())
symlinks = None
version = self.get_lib_version(env, **kw2)
disable = self.get_lib_noversionsymlinks(env, **kw2)
if Verbose:
- print '_LibSymlinkGenerator: version=%r' % version
- print '_LibSymlinkGenerator: disable=%r' % disable
+ print('_LibSymlinkGenerator: version=%r' % version)
+ print('_LibSymlinkGenerator: disable=%r' % disable)
if version and not disable:
prefix = self.get_lib_prefix(env,**kw2)
@@ -490,7 +525,7 @@ class _LibSymlinkGenerator(_LibInfoGeneratorBase):
symlinks = self.generate_versioned_lib_info(env, [libnode, version, prefix, suffix], **kw2)
if Verbose:
- print '_LibSymlinkGenerator: return symlinks=%r' % StringizeLibSymlinks(symlinks)
+ print('_LibSymlinkGenerator: return symlinks=%r' % StringizeLibSymlinks(symlinks))
return symlinks
ShLibSymlinkGenerator = _LibSymlinkGenerator('ShLib')
@@ -525,11 +560,11 @@ class _LibNameGenerator(_LibInfoGeneratorBase):
kw2 = kw
if Verbose:
- print "_LibNameGenerator: libnode=%r" % libnode.get_path()
+ print("_LibNameGenerator: libnode=%r" % libnode.get_path())
version = self.get_lib_version(env, **kw2)
if Verbose:
- print '_LibNameGenerator: version=%r' % version
+ print('_LibNameGenerator: version=%r' % version)
name = None
if version:
@@ -541,7 +576,7 @@ class _LibNameGenerator(_LibInfoGeneratorBase):
name = os.path.basename(libnode.get_path())
if Verbose:
- print '_LibNameGenerator: return name=%r' % name
+ print('_LibNameGenerator: return name=%r' % name)
return name
@@ -566,13 +601,13 @@ class _LibSonameGenerator(_LibInfoGeneratorBase):
kw2 = kw
if Verbose:
- print "_LibSonameGenerator: libnode=%r" % libnode.get_path()
+ print("_LibSonameGenerator: libnode=%r" % libnode.get_path())
soname = _call_env_subst(env, '$SONAME', **kw2)
if not soname:
version = self.get_lib_version(env,**kw2)
if Verbose:
- print "_LibSonameGenerator: version=%r" % version
+ print("_LibSonameGenerator: version=%r" % version)
if version:
prefix = self.get_lib_prefix(env,**kw2)
suffix = self.get_lib_suffix(env,**kw2)
@@ -582,10 +617,10 @@ class _LibSonameGenerator(_LibInfoGeneratorBase):
# fallback to library name (as returned by appropriate _LibNameGenerator)
soname = _LibNameGenerator(self.get_libtype())(env, libnode)
if Verbose:
- print "_LibSonameGenerator: FALLBACK: soname=%r" % soname
+ print("_LibSonameGenerator: FALLBACK: soname=%r" % soname)
if Verbose:
- print "_LibSonameGenerator: return soname=%r" % soname
+ print("_LibSonameGenerator: return soname=%r" % soname)
return soname
@@ -617,11 +652,11 @@ def EmitLibSymlinks(env, symlinks, libnode, **kw):
for link, linktgt in symlinks:
env.SideEffect(link, linktgt)
if(Verbose):
- print "EmitLibSymlinks: SideEffect(%r,%r)" % (link.get_path(), linktgt.get_path())
- clean_list = filter(lambda x : x != linktgt, nodes)
+ print("EmitLibSymlinks: SideEffect(%r,%r)" % (link.get_path(), linktgt.get_path()))
+ clean_list = [x for x in nodes if x != linktgt]
env.Clean(list(set([linktgt] + clean_targets)), clean_list)
if(Verbose):
- print "EmitLibSymlinks: Clean(%r,%r)" % (linktgt.get_path(), map(lambda x : x.get_path(), clean_list))
+ print("EmitLibSymlinks: Clean(%r,%r)" % (linktgt.get_path(), [x.get_path() for x in clean_list]))
def CreateLibSymlinks(env, symlinks):
"""Physically creates symlinks. The symlinks argument must be a list in
@@ -634,18 +669,18 @@ def CreateLibSymlinks(env, symlinks):
linktgt = link.get_dir().rel_path(linktgt)
link = link.get_path()
if(Verbose):
- print "CreateLibSymlinks: preparing to add symlink %r -> %r" % (link, linktgt)
+ print("CreateLibSymlinks: preparing to add symlink %r -> %r" % (link, linktgt))
# Delete the (previously created) symlink if exists. Let only symlinks
# to be deleted to prevent accidental deletion of source files...
if env.fs.islink(link):
env.fs.unlink(link)
if(Verbose):
- print "CreateLibSymlinks: removed old symlink %r" % link
+ print("CreateLibSymlinks: removed old symlink %r" % link)
# If a file or directory exists with the same name as link, an OSError
# will be thrown, which should be enough, I think.
env.fs.symlink(linktgt, link)
if(Verbose):
- print "CreateLibSymlinks: add symlink %r -> %r" % (link, linktgt)
+ print("CreateLibSymlinks: add symlink %r -> %r" % (link, linktgt))
return 0
def LibSymlinksActionFunction(target, source, env):
@@ -949,7 +984,7 @@ class ToolInitializer(object):
so we no longer copy and re-bind them when the construction
environment gets cloned.
"""
- for method in self.methods.values():
+ for method in list(self.methods.values()):
env.RemoveMethod(method)
def apply_tools(self, env):
diff --git a/src/engine/SCons/Tool/aixcc.py b/src/engine/SCons/Tool/aixcc.py
index 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 cf07a0b..3e30cd0 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 921f0eb..f69b886 100644
--- a/src/engine/SCons/Tool/cyglink.py
+++ b/src/engine/SCons/Tool/cyglink.py
@@ -7,6 +7,9 @@ It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
+
+from __future__ import absolute_import, print_function
+
import re
import os
@@ -14,12 +17,13 @@ import SCons.Action
import SCons.Util
import SCons.Tool
-import gnulink
-import link
+#MAYBE: from . import gnulink
+from . import gnulink
+from . import link
def _lib_generator(target, source, env, for_signature, **kw):
try: cmd = kw['cmd']
- except KeyError: cmd = SCons.Util.CLVar(['$SHLINK'])
+ except KeyError: cmd = SCons.Util.CLVar(['$SHLINK'])
try: vp = kw['varprefix']
except KeyError: vp = 'SHLIB'
@@ -40,7 +44,7 @@ def _lib_generator(target, source, env, for_signature, **kw):
])
else:
cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS'])
-
+
return [cmd]
@@ -58,37 +62,37 @@ def _lib_emitter(target, source, env, **kw):
Verbose = False
if Verbose:
- print "_lib_emitter: target[0]=%r" % target[0].get_path()
+ print("_lib_emitter: target[0]=%r" % target[0].get_path())
try: vp = kw['varprefix']
except KeyError: vp = 'SHLIB'
try: libtype = kw['libtype']
except KeyError: libtype = 'ShLib'
-
+
dll = env.FindIxes(target, '%sPREFIX' % vp, '%sSUFFIX' % vp)
no_import_lib = env.get('no_import_lib', 0)
if Verbose:
- print "_lib_emitter: dll=%r" % dll.get_path()
+ print("_lib_emitter: dll=%r" % dll.get_path())
if not dll or len(target) > 1:
raise SCons.Errors.UserError("A shared library should have exactly one target with the suffix: %s" % env.subst("$%sSUFFIX" % vp))
-
+
# Remove any "lib" after the prefix
pre = env.subst('$%sPREFIX' % vp)
if dll.name[len(pre):len(pre)+3] == 'lib':
dll.name = pre + dll.name[len(pre)+3:]
if Verbose:
- print "_lib_emitter: dll.name=%r" % dll.name
+ print("_lib_emitter: dll.name=%r" % dll.name)
orig_target = target
target = [env.fs.File(dll)]
target[0].attributes.shared = 1
if Verbose:
- print "_lib_emitter: after target=[env.fs.File(dll)]: target[0]=%r" % target[0].get_path()
+ print("_lib_emitter: after target=[env.fs.File(dll)]: target[0]=%r" % target[0].get_path())
# Append an import lib target
if not no_import_lib:
@@ -97,11 +101,11 @@ def _lib_emitter(target, source, env, **kw):
'%sPREFIX' % vp, '%sSUFFIX' % vp,
'IMPLIBPREFIX', 'IMPLIBSUFFIX')
if Verbose:
- print "_lib_emitter: target_strings=%r" % target_strings
-
+ print("_lib_emitter: target_strings=%r" % target_strings)
+
implib_target = env.fs.File(target_strings)
if Verbose:
- print "_lib_emitter: implib_target=%r" % implib_target.get_path()
+ print("_lib_emitter: implib_target=%r" % implib_target.get_path())
implib_target.attributes.shared = 1
target.append(implib_target)
@@ -109,7 +113,7 @@ def _lib_emitter(target, source, env, **kw):
implib_libtype=libtype,
generator_libtype=libtype+'ImpLib')
if Verbose:
- print "_lib_emitter: implib symlinks=%r" % SCons.Tool.StringizeLibSymlinks(symlinks)
+ print("_lib_emitter: implib symlinks=%r" % SCons.Tool.StringizeLibSymlinks(symlinks))
if symlinks:
SCons.Tool.EmitLibSymlinks(env, symlinks, implib_target, clean_targets = target[0])
implib_target.attributes.shliblinks = symlinks
@@ -121,19 +125,19 @@ def shlib_emitter(target, source, env):
def ldmod_emitter(target, source, env):
return _lib_emitter(target, source, env, varprefix='LDMODULE', libtype='LdMod')
-
+
def _versioned_lib_suffix(env, suffix, version):
"""Generate versioned shared library suffix from a unversioned one.
If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll'"""
Verbose = False
if Verbose:
- print "_versioned_lib_suffix: suffix= ", suffix
- print "_versioned_lib_suffix: version= ", version
+ print("_versioned_lib_suffix: suffix= ", suffix)
+ print("_versioned_lib_suffix: version= ", version)
cygversion = re.sub('\.', '-', version)
if not suffix.startswith('-' + cygversion):
suffix = '-' + cygversion + suffix
if Verbose:
- print "_versioned_lib_suffix: return suffix= ", suffix
+ print("_versioned_lib_suffix: return suffix= ", suffix)
return suffix
def _versioned_implib_name(env, libnode, version, prefix, suffix, **kw):
@@ -149,8 +153,8 @@ def _versioned_implib_symlinks(env, libnode, version, prefix, suffix, **kw):
Verbose = False
if Verbose:
- print "_versioned_implib_symlinks: libnode=%r" % libnode.get_path()
- print "_versioned_implib_symlinks: version=%r" % version
+ print("_versioned_implib_symlinks: libnode=%r" % libnode.get_path())
+ print("_versioned_implib_symlinks: version=%r" % version)
try: libtype = kw['libtype']
except KeyError: libtype = 'ShLib'
@@ -158,13 +162,13 @@ def _versioned_implib_symlinks(env, libnode, version, prefix, suffix, **kw):
linkdir = os.path.dirname(libnode.get_path())
if Verbose:
- print "_versioned_implib_symlinks: linkdir=%r" % linkdir
+ print("_versioned_implib_symlinks: linkdir=%r" % linkdir)
name = SCons.Tool.ImpLibNameGenerator(env, libnode,
implib_libtype=libtype,
generator_libtype=libtype+'ImpLib')
if Verbose:
- print "_versioned_implib_symlinks: name=%r" % name
+ print("_versioned_implib_symlinks: name=%r" % name)
major = version.split('.')[0]
@@ -172,7 +176,7 @@ def _versioned_implib_symlinks(env, libnode, version, prefix, suffix, **kw):
symlinks = [(link0, libnode)]
if Verbose:
- print "_versioned_implib_symlinks: return symlinks=%r" % SCons.Tool.StringizeLibSymlinks(symlinks)
+ print("_versioned_implib_symlinks: return symlinks=%r" % SCons.Tool.StringizeLibSymlinks(symlinks))
return symlinks
diff --git a/src/engine/SCons/Tool/docbook/__init__.py b/src/engine/SCons/Tool/docbook/__init__.py
index 71e93a7..2b22e17 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/f08.py b/src/engine/SCons/Tool/f08.py
index a45a61d..7fa5872 100644
--- a/src/engine/SCons/Tool/f08.py
+++ b/src/engine/SCons/Tool/f08.py
@@ -8,6 +8,8 @@ selection method.
"""
+from __future__ import absolute_import
+
#
# __COPYRIGHT__
#
@@ -36,7 +38,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_f08_to_env
compilers = ['f08']
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 392a92e..d33bf52 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 2f1aa03..b1d5088 100644
--- a/src/engine/SCons/Tool/gnulink.py
+++ b/src/engine/SCons/Tool/gnulink.py
@@ -39,7 +39,7 @@ import os
import sys
import re
-import link
+from . import link
def generate(env):
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 e84ec7a..e16bb5f 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__"
@@ -48,7 +49,7 @@ _UNIQUE_INSTALLED_FILES = None
class CopytreeError(EnvironmentError):
pass
-
+
# This is a patched version of shutil.copytree from python 2.5. It
# doesn't fail if the dir exists, which regular copytree does
# (annoyingly). Note the XXX comment in the docstring.
@@ -83,21 +84,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 SCons.Util.WinError:
# 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)
#
@@ -165,10 +166,9 @@ def listShlibLinksToInstall(dest, source, env):
def installShlibLinks(dest, source, env):
"""If we are installing a versioned shared library create the required links."""
Verbose = False
-
symlinks = listShlibLinksToInstall(dest, source, env)
if Verbose:
- print 'installShlibLinks: symlinks=%r' % SCons.Tool.StringizeLibSymlinks(symlinks)
+ print('installShlibLinks: symlinks={:r}'.format(SCons.Tool.StringizeLibSymlinks(symlinks)))
if symlinks:
SCons.Tool.CreateLibSymlinks(env, symlinks)
return
@@ -244,12 +244,10 @@ def add_versioned_targets_to_INSTALLED_FILES(target, source, env):
Verbose = False
_INSTALLED_FILES.extend(target)
if Verbose:
- print "add_versioned_targets_to_INSTALLED_FILES: target=%r" % map(str, target)
-
+ print("add_versioned_targets_to_INSTALLED_FILES: target={:r}".format(map(str, target)))
symlinks = listShlibLinksToInstall(target[0], source, env)
if symlinks:
SCons.Tool.EmitLibSymlinks(env, symlinks, target[0])
-
_UNIQUE_INSTALLED_FILES = None
return (target, source)
diff --git a/src/engine/SCons/Tool/intelc.py b/src/engine/SCons/Tool/intelc.py
index c28532c..185db9e 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__"
@@ -245,17 +245,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:
@@ -486,8 +485,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 a4a2a4c..ae2c4b8 100644
--- a/src/engine/SCons/Tool/link.py
+++ b/src/engine/SCons/Tool/link.py
@@ -1,3 +1,4 @@
+
"""SCons.Tool.link
Tool-specific initialization for the generic Posix linker.
@@ -30,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__"
@@ -44,8 +46,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
@@ -76,20 +77,20 @@ def smart_link(source, target, env, for_signature):
def _lib_emitter(target, source, env, **kw):
Verbose = False
if Verbose:
- print "_lib_emitter: target[0]=%r" % target[0].get_path()
+ print("_lib_emitter: target[0]={:r}".format(target[0].get_path()))
for tgt in target:
tgt.attributes.shared = 1
-
+
try:
symlink_generator = kw['symlink_generator']
except KeyError:
pass
else:
if Verbose:
- print "_lib_emitter: symlink_generator=%r" % symlink_generator
+ print("_lib_emitter: symlink_generator={:r}".format(symlink_generator))
symlinks = symlink_generator(env, target[0])
if Verbose:
- print "_lib_emitter: symlinks=%r" % symlinks
+ print("_lib_emitter: symlinks={:r}".format(symlinks))
if symlinks:
SCons.Tool.EmitLibSymlinks(env, symlinks, target[0])
@@ -108,28 +109,28 @@ def _versioned_lib_name(env, libnode, version, prefix, suffix, prefix_generator,
Verbose = False
if Verbose:
- print "_versioned_lib_name: libnode=%r" % libnode.get_path()
- print "_versioned_lib_name: version=%r" % version
- print "_versioned_lib_name: prefix=%r" % prefix
- print "_versioned_lib_name: suffix=%r" % suffix
- print "_versioned_lib_name: suffix_generator=%r" % suffix_generator
+ print("_versioned_lib_name: libnode={:r}".format(libnode.get_path()))
+ print("_versioned_lib_name: version={:r}".format(version))
+ print("_versioned_lib_name: prefix={:r}".format(prefix))
+ print("_versioned_lib_name: suffix={:r}".format(suffix))
+ print("_versioned_lib_name: suffix_generator={:r}".format(suffix_generator))
versioned_name = os.path.basename(libnode.get_path())
if Verbose:
- print "_versioned_lib_name: versioned_name=%r" % versioned_name
+ print("_versioned_lib_name: versioned_name={:r}".format(versioned_name))
versioned_prefix = prefix_generator(env, **kw)
versioned_suffix = suffix_generator(env, **kw)
if Verbose:
- print "_versioned_lib_name: versioned_prefix=%r" % versioned_prefix
- print "_versioned_lib_name: versioned_suffix=%r" % versioned_suffix
+ print("_versioned_lib_name: versioned_prefix={:r}".format(versioned_prefix))
+ print("_versioned_lib_name: versioned_suffix={:r}".format(versioned_suffix))
versioned_prefix_re = '^' + re.escape(versioned_prefix)
versioned_suffix_re = re.escape(versioned_suffix) + '$'
name = re.sub(versioned_prefix_re, prefix, versioned_name)
name = re.sub(versioned_suffix_re, suffix, name)
if Verbose:
- print "_versioned_lib_name: name=%r" % name
+ print("_versioned_lib_name: name={:r}".format(name))
return name
def _versioned_shlib_name(env, libnode, version, prefix, suffix, **kw):
@@ -146,33 +147,33 @@ def _versioned_lib_suffix(env, suffix, version):
"""For suffix='.so' and version='0.1.2' it returns '.so.0.1.2'"""
Verbose = False
if Verbose:
- print "_versioned_lib_suffix: suffix=%r" % suffix
- print "_versioned_lib_suffix: version=%r" % version
+ print("_versioned_lib_suffix: suffix={:r}".format(suffix))
+ print("_versioned_lib_suffix: version={:r}".format(version))
if not suffix.endswith(version):
suffix = suffix + '.' + version
if Verbose:
- print "_versioned_lib_suffix: return suffix=%r" % suffix
+ print("_versioned_lib_suffix: return suffix={:r}".format(suffix))
return suffix
def _versioned_lib_soname(env, libnode, version, prefix, suffix, name_func):
"""For libnode='/optional/dir/libfoo.so.X.Y.Z' it returns 'libfoo.so.X'"""
Verbose = False
if Verbose:
- print "_versioned_lib_soname: version=%r" % version
+ print("_versioned_lib_soname: version={:r}".format(version))
name = name_func(env, libnode, version, prefix, suffix)
if Verbose:
- print "_versioned_lib_soname: name=%r" % name
+ print("_versioned_lib_soname: name={:r}".format(name))
major = version.split('.')[0]
soname = name + '.' + major
if Verbose:
- print "_versioned_lib_soname: soname=%r" % soname
+ print("_versioned_lib_soname: soname={:r}".format(soname))
return soname
def _versioned_shlib_soname(env, libnode, version, prefix, suffix):
- return _versioned_lib_soname(env, libnode, version, prefix, suffix, _versioned_shlib_name)
+ return _versioned_lib_soname(env, libnode, version, prefix, suffix, _versioned_shlib_name)
def _versioned_ldmod_soname(env, libnode, version, prefix, suffix):
- return _versioned_lib_soname(env, libnode, version, prefix, suffix, _versioned_ldmod_name)
+ return _versioned_lib_soname(env, libnode, version, prefix, suffix, _versioned_ldmod_name)
def _versioned_lib_symlinks(env, libnode, version, prefix, suffix, name_func, soname_func):
"""Generate link names that should be created for a versioned shared lirbrary.
@@ -181,23 +182,23 @@ def _versioned_lib_symlinks(env, libnode, version, prefix, suffix, name_func, so
Verbose = False
if Verbose:
- print "_versioned_lib_symlinks: libnode=%r" % libnode.get_path()
- print "_versioned_lib_symlinks: version=%r" % version
+ print("_versioned_lib_symlinks: libnode={:r}".format(libnode.get_path()))
+ print("_versioned_lib_symlinks: version={:r}".format(version))
if sys.platform.startswith('openbsd'):
# OpenBSD uses x.y shared library versioning numbering convention
# and doesn't use symlinks to backwards-compatible libraries
if Verbose:
- print "_versioned_lib_symlinks: return symlinks=%r" % None
+ print("_versioned_lib_symlinks: return symlinks={:r}".format(None))
return None
linkdir = libnode.get_dir()
if Verbose:
- print "_versioned_lib_symlinks: linkdir=%r" % linkdir.get_path()
+ print("_versioned_lib_symlinks: linkdir={:r}".format(linkdir.get_path()))
name = name_func(env, libnode, version, prefix, suffix)
if Verbose:
- print "_versioned_lib_symlinks: name=%r" % name
+ print("_versioned_lib_symlinks: name={:r}".format(name))
soname = soname_func(env, libnode, version, prefix, suffix)
@@ -213,7 +214,7 @@ def _versioned_lib_symlinks(env, libnode, version, prefix, suffix, name_func, so
symlinks = [ (link0, libnode), (link1, libnode) ]
if Verbose:
- print "_versioned_lib_symlinks: return symlinks=%r" % SCons.Tool.StringizeLibSymlinks(symlinks)
+ print("_versioned_lib_symlinks: return symlinks={:r}".format(SCons.Tool.StringizeLibSymlinks(symlinks)))
return symlinks
@@ -247,7 +248,7 @@ def _setup_versioned_lib_variables(env, **kw):
except KeyError: pass
use_soname = False
- try: use_soname = kw['use_soname']
+ try: use_soname = kw['use_soname']
except KeyError: pass
# The $_SHLIBVERSIONFLAGS define extra commandline flags used when
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 2453979..c5a7a32 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 74c20d0..55cf33f 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:
@@ -191,7 +192,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)
@@ -203,7 +204,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
@@ -220,10 +221,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):
@@ -234,10 +235,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 878ec6e..f894562 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 113f859..6df4928 100644
--- a/src/engine/SCons/Tool/msvs.py
+++ b/src/engine/SCons/Tool/msvs.py
@@ -30,6 +30,8 @@ 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__"
import SCons.compat
@@ -38,7 +40,6 @@ import base64
import hashlib
import ntpath
import os
-# compat layer imports "cPickle" for us if it's available.
import pickle
import re
import sys
@@ -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
##############################################################################
@@ -70,7 +71,7 @@ def xmlify(s):
# Returns a tuple of nodes.
def processIncludes(includes, env, target, source):
return SCons.PathList.PathList(includes).subst_path(env, target, source)
-
+
external_makefile_guid = '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}'
@@ -168,15 +169,15 @@ class _UserGenerator(object):
Base class for .dsp.user file generator
'''
# Default instance values.
- # Ok ... a bit defensive, but it does not seem reasonable to crash the
+ # Ok ... a bit defensive, but it does not seem reasonable to crash the
# build for a workspace user file. :-)
usrhead = None
- usrdebg = None
+ usrdebg = None
usrconf = None
- createfile = False
+ createfile = False
def __init__(self, dspfile, source, env):
# DebugSettings should be a list of debug dictionary sorted in the same order
- # as the target list and variants
+ # as the target list and variants
if 'variant' not in env:
raise SCons.Errors.InternalError("You must specify a 'variant' argument (i.e. 'Debug' or " +\
"'Release') to create an MSVSProject.")
@@ -184,7 +185,7 @@ class _UserGenerator(object):
variants = [env['variant']]
elif SCons.Util.is_List(env['variant']):
variants = env['variant']
-
+
if 'DebugSettings' not in env or env['DebugSettings'] == None:
dbg_settings = []
elif SCons.Util.is_Dict(env['DebugSettings']):
@@ -200,12 +201,12 @@ class _UserGenerator(object):
dbg_settings.append({})
else:
dbg_settings = []
-
+
if len(dbg_settings) == 1:
dbg_settings = dbg_settings * len(variants)
-
+
self.createfile = self.usrhead and self.usrdebg and self.usrconf and \
- dbg_settings and bool([ds for ds in dbg_settings if ds])
+ dbg_settings and bool([ds for ds in dbg_settings if ds])
if self.createfile:
dbg_settings = dict(zip(variants, dbg_settings))
@@ -215,22 +216,22 @@ class _UserGenerator(object):
for key in [k for k in self.usrdebg.keys() if k in src]:
trg[key] = str(src[key])
self.configs[var].debug = trg
-
+
def UserHeader(self):
encoding = self.env.subst('$MSVSENCODING')
versionstr = self.versionstr
self.usrfile.write(self.usrhead % locals())
-
+
def UserProject(self):
pass
-
+
def Build(self):
if not self.createfile:
return
try:
filename = self.dspabs +'.user'
self.usrfile = open(filename, 'w')
- except IOError, detail:
+ except IOError as detail:
raise SCons.Errors.InternalError('Unable to open "' + filename + '" for writing:' + str(detail))
else:
self.UserHeader()
@@ -290,7 +291,7 @@ class _GenerateV7User(_UserGenerator):
self.usrconf = V9UserConfiguration
self.usrdebg = V9DebugSettings
_UserGenerator.__init__(self, dspfile, source, env)
-
+
def UserProject(self):
confkeys = sorted(self.configs.keys())
for kind in confkeys:
@@ -298,8 +299,8 @@ class _GenerateV7User(_UserGenerator):
platform = self.configs[kind].platform
debug = self.configs[kind].debug
if debug:
- debug_settings = '\n'.join(['\t\t\t\t%s="%s"' % (key, xmlify(value))
- for key, value in debug.items()
+ debug_settings = '\n'.join(['\t\t\t\t%s="%s"' % (key, xmlify(value))
+ for key, value in debug.items()
if value is not None])
self.usrfile.write(self.usrconf % locals())
self.usrfile.write('\t</Configurations>\n</VisualStudioUserFile>')
@@ -345,7 +346,7 @@ V10DebugSettings = {
class _GenerateV10User(_UserGenerator):
"""Generates a Project'user file for MSVS 2010"""
-
+
def __init__(self, dspfile, source, env):
self.versionstr = '4.0'
self.usrhead = V10UserHeader
@@ -360,8 +361,8 @@ class _GenerateV10User(_UserGenerator):
platform = self.configs[kind].platform
debug = self.configs[kind].debug
if debug:
- debug_settings = '\n'.join(['\t\t<%s>%s</%s>' % (key, xmlify(value), key)
- for key, value in debug.items()
+ debug_settings = '\n'.join(['\t\t<%s>%s</%s>' % (key, xmlify(value), key)
+ for key, value in debug.items()
if value is not None])
self.usrfile.write(self.usrconf % locals())
self.usrfile.write('</Project>')
@@ -457,7 +458,7 @@ class _DSPGenerator(object):
runfile.append(s)
self.sconscript = env['MSVSSCONSCRIPT']
-
+
if 'cmdargs' not in env or env['cmdargs'] == None:
cmdargs = [''] * len(variants)
elif SCons.Util.is_String(env['cmdargs']):
@@ -467,7 +468,7 @@ class _DSPGenerator(object):
raise SCons.Errors.InternalError("Sizes of 'cmdargs' and 'variant' lists must be the same.")
else:
cmdargs = env['cmdargs']
-
+
self.env = env
if 'name' in self.env:
@@ -525,7 +526,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[i])
@@ -725,7 +726,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()
@@ -817,7 +818,7 @@ class _GenerateV7DSP(_DSPGenerator, _GenerateV7User):
self.dspheader = V7DSPHeader
self.dspconfiguration = V7DSPConfiguration
self.file = None
-
+
_GenerateV7User.__init__(self, dspfile, source, env)
def PrintHeader(self):
@@ -894,7 +895,7 @@ class _GenerateV7DSP(_DSPGenerator, _GenerateV7User):
preprocdefs = xmlify(';'.join(processDefines(self.env.get('CPPDEFINES', []))))
includepath_Dirs = processIncludes(self.env.get('CPPPATH', []), self.env, None, None)
includepath = xmlify(';'.join([str(x) for x in includepath_Dirs]))
-
+
if not env_has_buildtarget:
del self.env['MSVSBUILDTARGET']
@@ -1037,13 +1038,13 @@ class _GenerateV7DSP(_DSPGenerator, _GenerateV7User):
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()
self.PrintProject()
self.file.close()
-
+
_GenerateV7User.Build(self)
V10DSPHeader = """\
@@ -1100,7 +1101,7 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
self.dspheader = V10DSPHeader
self.dspconfiguration = V10DSPProjectConfiguration
self.dspglobals = V10DSPGlobals
-
+
_GenerateV10User.__init__(self, dspfile, source, env)
def PrintHeader(self):
@@ -1131,27 +1132,27 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
'\t\t<SccLocalPath>%s</SccLocalPath>\n' % (scc_project_name, scc_local_path_legacy))
else:
self.dspglobals = self.dspglobals.replace('%(scc_attrs)s', '')
-
+
self.file.write(self.dspheader % locals())
-
+
self.file.write('\t<ItemGroup Label="ProjectConfigurations">\n')
-
+
confkeys = sorted(self.configs.keys())
for kind in confkeys:
variant = self.configs[kind].variant
platform = self.configs[kind].platform
self.file.write(self.dspconfiguration % locals())
-
+
self.file.write('\t</ItemGroup>\n')
-
+
self.file.write(self.dspglobals % locals())
-
+
def PrintProject(self):
name = self.name
confkeys = sorted(self.configs.keys())
-
+
self.file.write('\t<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />\n')
-
+
toolset = ''
if 'MSVC_VERSION' in self.env:
version_num, suite = msvs_parse_version(self.env['MSVC_VERSION'])
@@ -1164,16 +1165,16 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
self.file.write('\t<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />\n')
self.file.write('\t<ImportGroup Label="ExtensionSettings">\n')
self.file.write('\t</ImportGroup>\n')
-
+
for kind in confkeys:
variant = self.configs[kind].variant
platform = self.configs[kind].platform
self.file.write(V10DSPImportGroupCondition % locals())
-
+
self.file.write('\t<PropertyGroup Label="UserMacros" />\n')
self.file.write('\t<PropertyGroup>\n')
self.file.write('\t<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>\n')
-
+
for kind in confkeys:
variant = self.configs[kind].variant
platform = self.configs[kind].platform
@@ -1181,7 +1182,7 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
buildtarget = self.configs[kind].buildtarget
runfile = self.configs[kind].runfile
cmdargs = self.configs[kind].cmdargs
-
+
env_has_buildtarget = 'MSVSBUILDTARGET' in self.env
if not env_has_buildtarget:
self.env['MSVSBUILDTARGET'] = buildtarget
@@ -1206,29 +1207,29 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
del self.env['MSVSBUILDTARGET']
self.file.write(V10DSPCommandLine % locals())
-
+
self.file.write('\t</PropertyGroup>\n')
-
+
#filter settings in MSVS 2010 are stored in separate file
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'
'<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n')
-
+
self.PrintSourceFiles()
-
+
self.filters_file.write('</Project>')
self.filters_file.close()
-
+
self.file.write('\t<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />\n'
'\t<ImportGroup Label="ExtensionTargets">\n'
'\t</ImportGroup>\n'
'</Project>\n')
-
+
if self.nokeep == 0:
# now we pickle some data and add it to the file -- MSDEV will ignore it.
pdata = pickle.dumps(self.configs,1)
@@ -1240,7 +1241,7 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
def printFilters(self, hierarchy, name):
sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())
-
+
for key, value in sorteditems:
if SCons.Util.is_Dict(value):
filter_name = name + '\\' + key
@@ -1248,14 +1249,14 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
'\t\t\t<UniqueIdentifier>%s</UniqueIdentifier>\n'
'\t\t</Filter>\n' % (filter_name, _generateGUID(self.dspabs, filter_name)))
self.printFilters(value, filter_name)
-
+
def printSources(self, hierarchy, kind, commonprefix, filter_name):
keywords = {'Source Files': 'ClCompile',
'Header Files': 'ClInclude',
'Local Headers': 'ClInclude',
'Resource Files': 'None',
'Other Files': 'None'}
-
+
sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())
# First folders, then files
@@ -1269,7 +1270,7 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
if commonprefix:
file = os.path.join(commonprefix, value)
file = os.path.normpath(file)
-
+
self.file.write('\t\t<%s Include="%s" />\n' % (keywords[kind], file))
self.filters_file.write('\t\t<%s Include="%s">\n'
'\t\t\t<Filter>%s</Filter>\n'
@@ -1281,10 +1282,10 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
'Local Headers': 'h;hpp;hxx;hm;inl',
'Resource Files': 'r;rc;ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe',
'Other Files': ''}
-
+
cats = sorted([k for k in categories.keys() if self.sources[k]],
key = lambda a: a.lower())
-
+
# print vcxproj.filters file first
self.filters_file.write('\t<ItemGroup>\n')
for kind in cats:
@@ -1292,7 +1293,7 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
'\t\t\t<UniqueIdentifier>{7b42d31d-d53c-4868-8b92-ca2bc9fc052f}</UniqueIdentifier>\n'
'\t\t\t<Extensions>%s</Extensions>\n'
'\t\t</Filter>\n' % (kind, categories[kind]))
-
+
# First remove any common prefix
sources = self.sources[kind]
commonprefix = None
@@ -1305,17 +1306,17 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
# +1 because the filename starts after the separator
sources = [s[len(cp)+1:] for s in sources]
commonprefix = cp
-
+
hierarchy = makeHierarchy(sources)
self.printFilters(hierarchy, kind)
-
+
self.filters_file.write('\t</ItemGroup>\n')
-
+
# then print files and filters
for kind in cats:
self.file.write('\t<ItemGroup>\n')
self.filters_file.write('\t<ItemGroup>\n')
-
+
# First remove any common prefix
sources = self.sources[kind]
commonprefix = None
@@ -1328,13 +1329,13 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
# +1 because the filename starts after the separator
sources = [s[len(cp)+1:] for s in sources]
commonprefix = cp
-
+
hierarchy = makeHierarchy(sources)
self.printSources(hierarchy, kind, commonprefix, kind)
-
+
self.file.write('\t</ItemGroup>\n')
self.filters_file.write('\t</ItemGroup>\n')
-
+
# add the SConscript file outside of the groups
self.file.write('\t<ItemGroup>\n'
'\t\t<None Include="%s" />\n'
@@ -1342,18 +1343,18 @@ class _GenerateV10DSP(_DSPGenerator, _GenerateV10User):
'\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()
self.PrintProject()
self.file.close()
-
+
_GenerateV10User.Build(self)
class _DSWGenerator(object):
@@ -1428,7 +1429,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 " +\
@@ -1461,7 +1462,7 @@ class _GenerateV7DSW(_DSWGenerator):
'SLN_RELATIVE_FOLDER_PATH': dsp_relative_folder_path,
'SLN_RELATIVE_FILE_PATH': dsp_relative_file_path}
self.dspfiles_info.append(dspfile_info)
-
+
self.dspfiles_info = []
GenerateProjectFilesInfo(self)
@@ -1507,7 +1508,7 @@ class _GenerateV7DSW(_DSWGenerator):
self.file.write('# Visual Studio 2008\n')
elif self.version_num >= 8.0:
self.file.write('# Visual Studio 2005\n')
-
+
for dspinfo in self.dspfiles_info:
name = dspinfo['NAME']
base, suffix = SCons.Util.splitext(name)
@@ -1612,7 +1613,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()
@@ -1661,7 +1662,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()
@@ -1718,8 +1719,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())
@@ -1734,8 +1735,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())
@@ -1969,7 +1970,7 @@ def generate(env):
else:
env['MSVS']['PROJECTSUFFIX'] = '.vcxproj'
env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
-
+
if (version_num >= 10.0):
env['MSVSENCODING'] = 'utf-8'
else:
diff --git a/src/engine/SCons/Tool/msvsTests.py b/src/engine/SCons/Tool/msvsTests.py
index 261dbcc..2bd640f 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__"
@@ -827,7 +828,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 0f9a93d..1a95abe 100644
--- a/src/engine/SCons/Tool/packaging/__init__.py
+++ b/src/engine/SCons/Tool/packaging/__init__.py
@@ -119,7 +119,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))
@@ -140,7 +140,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
@@ -156,10 +156,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 41b7ab7..c25f856 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 0750113..a132555 100644
--- a/src/engine/SCons/Tool/packaging/rpm.py
+++ b/src/engine/SCons/Tool/packaging/rpm.py
@@ -101,7 +101,7 @@ def collectintargz(target, source, env):
tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
try:
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,
@@ -136,7 +136,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] )
@@ -324,7 +324,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
@@ -335,7 +335,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 7bc0ef6..f01fff6 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 680af03..39d9ec2 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 3a5a3cc..fa86174 100644
--- a/src/engine/SCons/Tool/swig.py
+++ b/src/engine/SCons/Tool/swig.py
@@ -7,6 +7,7 @@ It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
+from __future__ import print_function
#
# __COPYRIGHT__
@@ -140,13 +141,14 @@ def _get_swig_version(env, swig):
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
+ # MAYBE: out = SCons.Util.to_str (pipe.stdout.read())
out = pipe.stdout.read()
match = re.search(r'SWIG Version\s+(\S+).*', out, re.MULTILINE)
if match:
- if verbose: print "Version is:%s"%match.group(1)
+ if verbose: print("Version is:%s"%match.group(1))
return match.group(1)
else:
- if verbose: print "Unable to detect version: [%s]"%out
+ if verbose: print("Unable to detect version: [%s]"%out)
def generate(env):
"""Add Builders and construction variables for swig to an Environment."""
diff --git a/src/engine/SCons/Tool/tex.py b/src/engine/SCons/Tool/tex.py
index 3d429c9..85bd41f 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)
@@ -765,7 +766,7 @@ def tex_emitter_core(target, source, env, graphics_extensions):
else:
env['ENV']['TEXINPUTS'] = savedpath
if Verbose:
- print "search path ",paths
+ print("search path ",paths)
# scan all sources for side effect files
aux_files = []
@@ -774,7 +775,7 @@ def tex_emitter_core(target, source, env, graphics_extensions):
for (theSearch,suffix_list) in file_tests:
# add side effects if feature is present.If file is to be generated,add all side effects
if Verbose and theSearch:
- print "check side effects for ",suffix_list[-1]
+ print("check side effects for ",suffix_list[-1])
if (theSearch != None) or (not source[0].exists() ):
file_list = [targetbase,]
# for bibunit we need a list of files
@@ -788,11 +789,11 @@ def tex_emitter_core(target, source, env, graphics_extensions):
if suffix_list[-1] == 'multibib':
for multibibmatch in multibib_re.finditer(content):
if Verbose:
- print "multibib match ",multibibmatch.group(1)
+ print("multibib match ",multibibmatch.group(1))
if multibibmatch != None:
baselist = multibibmatch.group(1).split(',')
if Verbose:
- print "multibib list ", baselist
+ print("multibib list ", baselist)
for i in range(len(baselist)):
file_list.append(os.path.join(targetdir, baselist[i]))
# now define the side effects
@@ -800,14 +801,14 @@ def tex_emitter_core(target, source, env, graphics_extensions):
for suffix in suffix_list[:-1]:
env.SideEffect(file_name + suffix,target[0])
if Verbose:
- print "side effect tst :",file_name + suffix, " target is ",str(target[0])
+ print("side effect tst :",file_name + suffix, " target is ",str(target[0]))
env.Clean(target[0],file_name + suffix)
for aFile in aux_files:
aFile_base = SCons.Util.splitext(aFile)[0]
env.SideEffect(aFile_base + '.aux',target[0])
if Verbose:
- print "side effect aux :",aFile_base + '.aux'
+ print("side effect aux :",aFile_base + '.aux')
env.Clean(target[0],aFile_base + '.aux')
# read fls file to get all other files that latex creates and will read on the next pass
# remove files from list that we explicitly dealt with above
@@ -820,7 +821,7 @@ def tex_emitter_core(target, source, env, graphics_extensions):
out_files.remove(filename)
env.SideEffect(out_files,target[0])
if Verbose:
- print "side effect fls :",out_files
+ print("side effect fls :",out_files)
env.Clean(target[0],out_files)
return (target, source)
@@ -840,7 +841,7 @@ def generate(env):
generate_common(env)
- import dvi
+ from . import dvi
dvi.generate(env)
bld = env['BUILDERS']['DVI']
@@ -853,7 +854,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 76efbd7..e79badf 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 b8a88dc..e9b49b7 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
@@ -32,19 +32,19 @@ class _CmdRunner(object):
variables. It also provides `strfunction()` method, which shall be used by
scons Action objects to print command string. """
- def __init__( self, command, commandstr = None):
+ def __init__(self, command, commandstr = None):
self.out = None
self.err = None
self.status = None
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 +55,8 @@ 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(unicode(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 writing " + 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 7bcd6e2..0be6196 100644
--- a/src/engine/SCons/Util.py
+++ b/src/engine/SCons/Util.py
@@ -32,16 +32,36 @@ import copy
import re
import types
-from collections import UserDict, UserList, UserString
+try:
+ from UserDict import UserDict
+except ImportError as e:
+ from collections import UserDict
+
+try:
+ from UserList import UserList
+except ImportError as e:
+ from collections import UserList
+
+try:
+ from UserString import UserString
+except ImportError as e:
+ from collections 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
+
+# Below not used?
+# InstanceType = types.InstanceType
+
MethodType = types.MethodType
FunctionType = types.FunctionType
-try: unicode
-except NameError: UnicodeType = None
-else: UnicodeType = unicode
+
+try:
+ unicode
+except NameError:
+ UnicodeType = str
+else:
+ UnicodeType = unicode
def dictify(keys, values, result={}):
for k, v in zip(keys, values):
@@ -114,6 +134,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 +176,7 @@ class DisplayEngine(object):
return
if append_newline: text = text + '\n'
try:
- sys.stdout.write(unicode(text))
+ sys.stdout.write(UnicodeType(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
@@ -228,7 +251,7 @@ def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None):
"""
rname = str(root)
-
+
# Initialize 'visited' dict, if required
if visited is None:
visited = {}
@@ -311,11 +334,17 @@ SequenceTypes = (list, tuple, UserList)
# Note that profiling data shows a speed-up when comparing
# explicitly 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 explicitly 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)
@@ -341,7 +370,7 @@ def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes
# assumes that the obj argument is a string most 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):
@@ -349,7 +378,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.
@@ -367,7 +396,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.
@@ -388,7 +417,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):
@@ -401,11 +430,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
@@ -421,7 +450,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
@@ -479,7 +508,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
@@ -527,10 +556,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
@@ -725,7 +754,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:
@@ -733,7 +762,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
@@ -752,7 +781,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.
"""
@@ -774,7 +803,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
@@ -815,7 +844,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
@@ -833,7 +862,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.
"""
@@ -1206,11 +1235,11 @@ def logical_lines(physical_lines, joiner=''.join):
class LogicalLines(object):
""" Wrapper class for the logical_lines method.
-
+
Allows us to read all "logical" lines at once from a
given file object.
"""
-
+
def __init__(self, fileobj):
self.fileobj = fileobj
@@ -1377,8 +1406,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()
@@ -1391,26 +1421,28 @@ 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__))
+ 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))
+ 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
@@ -1432,7 +1464,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):
@@ -1442,10 +1474,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.
@@ -1494,6 +1526,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):
@@ -1516,6 +1550,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 9f80e86..9ebb924 100644
--- a/src/engine/SCons/UtilTests.py
+++ b/src/engine/SCons/UtilTests.py
@@ -195,16 +195,16 @@ class UtilTestCase(unittest.TestCase):
print_tree(node, get_children, showtags=1)
actual = sys.stdout.getvalue()
assert withtags == actual, (withtags, actual)
-
+
# Test that explicitly setting prune to zero works
# the same as the default (see above)
node, expect, withtags = self.tree_case_2(prune=0)
-
+
sys.stdout = io.StringIO()
print_tree(node, get_children, 0)
actual = sys.stdout.getvalue()
assert expect == actual, (expect, actual)
-
+
sys.stdout = io.StringIO()
print_tree(node, get_children, 0, showtags=1)
actual = sys.stdout.getvalue()
@@ -249,7 +249,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([])
@@ -265,12 +265,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):
@@ -296,7 +296,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."""
@@ -343,10 +343,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']
@@ -732,9 +732,7 @@ bling \
bling \ bling
bling
"""
- # Python 2.7 and beyond require unicode strings.
fobj = io.StringIO(unicode(content))
-
lines = LogicalLines(fobj).readlines()
assert lines == [
'\n',
@@ -746,8 +744,8 @@ bling
def test_intern(self):
s1 = silent_intern("spam")
- # Python 3.x does not have a unicode() global function
- if sys.version[0] == '2':
+ # TODO: Python 3.x does not have a unicode() global function
+ if sys.version[0] == '2':
s2 = silent_intern(unicode("unicode spam"))
s3 = silent_intern(42)
s4 = silent_intern("spam")
@@ -760,7 +758,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 50f7d13..7f2a978 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 10f9cb2..b03e5b5 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):
@@ -175,7 +175,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]
@@ -211,7 +211,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))
@@ -273,7 +273,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 5f94df2..0ddbdd5 100644
--- a/src/engine/SCons/compat/__init__.py
+++ b/src/engine/SCons/compat/__init__.py
@@ -82,17 +82,19 @@ def rename_module(new, old):
except ImportError:
return False
+# TODO: FIXME
# In 3.x, 'pickle' automatically loads the fast version if available.
rename_module('pickle', 'cPickle')
+# TODO: FIXME
# In 3.x, 'profile' automatically loads the fast version if available.
rename_module('profile', 'cProfile')
-
+# TODO: FIXME
# Before Python 3.0, the 'queue' module was named 'Queue'.
rename_module('queue', 'Queue')
-
+# TODO: FIXME
# Before Python 3.0, the 'winreg' module was named '_winreg'
rename_module('winreg', '_winreg')
diff --git a/src/engine/SCons/cppTests.py b/src/engine/SCons/cppTests.py
index 9f4b875..40236e4 100644
--- a/src/engine/SCons/cppTests.py
+++ b/src/engine/SCons/cppTests.py
@@ -21,6 +21,8 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
+from __future__ import absolute_import
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import atexit
diff --git a/src/engine/SCons/dblite.py b/src/engine/SCons/dblite.py
index 707a4f8..b12d320 100644
--- a/src/engine/SCons/dblite.py
+++ b/src/engine/SCons/dblite.py
@@ -1,10 +1,10 @@
# dblite.py module contributed by Ralf W. Grosse-Kunstleve.
# Extended for Unicode by Steven Knight.
+from __future__ import print_function
import SCons.compat
import os
-# compat layer imports "cPickle" for us if it's available.
import pickle
import shutil
import time
@@ -13,7 +13,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:
@@ -22,13 +22,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):
@@ -76,7 +79,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))
@@ -89,7 +92,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)
@@ -124,7 +127,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)
@@ -150,10 +153,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())
@@ -173,7 +176,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():
@@ -200,7 +203,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.")
@@ -210,13 +213,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")
@@ -240,11 +243,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 02168d8..ebdaf08 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__"
@@ -66,8 +65,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):
@@ -103,7 +102,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:
@@ -116,15 +115,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 ]
@@ -210,8 +209,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())
@@ -226,7 +225,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()
@@ -497,7 +496,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)
@@ -507,7 +506,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 = {}
@@ -647,7 +646,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)
@@ -708,7 +707,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)
@@ -813,7 +812,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)
@@ -846,13 +845,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':
@@ -1190,7 +1189,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 1b9a824..1cf9469 100644
--- a/src/script/scons.py
+++ b/src/script/scons.py
@@ -23,6 +23,8 @@
# 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__"
__version__ = "__VERSION__"
@@ -56,11 +58,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]
@@ -98,7 +100,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:
@@ -191,7 +193,7 @@ if __name__ == "__main__":
except ImportError:
print("SCons import failed. Unable to find engine files in:")
for path in libs:
- print(" %s" % path)
+ print(" {}".format(path))
raise
# this does all the work, and calls sys.exit
diff --git a/src/script/sconsign.py b/src/script/sconsign.py
index c95bf74..e046a2c 100644
--- a/src/script/sconsign.py
+++ b/src/script/sconsign.py
@@ -23,6 +23,8 @@
# 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__"
__version__ = "__VERSION__"
@@ -95,7 +97,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:
@@ -182,9 +184,12 @@ sys.path = libs + sys.path
# END STANDARD SCons SCRIPT HEADER
##############################################################################
-import SCons.compat # so pickle will import cPickle instead
+import SCons.compat
import whichdb
+
+# was added for py3, but breaks py2 on windows..
+#import dbm
import time
import pickle
import imp
@@ -202,9 +207,15 @@ def my_whichdb(filename):
pass
return _orig_whichdb(filename)
+
+# Should work on python2
_orig_whichdb = whichdb.whichdb
whichdb.whichdb = my_whichdb
+# was changed for python3
+#_orig_whichdb = whichdb.whichdb
+#dbm.whichdb = my_whichdb
+
def my_import(mname):
if '.' in mname:
i = mname.rfind('.')
@@ -323,14 +334,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:
@@ -343,9 +354,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()):
@@ -353,9 +364,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):
@@ -374,7 +385,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,
@@ -388,7 +399,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
@@ -399,7 +410,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
@@ -416,13 +427,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:
@@ -432,7 +443,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])
@@ -494,13 +505,13 @@ for o, a in opts:
SCons.dblite.ignore_corrupt_dbfiles = 0
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
@@ -520,6 +531,8 @@ if Do_Call:
Do_Call(a)
else:
for a in args:
+ # changed for py3 compat, broke py2 on windows
+ # dbm_name = dbm.whichdb(a)
dbm_name = whichdb.whichdb(a)
if dbm_name:
Map_Module = {'SCons.dblite' : 'dblite'}
diff --git a/src/setup.py b/src/setup.py
index 91b7752..9a02b25 100644
--- a/src/setup.py
+++ b/src/setup.py
@@ -32,6 +32,8 @@ NOTE: Installed SCons is not importable like usual Python packages. It is
below is dedicated to make it happen on various platforms.
"""
+from __future__ import print_function
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os
@@ -46,14 +48,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..b81ef3f 100644
--- a/src/test_interrupts.py
+++ b/src/test_interrupts.py
@@ -21,6 +21,8 @@
# 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,9 +131,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()
diff --git a/test/ARGLIST.py b/test/ARGLIST.py
index 186ad06..e246ba3 100644
--- a/test/ARGLIST.py
+++ b/test/ARGLIST.py
@@ -31,7 +31,7 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
i = 0
for key, value in ARGLIST:
- print "%d: %s = %s" % (i, key, value)
+ print("%d: %s = %s" % (i, key, value))
i = i + 1
""")
diff --git a/test/Actions/actions.py b/test/Actions/actions.py
index 03d67a0..785a0cb 100644
--- a/test/Actions/actions.py
+++ b/test/Actions/actions.py
@@ -70,7 +70,7 @@ import os
def func(env, target, source):
cmd = r'%(_python_)s build.py %%s 3 %%s' %% (' '.join(map(str, target)),
' '.join(map(str, source)))
- print cmd
+ print(cmd)
return os.system(cmd)
B = Builder(action = func)
env = Environment(BUILDERS = { 'B' : B })
@@ -91,7 +91,7 @@ class bld(object):
self.cmd = r'%(_python_)s build.py %%s 4 %%s'
def __call__(self, env, target, source):
cmd = self.get_contents(env, target, source)
- print cmd
+ print(cmd)
return os.system(cmd)
def get_contents(self, env, target, source):
return self.cmd %% (' '.join(map(str, target)),
@@ -114,9 +114,9 @@ def func(env, target, source):
env = Environment(S = Action('foo'),
F = Action(func),
L = Action(['arg1', 'arg2']))
-print env.subst('$S')
-print env.subst('$F')
-print env.subst('$L')
+print(env.subst('$S'))
+print(env.subst('$F'))
+print(env.subst('$L'))
""")
test.run(arguments = '-Q .', stdout = """\
diff --git a/test/Actions/pre-post.py b/test/Actions/pre-post.py
index 38a55df..f6997e2 100644
--- a/test/Actions/pre-post.py
+++ b/test/Actions/pre-post.py
@@ -118,14 +118,14 @@ def b(target, source, env):
env1 = Environment(X='111')
env2 = Environment(X='222')
B = Builder(action = b, env = env1, multi=1)
-print "B =", B
-print "B.env =", B.env
+print("B =", B)
+print("B.env =", B.env)
env1.Append(BUILDERS = {'B' : B})
env2.Append(BUILDERS = {'B' : B})
env3 = env1.Clone(X='333')
-print "env1 =", env1
-print "env2 =", env2
-print "env3 =", env3
+print("env1 =", env1)
+print("env2 =", env2)
+print("env3 =", env3)
f1 = env1.B(File('file1.out'), [])
f2 = env2.B('file2.out', [])
f3 = env3.B('file3.out', [])
@@ -133,12 +133,12 @@ def do_nothing(env, target, source):
pass
AddPreAction(f2[0], do_nothing)
AddPostAction(f3[0], do_nothing)
-print "f1[0].builder =", f1[0].builder
-print "f2[0].builder =", f2[0].builder
-print "f3[0].builder =", f3[0].builder
-print "f1[0].env =", f1[0].env
-print "f2[0].env =", f2[0].env
-print "f3[0].env =", f3[0].env
+print("f1[0].builder =", f1[0].builder)
+print("f2[0].builder =", f2[0].builder)
+print("f3[0].builder =", f3[0].builder)
+print("f1[0].env =", f1[0].env)
+print("f2[0].env =", f2[0].env)
+print("f3[0].env =", f3[0].env)
""")
test.run(chdir='work2', arguments = '.')
diff --git a/test/Actions/unicode-signature.py b/test/Actions/unicode-signature.py
index 0d0c469..d91bfa8 100644
--- a/test/Actions/unicode-signature.py
+++ b/test/Actions/unicode-signature.py
@@ -35,12 +35,12 @@ import TestSCons
test = TestSCons.TestSCons()
-try:
- unicode
-except NameError:
- import sys
- msg = "Unicode not supported by Python version %s; skipping test\n"
- test.skip_test(msg % sys.version[:3])
+## try:
+## unicode
+## except NameError:
+## import sys
+## msg = "Unicode not supported by Python version %s; skipping test\n"
+## test.skip_test(msg % sys.version[:3])
test.write('SConstruct', """
fnode = File(u'foo.txt')
diff --git a/test/AddMethod.py b/test/AddMethod.py
index af84cb3..6049ae2 100644
--- a/test/AddMethod.py
+++ b/test/AddMethod.py
@@ -40,10 +40,10 @@ def foo(self):
AddMethod(Environment, foo)
env = Environment(FOO = '111')
-print env.foo()
+print(env.foo())
env = Environment(FOO = '222')
-print env.foo()
+print(env.foo())
env.AddMethod(foo, 'bar')
env['FOO'] = '333'
@@ -51,8 +51,8 @@ env['FOO'] = '333'
e = env.Clone()
e['FOO'] = '444'
-print env.bar()
-print e.bar()
+print(env.bar())
+print(e.bar())
""")
expect = """\
diff --git a/test/AddOption/basic.py b/test/AddOption/basic.py
index a1bb7b3..b1b8f2e 100644
--- a/test/AddOption/basic.py
+++ b/test/AddOption/basic.py
@@ -48,8 +48,8 @@ AddOption('--prefix',
f = GetOption('force')
if f:
f = "True"
-print f
-print GetOption('prefix')
+print(f)
+print(GetOption('prefix'))
""")
test.run('-Q -q .',
diff --git a/test/AddOption/help.py b/test/AddOption/help.py
index d50e595..7b886cb 100644
--- a/test/AddOption/help.py
+++ b/test/AddOption/help.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__"
@@ -57,10 +58,10 @@ lines = test.stdout().split('\n')
missing = [e for e in expected_lines if e not in lines]
if missing:
- print "====== STDOUT:"
- print test.stdout()
- print "====== Missing the following lines in the above AddOption() help output:"
- print "\n".join(missing)
+ print("====== STDOUT:")
+ print(test.stdout())
+ print("====== Missing the following lines in the above AddOption() help output:")
+ print("\n".join(missing))
test.fail_test()
test.unlink('SConstruct')
@@ -70,10 +71,10 @@ lines = test.stdout().split('\n')
unexpected = [e for e in expected_lines if e in lines]
if unexpected:
- print "====== STDOUT:"
- print test.stdout()
- print "====== Unexpected lines in the above non-AddOption() help output:"
- print "\n".join(unexpected)
+ print("====== STDOUT:")
+ print(test.stdout())
+ print("====== Unexpected lines in the above non-AddOption() help output:")
+ print("\n".join(unexpected))
test.fail_test()
test.pass_test()
diff --git a/test/AddOption/optional-arg.py b/test/AddOption/optional-arg.py
index f976ad9..b88b796 100644
--- a/test/AddOption/optional-arg.py
+++ b/test/AddOption/optional-arg.py
@@ -43,7 +43,7 @@ AddOption('--install',
type='string',
metavar='DIR',
help='installation directory')
-print GetOption('install')
+print(GetOption('install'))
""")
test.run('-Q -q',
diff --git a/test/Batch/action-changed.py b/test/Batch/action-changed.py
index dc2805a..d031432 100644
--- a/test/Batch/action-changed.py
+++ b/test/Batch/action-changed.py
@@ -54,7 +54,7 @@ sys.exit(0)
"""
test.write('build.py', build_py_contents % (python, 'one'))
-os.chmod(test.workpath('build.py'), 0755)
+os.chmod(test.workpath('build.py'), 0o755)
test.write('SConstruct', """
env = Environment()
@@ -81,7 +81,7 @@ test.must_match('f3.out', "one\nf3.in\n")
test.up_to_date(arguments = '.')
test.write('build.py', build_py_contents % (python, 'two'))
-os.chmod(test.workpath('build.py'), 0755)
+os.chmod(test.workpath('build.py'), 0o755)
test.not_up_to_date(arguments = '.')
diff --git a/test/CC/CFLAGS.py b/test/CC/CFLAGS.py
index 6ea87ad..590d6b5 100644
--- a/test/CC/CFLAGS.py
+++ b/test/CC/CFLAGS.py
@@ -32,10 +32,10 @@ test = TestSCons.TestSCons()
# Make sure CFLAGS is not passed to CXX by just expanding CXXCOM
test.write('SConstruct', """
env = Environment(CFLAGS='-xyz', CCFLAGS='-abc')
-print env.subst('$CXXCOM')
-print env.subst('$CXXCOMSTR')
-print env.subst('$SHCXXCOM')
-print env.subst('$SHCXXCOMSTR')
+print(env.subst('$CXXCOM'))
+print(env.subst('$CXXCOMSTR'))
+print(env.subst('$SHCXXCOM'))
+print(env.subst('$SHCXXCOMSTR'))
""")
test.run(arguments = '.')
test.must_not_contain_any_line(test.stdout(), ["-xyz"])
@@ -46,7 +46,7 @@ _obj = TestSCons._obj
# Test passing CFLAGS to C compiler by actually compiling programs
if sys.platform == 'win32':
import SCons.Tool.MSCommon as msc
-
+
if not msc.msvc_exists():
fooflags = '-DFOO'
barflags = '-DBAR'
diff --git a/test/CPPDEFINES/append.py b/test/CPPDEFINES/append.py
index 6e69d09..14ea7b3 100644
--- a/test/CPPDEFINES/append.py
+++ b/test/CPPDEFINES/append.py
@@ -40,17 +40,17 @@ test.write('SConstruct', """\
env_1738_2 = Environment(CPPDEFPREFIX='-D')
env_1738_2['CPPDEFINES'] = ['FOO']
env_1738_2.Append(CPPDEFINES={'value' : '1'})
-print env_1738_2.subst('$_CPPDEFFLAGS')
+print(env_1738_2.subst('$_CPPDEFFLAGS'))
#env_1738_2.Object('test_1738_2', 'main.c')
# http://scons.tigris.org/issues/show_bug.cgi?id=2300
env_2300_1 = Environment(CPPDEFINES = 'foo', CPPDEFPREFIX='-D')
env_2300_1.Append(CPPDEFINES='bar')
-print env_2300_1.subst('$_CPPDEFFLAGS')
+print(env_2300_1.subst('$_CPPDEFFLAGS'))
env_2300_2 = Environment(CPPDEFINES = ['foo'], CPPDEFPREFIX='-D') # note the list
env_2300_2.Append(CPPDEFINES='bar')
-print env_2300_2.subst('$_CPPDEFFLAGS')
+print(env_2300_2.subst('$_CPPDEFFLAGS'))
# http://scons.tigris.org/issues/show_bug.cgi?id=1152
# http://scons.tigris.org/issues/show_bug.cgi?id=2900
@@ -62,18 +62,18 @@ cases=[('string', 'FOO'),
for (t1, c1) in cases:
for (t2, c2) in cases:
- print "==== Testing CPPDEFINES, appending a %s to a %s"%(t2, t1)
- print " orig = %s, append = %s"%(c1, c2)
+ print("==== Testing CPPDEFINES, appending a %s to a %s"%(t2, t1))
+ print(" orig = %s, append = %s"%(c1, c2))
env=Environment(CPPDEFINES = c1, CPPDEFPREFIX='-D')
env.Append(CPPDEFINES = c2)
final=env.subst('$_CPPDEFFLAGS',source="src", target="tgt")
- print 'Append: \\n\\tresult=%s\\n\\tfinal=%s'%\\
- (env['CPPDEFINES'], final)
+ print('Append:\\n\\tresult=%s\\n\\tfinal=%s'%\\
+ (env['CPPDEFINES'], final))
env=Environment(CPPDEFINES = c1, CPPDEFPREFIX='-D')
env.AppendUnique(CPPDEFINES = c2)
final=env.subst('$_CPPDEFFLAGS',source="src", target="tgt")
- print 'AppendUnique:\\n\\tresult=%s\\n\\tfinal=%s'%\\
- (env['CPPDEFINES'], final)
+ print('AppendUnique:\\n\\tresult=%s\\n\\tfinal=%s'%\\
+ (env['CPPDEFINES'], final))
""")
@@ -83,7 +83,7 @@ expect_print_output="""\
-Dfoo -Dbar
==== Testing CPPDEFINES, appending a string to a string
orig = FOO, append = FOO
-Append:
+Append:
result=['FOO', 'FOO']
final=-DFOO -DFOO
AppendUnique:
@@ -91,7 +91,7 @@ AppendUnique:
final=-DFOO
==== Testing CPPDEFINES, appending a list to a string
orig = FOO, append = ['NAME1', 'NAME2']
-Append:
+Append:
result=['FOO', 'NAME1', 'NAME2']
final=-DFOO -DNAME1 -DNAME2
AppendUnique:
@@ -99,7 +99,7 @@ AppendUnique:
final=-DFOO -DNAME1 -DNAME2
==== Testing CPPDEFINES, appending a list-of-2lists to a string
orig = FOO, append = [('NAME1', 'VAL1'), ['NAME2', 'VAL2']]
-Append:
+Append:
result=['FOO', ('NAME1', 'VAL1'), ['NAME2', 'VAL2']]
final=-DFOO -DNAME1=VAL1 -DNAME2=VAL2
AppendUnique:
@@ -107,7 +107,7 @@ AppendUnique:
final=-DFOO -DNAME1=VAL1 -DNAME2=VAL2
==== Testing CPPDEFINES, appending a dict to a string
orig = FOO, append = {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}
-Append:
+Append:
result=['FOO', {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}]
final=-DFOO -DNAME2=VAL2 -DNAME3 -DNAME1=VAL1
AppendUnique:
@@ -115,7 +115,7 @@ AppendUnique:
final=-DFOO -DNAME2=VAL2 -DNAME3 -DNAME1=VAL1
==== Testing CPPDEFINES, appending a string to a list
orig = ['NAME1', 'NAME2'], append = FOO
-Append:
+Append:
result=['NAME1', 'NAME2', 'FOO']
final=-DNAME1 -DNAME2 -DFOO
AppendUnique:
@@ -123,7 +123,7 @@ AppendUnique:
final=-DNAME1 -DNAME2 -DFOO
==== Testing CPPDEFINES, appending a list to a list
orig = ['NAME1', 'NAME2'], append = ['NAME1', 'NAME2']
-Append:
+Append:
result=['NAME1', 'NAME2', 'NAME1', 'NAME2']
final=-DNAME1 -DNAME2 -DNAME1 -DNAME2
AppendUnique:
@@ -131,7 +131,7 @@ AppendUnique:
final=-DNAME1 -DNAME2
==== Testing CPPDEFINES, appending a list-of-2lists to a list
orig = ['NAME1', 'NAME2'], append = [('NAME1', 'VAL1'), ['NAME2', 'VAL2']]
-Append:
+Append:
result=['NAME1', 'NAME2', ('NAME1', 'VAL1'), ['NAME2', 'VAL2']]
final=-DNAME1 -DNAME2 -DNAME1=VAL1 -DNAME2=VAL2
AppendUnique:
@@ -139,7 +139,7 @@ AppendUnique:
final=-DNAME1 -DNAME2 -DNAME1=VAL1 -DNAME2=VAL2
==== Testing CPPDEFINES, appending a dict to a list
orig = ['NAME1', 'NAME2'], append = {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}
-Append:
+Append:
result=['NAME1', 'NAME2', {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}]
final=-DNAME1 -DNAME2 -DNAME2=VAL2 -DNAME3 -DNAME1=VAL1
AppendUnique:
@@ -147,7 +147,7 @@ AppendUnique:
final=-DNAME1 -DNAME2 -DNAME2=VAL2 -DNAME3 -DNAME1=VAL1
==== Testing CPPDEFINES, appending a string to a list-of-2lists
orig = [('NAME1', 'VAL1'), ['NAME2', 'VAL2']], append = FOO
-Append:
+Append:
result=[('NAME1', 'VAL1'), ['NAME2', 'VAL2'], 'FOO']
final=-DNAME1=VAL1 -DNAME2=VAL2 -DFOO
AppendUnique:
@@ -155,7 +155,7 @@ AppendUnique:
final=-DNAME1=VAL1 -DNAME2=VAL2 -DFOO
==== Testing CPPDEFINES, appending a list to a list-of-2lists
orig = [('NAME1', 'VAL1'), ['NAME2', 'VAL2']], append = ['NAME1', 'NAME2']
-Append:
+Append:
result=[('NAME1', 'VAL1'), ['NAME2', 'VAL2'], 'NAME1', 'NAME2']
final=-DNAME1=VAL1 -DNAME2=VAL2 -DNAME1 -DNAME2
AppendUnique:
@@ -163,7 +163,7 @@ AppendUnique:
final=-DNAME1=VAL1 -DNAME2=VAL2 -DNAME1 -DNAME2
==== Testing CPPDEFINES, appending a list-of-2lists to a list-of-2lists
orig = [('NAME1', 'VAL1'), ['NAME2', 'VAL2']], append = [('NAME1', 'VAL1'), ['NAME2', 'VAL2']]
-Append:
+Append:
result=[('NAME1', 'VAL1'), ['NAME2', 'VAL2'], ('NAME1', 'VAL1'), ['NAME2', 'VAL2']]
final=-DNAME1=VAL1 -DNAME2=VAL2 -DNAME1=VAL1 -DNAME2=VAL2
AppendUnique:
@@ -171,7 +171,7 @@ AppendUnique:
final=-DNAME1=VAL1 -DNAME2=VAL2
==== Testing CPPDEFINES, appending a dict to a list-of-2lists
orig = [('NAME1', 'VAL1'), ['NAME2', 'VAL2']], append = {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}
-Append:
+Append:
result=[('NAME1', 'VAL1'), ['NAME2', 'VAL2'], {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}]
final=-DNAME1=VAL1 -DNAME2=VAL2 -DNAME2=VAL2 -DNAME3 -DNAME1=VAL1
AppendUnique:
@@ -179,7 +179,7 @@ AppendUnique:
final=-DNAME2=VAL2 -DNAME3 -DNAME1=VAL1
==== Testing CPPDEFINES, appending a string to a dict
orig = {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}, append = FOO
-Append:
+Append:
result={'FOO': None, 'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}
final=-DFOO -DNAME1=VAL1 -DNAME2=VAL2 -DNAME3
AppendUnique:
@@ -187,7 +187,7 @@ AppendUnique:
final=-DNAME2=VAL2 -DNAME3 -DNAME1=VAL1 -DFOO
==== Testing CPPDEFINES, appending a list to a dict
orig = {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}, append = ['NAME1', 'NAME2']
-Append:
+Append:
result=[('NAME2', 'VAL2'), ('NAME3',), ('NAME1', 'VAL1'), 'NAME1', 'NAME2']
final=-DNAME2=VAL2 -DNAME3 -DNAME1=VAL1 -DNAME1 -DNAME2
AppendUnique:
@@ -195,7 +195,7 @@ AppendUnique:
final=-DNAME2=VAL2 -DNAME3 -DNAME1=VAL1 -DNAME1 -DNAME2
==== Testing CPPDEFINES, appending a list-of-2lists to a dict
orig = {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}, append = [('NAME1', 'VAL1'), ['NAME2', 'VAL2']]
-Append:
+Append:
result=[('NAME2', 'VAL2'), ('NAME3',), ('NAME1', 'VAL1'), ('NAME1', 'VAL1'), ['NAME2', 'VAL2']]
final=-DNAME2=VAL2 -DNAME3 -DNAME1=VAL1 -DNAME1=VAL1 -DNAME2=VAL2
AppendUnique:
@@ -203,7 +203,7 @@ AppendUnique:
final=-DNAME2=VAL2 -DNAME3 -DNAME1=VAL1
==== Testing CPPDEFINES, appending a dict to a dict
orig = {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}, append = {'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}
-Append:
+Append:
result={'NAME2': 'VAL2', 'NAME3': None, 'NAME1': 'VAL1'}
final=-DNAME1=VAL1 -DNAME2=VAL2 -DNAME3
AppendUnique:
@@ -213,7 +213,7 @@ AppendUnique:
build_output="scons: `.' is up to date.\n"
-expect = test.wrap_stdout(build_str=build_output,
+expect = test.wrap_stdout(build_str=build_output,
read_str = expect_print_output)
test.run(arguments = '.', stdout=expect)
test.pass_test()
diff --git a/test/CPPDEFINES/basic.py b/test/CPPDEFINES/basic.py
index b54a421..57d7260 100644
--- a/test/CPPDEFINES/basic.py
+++ b/test/CPPDEFINES/basic.py
@@ -41,13 +41,13 @@ test_list = [
]
for i in test_list:
env = Environment(CPPDEFPREFIX='-D', CPPDEFSUFFIX='', INTEGER=0)
- print env.Clone(CPPDEFINES=i).subst('$_CPPDEFFLAGS')
+ print(env.Clone(CPPDEFINES=i).subst('$_CPPDEFFLAGS'))
for i in test_list:
env = Environment(CPPDEFPREFIX='|', CPPDEFSUFFIX='|', INTEGER=1)
- print env.Clone(CPPDEFINES=i).subst('$_CPPDEFFLAGS')
+ print(env.Clone(CPPDEFINES=i).subst('$_CPPDEFFLAGS'))
""")
-expect = test.wrap_stdout(build_str="scons: `.' is up to date.\n",
+expect = test.wrap_stdout(build_str="scons: `.' is up to date.\n",
read_str = """\
-Dxyz
-Dx -Dy -Dz
diff --git a/test/CPPDEFINES/pkg-config.py b/test/CPPDEFINES/pkg-config.py
index 1b308d3..4e81dec 100644
--- a/test/CPPDEFINES/pkg-config.py
+++ b/test/CPPDEFINES/pkg-config.py
@@ -60,26 +60,26 @@ test.write('SConstruct', """\
# Passing test cases
env_1 = Environment(CPPDEFINES=[('DEBUG','1'), 'TEST'])
env_1.ParseConfig('PKG_CONFIG_PATH=. %(pkg_config_path)s --cflags bug')
-print env_1.subst('$_CPPDEFFLAGS')
+print(env_1.subst('$_CPPDEFFLAGS'))
env_2 = Environment(CPPDEFINES=[('DEBUG','1'), 'TEST'])
env_2.MergeFlags('-DSOMETHING -DVARIABLE=2')
-print env_2.subst('$_CPPDEFFLAGS')
+print(env_2.subst('$_CPPDEFFLAGS'))
# Failing test cases
env_3 = Environment(CPPDEFINES={'DEBUG':1, 'TEST':None})
env_3.ParseConfig('PKG_CONFIG_PATH=. %(pkg_config_path)s --cflags bug')
-print env_3.subst('$_CPPDEFFLAGS')
+print(env_3.subst('$_CPPDEFFLAGS'))
env_4 = Environment(CPPDEFINES={'DEBUG':1, 'TEST':None})
env_4.MergeFlags('-DSOMETHING -DVARIABLE=2')
-print env_4.subst('$_CPPDEFFLAGS')
+print(env_4.subst('$_CPPDEFFLAGS'))
# http://scons.tigris.org/issues/show_bug.cgi?id=1738
env_1738_1 = Environment(tools=['default'])
env_1738_1.ParseConfig('PKG_CONFIG_PATH=. %(pkg_config_path)s --cflags --libs bug')
env_1738_1.Append(CPPDEFINES={'value' : '1'})
-print env_1738_1.subst('$_CPPDEFFLAGS')
+print(env_1738_1.subst('$_CPPDEFFLAGS'))
"""%locals() )
expect_print_output="""\
@@ -92,7 +92,7 @@ expect_print_output="""\
build_output="scons: `.' is up to date.\n"
-expect = test.wrap_stdout(build_str=build_output,
+expect = test.wrap_stdout(build_str=build_output,
read_str = expect_print_output)
test.run(arguments = '.', stdout=expect)
test.pass_test()
diff --git a/test/CPPDEFINES/undefined.py b/test/CPPDEFINES/undefined.py
index 47825b6..b26b05a 100644
--- a/test/CPPDEFINES/undefined.py
+++ b/test/CPPDEFINES/undefined.py
@@ -34,10 +34,10 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """\
env = Environment()
-print env.subst('$_CPPDEFFLAGS')
+print(env.subst('$_CPPDEFFLAGS'))
""")
-expect = test.wrap_stdout(build_str="scons: `.' is up to date.\n",
+expect = test.wrap_stdout(build_str="scons: `.' is up to date.\n",
read_str = "\n")
test.run(arguments = '.', stdout=expect)
diff --git a/test/CacheDir/scanner-target.py b/test/CacheDir/scanner-target.py
index 645b597..c39042e 100644
--- a/test/CacheDir/scanner-target.py
+++ b/test/CacheDir/scanner-target.py
@@ -52,7 +52,7 @@ def docopy(target,source,env):
f.close()
def sillyScanner(node, env, dirs):
- print 'This is never called (unless we build file.out)'
+ print('This is never called (unless we build file.out)')
return []
SillyScanner = SCons.Scanner.Base(function = sillyScanner, skeys = ['.res'])
diff --git a/test/CacheDir/source-scanner.py b/test/CacheDir/source-scanner.py
index e7db5e9..2359872 100644
--- a/test/CacheDir/source-scanner.py
+++ b/test/CacheDir/source-scanner.py
@@ -54,7 +54,7 @@ def docopy(target,source,env):
f.close()
def sillyScanner(node, env, dirs):
- print 'This is never called (unless we build file.out)'
+ print('This is never called (unless we build file.out)')
return []
SillyScanner = SCons.Scanner.Base(function = sillyScanner, skeys = ['.res'])
diff --git a/test/Chmod.py b/test/Chmod.py
index c5b2a8d..e5bb85f 100644
--- a/test/Chmod.py
+++ b/test/Chmod.py
@@ -98,26 +98,25 @@ test.subdir('d16')
test.subdir('d17')
test.subdir('d18')
-os.chmod(test.workpath('f1'), 0444)
-os.chmod(test.workpath('f1-File'), 0444)
-os.chmod(test.workpath('d2'), 0555)
-os.chmod(test.workpath('d2-Dir'), 0555)
-os.chmod(test.workpath('f3'), 0444)
-os.chmod(test.workpath('d4'), 0555)
-os.chmod(test.workpath('f5'), 0444)
-os.chmod(test.workpath('Chmod-f7.in'), 0444)
-os.chmod(test.workpath('f7.out-Chmod'), 0444)
-os.chmod(test.workpath('f9'), 0444)
-os.chmod(test.workpath('f10'), 0444)
-os.chmod(test.workpath('d11'), 0555)
-os.chmod(test.workpath('d12'), 0555)
-os.chmod(test.workpath('f13'), 0444)
-os.chmod(test.workpath('f14'), 0444)
-os.chmod(test.workpath('f15'), 0444)
-os.chmod(test.workpath('d16'), 0555)
-os.chmod(test.workpath('d17'), 0555)
-os.chmod(test.workpath('d18'), 0555)
-
+os.chmod(test.workpath('f1'), 0o444)
+os.chmod(test.workpath('f1-File'), 0o444)
+os.chmod(test.workpath('d2'), 0o555)
+os.chmod(test.workpath('d2-Dir'), 0o555)
+os.chmod(test.workpath('f3'), 0o444)
+os.chmod(test.workpath('d4'), 0o555)
+os.chmod(test.workpath('f5'), 0o444)
+os.chmod(test.workpath('Chmod-f7.in'), 0o444)
+os.chmod(test.workpath('f7.out-Chmod'), 0o444)
+os.chmod(test.workpath('f9'), 0o444)
+os.chmod(test.workpath('f10'), 0o444)
+os.chmod(test.workpath('d11'), 0o555)
+os.chmod(test.workpath('d12'), 0o555)
+os.chmod(test.workpath('f13'), 0o444)
+os.chmod(test.workpath('f14'), 0o444)
+os.chmod(test.workpath('f15'), 0o444)
+os.chmod(test.workpath('d16'), 0o555)
+os.chmod(test.workpath('d17'), 0o555)
+os.chmod(test.workpath('d18'), 0o555)
expect = test.wrap_stdout(read_str = """\
Chmod("f1", 0666)
Chmod("f1-File", 0666)
@@ -145,92 +144,92 @@ cat(["f8.out"], ["f8.in"])
test.run(options = '-n', arguments = '.', stdout = expect)
s = stat.S_IMODE(os.stat(test.workpath('f1'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('f1-File'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('d2'))[stat.ST_MODE])
-test.fail_test(s != 0555)
+test.fail_test(s != 0o555)
s = stat.S_IMODE(os.stat(test.workpath('d2-Dir'))[stat.ST_MODE])
-test.fail_test(s != 0555)
+test.fail_test(s != 0o555)
test.must_not_exist('bar.out')
s = stat.S_IMODE(os.stat(test.workpath('f3'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('d4'))[stat.ST_MODE])
-test.fail_test(s != 0555)
+test.fail_test(s != 0o555)
s = stat.S_IMODE(os.stat(test.workpath('f5'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
test.must_not_exist('f6.out')
test.must_not_exist('f7.out')
s = stat.S_IMODE(os.stat(test.workpath('Chmod-f7.in'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('f7.out-Chmod'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
test.must_not_exist('f8.out')
s = stat.S_IMODE(os.stat(test.workpath('f9'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('f10'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('d11'))[stat.ST_MODE])
-test.fail_test(s != 0555)
+test.fail_test(s != 0o555)
s = stat.S_IMODE(os.stat(test.workpath('d12'))[stat.ST_MODE])
-test.fail_test(s != 0555)
+test.fail_test(s != 0o555)
s = stat.S_IMODE(os.stat(test.workpath('f13'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('f14'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('f15'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('d16'))[stat.ST_MODE])
-test.fail_test(s != 0555)
+test.fail_test(s != 0o555)
s = stat.S_IMODE(os.stat(test.workpath('d17'))[stat.ST_MODE])
-test.fail_test(s != 0555)
+test.fail_test(s != 0o555)
s = stat.S_IMODE(os.stat(test.workpath('d18'))[stat.ST_MODE])
-test.fail_test(s != 0555)
+test.fail_test(s != 0o555)
test.run()
s = stat.S_IMODE(os.stat(test.workpath('f1'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
s = stat.S_IMODE(os.stat(test.workpath('f1-File'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
s = stat.S_IMODE(os.stat(test.workpath('d2'))[stat.ST_MODE])
-test.fail_test(s != 0777)
+test.fail_test(s != 0o777)
s = stat.S_IMODE(os.stat(test.workpath('d2-Dir'))[stat.ST_MODE])
-test.fail_test(s != 0777)
+test.fail_test(s != 0o777)
test.must_match('bar.out', "bar.in\n")
s = stat.S_IMODE(os.stat(test.workpath('f3'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
s = stat.S_IMODE(os.stat(test.workpath('d4'))[stat.ST_MODE])
-test.fail_test(s != 0777)
+test.fail_test(s != 0o777)
s = stat.S_IMODE(os.stat(test.workpath('f5'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
test.must_match('f6.out', "f6.in\n")
test.must_match('f7.out', "f7.in\n")
s = stat.S_IMODE(os.stat(test.workpath('Chmod-f7.in'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
s = stat.S_IMODE(os.stat(test.workpath('f7.out-Chmod'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
test.must_match('f8.out', "f8.in\n")
s = stat.S_IMODE(os.stat(test.workpath('f9'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
s = stat.S_IMODE(os.stat(test.workpath('f10'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
s = stat.S_IMODE(os.stat(test.workpath('d11'))[stat.ST_MODE])
-test.fail_test(s != 0777)
+test.fail_test(s != 0o777)
s = stat.S_IMODE(os.stat(test.workpath('d12'))[stat.ST_MODE])
-test.fail_test(s != 0777)
+test.fail_test(s != 0o777)
s = stat.S_IMODE(os.stat(test.workpath('f13'))[stat.ST_MODE])
-test.fail_test(s != 0444)
+test.fail_test(s != 0o444)
s = stat.S_IMODE(os.stat(test.workpath('f14'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
s = stat.S_IMODE(os.stat(test.workpath('f15'))[stat.ST_MODE])
-test.fail_test(s != 0666)
+test.fail_test(s != 0o666)
s = stat.S_IMODE(os.stat(test.workpath('d16'))[stat.ST_MODE])
-test.fail_test(s != 0777)
+test.fail_test(s != 0o777)
s = stat.S_IMODE(os.stat(test.workpath('d17'))[stat.ST_MODE])
-test.fail_test(s != 0777)
+test.fail_test(s != 0o777)
s = stat.S_IMODE(os.stat(test.workpath('d18'))[stat.ST_MODE])
-test.fail_test(s != 0777)
+test.fail_test(s != 0o777)
test.pass_test()
diff --git a/test/Clean/mkfifo.py b/test/Clean/mkfifo.py
index 0ef7662..01e4d98 100644
--- a/test/Clean/mkfifo.py
+++ b/test/Clean/mkfifo.py
@@ -38,35 +38,40 @@ test = TestSCons.TestSCons()
if not hasattr(os, 'mkfifo'):
test.skip_test('No os.mkfifo() function; skipping test\n')
+test_dir_name = 'testdir'
+pipe_path = os.path.join(test_dir_name, 'namedpipe')
+
test.write('SConstruct', """\
-Execute(Mkdir("testdir"))
-dir = Dir("testdir")
-Clean(dir, 'testdir')
-""")
+Execute(Mkdir("{0}"))
+dir = Dir("{0}")
+Clean(dir, '{0}')
+""".format(test_dir_name))
+
+test.run(arguments='-Q -q', stdout='Mkdir("{0}")\n'.format(test_dir_name))
-test.run(arguments='-Q -q', stdout='Mkdir("testdir")\n')
+os.mkfifo(pipe_path)
-os.mkfifo('testdir/namedpipe')
+test.must_exist(test.workpath(pipe_path))
expect1 = """\
-Mkdir("testdir")
-Path '%s' exists but isn't a file or directory.
-scons: Could not remove 'testdir': Directory not empty
-""" % os.path.join('testdir', 'namedpipe')
+Mkdir("{0}")
+Path '{1}' exists but isn't a file or directory.
+scons: Could not remove '{0}': Directory not empty
+""".format(test_dir_name, pipe_path)
expect2 = """\
-Mkdir("testdir")
-Path '%s' exists but isn't a file or directory.
-scons: Could not remove 'testdir': File exists
-""" % os.path.join('testdir', 'namedpipe')
+Mkdir("{0}")
+Path '{1}' exists but isn't a file or directory.
+scons: Could not remove '{0}': File exists
+""".format(test_dir_name, pipe_path)
test.run(arguments='-c -Q -q')
+test.must_exist(test.workpath(pipe_path))
+
if test.stdout() not in [expect1, expect2]:
test.diff(expect1, test.stdout(), 'STDOUT ')
test.fail_test()
-
-test.must_exist(test.workpath('testdir/namedpipe'))
test.pass_test()
diff --git a/test/Climb/filename--D.py b/test/Climb/filename--D.py
index 06d95e7..6fea9bc 100644
--- a/test/Climb/filename--D.py
+++ b/test/Climb/filename--D.py
@@ -36,12 +36,12 @@ test = TestSCons.TestSCons()
test.subdir('subdir', 'other')
test.write('main.scons', """\
-print "main.scons"
+print("main.scons")
SConscript('subdir/sub.scons')
""")
test.write(['subdir', 'sub.scons'], """\
-print "subdir/sub.scons"
+print("subdir/sub.scons")
""")
diff --git a/test/Climb/filename--U.py b/test/Climb/filename--U.py
index 7f2e60d..49ccc0a 100644
--- a/test/Climb/filename--U.py
+++ b/test/Climb/filename--U.py
@@ -36,12 +36,12 @@ test = TestSCons.TestSCons()
test.subdir('subdir', 'other')
test.write('main.scons', """\
-print "main.scons"
+print("main.scons")
SConscript('subdir/sub.scons')
""")
test.write(['subdir', 'sub.scons'], """\
-print "subdir/sub.scons"
+print("subdir/sub.scons")
""")
read_str = """\
diff --git a/test/Climb/filename-u.py b/test/Climb/filename-u.py
index 7bae153..4485c4b 100644
--- a/test/Climb/filename-u.py
+++ b/test/Climb/filename-u.py
@@ -36,12 +36,12 @@ test = TestSCons.TestSCons()
test.subdir('subdir', 'other')
test.write('main.scons', """\
-print "main.scons"
+print("main.scons")
SConscript('subdir/sub.scons')
""")
test.write(['subdir', 'sub.scons'], """\
-print "subdir/sub.scons"
+print("subdir/sub.scons")
""")
read_str = """\
diff --git a/test/Clone-compatibility.py b/test/Clone-compatibility.py
index 089b7a4..a2f6362 100644
--- a/test/Clone-compatibility.py
+++ b/test/Clone-compatibility.py
@@ -48,8 +48,8 @@ except AttributeError:
env1 = Environment(X = 1)
env2 = env1.Clone(X = 2)
-print env1['X']
-print env2['X']
+print(env1['X'])
+print(env2['X'])
""")
test.run(arguments = '-q -Q', stdout = "1\n2\n")
diff --git a/test/Configure/ConfigureDryRunError.py b/test/Configure/ConfigureDryRunError.py
index b4be67e..fa85042 100644
--- a/test/Configure/ConfigureDryRunError.py
+++ b/test/Configure/ConfigureDryRunError.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__"
@@ -97,7 +98,7 @@ test.checkLogAndStdout( ["Checking for C library %s... " % lib,
newLog = test.read(test.workpath('config.log'))
if newLog != oldLog:
- print "Unexpected update of log file within a dry run"
+ print("Unexpected update of log file within a dry run")
test.fail_test()
test.pass_test()
diff --git a/test/Configure/Streamer1.py b/test/Configure/Streamer1.py
index 8f35308..318a936 100644
--- a/test/Configure/Streamer1.py
+++ b/test/Configure/Streamer1.py
@@ -45,7 +45,7 @@ test.write('SConstruct', """
def hello(target, source, env):
import traceback
try:
- print 'hello!\\n' # this breaks the script
+ print('hello!\\n') # this breaks the script
with open(env.subst('$TARGET', target = target),'w') as f:
f.write('yes')
except:
diff --git a/test/Configure/cache-not-ok.py b/test/Configure/cache-not-ok.py
index ccbb7d5..7502f7a 100644
--- a/test/Configure/cache-not-ok.py
+++ b/test/Configure/cache-not-ok.py
@@ -53,7 +53,7 @@ r1 = conf.CheckCHeader( 'no_std_c_header.h' ) # leads to compile error
r2 = conf.CheckLib( 'no_c_library_SAFFDG' ) # leads to link error
env = conf.Finish()
if not (not r1 and not r2):
- print "FAIL: ", r1, r2
+ print("FAIL: ", r1, r2)
Exit(1)
""")
diff --git a/test/Configure/config-h.py b/test/Configure/config-h.py
index cda6c3b..ed95055 100644
--- a/test/Configure/config-h.py
+++ b/test/Configure/config-h.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__"
@@ -135,19 +136,19 @@ test.run(stdout=expected_stdout)
config_h = test.read(test.workpath('config.h'))
if expected_config_h != config_h:
- print "Unexpected config.h"
- print "Expected: "
- print "---------------------------------------------------------"
- print repr(expected_config_h)
- print "---------------------------------------------------------"
- print "Found: "
- print "---------------------------------------------------------"
- print repr(config_h)
- print "---------------------------------------------------------"
- print "Stdio: "
- print "---------------------------------------------------------"
- print test.stdout()
- print "---------------------------------------------------------"
+ print("Unexpected config.h")
+ print("Expected: ")
+ print("---------------------------------------------------------")
+ print(repr(expected_config_h))
+ print("---------------------------------------------------------")
+ print("Found: ")
+ print("---------------------------------------------------------")
+ print(repr(config_h))
+ print("---------------------------------------------------------")
+ print("Stdio: ")
+ print("---------------------------------------------------------")
+ print(test.stdout())
+ print("---------------------------------------------------------")
test.fail_test()
expected_read_str = re.sub(r'\b((yes)|(no))\b',
@@ -162,19 +163,19 @@ test.run(stdout=expected_stdout)
config_h = test.read(test.workpath('config.h'))
if expected_config_h != config_h:
- print "Unexpected config.h"
- print "Expected: "
- print "---------------------------------------------------------"
- print repr(expected_config_h)
- print "---------------------------------------------------------"
- print "Found: "
- print "---------------------------------------------------------"
- print repr(config_h)
- print "---------------------------------------------------------"
- print "Stdio: "
- print "---------------------------------------------------------"
- print test.stdout()
- print "---------------------------------------------------------"
+ print("Unexpected config.h")
+ print("Expected: ")
+ print("---------------------------------------------------------")
+ print(repr(expected_config_h))
+ print("---------------------------------------------------------")
+ print("Found: ")
+ print("---------------------------------------------------------")
+ print(repr(config_h))
+ print("---------------------------------------------------------")
+ print("Stdio: ")
+ print("---------------------------------------------------------")
+ print(test.stdout())
+ print("---------------------------------------------------------")
test.fail_test()
test.pass_test()
diff --git a/test/Configure/implicit-cache.py b/test/Configure/implicit-cache.py
index 0f04b1e..1a9ff34 100644
--- a/test/Configure/implicit-cache.py
+++ b/test/Configure/implicit-cache.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__"
@@ -93,11 +94,11 @@ test.run_sconsign('-d .sconf_temp -e conftest_0.c --raw .sconsign.dblite')
new_sconsign_dblite = test.stdout()
if old_sconsign_dblite != new_sconsign_dblite:
- print ".sconsign.dblite did not match:"
- print "FIRST RUN =========="
- print old_sconsign_dblite
- print "SECOND RUN =========="
- print new_sconsign_dblite
+ print(".sconsign.dblite did not match:")
+ print("FIRST RUN ==========")
+ print(old_sconsign_dblite)
+ print("SECOND RUN ==========")
+ print(new_sconsign_dblite)
test.fail_test()
test.pass_test()
diff --git a/test/ConstructionEnvironment.py b/test/ConstructionEnvironment.py
index bec46b9..e25f86a 100644
--- a/test/ConstructionEnvironment.py
+++ b/test/ConstructionEnvironment.py
@@ -38,7 +38,7 @@ import SCons.Defaults
SCons.Defaults.ConstructionEnvironment.update({
'XXX' : 777,
})
-print DefaultEnvironment()['XXX']
+print(DefaultEnvironment()['XXX'])
""")
expect = test.wrap_stdout(read_str = "777\n",
diff --git a/test/Copy-Action.py b/test/Copy-Action.py
index 51635c5..ded158a 100644
--- a/test/Copy-Action.py
+++ b/test/Copy-Action.py
@@ -84,8 +84,8 @@ test.subdir('d5')
test.write(['d5', 'f12.in'], "f12.in\n")
test.write('f 13.in', "f 13.in\n")
-os.chmod('f1.in', 0646)
-os.chmod('f4.in', 0644)
+os.chmod('f1.in', 0o646)
+os.chmod('f4.in', 0o644)
test.sleep()
diff --git a/test/D/SharedObjects/Common/common.py b/test/D/SharedObjects/Common/common.py
index e81cf5b..280c6f2 100644
--- a/test/D/SharedObjects/Common/common.py
+++ b/test/D/SharedObjects/Common/common.py
@@ -46,7 +46,7 @@ def testForTool(tool):
test.skip_test("Required executable for tool '{0}' not found, skipping test.\n".format(tool))
if tool == 'gdc':
- test.skip_test('gdc does not, as at version 4.9.1, support shared libraries.\n')
+ test.skip_test('gdc in GCC distribution does not, as at version 5.3.1, support shared libraries.\n')
if tool == 'dmd' and Base()['DC'] == 'gdmd':
test.skip_test('gdmd does not recognize the -shared option so cannot support linking of shared objects.\n')
diff --git a/test/Deprecated/Options/BoolOption.py b/test/Deprecated/Options/BoolOption.py
index 563939b..5d12fc6 100644
--- a/test/Deprecated/Options/BoolOption.py
+++ b/test/Deprecated/Options/BoolOption.py
@@ -55,8 +55,8 @@ opts.AddOptions(
env = Environment(options=opts)
Help(opts.GenerateHelpText(env))
-print env['warnings']
-print env['profile']
+print(env['warnings'])
+print(env['profile'])
Default(env.Alias('dummy', None))
""")
diff --git a/test/Deprecated/Options/EnumOption.py b/test/Deprecated/Options/EnumOption.py
index 57ae7eb..02afef1 100644
--- a/test/Deprecated/Options/EnumOption.py
+++ b/test/Deprecated/Options/EnumOption.py
@@ -43,6 +43,7 @@ def check(expect):
test.write(SConstruct_path, """\
+
from SCons.Options.EnumOption import EnumOption
EO = EnumOption
@@ -66,9 +67,9 @@ opts.AddOptions(
env = Environment(options=opts)
Help(opts.GenerateHelpText(env))
-print env['debug']
-print env['guilib']
-print env['some']
+print(env['debug'])
+print(env['guilib'])
+print(env['some'])
Default(env.Alias('dummy', None))
""")
diff --git a/test/Deprecated/Options/ListOption.py b/test/Deprecated/Options/ListOption.py
index bb3775b..42af511 100644
--- a/test/Deprecated/Options/ListOption.py
+++ b/test/Deprecated/Options/ListOption.py
@@ -67,15 +67,18 @@ env = Environment(options=opts)
opts.Save(optsfile, env)
Help(opts.GenerateHelpText(env))
-print env['shared']
-if 'ical' in env['shared']: print '1'
-else: print '0'
-for x in env['shared']:
- print x,
-print
-print env.subst('$shared')
+print(env['shared'])
+
+if 'ical' in env['shared']:
+ print('1')
+else:
+ print('0')
+
+print(" ".join(env['shared']))
+
+print(env.subst('$shared'))
# Test subst_path() because it's used in $CPPDEFINES expansions.
-print env.subst_path('$shared')
+print(env.subst_path('$shared'))
Default(env.Alias('dummy', None))
""")
@@ -169,7 +172,7 @@ opts.AddOptions(
env = Environment(options=opts)
Help(opts.GenerateHelpText(env))
-print env['gpib']
+print(env['gpib'])
Default(env.Alias('dummy', None))
""")
diff --git a/test/Deprecated/Options/Options.py b/test/Deprecated/Options/Options.py
index 8116a63..e435b9e 100644
--- a/test/Deprecated/Options/Options.py
+++ b/test/Deprecated/Options/Options.py
@@ -30,8 +30,8 @@ test = TestSCons.TestSCons(match = TestSCons.match_re_dotall)
test.write('SConstruct', """
env = Environment()
-print env['CC']
-print " ".join(env['CCFLAGS'])
+print(env['CC'])
+print(" ".join(env['CCFLAGS']))
Default(env.Alias('dummy', None))
""")
test.run()
@@ -99,12 +99,12 @@ env = Environment(options=opts, tools=['default', test_tool])
Help('Variables settable in custom.py or on the command line:\\n' + opts.GenerateHelpText(env))
-print env['RELEASE_BUILD']
-print env['DEBUG_BUILD']
-print env['CC']
-print " ".join(env['CCFLAGS'])
-print env['VALIDATE']
-print env['valid_key']
+print(env['RELEASE_BUILD'])
+print(env['DEBUG_BUILD'])
+print(env['CC'])
+print(" ".join(env['CCFLAGS']))
+print(env['VALIDATE'])
+print(env['valid_key'])
# unspecified options should not be set:
assert 'UNSPECIFIED' not in env
@@ -226,8 +226,8 @@ opts.Add('UNSPECIFIED',
env = Environment(options = opts)
-print env['RELEASE_BUILD']
-print env['DEBUG_BUILD']
+print(env['RELEASE_BUILD'])
+print(env['DEBUG_BUILD'])
opts.Save('options.saved', env)
""")
@@ -237,7 +237,7 @@ opts.Save('options.saved', 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)
# First test with no command line options
@@ -282,9 +282,9 @@ opts.Add('LISTOPTION_TEST',
env = Environment(options = opts)
-print env['RELEASE_BUILD']
-print env['DEBUG_BUILD']
-print env['LISTOPTION_TEST']
+print(env['RELEASE_BUILD'])
+print(env['DEBUG_BUILD'])
+print(env['LISTOPTION_TEST'])
opts.Save('options.saved', env)
""")
diff --git a/test/Deprecated/Options/PackageOption.py b/test/Deprecated/Options/PackageOption.py
index 424e5a7..ec8990c 100644
--- a/test/Deprecated/Options/PackageOption.py
+++ b/test/Deprecated/Options/PackageOption.py
@@ -59,7 +59,7 @@ opts.AddOptions(
env = Environment(options=opts)
Help(opts.GenerateHelpText(env))
-print env['x11']
+print(env['x11'])
Default(env.Alias('dummy', None))
""")
diff --git a/test/Deprecated/Options/PathOption.py b/test/Deprecated/Options/PathOption.py
index 4701420..0e6949c 100644
--- a/test/Deprecated/Options/PathOption.py
+++ b/test/Deprecated/Options/PathOption.py
@@ -25,7 +25,7 @@
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
-Test the PathOption canned option type, with tests for its
+Test the PathOption canned option type, with tests for its
various canned validators.
"""
@@ -65,9 +65,9 @@ opts.AddOptions(
env = Environment(options=opts)
Help(opts.GenerateHelpText(env))
-print env['qtdir']
-print env['qt_libraries']
-print env.subst('$qt_libraries')
+print(env['qtdir'])
+print(env['qt_libraries'])
+print(env.subst('$qt_libraries'))
Default(env.Alias('dummy', None))
""" % (workpath, os.path.join('$qtdir', 'lib') ))
@@ -144,7 +144,7 @@ opts.AddOptions(
env = Environment(options=opts)
-print env['X']
+print(env['X'])
Default(env.Alias('dummy', None))
""" % default_subdir)
@@ -177,7 +177,7 @@ opts.AddOptions(
env = Environment(options=opts)
-print env['X']
+print(env['X'])
Default(env.Alias('dummy', None))
""" % default_file)
@@ -218,7 +218,7 @@ opts.AddOptions(
env = Environment(options=opts)
-print env['X']
+print(env['X'])
Default(env.Alias('dummy', None))
""" % default_subdir)
@@ -263,7 +263,7 @@ opts.AddOptions(
env = Environment(options=opts)
-print env['X']
+print(env['X'])
Default(env.Alias('dummy', None))
""" % default_subdir)
diff --git a/test/Deprecated/Options/chdir.py b/test/Deprecated/Options/chdir.py
index a8fb6c6..977a351 100644
--- a/test/Deprecated/Options/chdir.py
+++ b/test/Deprecated/Options/chdir.py
@@ -46,7 +46,7 @@ SConscript_contents = """\
Import("opts")
env = Environment()
opts.Update(env)
-print "VARIABLE =", repr(env['VARIABLE'])
+print("VARIABLE =", repr(env['VARIABLE']))
"""
test.write(['bin', 'opts.cfg'], """\
diff --git a/test/Deprecated/Options/help.py b/test/Deprecated/Options/help.py
index 8c240e3..ad8a96b 100644
--- a/test/Deprecated/Options/help.py
+++ b/test/Deprecated/Options/help.py
@@ -49,7 +49,7 @@ libdirvar_re = re.escape(libdirvar)
test.subdir(qtpath)
test.subdir(libpath)
-
+
test.write('SConstruct', """
from SCons.Options import BoolOption, EnumOption, ListOption, \
PackageOption, PathOption
@@ -86,8 +86,8 @@ opts.AddOptions(
env = Environment(options=opts)
Help(opts.GenerateHelpText(env))
-print env['warnings']
-print env['profile']
+print(env['warnings'])
+print(env['profile'])
Default(env.Alias('dummy', None))
""" % locals())
diff --git a/test/Deprecated/Options/import.py b/test/Deprecated/Options/import.py
index a4d56b2..b93e6a2 100644
--- a/test/Deprecated/Options/import.py
+++ b/test/Deprecated/Options/import.py
@@ -48,7 +48,7 @@ SConscript_contents = """\
Import("opts")
env = Environment()
opts.Update(env)
-print "VARIABLE =", env.get('VARIABLE')
+print("VARIABLE =", env.get('VARIABLE'))
"""
test.write(['bin', 'opts.cfg'], """\
diff --git a/test/Deprecated/SourceCode/BitKeeper/BitKeeper.py b/test/Deprecated/SourceCode/BitKeeper/BitKeeper.py
index 3f0ffdd..04dfd9b 100644
--- a/test/Deprecated/SourceCode/BitKeeper/BitKeeper.py
+++ b/test/Deprecated/SourceCode/BitKeeper/BitKeeper.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__"
@@ -67,7 +68,7 @@ test.subdir('BK', 'import', ['import', 'sub'])
# Test using BitKeeper to fetch from SCCS/s.file files.
sccs = test.where_is('sccs')
if not sccs:
- print "Could not find SCCS, skipping sub-test of BitKeeper using SCCS files."
+ print("Could not find SCCS, skipping sub-test of BitKeeper using SCCS files.")
else:
test.subdir('work1',
['work1', 'SCCS'],
@@ -167,9 +168,9 @@ sub/fff.in 1.1 -> 1.2: 1 lines
rcs = test.where_is('rcs')
ci = test.where_is('ci')
if not rcs:
- print "Could not find RCS,\nskipping sub-test of BitKeeper using RCS files."
+ print("Could not find RCS,\nskipping sub-test of BitKeeper using RCS files.")
elif not ci:
- print "Could not find the RCS ci command,\nskipping sub-test of BitKeeper using RCS files."
+ print("Could not find the RCS ci command,\nskipping sub-test of BitKeeper using RCS files.")
else:
test.subdir('work2',
['work2', 'RCS'],
diff --git a/test/Deprecated/SourceCode/Subversion.py b/test/Deprecated/SourceCode/Subversion.py
index 1e7c562..7ed4b15 100644
--- a/test/Deprecated/SourceCode/Subversion.py
+++ b/test/Deprecated/SourceCode/Subversion.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__"
@@ -50,7 +51,7 @@ svnadmin = test.where_is('svnadmin')
if not svn:
test.skip_test("Could not find 'svnadmin'; skipping test(s).\n")
-print "Short-circuiting this test until we support Subversion"
+print("Short-circuiting this test until we support Subversion")
test.pass_test()
test.subdir('Subversion', 'import', ['import', 'sub'], 'work1', 'work2')
diff --git a/test/Dir/Dir.py b/test/Dir/Dir.py
index af0a10b..2e8204c 100644
--- a/test/Dir/Dir.py
+++ b/test/Dir/Dir.py
@@ -36,12 +36,12 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
env = Environment(FOO = 'fff', BAR = 'bbb')
-print Dir('ddd')
-print Dir('$FOO')
-print Dir('${BAR}_$BAR')
-print env.Dir('eee')
-print env.Dir('$FOO')
-print env.Dir('${BAR}_$BAR')
+print(Dir('ddd'))
+print(Dir('$FOO'))
+print(Dir('${BAR}_$BAR'))
+print(env.Dir('eee'))
+print(env.Dir('$FOO'))
+print(env.Dir('${BAR}_$BAR'))
""")
test.run(stdout = test.wrap_stdout(read_str = """\
diff --git a/test/Entry.py b/test/Entry.py
index 3767cc5..3d3255d 100644
--- a/test/Entry.py
+++ b/test/Entry.py
@@ -36,12 +36,12 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
env = Environment(FOO = 'fff', BAR = 'bbb')
-print Entry('ddd')
-print Entry('$FOO')
-print Entry('${BAR}_$BAR')
-print env.Entry('eee')
-print env.Entry('$FOO')
-print env.Entry('${BAR}_$BAR')
+print(Entry('ddd'))
+print(Entry('$FOO'))
+print(Entry('${BAR}_$BAR'))
+print(env.Entry('eee'))
+print(env.Entry('$FOO'))
+print(env.Entry('${BAR}_$BAR'))
""")
test.run(stdout = test.wrap_stdout(read_str = """\
diff --git a/test/Environment.py b/test/Environment.py
index 52b6488..6810979 100644
--- a/test/Environment.py
+++ b/test/Environment.py
@@ -42,8 +42,8 @@ assert Dir('.') == Dir('.').Dir('.')
assert target == target.File('foo.out')
e2 = env.Environment(XXX='$BAR', YYY='$BLAT')
-print e2['XXX']
-print e2['YYY']
+print(e2['XXX'])
+print(e2['YYY'])
""" % locals())
test.write('build.py', """
diff --git a/test/Errors/Exception.py b/test/Errors/Exception.py
index cc36035..30404fc 100644
--- a/test/Errors/Exception.py
+++ b/test/Errors/Exception.py
@@ -30,7 +30,7 @@ test = TestSCons.TestSCons(match = TestSCons.match_re_dotall)
test.write('SConstruct', """\
def foo(env, target, source):
- print str(target[0])
+ print(str(target[0]))
open(str(target[0]), 'wt').write('foo')
def exit(env, target, source):
diff --git a/test/ExecuteInvalidateCache.py b/test/ExecuteInvalidateCache.py
index a22c5ea..6d8063e 100644
--- a/test/ExecuteInvalidateCache.py
+++ b/test/ExecuteInvalidateCache.py
@@ -40,9 +40,9 @@ subfn = os.path.join('sub', 'foo')
test.write('SConstruct', """\
def exists(node):
if node.exists():
- print str(node), "exists"
+ print(str(node), "exists")
else:
- print str(node), "does not exist"
+ print(str(node), "does not exist")
Execute(Delete('abc'))
n1 = File('abc')
diff --git a/test/Exit.py b/test/Exit.py
index 877a0b6..394ee2f 100644
--- a/test/Exit.py
+++ b/test/Exit.py
@@ -40,7 +40,7 @@ subdir_foo_in = os.path.join('subdir', 'foo.in')
subdir_foo_out = os.path.join('subdir', 'foo.out')
test.write('SConstruct', """\
-print "SConstruct, Exit()"
+print("SConstruct, Exit()")
Exit()
""")
@@ -51,7 +51,7 @@ SConstruct, Exit()
test.write('SConstruct', """\
env = Environment()
-print "SConstruct, env.Exit()"
+print("SConstruct, env.Exit()")
env.Exit()
""")
@@ -61,7 +61,7 @@ SConstruct, env.Exit()
""")
test.write('SConstruct', """\
-print "SConstruct"
+print("SConstruct")
Exit(7)
""")
@@ -71,12 +71,12 @@ SConstruct
""")
test.write('SConstruct', """\
-print "SConstruct"
+print("SConstruct")
SConscript('subdir/SConscript')
""")
test.write(['subdir', 'SConscript'], """\
-print "subdir/SConscript"
+print("subdir/SConscript")
Exit()
""")
@@ -87,7 +87,7 @@ subdir/SConscript
""")
test.write(['subdir', 'SConscript'], """\
-print "subdir/SConscript"
+print("subdir/SConscript")
Exit(17)
""")
diff --git a/test/File.py b/test/File.py
index d919884..ec148b2 100644
--- a/test/File.py
+++ b/test/File.py
@@ -38,16 +38,16 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
env = Environment(FOO = 'fff', BAR = 'bbb')
-print File('ddd')
-print File('$FOO')
-print File('${BAR}_$BAR')
-print env.File('eee')
-print env.File('$FOO')
-print env.File('${BAR}_$BAR')
+print(File('ddd'))
+print(File('$FOO'))
+print(File('${BAR}_$BAR'))
+print(env.File('eee'))
+print(env.File('$FOO'))
+print(env.File('${BAR}_$BAR'))
f1 = env.File('f1')
-print f1
+print(f1)
f2 = f1.File('f2')
-print f2
+print(f2)
""")
expect = test.wrap_stdout(read_str = """\
diff --git a/test/FindFile.py b/test/FindFile.py
index 5d198ac..e878172 100644
--- a/test/FindFile.py
+++ b/test/FindFile.py
@@ -40,13 +40,13 @@ test.write(['bar', 'baz', 'testfile2'], 'test 4\n')
test.write('SConstruct', """
env = Environment(FILE = 'file', BAR = 'bar')
file1 = FindFile('testfile1', [ 'foo', '.', 'bar', 'bar/baz' ])
-print open(str(file1), 'r').read()
+print(open(str(file1), 'r').read())
file2 = env.FindFile('test${FILE}1', [ 'bar', 'foo', '.', 'bar/baz' ])
-print open(str(file2), 'r').read()
+print(open(str(file2), 'r').read())
file3 = FindFile('testfile2', [ 'foo', '.', 'bar', 'bar/baz' ])
-print open(str(file3), 'r').read()
+print(open(str(file3), 'r').read())
file4 = env.FindFile('testfile2', [ '$BAR/baz', 'foo', '.', 'bar' ])
-print open(str(file4), 'r').read()
+print(open(str(file4), 'r').read())
""")
expect = test.wrap_stdout(read_str = """test 1
diff --git a/test/Flatten.py b/test/Flatten.py
index b41c4fe..fd9943d 100644
--- a/test/Flatten.py
+++ b/test/Flatten.py
@@ -44,15 +44,15 @@ def cat(env, source, target):
env = Environment(BUILDERS={'Cat':Builder(action=cat)})
f1 = env.Cat('../file1.out', 'file1.in')
f2 = env.Cat('../file2.out', ['file2a.in', 'file2b.in'])
-print list(map(str, Flatten(['begin', f1, 'middle', f2, 'end'])))
-print list(map(str, env.Flatten([f1, [['a', 'b'], 'c'], f2])))
+print(list(map(str, Flatten(['begin', f1, 'middle', f2, 'end']))))
+print(list(map(str, env.Flatten([f1, [['a', 'b'], 'c'], f2]))))
SConscript('SConscript', "env")
""")
test.write(['work', 'SConscript'], """
Import("env")
-print Flatten([1, [2, 3], 4])
-print env.Flatten([[[[1], 2], 3], 4])
+print(Flatten([1, [2, 3], 4]))
+print(env.Flatten([[[[1], 2], 3], 4]))
""")
test.write('file1.in', "file1.in\n")
diff --git a/test/Fortran/F77FLAGS.py b/test/Fortran/F77FLAGS.py
index b708f9e..342adac 100644
--- a/test/Fortran/F77FLAGS.py
+++ b/test/Fortran/F77FLAGS.py
@@ -77,6 +77,9 @@ g77 = test.detect_tool(fc)
if g77:
+ directory = 'x'
+ test.subdir(directory)
+
test.write("wrapper.py",
"""import os
import sys
@@ -87,7 +90,7 @@ os.system(" ".join(sys.argv[1:]))
test.write('SConstruct', """
foo = Environment(F77 = '%(fc)s', tools = ['default', 'f77'], F77FILESUFFIXES = [".f"])
f77 = foo.Dictionary('F77')
-bar = foo.Clone(F77 = r'%(_python_)s wrapper.py ' + f77, F77FLAGS = '-Ix')
+bar = foo.Clone(F77 = r'%(_python_)s wrapper.py ' + f77, F77FLAGS = '-I%(directory)s')
foo.Program(target = 'foo', source = 'foo.f')
bar.Program(target = 'bar', source = 'bar.f')
""" % locals())
diff --git a/test/Fortran/FORTRANFLAGS.py b/test/Fortran/FORTRANFLAGS.py
index 8c5e781..150000a 100644
--- a/test/Fortran/FORTRANFLAGS.py
+++ b/test/Fortran/FORTRANFLAGS.py
@@ -95,6 +95,9 @@ g77 = test.detect_tool(fc)
if g77:
+ directory = 'x'
+ test.subdir(directory)
+
test.write("wrapper.py",
"""import os
import sys
@@ -105,7 +108,7 @@ os.system(" ".join(sys.argv[1:]))
test.write('SConstruct', """
foo = Environment(FORTRAN = '%(fc)s')
f77 = foo.Dictionary('FORTRAN')
-bar = foo.Clone(FORTRAN = r'%(_python_)s wrapper.py ' + f77, FORTRANFLAGS = '-Ix')
+bar = foo.Clone(FORTRAN = r'%(_python_)s wrapper.py ' + f77, FORTRANFLAGS = '-I%(directory)s')
foo.Program(target = 'foo', source = 'foo.f')
bar.Program(target = 'bar', source = 'bar.f')
""" % locals())
diff --git a/test/Fortran/SHF77FLAGS.py b/test/Fortran/SHF77FLAGS.py
index 644b827..79e46f3 100644
--- a/test/Fortran/SHF77FLAGS.py
+++ b/test/Fortran/SHF77FLAGS.py
@@ -75,6 +75,9 @@ g77 = test.detect_tool(fc)
if g77:
+ directory = 'x'
+ test.subdir(directory)
+
test.write("wrapper.py",
"""import os
import sys
@@ -87,7 +90,7 @@ foo = Environment(SHF77 = '%(fc)s')
shf77 = foo.Dictionary('SHF77')
bar = foo.Clone(SHF77 = r'%(_python_)s wrapper.py ' + shf77,
tools = ["default", 'f77'], F77FILESUFFIXES = [".f"])
-bar.Append(SHF77FLAGS = '-Ix')
+bar.Append(SHF77FLAGS = '-I%(directory)s')
foo.SharedLibrary(target = 'foo/foo', source = 'foo.f')
bar.SharedLibrary(target = 'bar/bar', source = 'bar.f')
""" % locals())
diff --git a/test/Fortran/SHFORTRANFLAGS.py b/test/Fortran/SHFORTRANFLAGS.py
index 11116f4..8e6f019 100644
--- a/test/Fortran/SHFORTRANFLAGS.py
+++ b/test/Fortran/SHFORTRANFLAGS.py
@@ -91,6 +91,9 @@ fortran = test.detect_tool(fc)
if fortran:
+ directory = 'x'
+ test.subdir(directory)
+
test.write("wrapper.py",
"""import os
import sys
@@ -102,7 +105,7 @@ os.system(" ".join(sys.argv[1:]))
foo = Environment(SHFORTRAN = '%(fc)s')
shfortran = foo.Dictionary('SHFORTRAN')
bar = foo.Clone(SHFORTRAN = r'%(_python_)s wrapper.py ' + shfortran)
-bar.Append(SHFORTRANFLAGS = '-Ix')
+bar.Append(SHFORTRANFLAGS = '-I%(directory)s')
foo.SharedLibrary(target = 'foo/foo', source = 'foo.f')
bar.SharedLibrary(target = 'bar/bar', source = 'bar.f')
""" % locals())
diff --git a/test/GetBuildFailures/option-k.py b/test/GetBuildFailures/option-k.py
index b4e8d54..0ff22e6 100644
--- a/test/GetBuildFailures/option-k.py
+++ b/test/GetBuildFailures/option-k.py
@@ -65,7 +65,7 @@ Command('f6', 'f6.in', r'@%(_python_)s mypass.py f5 - $TARGET $SOURCE')
def print_build_failures():
from SCons.Script import GetBuildFailures
for bf in sorted(GetBuildFailures(), key=lambda a: a.filename):
- print "%%s failed: %%s" %% (bf.node, bf.errstr)
+ print("%%s failed: %%s" %% (bf.node, bf.errstr))
import atexit
atexit.register(print_build_failures)
diff --git a/test/GetBuildFailures/parallel.py b/test/GetBuildFailures/parallel.py
index b7576af..ee0e831 100644
--- a/test/GetBuildFailures/parallel.py
+++ b/test/GetBuildFailures/parallel.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
"""
Verify that a failed build action with -j works as expected.
@@ -80,7 +81,7 @@ Command('f6', 'f6.in', r'@%(_python_)s mypass.py f5 - $TARGET $SOURCE')
def print_build_failures():
from SCons.Script import GetBuildFailures
for bf in sorted(GetBuildFailures(), key=lambda t: t.filename):
- print "%%s failed: %%s" %% (bf.node, bf.errstr)
+ print("%%s failed: %%s" %% (bf.node, bf.errstr))
import atexit
atexit.register(print_build_failures)
@@ -95,15 +96,15 @@ test.run(arguments = '-Q -j 4 .',
status = 2,
stderr = None)
-f4_error = "scons: *** [f4] Error 1\n"
+f4_error = "scons: *** [f4] Error 1\n"
f5_error = "scons: *** [f5] Error 1\n"
error_45 = f4_error + f5_error
error_54 = f5_error + f4_error
if test.stderr() not in [error_45, error_54]:
- print "Did not find the following output in list of expected strings:"
- print test.stderr(),
+ print("Did not find the following output in list of expected strings:")
+ print(test.stderr(), end=' ')
test.fail_test()
# We jump through hoops above to try to make sure that the individual
@@ -121,14 +122,14 @@ failed_45 = f4_failed + f5_failed
failed_54 = f5_failed + f4_failed
if test.stdout() not in [failed_45, failed_54]:
- print "Did not find the following output in list of expected strings:"
- print test.stdout(),
+ print("Did not find the following output in list of expected strings:")
+ print(test.stdout(), end=' ')
test.fail_test()
test.must_match(test.workpath('f3'), 'f3.in\n')
test.must_not_exist(test.workpath('f4'))
test.must_not_exist(test.workpath('f5'))
-test.must_match(test.workpath('f6'), 'f6.in\n')
+test.must_match(test.workpath('f6'), 'f6.in\n')
diff --git a/test/GetBuildFailures/serial.py b/test/GetBuildFailures/serial.py
index 9c56bb1..55a990f 100644
--- a/test/GetBuildFailures/serial.py
+++ b/test/GetBuildFailures/serial.py
@@ -82,8 +82,8 @@ Command('f08', 'f08.in', raiseExcAction(SCons.Errors.UserError("My User Error"))
Command('f09', 'f09.in', returnExcAction(SCons.Errors.UserError("My User Error")))
Command('f10', 'f10.in', raiseExcAction(MyBuildError(errstr="My Build Error", status=7)))
Command('f11', 'f11.in', returnExcAction(MyBuildError(errstr="My Build Error", status=7)))
-Command('f12', 'f12.in', raiseExcAction(EnvironmentError(123, "My EnvironmentError", "f12")))
-Command('f13', 'f13.in', returnExcAction(EnvironmentError(123, "My EnvironmentError", "f13")))
+Command('f12', 'f12.in', raiseExcAction(OSError(123, "My EnvironmentError", "f12")))
+Command('f13', 'f13.in', returnExcAction(OSError(123, "My EnvironmentError", "f13")))
Command('f14', 'f14.in', raiseExcAction(SCons.Errors.InternalError("My InternalError")))
Command('f15', 'f15.in', returnExcAction(SCons.Errors.InternalError("My InternalError")))
@@ -91,9 +91,9 @@ def print_build_failures():
from SCons.Script import GetBuildFailures
for bf in sorted(GetBuildFailures(), key=lambda t: str(t.node)):
assert( isinstance(bf, SCons.Errors.BuildError) )
- print "BF: %%s failed (%%s): %%s" %% (bf.node, bf.status, bf.errstr)
+ print("BF: %%s failed (%%s): %%s" %% (bf.node, bf.status, bf.errstr))
if bf.command:
- print "BF: %%s" %% " ".join(Flatten(bf.command))
+ print("BF: %%s" %% " ".join(Flatten(bf.command)))
import atexit
atexit.register(print_build_failures)
diff --git a/test/GetOption/help.py b/test/GetOption/help.py
index e2eeef7..4f15fe6 100644
--- a/test/GetOption/help.py
+++ b/test/GetOption/help.py
@@ -34,9 +34,9 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """\
if GetOption('help'):
- print "GetOption('help') set"
+ print("GetOption('help') set")
else:
- print "no help for you"
+ print("no help for you")
""")
test.run(arguments = '-q -Q', stdout = "no help for you\n")
diff --git a/test/Glob/glob-libpath.py b/test/Glob/glob-libpath.py
index b09aab9..0878090 100644
--- a/test/Glob/glob-libpath.py
+++ b/test/Glob/glob-libpath.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,10 +78,10 @@ test.write(['src', 'util', 'util.cpp'], """int i=0;
test.run(arguments = '-Q .')
if not test.match_re_dotall(test.stdout(), r".*(-L|/LIBPATH:)build[/\\]util.*"):
- print repr(test.stdout())+" should contain -Lbuild/util or /LIBPATH:build\\util"
+ print(repr(test.stdout())+" should contain -Lbuild/util or /LIBPATH:build\\util")
test.fail_test()
if test.match_re_dotall(test.stdout(), r".*(-L|/LIBPATH:)src[/\\]util.*"):
- print repr(test.stdout())+" should not contain -Lsrc/util or /LIBPATH:src\\util"
+ print(repr(test.stdout())+" should not contain -Lsrc/util or /LIBPATH:src\\util")
test.fail_test()
test.pass_test()
diff --git a/test/Install/Install.py b/test/Install/Install.py
index adadfd9..d66660b 100644
--- a/test/Install/Install.py
+++ b/test/Install/Install.py
@@ -129,7 +129,7 @@ test.must_match(['work', 'f2.out'], "f2.in\n")
# if a target can not be unlinked before building it:
test.write(['work', 'f1.in'], "f1.in again again\n")
-os.chmod(test.workpath('work', 'export'), 0555)
+os.chmod(test.workpath('work', 'export'), 0o555)
f = open(f1_out, 'rb')
diff --git a/test/Interactive/version.py b/test/Interactive/version.py
index 96ce51e..d0f362a 100644
--- a/test/Interactive/version.py
+++ b/test/Interactive/version.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__"
"""
@@ -72,7 +73,7 @@ expect2 = r"""scons>>> SCons by Steven Knight et al\.:
stdout = test.stdout() + '\n'
if not test.match_re(stdout, expect1) and not test.match_re(stdout, expect2):
- print repr(stdout)
+ print(repr(stdout))
test.fail_test()
diff --git a/test/Java/multi-step.py b/test/Java/multi-step.py
index 160c523..b43d641 100644
--- a/test/Java/multi-step.py
+++ b/test/Java/multi-step.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__"
@@ -564,7 +565,7 @@ test.must_exist(['buildout', 'jni', 'SampleTest.java'])
# it doesn't exist.
p = test.workpath('buildout', 'jni', 'SampleTest.class')
if not os.path.exists(p):
- print 'Warning: %s does not exist' % p
+ print('Warning: %s does not exist' % p)
test.up_to_date(arguments = '.')
diff --git a/test/LINK/VersionedLib.py b/test/LINK/VersionedLib.py
index 3f4a912..468e3e5 100644
--- a/test/LINK/VersionedLib.py
+++ b/test/LINK/VersionedLib.py
@@ -1,286 +1,288 @@
-#!/usr/bin/env python
-#
-# __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.
-#
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-
-import os
-import sys
-import TestSCons
-
-import SCons.Platform
-import SCons.Defaults
-
-env = SCons.Defaults.DefaultEnvironment()
-platform = SCons.Platform.platform_default()
-tool_list = SCons.Platform.DefaultToolList(platform, env)
-
-if 'gnulink' in tool_list:
- test_plan = [
- {
- 'libversion' : '2',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2') ],
- },
- {
- 'libversion' : '2.5',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5', 'test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2.5'), ('libtest.so.2', 'libtest.so.2.5') ],
- },
- {
- 'libversion' : '2.5.4',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4', 'test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2.5.4'), ('libtest.so.2', 'libtest.so.2.5.4') ],
- },
- {
- 'libversion' : '2.5.4.7.8',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4.7.8', 'test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4.7.8' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2.5.4.7.8'), ('libtest.so.2', 'libtest.so.2.5.4.7.8') ],
- },
- {
- 'libversion' : 'aabf114f',
- 'files' : [ 'libtest.so', 'libtest.so.aabf114f', 'test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.aabf114f' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.aabf114f') ],
- },
- {
- 'libversion' : '2.dfffa11',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.dfffa11', 'test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.dfffa11' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2.dfffa11'), ('libtest.so.2', 'libtest.so.2.dfffa11') ],
- },
- ]
-elif 'applelink' in tool_list:
- # All (?) the files we expect will get created in the current directory
- test_plan = [
- {
- 'libversion' : '2.5.4',
- 'files' : [ 'libtest.dylib', 'libtest.2.5.4.dylib', 'test.os' ],
- 'instfiles' : [ 'libtest.dylib', 'libtest.2.5.4.dylib' ],
- 'symlinks' : [],
- },
- ]
-elif 'cyglink' in tool_list:
- test_plan = [
- {
- 'libversion' : '2',
- 'files' : [ 'cygtest-2.dll', 'libtest-2.dll.a', 'libtest.dll.a', 'test.os' ],
- 'instfiles' : [ 'cygtest-2.dll', 'libtest-2.dll.a', 'libtest.dll.a' ],
- 'symlinks' : [ ('libtest.dll.a', 'libtest-2.dll.a') ],
- },
- {
- 'libversion' : '2.5',
- 'files' : [ 'cygtest-2-5.dll', 'libtest-2-5.dll.a', 'libtest.dll.a', 'test.os' ],
- 'instfiles' : [ 'cygtest-2-5.dll', 'libtest-2-5.dll.a', 'libtest.dll.a' ],
- 'symlinks' : [ ('libtest.dll.a', 'libtest-2-5.dll.a') ],
- },
- {
- 'libversion' : '2.5.4',
- 'files' : [ 'cygtest-2-5-4.dll', 'libtest-2-5-4.dll.a', 'libtest.dll.a', 'test.os' ],
- 'instfiles' : [ 'cygtest-2-5-4.dll', 'libtest-2-5-4.dll.a', 'libtest.dll.a' ],
- 'symlinks' : [ ('libtest.dll.a', 'libtest-2-5-4.dll.a') ],
- },
- {
- 'libversion' : '2.5.4.7.8',
- 'files' : [ 'cygtest-2-5-4-7-8.dll', 'libtest-2-5-4-7-8.dll.a', 'libtest.dll.a', 'test.os' ],
- 'instfiles' : [ 'cygtest-2-5-4-7-8.dll', 'libtest-2-5-4-7-8.dll.a', 'libtest.dll.a' ],
- 'symlinks' : [ ('libtest.dll.a', 'libtest-2-5-4-7-8.dll.a') ],
- },
- {
- 'libversion' : 'aabf114f',
- 'files' : [ 'cygtest-aabf114f.dll', 'libtest-aabf114f.dll.a', 'libtest.dll.a', 'test.os' ],
- 'instfiles' : [ 'cygtest-aabf114f.dll', 'libtest-aabf114f.dll.a', 'libtest.dll.a' ],
- 'symlinks' : [ ('libtest.dll.a', 'libtest-aabf114f.dll.a') ],
- },
- {
- 'libversion' : '2.dfffa11',
- 'files' : [ 'cygtest-2-dfffa11.dll', 'libtest-2-dfffa11.dll.a', 'libtest.dll.a', 'test.os' ],
- 'instfiles' : [ 'cygtest-2-dfffa11.dll', 'libtest-2-dfffa11.dll.a', 'libtest.dll.a' ],
- 'symlinks' : [ ('libtest.dll.a', 'libtest-2-dfffa11.dll.a') ],
- },
- ]
-elif 'mslink' in tool_list:
- test_plan = [
- {
- 'libversion' : '2.5.4',
- 'files' : [ 'test.dll', 'test.lib', 'test.obj' ],
- 'instfiles' : [ 'test.dll', 'test.lib' ],
- 'symlinks' : [],
- },
- ]
-elif 'sunlink' in tool_list:
- test_plan = [
- {
- 'libversion' : '2',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'so_test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2') ],
- },
- {
- 'libversion' : '2.5',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5', 'so_test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2.5'), ('libtest.so.2', 'libtest.so.2.5') ],
- },
- {
- 'libversion' : '2.5.4',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4', 'so_test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2.5.4'), ('libtest.so.2', 'libtest.so.2.5.4') ],
- },
- {
- 'libversion' : '2.5.4.7.8',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4.7.8', 'so_test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4.7.8' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2.5.4.7.8'), ('libtest.so.2', 'libtest.so.2.5.4.7.8') ],
- },
- {
- 'libversion' : 'aabf114f',
- 'files' : [ 'libtest.so', 'libtest.so.aabf114f', 'so_test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.aabf114f' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.aabf114f') ],
- },
- {
- 'libversion' : '2.dfffa11',
- 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.dfffa11', 'so_test.os' ],
- 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.dfffa11' ],
- 'symlinks' : [ ('libtest.so', 'libtest.so.2.dfffa11'), ('libtest.so.2', 'libtest.so.2.dfffa11') ],
- },
- ]
-else:
- test_plan = [
- {
- 'libversion' : '2.5.4',
- 'files' : [ 'libtest.so', 'test.os' ],
- 'instfiles' : [ ],
- },
- ]
-
-test_c_src = """\
-#if _WIN32
-__declspec(dllexport)
-#endif
-int testlib(int n) { return n+1 ; }
-"""
-
-test_c_src2 = """\
-#if _WIN32
-__declspec(dllexport)
-#endif
-int testlib(int n) { return n+11 ; }
-"""
-
-testapp_c_src = """\
-#if _WIN32
-__declspec(dllimport)
-#endif
-int testlib(int n);
-#include <stdio.h>
-int main(int argc, char **argv)
-{
-int itest ;
-
-itest = testlib(2) ;
-printf("results: testlib(2) = %d\\n",itest) ;
-return 0 ;
-}
-"""
-
-for t in test_plan:
-
- test = TestSCons.TestSCons()
-
- libversion = t['libversion']
- files = t['files']
- symlinks = t['symlinks']
- instfiles = t['instfiles']
-
- test.write('SConstruct', """\
-import os
-env = Environment()
-objs = env.SharedObject('test.c')
-mylib = env.SharedLibrary('test', objs, SHLIBVERSION = '%s')
-env.Program('testapp1.c', LIBS = mylib, LIBPATH='.')
-env.Program('testapp2.c', LIBS = ['test'], LIBPATH='.')
-instnode = env.InstallVersionedLib("#/installtest",mylib)
-env.Default(instnode)
-
-# Extra test to ensure that InstallVersionedLib can be called from the DefaultEnvironment
-# Ensures orthogonality where InstallVersionedLib wasn't previously available: SCons gave NameError.
-instnode = InstallVersionedLib("defaultenv-installtest",mylib)
-Default(instnode)
-
-""" % libversion)
-
- test.write('test.c', test_c_src)
- test.write('testapp1.c', testapp_c_src)
- test.write('testapp2.c', testapp_c_src)
-
- test.run(arguments = ['--tree=all'])
-
- for f in files:
- test.must_exist([ f])
- for f in instfiles:
- test.must_exist(['installtest', f])
- test.must_exist(['defaultenv-installtest', f])
-
- wrong_symlinks = []
- for (linkname,expected) in symlinks:
- try:
- endpoint = os.readlink(linkname)
- except OSError, err:
- print "%s (expected symlink %r -> %r)" % (err, linkname, expected)
- wrong_symlinks.append(linkname)
- else:
- if endpoint != expected:
- print "Wrong symlink: %r -> %r (expected symlink: %r -> %r)" % (linkname, endpoint, linkname, expected)
- wrong_symlinks.append(linkname)
-
- if wrong_symlinks:
- test.fail_test(wrong_symlinks)
-
- # modify test.c and make sure it can recompile when links already exist
- test.write('test.c', test_c_src2)
-
- test.run()
-
- test.run(arguments = ['-c'])
-
- for f in files:
- test.must_not_exist([ f])
-
- for f in instfiles:
- test.must_not_exist(['installtest', f])
- test.must_not_exist(['defaultenv-installtest', f])
-
-test.pass_test()
-
-# Local Variables:
-# tab-width:4
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=4 shiftwidth=4:
+#!/usr/bin/env python
+#
+# __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.
+#
+
+from __future__ import print_function
+
+__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
+
+import os
+import sys
+import TestSCons
+
+import SCons.Platform
+import SCons.Defaults
+
+env = SCons.Defaults.DefaultEnvironment()
+platform = SCons.Platform.platform_default()
+tool_list = SCons.Platform.DefaultToolList(platform, env)
+
+if 'gnulink' in tool_list:
+ test_plan = [
+ {
+ 'libversion' : '2',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2') ],
+ },
+ {
+ 'libversion' : '2.5',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5', 'test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2.5'), ('libtest.so.2', 'libtest.so.2.5') ],
+ },
+ {
+ 'libversion' : '2.5.4',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4', 'test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2.5.4'), ('libtest.so.2', 'libtest.so.2.5.4') ],
+ },
+ {
+ 'libversion' : '2.5.4.7.8',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4.7.8', 'test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4.7.8' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2.5.4.7.8'), ('libtest.so.2', 'libtest.so.2.5.4.7.8') ],
+ },
+ {
+ 'libversion' : 'aabf114f',
+ 'files' : [ 'libtest.so', 'libtest.so.aabf114f', 'test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.aabf114f' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.aabf114f') ],
+ },
+ {
+ 'libversion' : '2.dfffa11',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.dfffa11', 'test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.dfffa11' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2.dfffa11'), ('libtest.so.2', 'libtest.so.2.dfffa11') ],
+ },
+ ]
+elif 'applelink' in tool_list:
+ # All (?) the files we expect will get created in the current directory
+ test_plan = [
+ {
+ 'libversion' : '2.5.4',
+ 'files' : [ 'libtest.dylib', 'libtest.2.5.4.dylib', 'test.os' ],
+ 'instfiles' : [ 'libtest.dylib', 'libtest.2.5.4.dylib' ],
+ 'symlinks' : [],
+ },
+ ]
+elif 'cyglink' in tool_list:
+ test_plan = [
+ {
+ 'libversion' : '2',
+ 'files' : [ 'cygtest-2.dll', 'libtest-2.dll.a', 'libtest.dll.a', 'test.os' ],
+ 'instfiles' : [ 'cygtest-2.dll', 'libtest-2.dll.a', 'libtest.dll.a' ],
+ 'symlinks' : [ ('libtest.dll.a', 'libtest-2.dll.a') ],
+ },
+ {
+ 'libversion' : '2.5',
+ 'files' : [ 'cygtest-2-5.dll', 'libtest-2-5.dll.a', 'libtest.dll.a', 'test.os' ],
+ 'instfiles' : [ 'cygtest-2-5.dll', 'libtest-2-5.dll.a', 'libtest.dll.a' ],
+ 'symlinks' : [ ('libtest.dll.a', 'libtest-2-5.dll.a') ],
+ },
+ {
+ 'libversion' : '2.5.4',
+ 'files' : [ 'cygtest-2-5-4.dll', 'libtest-2-5-4.dll.a', 'libtest.dll.a', 'test.os' ],
+ 'instfiles' : [ 'cygtest-2-5-4.dll', 'libtest-2-5-4.dll.a', 'libtest.dll.a' ],
+ 'symlinks' : [ ('libtest.dll.a', 'libtest-2-5-4.dll.a') ],
+ },
+ {
+ 'libversion' : '2.5.4.7.8',
+ 'files' : [ 'cygtest-2-5-4-7-8.dll', 'libtest-2-5-4-7-8.dll.a', 'libtest.dll.a', 'test.os' ],
+ 'instfiles' : [ 'cygtest-2-5-4-7-8.dll', 'libtest-2-5-4-7-8.dll.a', 'libtest.dll.a' ],
+ 'symlinks' : [ ('libtest.dll.a', 'libtest-2-5-4-7-8.dll.a') ],
+ },
+ {
+ 'libversion' : 'aabf114f',
+ 'files' : [ 'cygtest-aabf114f.dll', 'libtest-aabf114f.dll.a', 'libtest.dll.a', 'test.os' ],
+ 'instfiles' : [ 'cygtest-aabf114f.dll', 'libtest-aabf114f.dll.a', 'libtest.dll.a' ],
+ 'symlinks' : [ ('libtest.dll.a', 'libtest-aabf114f.dll.a') ],
+ },
+ {
+ 'libversion' : '2.dfffa11',
+ 'files' : [ 'cygtest-2-dfffa11.dll', 'libtest-2-dfffa11.dll.a', 'libtest.dll.a', 'test.os' ],
+ 'instfiles' : [ 'cygtest-2-dfffa11.dll', 'libtest-2-dfffa11.dll.a', 'libtest.dll.a' ],
+ 'symlinks' : [ ('libtest.dll.a', 'libtest-2-dfffa11.dll.a') ],
+ },
+ ]
+elif 'mslink' in tool_list:
+ test_plan = [
+ {
+ 'libversion' : '2.5.4',
+ 'files' : [ 'test.dll', 'test.lib', 'test.obj' ],
+ 'instfiles' : [ 'test.dll', 'test.lib' ],
+ 'symlinks' : [],
+ },
+ ]
+elif 'sunlink' in tool_list:
+ test_plan = [
+ {
+ 'libversion' : '2',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'so_test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2') ],
+ },
+ {
+ 'libversion' : '2.5',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5', 'so_test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2.5'), ('libtest.so.2', 'libtest.so.2.5') ],
+ },
+ {
+ 'libversion' : '2.5.4',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4', 'so_test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2.5.4'), ('libtest.so.2', 'libtest.so.2.5.4') ],
+ },
+ {
+ 'libversion' : '2.5.4.7.8',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4.7.8', 'so_test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.5.4.7.8' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2.5.4.7.8'), ('libtest.so.2', 'libtest.so.2.5.4.7.8') ],
+ },
+ {
+ 'libversion' : 'aabf114f',
+ 'files' : [ 'libtest.so', 'libtest.so.aabf114f', 'so_test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.aabf114f' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.aabf114f') ],
+ },
+ {
+ 'libversion' : '2.dfffa11',
+ 'files' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.dfffa11', 'so_test.os' ],
+ 'instfiles' : [ 'libtest.so', 'libtest.so.2', 'libtest.so.2.dfffa11' ],
+ 'symlinks' : [ ('libtest.so', 'libtest.so.2.dfffa11'), ('libtest.so.2', 'libtest.so.2.dfffa11') ],
+ },
+ ]
+else:
+ test_plan = [
+ {
+ 'libversion' : '2.5.4',
+ 'files' : [ 'libtest.so', 'test.os' ],
+ 'instfiles' : [ ],
+ },
+ ]
+
+test_c_src = """\
+#if _WIN32
+__declspec(dllexport)
+#endif
+int testlib(int n) { return n+1 ; }
+"""
+
+test_c_src2 = """\
+#if _WIN32
+__declspec(dllexport)
+#endif
+int testlib(int n) { return n+11 ; }
+"""
+
+testapp_c_src = """\
+#if _WIN32
+__declspec(dllimport)
+#endif
+int testlib(int n);
+#include <stdio.h>
+int main(int argc, char **argv)
+{
+int itest ;
+
+itest = testlib(2) ;
+printf("results: testlib(2) = %d\\n",itest) ;
+return 0 ;
+}
+"""
+
+for t in test_plan:
+
+ test = TestSCons.TestSCons()
+
+ libversion = t['libversion']
+ files = t['files']
+ symlinks = t['symlinks']
+ instfiles = t['instfiles']
+
+ test.write('SConstruct', """\
+import os
+env = Environment()
+objs = env.SharedObject('test.c')
+mylib = env.SharedLibrary('test', objs, SHLIBVERSION = '%s')
+env.Program('testapp1.c', LIBS = mylib, LIBPATH='.')
+env.Program('testapp2.c', LIBS = ['test'], LIBPATH='.')
+instnode = env.InstallVersionedLib("#/installtest",mylib)
+env.Default(instnode)
+
+# Extra test to ensure that InstallVersionedLib can be called from the DefaultEnvironment
+# Ensures orthogonality where InstallVersionedLib wasn't previously available: SCons gave NameError.
+instnode = InstallVersionedLib("defaultenv-installtest",mylib)
+Default(instnode)
+
+""" % libversion)
+
+ test.write('test.c', test_c_src)
+ test.write('testapp1.c', testapp_c_src)
+ test.write('testapp2.c', testapp_c_src)
+
+ test.run(arguments = ['--tree=all'])
+
+ for f in files:
+ test.must_exist([ f])
+ for f in instfiles:
+ test.must_exist(['installtest', f])
+ test.must_exist(['defaultenv-installtest', f])
+
+ wrong_symlinks = []
+ for (linkname,expected) in symlinks:
+ try:
+ endpoint = os.readlink(linkname)
+ except OSError as err:
+ print("%s (expected symlink %r -> %r)" % (err, linkname, expected))
+ wrong_symlinks.append(linkname)
+ else:
+ if endpoint != expected:
+ print("Wrong symlink: %r -> %r (expected symlink: %r -> %r)" % (linkname, endpoint, linkname, expected))
+ wrong_symlinks.append(linkname)
+
+ if wrong_symlinks:
+ test.fail_test(wrong_symlinks)
+
+ # modify test.c and make sure it can recompile when links already exist
+ test.write('test.c', test_c_src2)
+
+ test.run()
+
+ test.run(arguments = ['-c'])
+
+ for f in files:
+ test.must_not_exist([ f])
+
+ for f in instfiles:
+ test.must_not_exist(['installtest', f])
+ test.must_not_exist(['defaultenv-installtest', f])
+
+test.pass_test()
+
+# Local Variables:
+# tab-width:4
+# indent-tabs-mode:nil
+# End:
+# vim: set expandtab tabstop=4 shiftwidth=4:
diff --git a/test/Libs/SharedLibraryIxes.py b/test/Libs/SharedLibraryIxes.py
index 6924769..93d67ea 100644
--- a/test/Libs/SharedLibraryIxes.py
+++ b/test/Libs/SharedLibraryIxes.py
@@ -102,7 +102,7 @@ def nameInLib(source, lib, libname):
# When using non-standard prefixes and suffixes, one has to
# provide the full name of the library since scons can not know
# which of the non-standard extension to use.
- #
+ #
# Note that this is not necessarily SHLIBPREFIX and
# SHLIBSUFFIX. These are the ixes of the target library, not the
# ixes of the library that we are linking against.
@@ -130,7 +130,7 @@ def buildAndlinkAgainst(builder, target, source, method, lib, libname, **kw):
# for the linker command line...
if (isMingw or isCygwin) and len(lib) > 1:
lib = lib[1:]
-
+
# Apply the naming method to be tested and call the specified Builder.
(source, LIBS) = method(source, lib, libname)
#build = builder(target=target, source=source, LIBS=LIBS, **kw)
@@ -153,8 +153,8 @@ def buildAndlinkAgainst(builder, target, source, method, lib, libname, **kw):
(list(map(str,lib)), list(map(str, build[0].children())), method.__name__, libname, shlibsuffix)
return build
-def prog(i,
- goomethod, goolibprefix, goolibsuffix,
+def prog(i,
+ goomethod, goolibprefix, goolibsuffix,
foomethod, foolibprefix, foolibsuffix):
'''Build a program
@@ -166,7 +166,7 @@ def prog(i,
foo_name = foolibprefix+'foo'+str(i)+foolibsuffix
prog_name = progprefix+'prog'+str(i)+progsuffix
- print 'Prog: %d, %s, %s, %s' % (i, goo_name, foo_name, prog_name)
+ print('Prog: %d, %s, %s, %s' % (i, goo_name, foo_name, prog_name))
# On Windows, we have to link against the .lib file.
if isWindows:
@@ -179,7 +179,7 @@ def prog(i,
goo_lib = env.SharedLibrary(
goo_name, goo_obj, SHLIBSUFFIX=goolibsuffix)
foo_lib = buildAndlinkAgainst(
- env.SharedLibrary, foo_name, foo_obj,
+ env.SharedLibrary, foo_name, foo_obj,
goomethod, goo_lib, goo_libname, SHLIBSUFFIX=foolibsuffix)
prog = buildAndlinkAgainst(env.Program, prog_name, prog_obj,
foomethod, foo_lib, foo_libname)
@@ -199,8 +199,8 @@ for foolibprefix in prefixes:
for goolibsuffix in suffixes:
for goomethod in libmethods:
tests.append(
- (i,
- goomethod, goolibprefix, goolibsuffix,
+ (i,
+ goomethod, goolibprefix, goolibsuffix,
foomethod, foolibprefix, foolibsuffix))
i = i + 1
diff --git a/test/MSVC/batch-longlines.py b/test/MSVC/batch-longlines.py
index ef7233b..c584aba 100644
--- a/test/MSVC/batch-longlines.py
+++ b/test/MSVC/batch-longlines.py
@@ -1,61 +1,61 @@
-#!/usr/bin/env python
-#
-# __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.
-#
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-
-"""
-Verify operation of Visual C/C++ batch builds with long lines.
-
-Only runs on Windows.
-"""
-
-import TestSCons
-
-test = TestSCons.TestSCons()
-
-test.skip_if_not_msvc()
-
-_python_ = TestSCons._python_
-
-for i in xrange(1,200):
- test.write('source-file-with-quite-a-long-name-maybe-unrealistic-but-who-cares-%05d.cxx'%i,
- '/* source file %d */\nint var%d;\n'%(i,i))
-
-test.write('SConstruct', """
-env = Environment(tools=['msvc', 'mslink'],
- MSVC_BATCH=ARGUMENTS.get('MSVC_BATCH'))
-env.SharedLibrary('mylib', Glob('source*.cxx'))
-""" % locals())
-
-test.run(arguments = 'MSVC_BATCH=1 .')
-
-test.must_exist('mylib.dll')
-
-test.pass_test()
-
-# Local Variables:
-# tab-width:4
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=4 shiftwidth=4:
+#!/usr/bin/env python
+#
+# __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.
+#
+
+__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
+
+"""
+Verify operation of Visual C/C++ batch builds with long lines.
+
+Only runs on Windows.
+"""
+
+import TestSCons
+
+test = TestSCons.TestSCons()
+
+test.skip_if_not_msvc()
+
+_python_ = TestSCons._python_
+
+for i in range(1,200):
+ test.write('source-file-with-quite-a-long-name-maybe-unrealistic-but-who-cares-%05d.cxx'%i,
+ '/* source file %d */\nint var%d;\n'%(i,i))
+
+test.write('SConstruct', """
+env = Environment(tools=['msvc', 'mslink'],
+ MSVC_BATCH=ARGUMENTS.get('MSVC_BATCH'))
+env.SharedLibrary('mylib', Glob('source*.cxx'))
+""" % locals())
+
+test.run(arguments = 'MSVC_BATCH=1 .')
+
+test.must_exist('mylib.dll')
+
+test.pass_test()
+
+# Local Variables:
+# tab-width:4
+# indent-tabs-mode:nil
+# End:
+# vim: set expandtab tabstop=4 shiftwidth=4:
diff --git a/test/MSVC/msvc.py b/test/MSVC/msvc.py
index c68fb45..a70ed67 100644
--- a/test/MSVC/msvc.py
+++ b/test/MSVC/msvc.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__"
@@ -181,9 +182,9 @@ slow = time.time() - start
# using precompiled headers should be faster
limit = slow*0.90
if fast >= limit:
- print "Using precompiled headers was not fast enough:"
- print "slow.obj: %.3fs" % slow
- print "fast.obj: %.3fs (expected less than %.3fs)" % (fast, limit)
+ print("Using precompiled headers was not fast enough:")
+ print("slow.obj: %.3fs" % slow)
+ print("fast.obj: %.3fs (expected less than %.3fs)" % (fast, limit))
test.fail_test()
# Modifying resource.h should cause both the resource and precompiled header to be rebuilt:
diff --git a/test/MSVC/query_vcbat.py b/test/MSVC/query_vcbat.py
index 328345d..428fe56 100644
--- a/test/MSVC/query_vcbat.py
+++ b/test/MSVC/query_vcbat.py
@@ -49,7 +49,7 @@ DefaultEnvironment(tools = [])
# print k, v
#MergeMSVSBatFile(env, 9.0)
#print env['ENV']['PATH']
-print query_versions()
+print(query_versions())
""")
test.run(stderr = None)
diff --git a/test/MSVS/vs-10.0-exec.py b/test/MSVS/vs-10.0-exec.py
index 86b4042..1a4b59a 100644
--- a/test/MSVS/vs-10.0-exec.py
+++ b/test/MSVS/vs-10.0-exec.py
@@ -55,7 +55,7 @@ if not msvs_version in test.msvs_versions():
test.run(arguments = '-n -q -Q -f -', stdin = """\
env = Environment(tools = ['msvc'], MSVS_VERSION='%(msvs_version)s')
-print "os.environ.update(%%s)" %% repr(env['ENV'])
+print("os.environ.update(%%s)" %% repr(env['ENV']))
""" % locals())
exec(test.stdout())
diff --git a/test/MSVS/vs-8.0-exec.py b/test/MSVS/vs-8.0-exec.py
index cff7ca2..96c4c29 100644
--- a/test/MSVS/vs-8.0-exec.py
+++ b/test/MSVS/vs-8.0-exec.py
@@ -55,7 +55,7 @@ if not msvs_version in test.msvs_versions():
test.run(arguments = '-n -q -Q -f -', stdin = """\
env = Environment(tools = ['msvc'], MSVS_VERSION='%(msvs_version)s')
-print "os.environ.update(%%s)" %% repr(env['ENV'])
+print("os.environ.update(%%s)" %% repr(env['ENV']))
""" % locals())
exec(test.stdout())
diff --git a/test/Mkdir.py b/test/Mkdir.py
index 4d309bb..8ace476 100644
--- a/test/Mkdir.py
+++ b/test/Mkdir.py
@@ -178,7 +178,7 @@ test.write(['work3', 'sub1', 'sub11', 'SConscript'], """\
#/sub1/sub11/SConscript-------------------------
Import('env test1')
test11 = test1 + '/test11'
-print 'test11 = ' + test11
+print('test11 = ' + test11)
env.Command(Dir(test11), '', Mkdir('$TARGET'))
""")
diff --git a/test/NodeOps.py b/test/NodeOps.py
index 5062b72..1f856c3 100644
--- a/test/NodeOps.py
+++ b/test/NodeOps.py
@@ -43,7 +43,7 @@ _lib = TestSCons._lib
_obj = TestSCons._obj
dll_ = TestSCons.dll_
_dll = TestSCons._dll
-
+
if os.name == 'posix':
os.environ['LD_LIBRARY_PATH'] = '.'
if sys.platform.find('irix') > -1:
@@ -71,7 +71,7 @@ if %(_E)s:
exists = [N.exists() for N in Nodes]
real2 = [os.path.exists(str(N)) for N in Nodes]
for N,D,R,E,F in zip(Nodes, derived, real1, exists, real2):
- print '%%s: %%s %%s %%s %%s'%%(N,D,R,E,F)
+ print('%%s: %%s %%s %%s %%s'%%(N,D,R,E,F))
foo.SharedLibrary(target = 'foo', source = 'foo%(_obj)s')
bar.SharedLibrary(target = 'bar', source = 'bar%(_obj)s')
diff --git a/test/ParseConfig.py b/test/ParseConfig.py
index 9bcc440..efb3a75 100644
--- a/test/ParseConfig.py
+++ b/test/ParseConfig.py
@@ -38,17 +38,17 @@ test_config3 = test.workpath('test-config3')
# File node.
# It used to be returned as the 'static_libs' output of ParseConfig.
test.write(test_config1, """\
-print "-I/usr/include/fum -Ibar -X -arch i386"
-print "-L/usr/fax -Lfoo -lxxx abc"
+print("-I/usr/include/fum -Ibar -X -arch i386")
+print("-L/usr/fax -Lfoo -lxxx abc")
""")
test.write(test_config2, """\
-print "-L foo -L lib_dir"
+print("-L foo -L lib_dir")
""")
# This is like what wxWidgets does on OSX w/ Universal Binaries
test.write(test_config3, """\
-print "-L foo -L lib_dir -isysroot /tmp -arch ppc -arch i386"
+print("-L foo -L lib_dir -isysroot /tmp -arch ppc -arch i386")
""")
test.write('SConstruct1', """
@@ -56,10 +56,10 @@ env = Environment(CPPPATH = [], LIBPATH = [], LIBS = [],
CCFLAGS = '-pipe -Wall')
env.ParseConfig([r'%(_python_)s', r"%(test_config1)s", "--libs --cflags"])
env.ParseConfig([r'%(_python_)s', r"%(test_config2)s", "--libs --cflags"])
-print env['CPPPATH']
-print env['LIBPATH']
-print [str(x) for x in env['LIBS']]
-print env['CCFLAGS']
+print(env['CPPPATH'])
+print(env['LIBPATH'])
+print([str(x) for x in env['LIBS']])
+print(env['CCFLAGS'])
""" % locals())
test.write('SConstruct2', """
@@ -68,10 +68,10 @@ env = Environment(CPPPATH = [], LIBPATH = [], LIBS = [],
PYTHON = r'%(_python_)s')
env.ParseConfig(r"$PYTHON %(test_config1)s --libs --cflags")
env.ParseConfig(r"$PYTHON %(test_config2)s --libs --cflags")
-print env['CPPPATH']
-print env['LIBPATH']
-print [str(x) for x in env['LIBS']]
-print env['CCFLAGS']
+print(env['CPPPATH'])
+print(env['LIBPATH'])
+print([str(x) for x in env['LIBS']])
+print(env['CCFLAGS'])
""" % locals())
test.write('SConstruct3', """
@@ -79,10 +79,10 @@ env = Environment(CPPPATH = [], LIBPATH = [], LIBS = [],
CCFLAGS = '-pipe -Wall',
PYTHON = r'%(_python_)s')
env.ParseConfig(r"$PYTHON %(test_config3)s --libs --cflags")
-print env['CPPPATH']
-print env['LIBPATH']
-print [str(x) for x in env['LIBS']]
-print env['CCFLAGS']
+print(env['CPPPATH'])
+print(env['LIBPATH'])
+print([str(x) for x in env['LIBS']])
+print(env['CCFLAGS'])
""" % locals())
good_stdout = """\
diff --git a/test/Platform.py b/test/Platform.py
index 23068c4..924dbc7 100644
--- a/test/Platform.py
+++ b/test/Platform.py
@@ -31,27 +31,27 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
env = Environment()
Platform('cygwin')(env)
-print "'%s'" % env['PROGSUFFIX']
+print("'%s'" % env['PROGSUFFIX'])
assert env['SHELL'] == 'sh'
Platform('os2')(env)
-print "'%s'" % env['PROGSUFFIX']
+print("'%s'" % env['PROGSUFFIX'])
env.Platform('posix')
-print "'%s'" % env['PROGSUFFIX']
+print("'%s'" % env['PROGSUFFIX'])
Platform('win32')(env)
-print "'%s'" % env['PROGSUFFIX']
+print("'%s'" % env['PROGSUFFIX'])
SConscript('SConscript')
""")
test.write('SConscript', """
env = Environment()
Platform('cygwin')(env)
-print "'%s'" % env['LIBSUFFIX']
+print("'%s'" % env['LIBSUFFIX'])
Platform('os2')(env)
-print "'%s'" % env['LIBSUFFIX']
+print("'%s'" % env['LIBSUFFIX'])
env.Platform('posix')
-print "'%s'" % env['LIBSUFFIX']
+print("'%s'" % env['LIBSUFFIX'])
Platform('win32')(env)
-print "'%s'" % env['LIBSUFFIX']
+print("'%s'" % env['LIBSUFFIX'])
""")
expect = test.wrap_stdout(read_str = """'.exe'
diff --git a/test/QT/QTFLAGS.py b/test/QT/QTFLAGS.py
index 008397a..f6aa00f 100644
--- a/test/QT/QTFLAGS.py
+++ b/test/QT/QTFLAGS.py
@@ -136,7 +136,7 @@ int main() {
""")
test.run(chdir = 'work1', arguments = "mytest" + _exe)
-
+
test.must_exist(['work1', 'mmmmocFromH.cxx'],
['work1', 'mocmocFromCpp.inl'],
['work1', 'an_ui_file.cxx'],
@@ -168,15 +168,15 @@ env1 = Environment(tools=['qt'],
cpppath = env1.subst('$CPPPATH')
if os.path.normpath(cpppath) != os.path.join(r'%(QTDIR)s', 'h64'):
- print cpppath
+ print(cpppath)
Exit(1)
libpath = env1.subst('$LIBPATH')
if os.path.normpath(libpath) != os.path.join(r'%(QTDIR)s', 'lib64'):
- print libpath
+ print(libpath)
Exit(2)
qt_moc = env1.subst('$QT_MOC')
if os.path.normpath(qt_moc) != os.path.join(r'%(QTDIR)s', 'bin64', 'moc'):
- print qt_moc
+ print(qt_moc)
Exit(3)
env2 = Environment(tools=['default', 'qt'],
diff --git a/test/QT/copied-env.py b/test/QT/copied-env.py
index efa91be..3989143 100644
--- a/test/QT/copied-env.py
+++ b/test/QT/copied-env.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__"
@@ -70,8 +71,8 @@ moc_MyForm = [x for x in test.stdout().split('\n') if x.find('moc_MyForm') != -1
MYLIB_IMPL = [x for x in moc_MyForm if x.find('MYLIB_IMPL') != -1]
if not MYLIB_IMPL:
- print "Did not find MYLIB_IMPL on moc_MyForm compilation line:"
- print test.stdout()
+ print("Did not find MYLIB_IMPL on moc_MyForm compilation line:")
+ print(test.stdout())
test.fail_test()
test.pass_test()
diff --git a/test/QT/manual.py b/test/QT/manual.py
index d911fb3..1f140ae 100644
--- a/test/QT/manual.py
+++ b/test/QT/manual.py
@@ -58,7 +58,7 @@ env.Ignore( moc, moc )
sources.extend(env.Uic(['include/uic_fff.hpp', 'fff.cpp', 'fff.moc.cpp'],
'ui/fff.ui')[1:])
-print list(map(str,sources))
+print(list(map(str,sources)))
env.Program(target='aaa',
source=sources,
CPPPATH=['$CPPPATH', './include'],
@@ -68,7 +68,7 @@ env.Program(target='aaa',
test.write('aaa.cpp', r"""
#include "aaa.h"
""")
-
+
test.write(['include', 'aaa.h'], r"""
#include "my_qobject.h"
void aaa(void) Q_OBJECT;
@@ -91,7 +91,7 @@ void ccc(void)
test.write('ddd.cpp', r"""
#include "ddd.h"
""")
-
+
test.write(['include', 'ddd.h'], r"""
#include "my_qobject.h"
void ddd(void) Q_OBJECT;
diff --git a/test/QT/warnings.py b/test/QT/warnings.py
index a861b24..a1cf221 100644
--- a/test/QT/warnings.py
+++ b/test/QT/warnings.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__"
@@ -59,8 +60,8 @@ scons: warning: Generated moc file 'aaa.moc' is not included by 'aaa.cpp'
""" + TestSCons.file_expr
if not re.search(match12, test.stderr()):
- print "Did not find expected regular expression in stderr:"
- print test.stderr()
+ print("Did not find expected regular expression in stderr:")
+ print(test.stderr())
test.fail_test()
os.environ['QTDIR'] = test.QT
diff --git a/test/Repository/Default.py b/test/Repository/Default.py
index 127c29a..44aecfb 100644
--- a/test/Repository/Default.py
+++ b/test/Repository/Default.py
@@ -46,7 +46,7 @@ test.write(['repository', 'SConstruct'], r"""
def copy(env, source, target):
source = str(source[0])
target = str(target[0])
- print 'copy() < %s > %s' % (source, target)
+ print('copy() < %s > %s' % (source, target))
open(target, "wb").write(open(source, "rb").read())
Build = Builder(action=copy)
diff --git a/test/Repository/Local.py b/test/Repository/Local.py
index 1b63345..ea03281 100644
--- a/test/Repository/Local.py
+++ b/test/Repository/Local.py
@@ -48,7 +48,7 @@ test.write(['repository', 'SConstruct'], r"""
def copy(env, source, target):
source = str(source[0])
target = str(target[0])
- print 'copy() < %s > %s' % (source, target)
+ print('copy() < %s > %s' % (source, target))
open(target, "wb").write(open(source, "rb").read())
Build = Builder(action=copy)
@@ -65,7 +65,7 @@ SConscript('build/SConscript')
test.write(['repository', 'src', 'SConscript'], r"""
def bbb_copy(env, source, target):
target = str(target[0])
- print 'bbb_copy()'
+ print('bbb_copy()')
open(target, "wb").write(open('build/bbb.1', "rb").read())
Import("env")
diff --git a/test/Repository/VariantDir.py b/test/Repository/VariantDir.py
index ec723c8..0258ff5 100644
--- a/test/Repository/VariantDir.py
+++ b/test/Repository/VariantDir.py
@@ -48,7 +48,7 @@ test.write(['repository', 'src', 'SConscript'], r"""
def cat(env, source, target):
target = str(target[0])
source = list(map(str, source))
- print 'cat(%s) > %s' % (source, target)
+ print('cat(%s) > %s' % (source, target))
f = open(target, "wb")
for src in source:
f.write(open(src, "rb").read())
diff --git a/test/Repository/option-c.py b/test/Repository/option-c.py
index ea989c2..c06c7d8 100644
--- a/test/Repository/option-c.py
+++ b/test/Repository/option-c.py
@@ -65,7 +65,7 @@ test.write(['repository', 'SConstruct'], r"""
def copy(env, source, target):
source = str(source[0])
target = str(target[0])
- print 'copy() < %s > %s' % (source, target)
+ print('copy() < %s > %s' % (source, target))
open(target, "wb").write(open(source, "rb").read())
Build = Builder(action=copy)
diff --git a/test/Repository/option-n.py b/test/Repository/option-n.py
index 220baad..2a0ae5d 100644
--- a/test/Repository/option-n.py
+++ b/test/Repository/option-n.py
@@ -48,7 +48,7 @@ test.write(['repository', 'SConstruct'], r"""
def copy(env, source, target):
source = str(source[0])
target = str(target[0])
- print 'copy() < %s > %s' % (source, target)
+ print('copy() < %s > %s' % (source, target))
open(target, "wb").write(open(source, "rb").read())
Build = Builder(action=copy)
diff --git a/test/Repository/targets.py b/test/Repository/targets.py
index 62f4785..0fbc896 100644
--- a/test/Repository/targets.py
+++ b/test/Repository/targets.py
@@ -43,7 +43,7 @@ test.write(['repository', 'SConstruct'], """
def cat(env, source, target):
target = str(target[0])
source = list(map(str, source))
- print 'cat(%s) > %s' % (source, target)
+ print('cat(%s) > %s' % (source, target))
f = open(target, "wb")
for src in source:
f.write(open(src, "rb").read())
diff --git a/test/SConscript/Return.py b/test/SConscript/Return.py
index a810c7c..997de9d 100644
--- a/test/SConscript/Return.py
+++ b/test/SConscript/Return.py
@@ -39,50 +39,50 @@ x = SConscript('SConscript2')
y, z = SConscript('SConscript3')
a4, b4 = SConscript('SConscript4')
foo, bar = SConscript('SConscript5')
-print "x =", x
-print "y =", y
-print "z =", z
-print "a4 =", a4
-print "b4 =", b4
-print "foo =", foo
-print "bar =", bar
+print ("x =", x)
+print ("y =", y)
+print ("z =", z)
+print ("a4 =", a4)
+print ("b4 =", b4)
+print ("foo =", foo)
+print ("bar =", bar)
""")
test.write('SConscript1', """\
-print "line 1"
+print ("line 1")
Return()
-print "line 2"
+print ("line 2")
""")
test.write('SConscript2', """\
-print "line 3"
+print ("line 3")
x = 7
Return('x')
-print "line 4"
+print ("line 4")
""")
test.write('SConscript3', """\
-print "line 5"
+print ("line 5")
y = 8
z = 9
Return('y z')
-print "line 6"
+print ("line 6")
""")
test.write('SConscript4', """\
a4 = 'aaa'
b4 = 'bbb'
-print "line 7"
+print ("line 7")
Return('a4', 'b4', stop=False)
b4 = 'b-after'
-print "line 8"
+print ("line 8")
""")
test.write('SConscript5', """\
foo = 'foo'
bar = 'bar'
Return(["foo", "bar"])
-print "line 9"
+print ("line 9")
""")
expect = """\
diff --git a/test/SConscript/SConscript.py b/test/SConscript/SConscript.py
index c8453a7..d1e09ce 100644
--- a/test/SConscript/SConscript.py
+++ b/test/SConscript/SConscript.py
@@ -37,7 +37,7 @@ import foo
assert foo.foo == 4
-print "SConstruct", os.getcwd()
+print ("SConstruct", os.getcwd())
SConscript('SConscript')
x1 = "SConstruct x1"
@@ -85,11 +85,11 @@ SConscript('SConscript7')
test.write('SConscript', """\
-# os should not be automajically imported:
+# os should not be automatically imported:
assert "os" not in globals()
import os
-print "SConscript " + os.getcwd()
+print ("SConscript " + os.getcwd())
""")
test.write('SConscript1', """
diff --git a/test/SConscript/env.py b/test/SConscript/env.py
index 42963ff..a16866c 100644
--- a/test/SConscript/env.py
+++ b/test/SConscript/env.py
@@ -36,7 +36,7 @@ test.subdir('sub1', 'sub2')
test.write("SConstruct", """\
env = Environment(SUB1='sub1', SUB2='sub2')
-print "SConstruct"
+print("SConstruct")
x = 'xxx'
y = 'yyy'
env.Export(["x", "y"])
@@ -49,15 +49,15 @@ env.SConscript(['s3', 's4'])
test.write(['sub1', 'SConscript'], """\
env = Environment()
env.Import("x")
-print "sub1/SConscript"
-print "x =", x
+print("sub1/SConscript")
+print("x =", x)
""")
test.write(['sub2', 'SConscript'], """\
env = Environment()
env.Import("y")
-print "sub2/SConscript"
-print "y =", y
+print("sub2/SConscript")
+print("y =", y)
""")
test.write('s1', "\n")
diff --git a/test/SConscript/white-space.py b/test/SConscript/white-space.py
index 06acea8..cc8f00e 100644
--- a/test/SConscript/white-space.py
+++ b/test/SConscript/white-space.py
@@ -38,7 +38,7 @@ SConscript('white space/SConscript')
""")
test.write(['white space', 'SConscript'], """\
-print "`white space/SConscript'"
+print("`white space/SConscript'")
""")
expect = test.wrap_stdout(read_str = "`white space/SConscript'\n",
diff --git a/test/SConsignFile/use-dbhash.py b/test/SConsignFile/use-dbhash.py
index bf9868b..f70c8b0 100644
--- a/test/SConsignFile/use-dbhash.py
+++ b/test/SConsignFile/use-dbhash.py
@@ -35,7 +35,7 @@ _python_ = TestSCons._python_
test = TestSCons.TestSCons()
try:
- import dbhash
+ import dbm.bsd
except ImportError:
test.skip_test('No dbhash in this version of Python; skipping test.\n')
diff --git a/test/SConsignFile/use-dbm.py b/test/SConsignFile/use-dbm.py
index 75f088d..90983b3 100644
--- a/test/SConsignFile/use-dbm.py
+++ b/test/SConsignFile/use-dbm.py
@@ -35,7 +35,7 @@ _python_ = TestSCons._python_
test = TestSCons.TestSCons()
try:
- import dbm
+ import dbm.ndbm
except ImportError:
test.skip_test('No dbm in this version of Python; skipping test.\n')
diff --git a/test/SConsignFile/use-dumbdbm.py b/test/SConsignFile/use-dumbdbm.py
index 434435a..02a52da 100644
--- a/test/SConsignFile/use-dumbdbm.py
+++ b/test/SConsignFile/use-dumbdbm.py
@@ -35,7 +35,7 @@ _python_ = TestSCons._python_
test = TestSCons.TestSCons()
try:
- import dumbdbm
+ import dbm.dumb
except ImportError:
test.skip_test('No dumbdbm in this version of Python; skipping test.\n')
diff --git a/test/SConsignFile/use-gdbm.py b/test/SConsignFile/use-gdbm.py
index 1eb3645..a7e4f59 100644
--- a/test/SConsignFile/use-gdbm.py
+++ b/test/SConsignFile/use-gdbm.py
@@ -35,7 +35,7 @@ _python_ = TestSCons._python_
test = TestSCons.TestSCons()
try:
- import gdbm
+ import dbm.gnu
except ImportError:
test.skip_test('No gdbm in this version of Python; skipping test.\n')
diff --git a/test/SConstruct.py b/test/SConstruct.py
index 15e1c1b..9b2807f 100644
--- a/test/SConstruct.py
+++ b/test/SConstruct.py
@@ -41,7 +41,7 @@ wpath = test.workpath()
test.write('sconstruct', """
import os
-print "sconstruct", os.getcwd()
+print("sconstruct", os.getcwd())
""")
test.run(arguments = ".",
@@ -51,7 +51,7 @@ test.run(arguments = ".",
test.write('Sconstruct', """
import os
-print "Sconstruct", os.getcwd()
+print("Sconstruct", os.getcwd())
""")
test.run(arguments = ".",
@@ -60,7 +60,7 @@ test.run(arguments = ".",
test.write('SConstruct', """
import os
-print "SConstruct", os.getcwd()
+print("SConstruct", os.getcwd())
""")
test.run(arguments = ".",
diff --git a/test/SHELL.py b/test/SHELL.py
index 93ed0b1..faee27f 100644
--- a/test/SHELL.py
+++ b/test/SHELL.py
@@ -64,7 +64,7 @@ ofp.close()
sys.exit(0)
""" % locals())
-os.chmod(my_shell, 0755)
+os.chmod(my_shell, 0o755)
test.write('SConstruct', """\
env = Environment(SHELL = r'%(my_shell)s')
diff --git a/test/SWIG/SWIG.py b/test/SWIG/SWIG.py
index d53fa49..38bdc97 100644
--- a/test/SWIG/SWIG.py
+++ b/test/SWIG/SWIG.py
@@ -48,14 +48,14 @@ for opt, arg in opts:
if opt == '-c': pass
elif opt == '-o': out = arg
elif opt == '-v' and arg == 'ersion':
- print ""
- print "SWIG Version 0.1.2"
- print ""
- print "Compiled with g++ [x86_64-pc-linux-gnu]"
- print ""
- print "Configured options: +pcre"
- print ""
- print "Please see http://www.swig.org for reporting bugs and further information"
+ print("")
+ print("SWIG Version 0.1.2")
+ print("")
+ print("Compiled with g++ [x86_64-pc-linux-gnu]")
+ print("")
+ print("Configured options: +pcre")
+ print("")
+ print("Please see http://www.swig.org for reporting bugs and further information")
sys.exit(0)
infile = open(args[0], 'rb')
outfile = open(out, 'wb')
@@ -68,7 +68,7 @@ sys.exit(0)
test.write('SConstruct', """
env = Environment(tools=['default', 'swig'],
SWIG = [r'%(python)s', 'myswig.py'])
-print env.subst("Using SWIG $SWIGVERSION")
+print(env.subst("Using SWIG $SWIGVERSION"))
env.Program(target = 'test1', source = 'test1.i')
env.CFile(target = 'test2', source = 'test2.i')
env.Clone(SWIGFLAGS = '-c++').Program(target = 'test3', source = 'test3.i')
diff --git a/test/Scanner/CrossLanguageNoExtension.py b/test/Scanner/CrossLanguageNoExtension.py
index 5bf205f..0016ca5 100644
--- a/test/Scanner/CrossLanguageNoExtension.py
+++ b/test/Scanner/CrossLanguageNoExtension.py
@@ -45,11 +45,11 @@ def scan(node, env, scanpaths, arg):
return includes
def kfile_scan(node, env, scanpaths, arg):
- print 'kscan: ' + str(node)
+ print('kscan: ' + str(node))
return scan(node, env, scanpaths, arg)
def k2file_scan(node, env, scanpaths, arg):
- print 'k2scan: ' + str(node)
+ print('k2scan: ' + str(node))
return scan(node, env, scanpaths, arg)
kscan = Scanner(name = 'kfile',
diff --git a/test/Scanner/empty-implicit.py b/test/Scanner/empty-implicit.py
index 0323240..45fe952 100644
--- a/test/Scanner/empty-implicit.py
+++ b/test/Scanner/empty-implicit.py
@@ -37,7 +37,7 @@ test.write('SConstruct', r"""
import os.path
def scan(node, env, envkey, arg):
- print 'XScanner: node =', os.path.split(str(node))[1]
+ print('XScanner: node =', os.path.split(str(node))[1])
return []
def exists_check(node, env):
@@ -52,7 +52,7 @@ XScanner = Scanner(name = 'XScanner',
def echo(env, target, source):
t = os.path.split(str(target[0]))[1]
s = os.path.split(str(source[0]))[1]
- print 'create %s from %s' % (t, s)
+ print('create %s from %s' % (t, s))
open(t, 'wb').write(open(s, 'rb').read())
Echo = Builder(action = Action(echo, None),
diff --git a/test/Scanner/generated.py b/test/Scanner/generated.py
index b41c7c8..7246cbe 100644
--- a/test/Scanner/generated.py
+++ b/test/Scanner/generated.py
@@ -317,8 +317,8 @@ def write_out(file, dict):
class CScannerCounter(object):
def __init__(self, original_CScanner, *args, **kw):
self.original_CScanner = original_CScanner
- def __cmp__(self, *args, **kw):
- return self.original_CScanner.__cmp__(*args, **kw)
+ def __eq__(self, *args, **kw):
+ return self.original_CScanner.__eq__(*args, **kw)
def __hash__(self, *args, **kw):
return self.original_CScanner.__hash__(*args, **kw)
def __str__(self, *args, **kw):
diff --git a/test/Scanner/scan-once.py b/test/Scanner/scan-once.py
index d68f918..eac1f49 100644
--- a/test/Scanner/scan-once.py
+++ b/test/Scanner/scan-once.py
@@ -36,7 +36,7 @@ test.write('SConstruct', r"""
import os.path
def scan(node, env, envkey, arg):
- print 'XScanner: node =', os.path.split(str(node))[1]
+ print('XScanner: node =', os.path.split(str(node))[1])
return []
def exists_check(node, env):
@@ -51,7 +51,7 @@ XScanner = Scanner(name = 'XScanner',
def echo(env, target, source):
t = os.path.split(str(target[0]))[1]
s = os.path.split(str(source[0]))[1]
- print 'create %s from %s' % (t, s)
+ print('create %s from %s' % (t, s))
Echo = Builder(action = Action(echo, None),
src_suffix = '.x',
diff --git a/test/Scanner/unicode.py b/test/Scanner/unicode.py
index 55e22bd..2737f7d 100644
--- a/test/Scanner/unicode.py
+++ b/test/Scanner/unicode.py
@@ -35,12 +35,12 @@ _python_ = TestSCons._python_
test = TestSCons.TestSCons()
-try:
- unicode
-except NameError:
- import sys
- msg = "Unicode not supported by Python version %s; skipping test\n"
- test.skip_test(msg % sys.version[:3])
+## try:
+## unicode
+## except NameError:
+## import sys
+## msg = "Unicode not supported by Python version %s; skipping test\n"
+## test.skip_test(msg % sys.version[:3])
import codecs
@@ -102,28 +102,28 @@ include utf16be.k
foo.k 1 line 4
""")
-contents = unicode("""\
+contents = (u"""\
ascii.k 1 line 1
include ascii.inc
ascii.k 1 line 3
""")
test.write('ascii.k', contents.encode('ascii'))
-contents = unicode("""\
+contents = (u"""\
utf8.k 1 line 1
include utf8.inc
utf8.k 1 line 3
""")
test.write('utf8.k', codecs.BOM_UTF8 + contents.encode('utf-8'))
-contents = unicode("""\
+contents = (u"""\
utf16le.k 1 line 1
include utf16le.inc
utf16le.k 1 line 3
""")
test.write('utf16le.k', codecs.BOM_UTF16_LE + contents.encode('utf-16-le'))
-contents = unicode("""\
+contents = (u"""\
utf16be.k 1 line 1
include utf16be.inc
utf16be.k 1 line 3
diff --git a/test/Split.py b/test/Split.py
index e98e299..c0533fa 100644
--- a/test/Split.py
+++ b/test/Split.py
@@ -30,19 +30,19 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
env = Environment(BBB = 'bbb', CCC = 'ccc')
-print Split('aaa')
-print Split('aaa $BBB')
-print env.Split('bbb $CCC')
-print env.Split('$BBB ccc')
-print Split(['ddd', 'eee'])
+print(Split('aaa'))
+print(Split('aaa $BBB'))
+print(env.Split('bbb $CCC'))
+print(env.Split('$BBB ccc'))
+print(Split(['ddd', 'eee']))
SConscript('SConscript')
""")
test.write('SConscript', """
env = Environment(FFF='fff', JJJ='jjj')
-print env.Split('${FFF}.f')
-print Split('ggg hhh')
-print env.Split(['iii', '$JJJ'])
+print(env.Split('${FFF}.f'))
+print(Split('ggg hhh'))
+print(env.Split(['iii', '$JJJ']))
""")
expect = """\
diff --git a/test/Subst/AllowSubstExceptions.py b/test/Subst/AllowSubstExceptions.py
index 286f189..7f2a9aa 100644
--- a/test/Subst/AllowSubstExceptions.py
+++ b/test/Subst/AllowSubstExceptions.py
@@ -52,37 +52,37 @@ assert env.subst_list('${INDEX[999]}') == [[]]
AllowSubstExceptions()
try: env.subst('$NAME')
-except SCons.Errors.UserError, e: print e
+except SCons.Errors.UserError, e: print(e)
else: raise Exception("did not catch expected SCons.Errors.UserError")
try: env.subst('${NAME}')
-except SCons.Errors.UserError, e: print e
+except SCons.Errors.UserError, e: print(e)
else: raise Exception("did not catch expected SCons.Errors.UserError")
try: env.subst('${INDEX[999]}')
-except SCons.Errors.UserError, e: print e
+except SCons.Errors.UserError, e: print(e)
else: raise Exception("did not catch expected SCons.Errors.UserError")
try: env.subst_list('$NAME')
-except SCons.Errors.UserError, e: print e
+except SCons.Errors.UserError, e: print(e)
else: raise Exception("did not catch expected SCons.Errors.UserError")
try: env.subst_list('${NAME}')
-except SCons.Errors.UserError, e: print e
+except SCons.Errors.UserError, e: print(e)
else: raise Exception("did not catch expected SCons.Errors.UserError")
try: env.subst_list('${INDEX[999]}')
-except SCons.Errors.UserError, e: print e
+except SCons.Errors.UserError, e: print(e)
else: raise Exception("did not catch expected SCons.Errors.UserError")
try: env.subst('${1/0}')
-except SCons.Errors.UserError, e: print e
+except SCons.Errors.UserError, e: print(e)
else: raise Exception("did not catch expected SCons.Errors.UserError")
try: env.subst_list('${1/0}')
-except SCons.Errors.UserError, e: print e
+except SCons.Errors.UserError, e: print(e)
else: raise Exception("did not catch expected SCons.Errors.UserError")
AllowSubstExceptions(ZeroDivisionError)
diff --git a/test/TARGETS.py b/test/TARGETS.py
index 5b36c49..0ffc3b6 100644
--- a/test/TARGETS.py
+++ b/test/TARGETS.py
@@ -35,11 +35,11 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
-print COMMAND_LINE_TARGETS
-print list(map(str, BUILD_TARGETS))
+print(COMMAND_LINE_TARGETS)
+print(list(map(str, BUILD_TARGETS)))
Default('.')
-print COMMAND_LINE_TARGETS
-print list(map(str, BUILD_TARGETS))
+print(COMMAND_LINE_TARGETS)
+print(list(map(str, BUILD_TARGETS)))
""")
test.write('aaa', 'aaa\n')
@@ -68,17 +68,17 @@ test.run(arguments = 'bbb ccc=xyz -n aaa', stdout = expect)
test.write('SConstruct', """
env = Environment()
-print list(map(str, DEFAULT_TARGETS))
-print list(map(str, BUILD_TARGETS))
+print(list(map(str, DEFAULT_TARGETS)))
+print(list(map(str, BUILD_TARGETS)))
Default('aaa')
-print list(map(str, DEFAULT_TARGETS))
-print list(map(str, BUILD_TARGETS))
+print(list(map(str, DEFAULT_TARGETS)))
+print(list(map(str, BUILD_TARGETS)))
env.Default('bbb')
-print list(map(str, DEFAULT_TARGETS))
-print list(map(str, BUILD_TARGETS))
+print(list(map(str, DEFAULT_TARGETS)))
+print(list(map(str, BUILD_TARGETS)))
env.Default(None)
-print list(map(str, DEFAULT_TARGETS))
-print list(map(str, BUILD_TARGETS))
+print(list(map(str, DEFAULT_TARGETS)))
+print(list(map(str, BUILD_TARGETS)))
env.Default('ccc')
""")
@@ -113,9 +113,9 @@ test.run(arguments = '.', stdout = expect)
test.write('SConstruct', """\
-print list(map(str, BUILD_TARGETS))
+print(list(map(str, BUILD_TARGETS)))
SConscript('SConscript')
-print list(map(str, BUILD_TARGETS))
+print(list(map(str, BUILD_TARGETS)))
""")
test.write('SConscript', """\
diff --git a/test/TEMPFILEPREFIX.py b/test/TEMPFILEPREFIX.py
index f9b3240..8e756af 100644
--- a/test/TEMPFILEPREFIX.py
+++ b/test/TEMPFILEPREFIX.py
@@ -45,7 +45,7 @@ print sys.argv
echo_py = test.workpath('echo.py')
st = os.stat(echo_py)
-os.chmod(echo_py, st[stat.ST_MODE]|0111)
+os.chmod(echo_py, st[stat.ST_MODE]|0o111)
test.write('SConstruct', """
import os
diff --git a/test/TEX/TEX.py b/test/TEX/TEX.py
index 42c1903..e1d634f 100644
--- a/test/TEX/TEX.py
+++ b/test/TEX/TEX.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__"
@@ -176,14 +177,14 @@ Run \texttt{latex}, then \texttt{bibtex}, then \texttt{latex} twice again \cite{
reruns = [x for x in output_lines if x.find('latex -interaction=nonstopmode -recorder rerun.tex') != -1]
if len(reruns) != 2:
- print "Expected 2 latex calls, got %s:" % len(reruns)
- print '\n'.join(reruns)
+ print("Expected 2 latex calls, got %s:" % len(reruns))
+ print('\n'.join(reruns))
test.fail_test()
bibtex = [x for x in output_lines if x.find('bibtex bibtex-test') != -1]
if len(bibtex) != 1:
- print "Expected 1 bibtex call, got %s:" % len(bibtex)
- print '\n'.join(bibtex)
+ print("Expected 1 bibtex call, got %s:" % len(bibtex))
+ print('\n'.join(bibtex))
test.fail_test()
test.pass_test()
diff --git a/test/Value.py b/test/Value.py
index f3ad458..7abe758 100644
--- a/test/Value.py
+++ b/test/Value.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__"
@@ -81,7 +82,7 @@ open(sys.argv[-1],'wb').write(" ".join(sys.argv[1:-2]))
# to make sure there's no difference in behavior.
for source_signature in ['MD5', 'timestamp-newer']:
- print "Testing Value node with source signatures:", source_signature
+ print("Testing Value node with source signatures:", source_signature)
test.write('SConstruct', SConstruct_content % locals())
diff --git a/test/Variables/BoolVariable.py b/test/Variables/BoolVariable.py
index 365567e..d259984 100644
--- a/test/Variables/BoolVariable.py
+++ b/test/Variables/BoolVariable.py
@@ -57,8 +57,8 @@ opts.AddVariables(
env = Environment(variables=opts)
Help(opts.GenerateHelpText(env))
-print env['warnings']
-print env['profile']
+print(env['warnings'])
+print(env['profile'])
Default(env.Alias('dummy', None))
""")
diff --git a/test/Variables/EnumVariable.py b/test/Variables/EnumVariable.py
index c04b396..cf35b9b 100644
--- a/test/Variables/EnumVariable.py
+++ b/test/Variables/EnumVariable.py
@@ -66,9 +66,9 @@ opts.AddVariables(
env = Environment(variables=opts)
Help(opts.GenerateHelpText(env))
-print env['debug']
-print env['guilib']
-print env['some']
+print(env['debug'])
+print(env['guilib'])
+print(env['some'])
Default(env.Alias('dummy', None))
""")
diff --git a/test/Variables/ListVariable.py b/test/Variables/ListVariable.py
index e5be625..e463840 100644
--- a/test/Variables/ListVariable.py
+++ b/test/Variables/ListVariable.py
@@ -66,15 +66,18 @@ env = Environment(variables=opts)
opts.Save(optsfile, env)
Help(opts.GenerateHelpText(env))
-print env['shared']
-if 'ical' in env['shared']: print '1'
-else: print '0'
-for x in env['shared']:
- print x,
-print
-print env.subst('$shared')
+print(env['shared'])
+
+if 'ical' in env['shared']:
+ print('1')
+else:
+ print('0')
+
+print(" ".join(env['shared']))
+
+print(env.subst('$shared'))
# Test subst_path() because it's used in $CPPDEFINES expansions.
-print env.subst_path('$shared')
+print(env.subst_path('$shared'))
Default(env.Alias('dummy', None))
""")
@@ -162,7 +165,7 @@ opts.AddVariables(
env = Environment(variables=opts)
Help(opts.GenerateHelpText(env))
-print env['gpib']
+print(env['gpib'])
Default(env.Alias('dummy', None))
""")
diff --git a/test/Variables/PackageVariable.py b/test/Variables/PackageVariable.py
index 322bc9b..b3fd10a 100644
--- a/test/Variables/PackageVariable.py
+++ b/test/Variables/PackageVariable.py
@@ -59,7 +59,7 @@ opts.AddVariables(
env = Environment(variables=opts)
Help(opts.GenerateHelpText(env))
-print env['x11']
+print(env['x11'])
Default(env.Alias('dummy', None))
""")
diff --git a/test/Variables/PathVariable.py b/test/Variables/PathVariable.py
index bfe82ba..753aa11 100644
--- a/test/Variables/PathVariable.py
+++ b/test/Variables/PathVariable.py
@@ -64,9 +64,9 @@ opts.AddVariables(
env = Environment(variables=opts)
Help(opts.GenerateHelpText(env))
-print env['qtdir']
-print env['qt_libraries']
-print env.subst('$qt_libraries')
+print(env['qtdir'])
+print(env['qt_libraries'])
+print(env.subst('$qt_libraries'))
Default(env.Alias('dummy', None))
""" % (workpath, os.path.join('$qtdir', 'lib') ))
@@ -132,7 +132,7 @@ opts.AddVariables(
env = Environment(variables=opts)
-print env['X']
+print(env['X'])
Default(env.Alias('dummy', None))
""" % default_subdir)
@@ -165,7 +165,7 @@ opts.AddVariables(
env = Environment(variables=opts)
-print env['X']
+print(env['X'])
Default(env.Alias('dummy', None))
""" % default_file)
@@ -211,7 +211,7 @@ opts.AddVariables(
env = Environment(variables=opts)
-print env['X']
+print(env['X'])
Default(env.Alias('dummy', None))
""" % default_subdir)
@@ -259,7 +259,7 @@ opts.AddVariables(
env = Environment(variables=opts)
-print env['X']
+print(env['X'])
Default(env.Alias('dummy', None))
""" % default_subdir)
diff --git a/test/Variables/Variables.py b/test/Variables/Variables.py
index 454e32e..1c60635 100644
--- a/test/Variables/Variables.py
+++ b/test/Variables/Variables.py
@@ -30,8 +30,8 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
env = Environment()
-print env['CC']
-print " ".join(env['CCFLAGS'])
+print(env['CC'])
+print(" ".join(env['CCFLAGS']))
Default(env.Alias('dummy', None))
""")
test.run()
@@ -99,12 +99,12 @@ env = Environment(variables=opts, tools=['default', test_tool])
Help('Variables settable in custom.py or on the command line:\\n' + opts.GenerateHelpText(env))
-print env['RELEASE_BUILD']
-print env['DEBUG_BUILD']
-print env['CC']
-print " ".join(env['CCFLAGS'])
-print env['VALIDATE']
-print env['valid_key']
+print(env['RELEASE_BUILD'])
+print(env['DEBUG_BUILD'])
+print(env['CC'])
+print(" ".join(env['CCFLAGS']))
+print(env['VALIDATE'])
+print(env['valid_key'])
# unspecified variables should not be set:
assert 'UNSPECIFIED' not in env
@@ -220,8 +220,8 @@ opts.Add('UNSPECIFIED',
env = Environment(variables = opts)
-print env['RELEASE_BUILD']
-print env['DEBUG_BUILD']
+print(env['RELEASE_BUILD'])
+print(env['DEBUG_BUILD'])
opts.Save('variables.saved', env)
""")
@@ -231,7 +231,7 @@ opts.Save('variables.saved', 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)
# First test with no command line variables
@@ -276,9 +276,9 @@ opts.Add('LISTOPTION_TEST',
env = Environment(variables = opts)
-print env['RELEASE_BUILD']
-print env['DEBUG_BUILD']
-print env['LISTOPTION_TEST']
+print(env['RELEASE_BUILD'])
+print(env['DEBUG_BUILD'])
+print(env['LISTOPTION_TEST'])
opts.Save('variables.saved', env)
""")
diff --git a/test/Variables/chdir.py b/test/Variables/chdir.py
index 621e166..2d097d5 100644
--- a/test/Variables/chdir.py
+++ b/test/Variables/chdir.py
@@ -46,7 +46,7 @@ SConscript_contents = """\
Import("opts")
env = Environment()
opts.Update(env)
-print "VARIABLE =", repr(env['VARIABLE'])
+print("VARIABLE =", repr(env['VARIABLE']))
"""
test.write(['bin', 'opts.cfg'], """\
diff --git a/test/Variables/help.py b/test/Variables/help.py
index f04f962..bee6011 100644
--- a/test/Variables/help.py
+++ b/test/Variables/help.py
@@ -81,8 +81,8 @@ opts.AddVariables(
env = Environment(variables=opts)
Help(opts.GenerateHelpText(env))
-print env['warnings']
-print env['profile']
+print(env['warnings'])
+print(env['profile'])
Default(env.Alias('dummy', None))
""" % locals())
diff --git a/test/Variables/import.py b/test/Variables/import.py
index 7cdd274..2da670a 100644
--- a/test/Variables/import.py
+++ b/test/Variables/import.py
@@ -48,7 +48,7 @@ SConscript_contents = """\
Import("opts")
env = Environment()
opts.Update(env)
-print "VARIABLE =", env.get('VARIABLE')
+print("VARIABLE =", env.get('VARIABLE'))
"""
test.write(['bin', 'opts.cfg'], """\
diff --git a/test/WhereIs.py b/test/WhereIs.py
index dc127b6..c765848 100644
--- a/test/WhereIs.py
+++ b/test/WhereIs.py
@@ -45,10 +45,10 @@ if sys.platform != 'win32':
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']
@@ -67,14 +67,14 @@ pathdirs_1243 = [ test.workpath('sub1'),
test.write('SConstruct', """
SConscript('%s')
env = Environment()
-print WhereIs('xxx.exe')
-print WhereIs('xxx.exe', %s)
-print env.WhereIs('xxx.exe', %s)
-print WhereIs('xxx.exe', %s)
-print WhereIs('xxx.exe', %s)
-print WhereIs('xxx.exe', %s, reject=%s)
+print(WhereIs('xxx.exe'))
+print(WhereIs('xxx.exe', %s))
+print(env.WhereIs('xxx.exe', %s))
+print(WhereIs('xxx.exe', %s))
+print(WhereIs('xxx.exe', %s))
+print(WhereIs('xxx.exe', %s, reject=%s))
env.Replace( XXXNAME='xxx.exe' )
-print env.WhereIs( '$XXXNAME', %s )
+print(env.WhereIs( '$XXXNAME', %s ))
""" % (subdir_SConscript,
repr(os.pathsep.join(pathdirs_1234)),
repr(os.pathsep.join(pathdirs_1243)),
@@ -87,11 +87,11 @@ print env.WhereIs( '$XXXNAME', %s )
test.write(subdir_SConscript, """
env = Environment()
-print WhereIs('xxx.exe')
-print WhereIs('xxx.exe', %s)
-print env.WhereIs('xxx.exe', %s)
-print WhereIs('xxx.exe', %s)
-print WhereIs('xxx.exe', %s)
+print(WhereIs('xxx.exe'))
+print(WhereIs('xxx.exe', %s))
+print(env.WhereIs('xxx.exe', %s))
+print(WhereIs('xxx.exe', %s))
+print(WhereIs('xxx.exe', %s))
""" % (repr(os.pathsep.join(pathdirs_1234)),
repr(os.pathsep.join(pathdirs_1243)),
repr(pathdirs_1234),
diff --git a/test/Win32/bad-drive.py b/test/Win32/bad-drive.py
index f2a55b8..67a287a 100644
--- a/test/Win32/bad-drive.py
+++ b/test/Win32/bad-drive.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
"""
This test verifies (on Windows systems) that we fail gracefully and
@@ -50,15 +51,15 @@ for i in range(len(uppercase)-1, -1, -1):
break
if bad_drive is None:
- print "All drive letters appear to be in use."
- print "Cannot test SCons handling of invalid Windows drive letters."
+ print("All drive letters appear to be in use.")
+ print("Cannot test SCons handling of invalid Windows drive letters.")
test.no_result(1);
test.write('SConstruct', """
def cat(env, source, target):
target = str(target[0])
source = list(map(str, source))
- print 'cat(%%s) > %%s' %% (source, target)
+ print('cat(%%s) > %%s' %% (source, target))
f = open(target, "wb")
for src in source:
f.write(open(src, "rb").read())
diff --git a/test/Win32/default-drive.py b/test/Win32/default-drive.py
index f427a20..31253e4 100644
--- a/test/Win32/default-drive.py
+++ b/test/Win32/default-drive.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
"""
This test verifies (on Windows systems) that specifying an
@@ -59,7 +60,7 @@ test.write(['src', 'file.in'], "src/file.in\n")
build_file_out = test.workpath('build', 'file.out')
-print os.path.splitdrive(build_file_out)[1]
+print(os.path.splitdrive(build_file_out)[1])
test.run(chdir = 'src',
arguments = os.path.splitdrive(build_file_out)[1])
diff --git a/test/Win32/mingw.py b/test/Win32/mingw.py
index 6b23314..80067bc 100644
--- a/test/Win32/mingw.py
+++ b/test/Win32/mingw.py
@@ -47,7 +47,7 @@ from SCons.Tool.mingw import exists
import sys
env = Environment()
if exists(env):
- print 'mingw exists'
+ print('mingw exists')
sys.exit(0)
""")
diff --git a/test/ZIP/ZIP.py b/test/ZIP/ZIP.py
index af2450b..f2acad8 100644
--- a/test/ZIP/ZIP.py
+++ b/test/ZIP/ZIP.py
@@ -47,7 +47,7 @@ def zipfile_contains(zipfilename, names):
for name in names:
try:
info=zf.getinfo(name)
- except KeyError, e: # name not found
+ except KeyError as e: # name not found
zf.close()
return False
return True
diff --git a/test/ZIP/ZIPROOT.py b/test/ZIP/ZIPROOT.py
index 96747a7..f3e4496 100644
--- a/test/ZIP/ZIPROOT.py
+++ b/test/ZIP/ZIPROOT.py
@@ -1,98 +1,98 @@
-#!/usr/bin/env python
-#
-# __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.
-#
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-
-import os
-import stat
-
-import TestSCons
-
-_python_ = TestSCons._python_
-
-test = TestSCons.TestSCons()
-
-import zipfile
-
-def zipfile_contains(zipfilename, names):
- """Returns True if zipfilename contains all the names, False otherwise."""
- zf=zipfile.ZipFile(zipfilename, 'r')
- if type(names)==type(''):
- names=[names]
- for name in names:
- try:
- info=zf.getinfo(name)
- except KeyError, e: # name not found
- zf.close()
- return False
- return True
-
-def zipfile_files(fname):
- """Returns all the filenames in zip file fname."""
- zf = zipfile.ZipFile(fname, 'r')
- return [x.filename for x in zf.infolist()]
-
-test.subdir('sub1')
-test.subdir(['sub1', 'sub2'])
-
-test.write('SConstruct', """
-env = Environment(tools = ['zip'])
-env.Zip(target = 'aaa.zip', source = ['sub1/file1'], ZIPROOT='sub1')
-env.Zip(target = 'bbb.zip', source = ['sub1/file2', 'sub1/sub2/file2'], ZIPROOT='sub1')
-""" % locals())
-
-test.write(['sub1', 'file1'], "file1\n")
-test.write(['sub1', 'file2'], "file2a\n")
-test.write(['sub1', 'sub2', 'file2'], "file2b\n")
-
-test.run(arguments = 'aaa.zip', stderr = None)
-
-test.must_exist('aaa.zip')
-
-# TEST: Zip file should contain 'file1', not 'sub1/file1', because of ZIPROOT.
-zf=zipfile.ZipFile('aaa.zip', 'r')
-test.fail_test(zf.testzip() is not None)
-zf.close()
-
-files=zipfile_files('aaa.zip')
-test.fail_test(zipfile_files('aaa.zip') != ['file1'],
- message='Zip file aaa.zip has wrong files: %s'%repr(files))
-
-###
-
-test.run(arguments = 'bbb.zip', stderr = None)
-
-test.must_exist('bbb.zip')
-
-# TEST: Zip file should contain 'sub2/file2', not 'sub1/sub2/file2', because of ZIPROOT.
-zf=zipfile.ZipFile('bbb.zip', 'r')
-test.fail_test(zf.testzip() is not None)
-zf.close()
-
-files=zipfile_files('bbb.zip')
-test.fail_test(zipfile_files('bbb.zip') != ['file2', 'sub2/file2'],
- message='Zip file bbb.zip has wrong files: %s'%repr(files))
-
-
-test.pass_test()
+#!/usr/bin/env python
+#
+# __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.
+#
+
+__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
+
+import os
+import stat
+
+import TestSCons
+
+_python_ = TestSCons._python_
+
+test = TestSCons.TestSCons()
+
+import zipfile
+
+def zipfile_contains(zipfilename, names):
+ """Returns True if zipfilename contains all the names, False otherwise."""
+ zf=zipfile.ZipFile(zipfilename, 'r')
+ if type(names)==type(''):
+ names=[names]
+ for name in names:
+ try:
+ info=zf.getinfo(name)
+ except KeyError as e: # name not found
+ zf.close()
+ return False
+ return True
+
+def zipfile_files(fname):
+ """Returns all the filenames in zip file fname."""
+ zf = zipfile.ZipFile(fname, 'r')
+ return [x.filename for x in zf.infolist()]
+
+test.subdir('sub1')
+test.subdir(['sub1', 'sub2'])
+
+test.write('SConstruct', """
+env = Environment(tools = ['zip'])
+env.Zip(target = 'aaa.zip', source = ['sub1/file1'], ZIPROOT='sub1')
+env.Zip(target = 'bbb.zip', source = ['sub1/file2', 'sub1/sub2/file2'], ZIPROOT='sub1')
+""" % locals())
+
+test.write(['sub1', 'file1'], "file1\n")
+test.write(['sub1', 'file2'], "file2a\n")
+test.write(['sub1', 'sub2', 'file2'], "file2b\n")
+
+test.run(arguments = 'aaa.zip', stderr = None)
+
+test.must_exist('aaa.zip')
+
+# TEST: Zip file should contain 'file1', not 'sub1/file1', because of ZIPROOT.
+zf=zipfile.ZipFile('aaa.zip', 'r')
+test.fail_test(zf.testzip() is not None)
+zf.close()
+
+files=zipfile_files('aaa.zip')
+test.fail_test(zipfile_files('aaa.zip') != ['file1'],
+ message='Zip file aaa.zip has wrong files: %s'%repr(files))
+
+###
+
+test.run(arguments = 'bbb.zip', stderr = None)
+
+test.must_exist('bbb.zip')
+
+# TEST: Zip file should contain 'sub2/file2', not 'sub1/sub2/file2', because of ZIPROOT.
+zf=zipfile.ZipFile('bbb.zip', 'r')
+test.fail_test(zf.testzip() is not None)
+zf.close()
+
+files=zipfile_files('bbb.zip')
+test.fail_test(zipfile_files('bbb.zip') != ['file2', 'sub2/file2'],
+ message='Zip file bbb.zip has wrong files: %s'%repr(files))
+
+
+test.pass_test()
diff --git a/test/_CPPINCFLAGS.py b/test/_CPPINCFLAGS.py
index ccf5e79..c5096ba 100644
--- a/test/_CPPINCFLAGS.py
+++ b/test/_CPPINCFLAGS.py
@@ -39,9 +39,9 @@ env=Environment(CPPPATH=['tmp'], INCPREFIX='-I')
d=Entry('foo.d')
e=Entry('foo.e')
f=File('foo.f')
-print env.subst('$_CPPINCFLAGS', target=e, source=f)
-print env.subst('$_CPPINCFLAGS', target=d, source=f)
-print env.subst('$_CPPINCFLAGS', target=f, source=d)
+print(env.subst('$_CPPINCFLAGS', target=e, source=f))
+print(env.subst('$_CPPINCFLAGS', target=d, source=f))
+print(env.subst('$_CPPINCFLAGS', target=f, source=d))
""")
expect = """\
diff --git a/test/custom-concat.py b/test/custom-concat.py
index 56c7f64..730e6cd 100644
--- a/test/custom-concat.py
+++ b/test/custom-concat.py
@@ -44,7 +44,7 @@ env1 = Environment(MYFLAGS=myflags, _concat = my_concat1,
MYPREFIX='p', MYSUFFIX='s',
STRIPPREFIX='xxx', STRIPSUFFIX='yyy',
LIST=['a', 'xxxb', 'cyyy', 'd'])
-print env1.subst('$MYFLAGS')
+print(env1.subst('$MYFLAGS'))
""")
expect = test.wrap_stdout(read_str = "mypas1 mypbs1 mypcs1 mypds1\n",
diff --git a/test/exitfns.py b/test/exitfns.py
index f64969b..d1bda3a 100644
--- a/test/exitfns.py
+++ b/test/exitfns.py
@@ -32,11 +32,11 @@ sconstruct = """
from SCons.exitfuncs import *
def x1():
- print "running x1"
+ print("running x1")
def x2(n):
- print "running x2(%s)" % repr(n)
+ print("running x2(%s)" % repr(n))
def x3(n, kwd=None):
- print "running x3(%s, kwd=%s)" % (repr(n), repr(kwd))
+ print("running x3(%s, kwd=%s)" % (repr(n), repr(kwd)))
register(x3, "no kwd args")
register(x1)
diff --git a/test/gnutools.py b/test/gnutools.py
index e1b7e42..b0ebc1c 100644
--- a/test/gnutools.py
+++ b/test/gnutools.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__"
@@ -118,7 +119,7 @@ def testObject(test, obj, expect):
line1 = contents.split('\n')[0]
actual = ' '.join(line1.split())
if not expect == actual:
- print "%s: %s != %s\n" % (obj, repr(expect), repr(actual))
+ print("%s: %s != %s\n" % (obj, repr(expect), repr(actual)))
test.fail_test()
if sys.platform in ('win32', 'cygwin'):
diff --git a/test/import.py b/test/import.py
index ef5ee61..c23657a 100644
--- a/test/import.py
+++ b/test/import.py
@@ -63,7 +63,7 @@ platforms = [
for platform in platforms:
test.write('SConstruct', """
-print "Platform %(platform)s"
+print("Platform %(platform)s")
env = Environment(platform = '%(platform)s')
import SCons.Platform.%(platform)s
x = SCons.Platform.%(platform)s.generate
@@ -150,7 +150,7 @@ error_output = {
# An SConstruct for importing Tool names that have illegal characters
# for Python variable names.
indirect_import = """\
-print "Tool %(tool)s (indirect)"
+print("Tool %(tool)s (indirect)")
env = Environment(tools = ['%(tool)s'])
SCons = __import__('SCons.Tool.%(tool)s', globals(), locals(), [])
@@ -161,7 +161,7 @@ m.generate(env)
# An SConstruct for importing Tool names "normally."
direct_import = """\
-print "Tool %(tool)s (direct)"
+print("Tool %(tool)s (direct)")
env = Environment(tools = ['%(tool)s'])
import SCons.Tool.%(tool)s
@@ -185,8 +185,8 @@ for tool in tools:
matched = 1
break
if not matched:
- print "Failed importing '%s', stderr:" % tool
- print stderr
+ print("Failed importing '%s', stderr:" % tool)
+ print(stderr)
failures.append(tool)
test.fail_test(len(failures))
diff --git a/test/long-lines/signature.py b/test/long-lines/signature.py
index bc5d11a..ce38bec 100644
--- a/test/long-lines/signature.py
+++ b/test/long-lines/signature.py
@@ -51,7 +51,7 @@ fp.write('FILEFLAG=%s\\n' % args[2])
fp.write('TIMESTAMP=%s\\n' % args[3])
""")
-os.chmod(build_py, 0755)
+os.chmod(build_py, 0o755)
test.write('SConstruct', """\
arg = 'a_long_ignored_argument'
diff --git a/test/no-arguments.py b/test/no-arguments.py
index e447ff6..953d827 100644
--- a/test/no-arguments.py
+++ b/test/no-arguments.py
@@ -40,7 +40,7 @@ test.write('SConstruct', r"""
def cat(env, source, target):
target = str(target[0])
source = list(map(str, source))
- print 'cat(%s) > %s' % (source, target)
+ print('cat(%s) > %s' % (source, target))
f = open(target, "wb")
for src in source:
f.write(open(src, "rb").read())
diff --git a/test/option--C.py b/test/option--C.py
index 27f4950..1df3c1a 100644
--- a/test/option--C.py
+++ b/test/option--C.py
@@ -51,18 +51,18 @@ test.subdir('sub', ['sub', 'dir'])
test.write('SConstruct', """
import os
-print "SConstruct", os.getcwd()
+print("SConstruct", os.getcwd())
""")
test.write(['sub', 'SConstruct'], """
import os
-print GetBuildPath('..')
+print(GetBuildPath('..'))
""")
test.write(['sub', 'dir', 'SConstruct'], """
import os
env = Environment(FOO='foo', BAR='bar')
-print env.GetBuildPath('../$FOO/$BAR')
+print(env.GetBuildPath('../$FOO/$BAR'))
""")
test.run(arguments = '-C sub .',
diff --git a/test/option--I.py b/test/option--I.py
index d65349a..0ca262d 100644
--- a/test/option--I.py
+++ b/test/option--I.py
@@ -44,9 +44,9 @@ variable = "sub2/bar"
test.write('SConstruct', """
import foo
-print foo.variable
+print(foo.variable)
import bar
-print bar.variable
+print(bar.variable)
""")
test.run(arguments = '-I sub1 -I sub2 .',
diff --git a/test/option--random.py b/test/option--random.py
index a9b9b9d..357cf2e 100644
--- a/test/option--random.py
+++ b/test/option--random.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__"
@@ -66,7 +67,7 @@ tries = 0
max_tries = 10
while test.stdout() == non_random_output:
if tries >= max_tries:
- print "--random generated the non-random output %s times!" % max_tries
+ print("--random generated the non-random output %s times!" % max_tries)
test.fail_test()
tries = tries + 1
test.run(arguments = '-n -Q --random')
@@ -84,7 +85,7 @@ tries = 0
max_tries = 10
while test.stdout() == non_random_output:
if tries >= max_tries:
- print "--random generated the non-random output %s times!" % max_tries
+ print("--random generated the non-random output %s times!" % max_tries)
test.fail_test()
tries = tries + 1
test.run(arguments = '-n -Q --random')
diff --git a/test/option-f.py b/test/option-f.py
index 2a238d3..9fd1a57 100644
--- a/test/option-f.py
+++ b/test/option-f.py
@@ -36,17 +36,17 @@ subdir_BuildThis = os.path.join('subdir', 'Buildthis')
test.write('SConscript', """
import os
-print "SConscript " + os.getcwd()
+print("SConscript " + os.getcwd())
""")
test.write(subdir_BuildThis, """
import os
-print "subdir/BuildThis", os.getcwd()
+print("subdir/BuildThis", os.getcwd())
""")
test.write('Build2', """
import os
-print "Build2", os.getcwd()
+print("Build2", os.getcwd())
""")
wpath = test.workpath()
@@ -85,7 +85,7 @@ test.run(arguments = '--sconstruct=%s .' % subdir_BuildThis,
test.run(arguments = '-f - .', stdin = """
import os
-print "STDIN " + os.getcwd()
+print("STDIN " + os.getcwd())
""",
stdout = test.wrap_stdout(read_str = 'STDIN %s\n' % wpath,
build_str = "scons: `.' is up to date.\n"))
diff --git a/test/option-v.py b/test/option-v.py
index f3eb61c..4a67df0 100644
--- a/test/option-v.py
+++ b/test/option-v.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__"
@@ -53,13 +54,13 @@ expect2 = r"""SCons by Steven Knight et al.:
test.run(arguments = '-v')
stdout = test.stdout()
if not test.match_re(stdout, expect1) and not test.match_re(stdout, expect2):
- print stdout
+ print(stdout)
test.fail_test()
test.run(arguments = '--version')
stdout = test.stdout()
if not test.match_re(stdout, expect1) and not test.match_re(stdout, expect2):
- print stdout
+ print(stdout)
test.fail_test()
test.pass_test()
diff --git a/test/option/debug-count.py b/test/option/debug-count.py
index 39c1222..b82a434 100644
--- a/test/option/debug-count.py
+++ b/test/option/debug-count.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__"
@@ -75,10 +76,10 @@ for args in ['-h --debug=count', '--debug=count']:
missing = [o for o in objects if find_object_count(o, stdout) is None]
if missing:
- print "Missing the following object lines from '%s' output:" % args
- print "\t", ' '.join(missing)
- print "STDOUT =========="
- print stdout
+ print("Missing the following object lines from '%s' output:" % args)
+ print("\t", ' '.join(missing))
+ print("STDOUT ==========")
+ print(stdout)
test.fail_test(1)
expect_warning = """
diff --git a/test/option/debug-multiple.py b/test/option/debug-multiple.py
index f5bbdf0..f121a2c 100644
--- a/test/option/debug-multiple.py
+++ b/test/option/debug-multiple.py
@@ -21,6 +21,8 @@
# 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__"
"""
@@ -65,16 +67,16 @@ for args in ['--debug=prepare,count', '--debug=count,prepare']:
missing = [o for o in objects if find_object_count(o, stdout) is None]
if missing:
- print "Missing the following object lines from '%s' output:" % args
- print "\t", ' '.join(missing)
- print "STDOUT =========="
- print stdout
+ print("Missing the following object lines from '%s' output:" % args)
+ print("\t", ' '.join(missing))
+ print("STDOUT ==========")
+ print(stdout)
test.fail_test(1)
if 'Preparing target file.out...' not in stdout:
- print "Missing 'Preparing' lines from '%s' output:" % args
- print "STDOUT =========="
- print stdout
+ print("Missing 'Preparing' lines from '%s' output:" % args)
+ print("STDOUT ==========")
+ print(stdout)
test.fail_test(1)
test.pass_test()
diff --git a/test/option/debug-time.py b/test/option/debug-time.py
index 198d71d..7dd17fe 100644
--- a/test/option/debug-time.py
+++ b/test/option/debug-time.py
@@ -20,7 +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 division
+from __future__ import division, print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
@@ -164,7 +164,7 @@ outside of the 15%% tolerance.
""" % locals())
if failures or warnings:
- print '\n'.join([test.stdout()] + failures + warnings)
+ print('\n'.join([test.stdout()] + failures + warnings))
if failures:
test.fail_test(1)
@@ -172,7 +172,7 @@ test.run(arguments = "--debug=time . SLEEP=0")
command_time = get_command_time(test.stdout())
if command_time != 0.0:
- print "Up-to-date run received non-zero command time of %s" % command_time
+ print("Up-to-date run received non-zero command time of %s" % command_time)
test.fail_test()
@@ -201,14 +201,14 @@ outside of the 1%% tolerance.
""" % locals())
if failures:
- print '\n'.join([test.stdout()] + failures)
+ print('\n'.join([test.stdout()] + failures))
test.fail_test(1)
test.run(arguments = "-j4 --debug=time . SLEEP=1")
command_time = get_command_time(test.stdout())
if command_time != 0.0:
- print "Up-to-date run received non-zero command time of %s" % command_time
+ print("Up-to-date run received non-zero command time of %s" % command_time)
test.fail_test()
diff --git a/test/option/help-options.py b/test/option/help-options.py
index 45bbfa0..e14eff2 100644
--- a/test/option/help-options.py
+++ b/test/option/help-options.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__"
@@ -60,8 +61,8 @@ options = [x[-1] == ',' and x[:-1] or x for x in options]
lowered = [x.lower() for x in options]
ordered = sorted(lowered)
if lowered != ordered:
- print "lowered =", lowered
- print "sorted =", ordered
+ print("lowered =", lowered)
+ print("sorted =", ordered)
test.fail_test()
test.pass_test()
diff --git a/test/option/profile.py b/test/option/profile.py
index 4d6caae..4d942cf 100644
--- a/test/option/profile.py
+++ b/test/option/profile.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.
+
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import sys
@@ -106,7 +107,7 @@ memory_lines = [l for l in lines if l.find(expect) != -1]
test.fail_test(len(memory_lines) != 1)
-
+
test.pass_test()
diff --git a/test/overrides.py b/test/overrides.py
index d706ab7..69d5207 100644
--- a/test/overrides.py
+++ b/test/overrides.py
@@ -35,9 +35,9 @@ _python_ = TestSCons._python_
test.write('SConstruct', """
env = Environment(CCFLAGS='-DFOO', LIBS=['a'])
def build(target, source, env):
- print "env['CC'] =", env['CC']
- print "env['CCFLAGS'] =", env['CCFLAGS']
- print "env['LIBS'] =", env['LIBS']
+ print("env['CC'] =", env['CC'])
+ print("env['CCFLAGS'] =", env['CCFLAGS'])
+ print("env['LIBS'] =", env['LIBS'])
builder = Builder(action=build, CC='buildcc', LIBS='buildlibs')
env['BUILDERS']['Build'] = builder
diff --git a/test/packaging/convenience-functions/image/SConstruct b/test/packaging/convenience-functions/image/SConstruct
index 461961e..f35c3e3 100644
--- a/test/packaging/convenience-functions/image/SConstruct
+++ b/test/packaging/convenience-functions/image/SConstruct
@@ -1,3 +1,4 @@
+from __future__ import print_function
env = Environment(tools=['default', 'packaging'])
prog = env.Install( 'bin/', ["f1", "f2"] )
@@ -6,5 +7,5 @@ env.File( "f3" )
src_files = sorted(map(str, env.FindSourceFiles()))
oth_files = sorted(map(str, env.FindInstalledFiles()))
-print src_files
-print oth_files
+print(src_files)
+print(oth_files)
diff --git a/test/preserve-source.py b/test/preserve-source.py
index 6e09073..b7eccd1 100644
--- a/test/preserve-source.py
+++ b/test/preserve-source.py
@@ -35,7 +35,7 @@ test.write('SConstruct', r"""
def cat(env, source, target):
target = str(target[0])
source = list(map(str, source))
- print 'cat(%s) > %s' % (source, target)
+ print('cat(%s) > %s' % (source, target))
f = open(target, "wb")
for src in source:
f.write(open(src, "rb").read())
diff --git a/test/scons-time/run/config/python.py b/test/scons-time/run/config/python.py
index 6cf965b..57b732d 100644
--- a/test/scons-time/run/config/python.py
+++ b/test/scons-time/run/config/python.py
@@ -53,7 +53,7 @@ for arg in sys.argv[1:]:
print 'my_python.py: %s' % profile
""")
-os.chmod(my_python_py, 0755)
+os.chmod(my_python_py, 0o755)
test.run(arguments = 'run -f config foo.tar.gz')
diff --git a/test/scons-time/run/option/python.py b/test/scons-time/run/option/python.py
index a28e23f..70feb70 100644
--- a/test/scons-time/run/option/python.py
+++ b/test/scons-time/run/option/python.py
@@ -49,7 +49,7 @@ for arg in sys.argv[1:]:
sys.stdout.write('my_python.py: %s\\n' % profile)
""")
-os.chmod(my_python_py, 0755)
+os.chmod(my_python_py, 0o755)
test.run(arguments = 'run --python %s foo.tar.gz' % my_python_py)
diff --git a/test/sconsign/nonwritable.py b/test/sconsign/nonwritable.py
index 913dcf1..5ae55bb 100644
--- a/test/sconsign/nonwritable.py
+++ b/test/sconsign/nonwritable.py
@@ -78,7 +78,7 @@ test.write(['work1', 'foo.in'], "work1/foo.in\n")
test.write(work1__sconsign_dblite, "")
-os.chmod(work1__sconsign_dblite, 0444)
+os.chmod(work1__sconsign_dblite, 0o444)
test.run(chdir='work1', arguments='.')
@@ -95,7 +95,7 @@ test.write(['work2', 'foo.in'], "work2/foo.in\n")
pickle.dump({}, open(work2_sub1__sconsign, 'wb'), 1)
pickle.dump({}, open(work2_sub2__sconsign, 'wb'), 1)
-os.chmod(work2_sub1__sconsign, 0444)
+os.chmod(work2_sub1__sconsign, 0o444)
test.run(chdir='work2', arguments='.')
diff --git a/test/sconsign/script/SConsignFile.py b/test/sconsign/script/SConsignFile.py
index 74fb1f0..dc45cc1 100644
--- a/test/sconsign/script/SConsignFile.py
+++ b/test/sconsign/script/SConsignFile.py
@@ -86,8 +86,8 @@ output.write(input.read())
sys.exit(0)
""")
-test.chmod(fake_cc_py, 0755)
-test.chmod(fake_link_py, 0755)
+test.chmod(fake_cc_py, 0o755)
+test.chmod(fake_link_py, 0o755)
# Note: We don't use os.path.join() representations of the file names
# in the expected output because paths in the .sconsign files are
diff --git a/test/sconsign/script/Signatures.py b/test/sconsign/script/Signatures.py
index cfd2a7f..5babe67 100644
--- a/test/sconsign/script/Signatures.py
+++ b/test/sconsign/script/Signatures.py
@@ -105,8 +105,8 @@ output.write(input.read())
sys.exit(0)
""")
-test.chmod(fake_cc_py, 0755)
-test.chmod(fake_link_py, 0755)
+test.chmod(fake_cc_py, 0o755)
+test.chmod(fake_link_py, 0o755)
test.write('SConstruct', """
SConsignFile(None)
diff --git a/test/sconsign/script/no-SConsignFile.py b/test/sconsign/script/no-SConsignFile.py
index 09ecfa2..4e9915b 100644
--- a/test/sconsign/script/no-SConsignFile.py
+++ b/test/sconsign/script/no-SConsignFile.py
@@ -94,8 +94,8 @@ output.write(input.read())
sys.exit(0)
""")
-test.chmod(fake_cc_py, 0755)
-test.chmod(fake_link_py, 0755)
+test.chmod(fake_cc_py, 0o755)
+test.chmod(fake_link_py, 0o755)
# Note: We don't use os.path.join() representations of the file names
# in the expected output because paths in the .sconsign files are
diff --git a/test/site_scons/basic.py b/test/site_scons/basic.py
index 1868723..b3ae9f2 100644
--- a/test/site_scons/basic.py
+++ b/test/site_scons/basic.py
@@ -40,7 +40,7 @@ test.subdir('site_scons', ['site_scons', 'site_tools'])
test.write(['site_scons', 'site_init.py'], """
from SCons.Script import *
-print "Hi there, I am in site_scons/site_init.py!"
+print("Hi there, I am in site_scons/site_init.py!")
""")
test.write(['site_scons', 'site_tools', 'mytool.py'], """
@@ -54,7 +54,7 @@ def exists(env):
test.write('SConstruct', """
e=Environment(tools=['default', 'mytool'])
-print e.subst('My site tool is $MYTOOL')
+print(e.subst('My site tool is $MYTOOL'))
""")
test.run(arguments = '-Q .',
diff --git a/test/site_scons/no-site-dir.py b/test/site_scons/no-site-dir.py
index d01d419..c31ec94 100644
--- a/test/site_scons/no-site-dir.py
+++ b/test/site_scons/no-site-dir.py
@@ -37,7 +37,7 @@ test.subdir('site_scons', ['site_scons', 'site_tools'])
test.write(['site_scons', 'site_init.py'], """
from SCons.Script import *
-print "Hi there, I am in site_scons/site_init.py!"
+print("Hi there, I am in site_scons/site_init.py!")
""")
test.write(['site_scons', 'site_tools', 'mytool.py'], """
@@ -68,7 +68,7 @@ test.run(arguments = '-Q --no-site-dir .',
test.write('SConstruct', """
e=Environment()
-print e.subst('no site: M4 is $M4, M4_MINE is $M4_MINE')
+print(e.subst('no site: M4 is $M4, M4_MINE is $M4_MINE'))
""")
test.run(arguments = '-Q --no-site-dir .')
diff --git a/test/site_scons/override.py b/test/site_scons/override.py
index e33bb88..d65c09e 100644
--- a/test/site_scons/override.py
+++ b/test/site_scons/override.py
@@ -49,7 +49,7 @@ def exists(env):
test.write('SConstruct', """
e=Environment(tools=['m4'])
-print e.subst('M4 is $M4, M4_MINE is $M4_MINE')
+print(e.subst('M4 is $M4, M4_MINE is $M4_MINE'))
""")
test.run(arguments = '-Q .',
stdout = """M4 is my_m4, M4_MINE is 1
diff --git a/test/site_scons/site-dir.py b/test/site_scons/site-dir.py
index 8e82e94..d60e7d9 100644
--- a/test/site_scons/site-dir.py
+++ b/test/site_scons/site-dir.py
@@ -38,7 +38,7 @@ test.subdir('site_scons', ['site_scons', 'site_tools'])
test.write(['site_scons', 'site_init.py'], """
from SCons.Script import *
-print "Hi there, I am in site_scons/site_init.py!"
+print("Hi there, I am in site_scons/site_init.py!")
""")
test.write(['site_scons', 'site_tools', 'mytool.py'], """
@@ -55,7 +55,7 @@ test.subdir('alt_site', ['alt_site', 'site_tools'])
test.write(['alt_site', 'site_init.py'], """
from SCons.Script import *
-print "Hi there, I am in alt_site/site_init.py!"
+print("Hi there, I am in alt_site/site_init.py!")
""")
test.write('SConstruct', """
diff --git a/test/site_scons/site_init.py b/test/site_scons/site_init.py
index 9f2e411..27768a9 100644
--- a/test/site_scons/site_init.py
+++ b/test/site_scons/site_init.py
@@ -51,17 +51,17 @@ import os.path
import re
special = []
-for x in globals().keys():
+for x in list(globals().keys()):
if re.match("__[^_]+__", x):
if x in ("__builtins__", "__package__",):
# Ignore certain keywords, as they are known to be added by Python
continue
special.append(x)
-print sorted(special)
-print __doc__
-print os.path.realpath(__file__)
-print __name__
+print(sorted(special))
+print(__doc__)
+print(os.path.realpath(__file__))
+print(__name__)
""")
test.write('SConstruct', "\n")
diff --git a/test/site_scons/sysdirs.py b/test/site_scons/sysdirs.py
index f50485a..60b4f0b 100644
--- a/test/site_scons/sysdirs.py
+++ b/test/site_scons/sysdirs.py
@@ -1,71 +1,73 @@
-#!/usr/bin/env python
-#
-# __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.
-#
-
-__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
-
-import TestSCons
-
-"""
-Verify site_scons system dirs are getting loaded.
-Uses an internal test fixture to get at the site_scons dirs.
-
-TODO: it would be great to test if it can actually load site_scons
-files from the system dirs, but the test harness can't put files in
-those dirs (which may not even exist on a build system).
-"""
-
-test = TestSCons.TestSCons()
-
-test.write('SConstruct', """
-import SCons.Script
-SCons.Script.Main.test_load_all_site_scons_dirs(Dir('.').get_internal_path())
-""")
-
-test.run(arguments = '-Q .')
-
-import SCons.Platform
-platform = SCons.Platform.platform_default()
-if platform in ('win32', 'cygwin'):
- dir_to_check_for='Application Data'
-elif platform in ('darwin'):
- dir_to_check_for='Library'
-else:
- dir_to_check_for='.scons'
-
-if 'Loading site dir' not in test.stdout():
- print test.stdout()
- test.fail_test()
-if dir_to_check_for not in test.stdout():
- print test.stdout()
- test.fail_test()
-
-test.pass_test()
-
-# end of file
-
-# Local Variables:
-# tab-width:4
-# indent-tabs-mode:nil
-# End:
-# vim: set expandtab tabstop=4 shiftwidth=4:
+#!/usr/bin/env python
+#
+# __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.
+#
+
+from __future__ import print_function
+
+__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
+
+import TestSCons
+
+"""
+Verify site_scons system dirs are getting loaded.
+Uses an internal test fixture to get at the site_scons dirs.
+
+TODO: it would be great to test if it can actually load site_scons
+files from the system dirs, but the test harness can't put files in
+those dirs (which may not even exist on a build system).
+"""
+
+test = TestSCons.TestSCons()
+
+test.write('SConstruct', """
+import SCons.Script
+SCons.Script.Main.test_load_all_site_scons_dirs(Dir('.').get_internal_path())
+""")
+
+test.run(arguments = '-Q .')
+
+import SCons.Platform
+platform = SCons.Platform.platform_default()
+if platform in ('win32', 'cygwin'):
+ dir_to_check_for='Application Data'
+elif platform in ('darwin'):
+ dir_to_check_for='Library'
+else:
+ dir_to_check_for='.scons'
+
+if 'Loading site dir' not in test.stdout():
+ print(test.stdout())
+ test.fail_test()
+if dir_to_check_for not in test.stdout():
+ print(test.stdout())
+ test.fail_test()
+
+test.pass_test()
+
+# end of file
+
+# Local Variables:
+# tab-width:4
+# indent-tabs-mode:nil
+# End:
+# vim: set expandtab tabstop=4 shiftwidth=4:
diff --git a/test/spaces.py b/test/spaces.py
index db1ae97..1309047 100644
--- a/test/spaces.py
+++ b/test/spaces.py
@@ -36,7 +36,7 @@ if sys.platform == 'win32':
else:
test.write('duplicate a file.sh', 'cp foo.in foo.out\n')
copy = test.workpath('duplicate a file.sh')
- os.chmod(test.workpath('duplicate a file.sh'), 0777)
+ os.chmod(test.workpath('duplicate a file.sh'), 0o777)
test.write('SConstruct', r'''
diff --git a/test/subdivide.py b/test/subdivide.py
index 2978e08..44402c9 100644
--- a/test/subdivide.py
+++ b/test/subdivide.py
@@ -76,8 +76,8 @@ for s in sys.argv[2:]:
ofp.write(open(s, 'rb').read())
""")
-test.chmod(fake_cc_py, 0755)
-test.chmod(fake_link_py, 0755)
+test.chmod(fake_cc_py, 0o755)
+test.chmod(fake_link_py, 0o755)
test.write('SConstruct', """\
SConsignFile(None)
diff --git a/test/tool_args.py b/test/tool_args.py
index 692f6a5..b0f69ef 100644
--- a/test/tool_args.py
+++ b/test/tool_args.py
@@ -38,13 +38,13 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
# Test passing kw args to Tool constructor
env1 = Environment(tools=[Tool('FooTool', toolpath=['.'], kw1='kw1val')])
-print "env1['TOOL_FOO'] =", env1.get('TOOL_FOO')
-print "env1['kw1'] =", env1.get('kw1')
+print("env1['TOOL_FOO'] =", env1.get('TOOL_FOO'))
+print("env1['kw1'] =", env1.get('kw1'))
# Test apply_tools taking a list of (name, kwargs_dict)
env2 = Environment(tools=[('FooTool', {'kw2':'kw2val'})], toolpath=['.'])
-print "env2['TOOL_FOO'] =", env2.get('TOOL_FOO')
-print "env2['kw2'] =", env2.get('kw2')
+print("env2['TOOL_FOO'] =", env2.get('TOOL_FOO'))
+print("env2['kw2'] =", env2.get('kw2'))
""")
diff --git a/test/toolpath/basic.py b/test/toolpath/basic.py
index e1e6f3c..509d4cb 100644
--- a/test/toolpath/basic.py
+++ b/test/toolpath/basic.py
@@ -33,63 +33,63 @@ test = TestSCons.TestSCons()
test.write('SConstruct', """
def foo(env):
env['TOOL_FOO'] = 1
-
+
env1 = Environment(tools=[foo, 'bar'], toolpath=['tools'])
-print "env1['TOOL_FOO'] =", env1.get('TOOL_FOO')
-print "env1['TOOL_BAR'] =", env1.get('TOOL_BAR')
+print("env1['TOOL_FOO'] =", env1.get('TOOL_FOO'))
+print("env1['TOOL_BAR'] =", env1.get('TOOL_BAR'))
# pick a built-in tool with pretty simple behavior
env2 = Environment(tools=['SCCS'])
-print "env2['SCCS'] =", env2.get('SCCS')
-print "env2['TOOL_SCCS1'] =", env2.get('TOOL_SCCS1')
-print "env2['TOOL_SCCS2'] =", env2.get('TOOL_SCCS2')
+print("env2['SCCS'] =", env2.get('SCCS'))
+print("env2['TOOL_SCCS1'] =", env2.get('TOOL_SCCS1'))
+print("env2['TOOL_SCCS2'] =", env2.get('TOOL_SCCS2'))
env3 = Environment(tools=['SCCS'], toolpath=['.'])
-print "env3['SCCS'] =", env3.get('SCCS')
-print "env3['TOOL_SCCS1'] =", env3.get('TOOL_SCCS1')
-print "env3['TOOL_SCCS2'] =", env3.get('TOOL_SCCS2')
+print("env3['SCCS'] =", env3.get('SCCS'))
+print("env3['TOOL_SCCS1'] =", env3.get('TOOL_SCCS1'))
+print("env3['TOOL_SCCS2'] =", env3.get('TOOL_SCCS2'))
env4 = Environment(tools=['SCCS'], toolpath=['tools'])
-print "env4['SCCS'] =", env4.get('SCCS')
-print "env4['TOOL_SCCS1'] =", env4.get('TOOL_SCCS1')
-print "env4['TOOL_SCCS2'] =", env4.get('TOOL_SCCS2')
+print("env4['SCCS'] =", env4.get('SCCS'))
+print("env4['TOOL_SCCS1'] =", env4.get('TOOL_SCCS1'))
+print("env4['TOOL_SCCS2'] =", env4.get('TOOL_SCCS2'))
env5 = Environment(tools=['SCCS'], toolpath=['tools', '.'])
-print "env5['SCCS'] =", env5.get('SCCS')
-print "env5['TOOL_SCCS1'] =", env5.get('TOOL_SCCS1')
-print "env5['TOOL_SCCS2'] =", env5.get('TOOL_SCCS2')
+print("env5['SCCS'] =", env5.get('SCCS'))
+print("env5['TOOL_SCCS1'] =", env5.get('TOOL_SCCS1'))
+print("env5['TOOL_SCCS2'] =", env5.get('TOOL_SCCS2'))
env6 = Environment(tools=['SCCS'], toolpath=['.', 'tools'])
-print "env6['SCCS'] =", env6.get('SCCS')
-print "env6['TOOL_SCCS1'] =", env6.get('TOOL_SCCS1')
-print "env6['TOOL_SCCS2'] =", env6.get('TOOL_SCCS2')
+print("env6['SCCS'] =", env6.get('SCCS'))
+print("env6['TOOL_SCCS1'] =", env6.get('TOOL_SCCS1'))
+print("env6['TOOL_SCCS2'] =", env6.get('TOOL_SCCS2'))
env7 = Environment(TOOLPATH="tools", tools=['SCCS'], toolpath=['$TOOLPATH'])
-print "env7['SCCS'] =", env7.get('SCCS')
-print "env7['TOOL_SCCS1'] =", env7.get('TOOL_SCCS1')
-print "env7['TOOL_SCCS2'] =", env7.get('TOOL_SCCS2')
+print("env7['SCCS'] =", env7.get('SCCS'))
+print("env7['TOOL_SCCS1'] =", env7.get('TOOL_SCCS1'))
+print("env7['TOOL_SCCS2'] =", env7.get('TOOL_SCCS2'))
env8 = Environment(tools=[])
env8.Tool('SCCS', toolpath=['tools'])
-print "env8['SCCS'] =", env8.get('SCCS')
-print "env8['TOOL_SCCS1'] =", env8.get('TOOL_SCCS1')
-print "env8['TOOL_SCCS2'] =", env8.get('TOOL_SCCS2')
+print("env8['SCCS'] =", env8.get('SCCS'))
+print("env8['TOOL_SCCS1'] =", env8.get('TOOL_SCCS1'))
+print("env8['TOOL_SCCS2'] =", env8.get('TOOL_SCCS2'))
env9 = Environment(tools=[])
Tool('SCCS', toolpath=['tools'])(env9)
-print "env9['SCCS'] =", env9.get('SCCS')
-print "env9['TOOL_SCCS1'] =", env9.get('TOOL_SCCS1')
-print "env9['TOOL_SCCS2'] =", env9.get('TOOL_SCCS2')
+print("env9['SCCS'] =", env9.get('SCCS'))
+print("env9['TOOL_SCCS1'] =", env9.get('TOOL_SCCS1'))
+print("env9['TOOL_SCCS2'] =", env9.get('TOOL_SCCS2'))
env0 = Environment(TOOLPATH='tools', tools=[])
env0.Tool('SCCS', toolpath=['$TOOLPATH'])
-print "env0['SCCS'] =", env0.get('SCCS')
-print "env0['TOOL_SCCS1'] =", env0.get('TOOL_SCCS1')
-print "env0['TOOL_SCCS2'] =", env0.get('TOOL_SCCS2')
+print("env0['SCCS'] =", env0.get('SCCS'))
+print("env0['TOOL_SCCS1'] =", env0.get('TOOL_SCCS1'))
+print("env0['TOOL_SCCS2'] =", env0.get('TOOL_SCCS2'))
base = Environment(tools=[], toolpath=['tools'])
derived = base.Clone(tools=['bar'])
-print "derived['TOOL_BAR'] =", derived.get('TOOL_BAR')
+print("derived['TOOL_BAR'] =", derived.get('TOOL_BAR'))
""")
test.write('SCCS.py', r"""\
diff --git a/timings/ElectricCloud/TimeSCons-run.py b/timings/ElectricCloud/TimeSCons-run.py
index be75d12..130d916 100644
--- a/timings/ElectricCloud/TimeSCons-run.py
+++ b/timings/ElectricCloud/TimeSCons-run.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
"""
This configuration comes from the following blog article:
@@ -87,7 +88,7 @@ test.run(program=test.workpath('genscons.pl'), arguments=' '.join(arguments))
# This print is nott for debugging, leave it alone!
# We want to display the output from genscons.pl's generation the build
# configuration, so the buildbot logs contain more info.
-print test.stdout()
+print(test.stdout())
test.main(chdir='sconsbld')
diff --git a/www/gen_sched_table.py b/www/gen_sched_table.py
index e67f0d7..85b1b81 100755
--- a/www/gen_sched_table.py
+++ b/www/gen_sched_table.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+from __future__ import print_function
import sys
import datetime
@@ -6,13 +7,13 @@ import datetime
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
-print '<table width="100%">'
+print('<table width="100%">')
def row(*cells, **kw):
td = kw.get('tr','td')
- print ' <tr>'
+ print(' <tr>')
for cell in cells:
- print ' <%s>%s</%s>' % (td,cell,td)
- print ' </tr>'
+ print(' <%s>%s</%s>' % (td,cell,td))
+ print(' </tr>')
row('Estimated&nbsp;date', 'Type', 'Comments', tr = 'th')
if len(sys.argv) > 1:
@@ -30,7 +31,7 @@ for line in f:
incr,type,desc = line[1:].strip().split(None,2)
now = now + datetime.timedelta(int(incr))
else:
- print 'dunna understand code', line[0]
+ print('dunna understand code', line[0])
sys.exit(1)
#name = current + '.d' + str(now).replace('-','')
date = '%s-%s-%s' % (now.day,months[now.month-1],now.year)
@@ -41,7 +42,7 @@ for line in f:
else:
category = current = type
row(date, category, desc)
-print '</table>'
+print('</table>')
# Local Variables:
# tab-width:4