Gabe Black has submitted this change and it was merged. ( https://gem5-review.googlesource.com/8761 )

Change subject: scons: Switch from the print statement to the print function.
......................................................................

scons: Switch from the print statement to the print function.

Starting with version 3, scons imposes using the print function instead
of the print statement in code it processes. To get things building
again, this change moves all python code within gem5 to use the
function version. Another change by another author separately made this
same change to the site_tools and site_init.py files.

Change-Id: I2de7dc3b1be756baad6f60574c47c8b7e80ea3b0
Reviewed-on: https://gem5-review.googlesource.com/8761
Reviewed-by: Andreas Sandberg <andreas.sandb...@arm.com>
Reviewed-by: Jason Lowe-Power <ja...@lowepower.com>
Maintainer: Gabe Black <gabebl...@google.com>
---
M SConstruct
M ext/libelf/SConscript
M ext/systemc/SConscript
M ext/systemc/src/sysc/kernel/SConscript.sc
M ext/systemc/src/sysc/qt/SConscript.sc
M src/SConscript
M src/arch/hsail/gen.py
M src/arch/isa_parser.py
M src/arch/micro_asm.py
M src/arch/micro_asm_test.py
M src/cpu/BaseCPU.py
M src/cpu/minor/MinorCPU.py
M src/cpu/o3/O3CPU.py
M src/cpu/simple/BaseSimpleCPU.py
M src/mem/ruby/SConscript
M src/mem/slicc/main.py
M src/mem/slicc/util.py
M src/python/m5/SimObject.py
M src/python/m5/debug.py
M src/python/m5/event.py
M src/python/m5/main.py
M src/python/m5/params.py
M src/python/m5/simulate.py
M src/python/m5/ticks.py
M src/python/m5/util/__init__.py
M src/python/m5/util/attrdict.py
M src/python/m5/util/code_formatter.py
M src/python/m5/util/jobfile.py
M src/python/m5/util/multidict.py
M src/python/m5/util/sorteddict.py
M src/python/m5/util/terminal.py
M src/unittest/genini.py
M tests/SConscript
33 files changed, 386 insertions(+), 318 deletions(-)

Approvals:
  Jason Lowe-Power: Looks good to me, approved
  Andreas Sandberg: Looks good to me, approved
  Gabe Black: Looks good to me, approved



diff --git a/SConstruct b/SConstruct
index df647e7..0bb0f69 100755
--- a/SConstruct
+++ b/SConstruct
@@ -78,6 +78,8 @@
 #
 ###################################################

+from __future__ import print_function
+
 # Global Python includes
 import itertools
 import os
@@ -164,7 +166,7 @@
                help='Build with Address Sanitizer if available')

 if GetOption('no_lto') and GetOption('force_lto'):
-    print '--no-lto and --force-lto are mutually exclusive'
+    print('--no-lto and --force-lto are mutually exclusive')
     Exit(1)

 ########################################################################
@@ -183,7 +185,7 @@

 # Check that we have a C/C++ compiler
 if not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
-    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
+    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
     Exit(1)

 ###################################################
@@ -230,15 +232,15 @@
     try:
         build_top = rfind(path_dirs, 'build', -2)
     except:
-        print "Error: no non-leaf 'build' dir found on target path", t
+        print("Error: no non-leaf 'build' dir found on target path", t)
         Exit(1)
     this_build_root = joinpath('/',*path_dirs[:build_top+1])
     if not build_root:
         build_root = this_build_root
     else:
         if this_build_root != build_root:
-            print "Error: build targets not under same build root\n"\
-                  "  %s\n  %s" % (build_root, this_build_root)
+            print("Error: build targets not under same build root\n"
+                  "  %s\n  %s" % (build_root, this_build_root))
             Exit(1)
     variant_path = joinpath('/',*path_dirs[:build_top+2])
     if variant_path not in variant_paths:
@@ -335,7 +337,7 @@
 main['GCC'] = CXX_version and CXX_version.find('g++') >= 0
 main['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
 if main['GCC'] + main['CLANG'] > 1:
-    print 'Error: How can we have two at the same time?'
+    print('Error: How can we have two at the same time?')
     Exit(1)

 # Set up default C++ compiler flags
@@ -367,22 +369,22 @@
                          '-Wno-error=deprecated',
                         ])
 else:
-    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
-    print "Don't know what compiler options to use for your compiler."
-    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
-    print termcap.Yellow + '       version:' + termcap.Normal,
+ print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
+    print("Don't know what compiler options to use for your compiler.")
+ print(termcap.Yellow + ' compiler:' + termcap.Normal, main['CXX'])
+    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
     if not CXX_version:
-        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
-               termcap.Normal
+        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
+              termcap.Normal)
     else:
-        print CXX_version.replace('\n', '<nl>')
-    print "       If you're trying to use a compiler other than GCC"
-    print "       or clang, there appears to be something wrong with your"
-    print "       environment."
-    print "       "
- print " If you are trying to use a compiler other than those listed"
-    print "       above you will need to ease fix SConstruct and "
-    print "       src/SConscript to support that compiler."
+        print(CXX_version.replace('\n', '<nl>'))
+    print("       If you're trying to use a compiler other than GCC")
+    print("       or clang, there appears to be something wrong with your")
+    print("       environment.")
+    print("       ")
+ print(" If you are trying to use a compiler other than those listed")
+    print("       above you will need to ease fix SConstruct and ")
+    print("       src/SConscript to support that compiler.")
     Exit(1)

 if main['GCC']:
@@ -391,8 +393,8 @@
     # http://gcc.gnu.org/projects/cxx0x.html for details.
gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
     if compareVersions(gcc_version, "4.8") < 0:
-        print 'Error: gcc version 4.8 or newer required.'
-        print '       Installed version:', gcc_version
+        print('Error: gcc version 4.8 or newer required.')
+        print('       Installed version: ', gcc_version)
         Exit(1)

     main['GCC_VERSION'] = gcc_version
@@ -433,31 +435,31 @@
as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None

     if not as_version or compareVersions(as_version, "2.23") < 0:
-        print termcap.Yellow + termcap.Bold + \
-            'Warning: This combination of gcc and binutils have' + \
-            ' known incompatibilities.\n' + \
-            '         If you encounter build problems, please update ' + \
-            'binutils to 2.23.' + \
-            termcap.Normal
+        print(termcap.Yellow + termcap.Bold +
+            'Warning: This combination of gcc and binutils have' +
+            ' known incompatibilities.\n' +
+            '         If you encounter build problems, please update ' +
+            'binutils to 2.23.' +
+            termcap.Normal)

     # Make sure we warn if the user has requested to compile with the
     # Undefined Benahvior Sanitizer and this version of gcc does not
     # support it.
     if GetOption('with_ubsan') and \
             compareVersions(gcc_version, '4.9') < 0:
-        print termcap.Yellow + termcap.Bold + \
-            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
-            termcap.Normal
+        print(termcap.Yellow + termcap.Bold +
+            'Warning: UBSan is only supported using gcc 4.9 and later.' +
+            termcap.Normal)

     disable_lto = GetOption('no_lto')
     if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
             not GetOption('force_lto'):
-        print termcap.Yellow + termcap.Bold + \
- 'Warning: Your compiler doesn\'t support incremental linking' + \ - ' and lto at the same time, so lto is being disabled. To force' + \ - ' lto on anyway, use the --force-lto option. That will disable' + \
-            ' partial linking.' + \
-            termcap.Normal
+        print(termcap.Yellow + termcap.Bold +
+            'Warning: Your compiler doesn\'t support incremental linking' +
+ ' and lto at the same time, so lto is being disabled. To force' + + ' lto on anyway, use the --force-lto option. That will disable' +
+            ' partial linking.' +
+            termcap.Normal)
         disable_lto = True

     # Add the appropriate Link-Time Optimization (LTO) flags
@@ -508,11 +510,11 @@
     if (clang_version_match):
         clang_version = clang_version_match.groups()[0]
         if compareVersions(clang_version, "3.1") < 0:
-            print 'Error: clang version 3.1 or newer required.'
-            print '       Installed version:', clang_version
+            print('Error: clang version 3.1 or newer required.')
+            print('       Installed version:', clang_version)
             Exit(1)
     else:
-        print 'Error: Unable to determine clang version.'
+        print('Error: Unable to determine clang version.')
         Exit(1)

     # clang has a few additional warnings that we disable, extraneous
@@ -556,22 +558,22 @@
                    LINKFLAGS='-fsanitize=address')

 else:
-    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
-    print "Don't know what compiler options to use for your compiler."
-    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
-    print termcap.Yellow + '       version:' + termcap.Normal,
+ print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
+    print("Don't know what compiler options to use for your compiler.")
+ print(termcap.Yellow + ' compiler:' + termcap.Normal, main['CXX'])
+    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
     if not CXX_version:
-        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
-               termcap.Normal
+        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
+              termcap.Normal)
     else:
-        print CXX_version.replace('\n', '<nl>')
-    print "       If you're trying to use a compiler other than GCC"
-    print "       or clang, there appears to be something wrong with your"
-    print "       environment."
-    print "       "
- print " If you are trying to use a compiler other than those listed"
-    print "       above you will need to ease fix SConstruct and "
-    print "       src/SConscript to support that compiler."
+        print(CXX_version.replace('\n', '<nl>'))
+    print("       If you're trying to use a compiler other than GCC")
+    print("       or clang, there appears to be something wrong with your")
+    print("       environment.")
+    print("       ")
+ print(" If you are trying to use a compiler other than those listed")
+    print("       above you will need to ease fix SConstruct and ")
+    print("       src/SConscript to support that compiler.")
     Exit(1)

 # Set up common yacc/bison flags (needed for Ruby)
@@ -597,21 +599,21 @@

 # First two words should be "libprotoc x.y.z"
 if len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
-    print termcap.Yellow + termcap.Bold + \
-        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
- ' Please install protobuf-compiler for tracing support.' + \
-        termcap.Normal
+    print(termcap.Yellow + termcap.Bold +
+        'Warning: Protocol buffer compiler (protoc) not found.\n' +
+        '         Please install protobuf-compiler for tracing support.' +
+        termcap.Normal)
     main['PROTOC'] = False
 else:
     # Based on the availability of the compress stream wrappers,
     # require 2.1.0
     min_protoc_version = '2.1.0'
     if compareVersions(protoc_version[1], min_protoc_version) < 0:
-        print termcap.Yellow + termcap.Bold + \
-            'Warning: protoc version', min_protoc_version, \
-            'or newer required.\n' + \
-            '         Installed version:', protoc_version[1], \
-            termcap.Normal
+        print(termcap.Yellow + termcap.Bold +
+            'Warning: protoc version', min_protoc_version,
+            'or newer required.\n' +
+            '         Installed version:', protoc_version[1],
+            termcap.Normal)
         main['PROTOC'] = False
     else:
         # Attempt to determine the appropriate include path and
@@ -626,9 +628,9 @@
                 # using pkg-config
main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
             except:
-                print termcap.Yellow + termcap.Bold + \
-                    'Warning: pkg-config could not get protobuf flags.' + \
-                    termcap.Normal
+                print(termcap.Yellow + termcap.Bold +
+                    'Warning: pkg-config could not get protobuf flags.' +
+                    termcap.Normal)


 # Check for 'timeout' from GNU coreutils. If present, regressions will
@@ -708,7 +710,7 @@

 # Cache build files in the supplied directory.
 if main['M5_BUILD_CACHE']:
-    print 'Using build cache located at', main['M5_BUILD_CACHE']
+    print('Using build cache located at', main['M5_BUILD_CACHE'])
     CacheDir(main['M5_BUILD_CACHE'])

 main['USE_PYTHON'] = not GetOption('without_python')
@@ -748,27 +750,28 @@

     # verify that this stuff works
     if not conf.CheckHeader('Python.h', '<>'):
-        print "Error: can't find Python.h header in", py_includes
- print "Install Python headers (package python-dev on Ubuntu and RedHat)"
+        print("Error: can't find Python.h header in", py_includes)
+        print("Install Python headers (package python-dev on " +
+              "Ubuntu and RedHat)")
         Exit(1)

     for lib in py_libs:
         if not conf.CheckLib(lib):
-            print "Error: can't find library %s required by python" % lib
+            print("Error: can't find library %s required by python" % lib)
             Exit(1)

 # On Solaris you need to use libsocket for socket ops
if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'): if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
-       print "Can't find library with socket calls (e.g. accept())"
+       print("Can't find library with socket calls (e.g. accept())")
        Exit(1)

 # Check for zlib.  If the check passes, libz will be automatically
 # added to the LIBS environment variable.
 if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
-    print 'Error: did not find needed zlib compression library '\
-          'and/or zlib.h header file.'
-    print '       Please install zlib and try again.'
+    print('Error: did not find needed zlib compression library '
+          'and/or zlib.h header file.')
+    print('       Please install zlib and try again.')
     Exit(1)

 # If we have the protobuf compiler, also make sure we have the
@@ -782,10 +785,10 @@

 # If we have the compiler but not the library, print another warning.
 if main['PROTOC'] and not main['HAVE_PROTOBUF']:
-    print termcap.Yellow + termcap.Bold + \
- 'Warning: did not find protocol buffer library and/or headers.\n' + \
-    '       Please install libprotobuf-dev for tracing support.' + \
-    termcap.Normal
+    print(termcap.Yellow + termcap.Bold +
+        'Warning: did not find protocol buffer library and/or headers.\n' +
+    '       Please install libprotobuf-dev for tracing support.' +
+    termcap.Normal)

 # Check for librt.
 have_posix_clock = \
@@ -804,10 +807,10 @@
     elif conf.CheckLib('tcmalloc_minimal'):
         main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
     else:
-        print termcap.Yellow + termcap.Bold + \
-              "You can get a 12% performance improvement by "\
-              "installing tcmalloc (libgoogle-perftools-dev package "\
-              "on Ubuntu or RedHat)." + termcap.Normal
+        print(termcap.Yellow + termcap.Bold +
+              "You can get a 12% performance improvement by "
+              "installing tcmalloc (libgoogle-perftools-dev package "
+              "on Ubuntu or RedHat)." + termcap.Normal)


 # Detect back trace implementations. The last implementation in the
@@ -826,26 +829,26 @@

 if backtrace_impls[-1] == "none":
     default_backtrace_impl = "none"
-    print termcap.Yellow + termcap.Bold + \
-        "No suitable back trace implementation found." + \
-        termcap.Normal
+    print(termcap.Yellow + termcap.Bold +
+        "No suitable back trace implementation found." +
+        termcap.Normal)

 if not have_posix_clock:
-    print "Can't find library for POSIX clocks."
+    print("Can't find library for POSIX clocks.")

 # Check for <fenv.h> (C99 FP environment control)
 have_fenv = conf.CheckHeader('fenv.h', '<>')
 if not have_fenv:
-    print "Warning: Header file <fenv.h> not found."
-    print "         This host has no IEEE FP rounding mode control."
+    print("Warning: Header file <fenv.h> not found.")
+    print("         This host has no IEEE FP rounding mode control.")

 # Check for <png.h> (libpng library needed if wanting to dump
 # frame buffer image in png format)
 have_png = conf.CheckHeader('png.h', '<>')
 if not have_png:
-    print "Warning: Header file <png.h> not found."
-    print "         This host has no libpng library."
-    print "         Disabling support for PNG framebuffers."
+    print("Warning: Header file <png.h> not found.")
+    print("         This host has no libpng library.")
+    print("         Disabling support for PNG framebuffers.")

 # Check if we should enable KVM-based hardware virtualization. The API
 # we rely on exists since version 2.6.36 of the kernel, but somehow
@@ -853,13 +856,13 @@
 # the types as a fall back.
 have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
 if not have_kvm:
-    print "Info: Compatible header file <linux/kvm.h> not found, " \
-        "disabling KVM support."
+    print("Info: Compatible header file <linux/kvm.h> not found, "
+          "disabling KVM support.")

 # Check if the TUN/TAP driver is available.
 have_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
 if not have_tuntap:
-    print "Info: Compatible header file <linux/if_tun.h> not found."
+    print("Info: Compatible header file <linux/if_tun.h> not found.")

 # x86 needs support for xsave. We test for the structure here since we
 # won't be able to run new tests by the time we know which ISA we're
@@ -873,12 +876,12 @@
         import platform
         host_isa = platform.machine()
     except:
-        print "Warning: Failed to determine host ISA."
+        print("Warning: Failed to determine host ISA.")
         return False

     if not have_posix_timers:
-        print "Warning: Can not enable KVM, host seems to lack support " \
-            "for POSIX timers"
+        print("Warning: Can not enable KVM, host seems to lack support "
+              "for POSIX timers")
         return False

     if isa == "arm":
@@ -888,7 +891,7 @@
             return False

         if not have_kvm_xsave:
-            print "KVM on x86 requires xsave support in kernel headers."
+            print("KVM on x86 requires xsave support in kernel headers.")
             return False

         return True
@@ -961,15 +964,15 @@
 # Walk the tree and execute all SConsopts scripts that wil add to the
 # above variables
 if GetOption('verbose'):
-    print "Reading SConsopts"
+    print("Reading SConsopts")
 for bdir in [ base_dir ] + extras_dir_list:
     if not isdir(bdir):
-        print "Error: directory '%s' does not exist" % bdir
+        print("Error: directory '%s' does not exist" % bdir)
         Exit(1)
     for root, dirs, files in os.walk(bdir):
         if 'SConsopts' in files:
             if GetOption('verbose'):
-                print "Reading", joinpath(root, 'SConsopts')
+                print("Reading", joinpath(root, 'SConsopts'))
             SConscript(joinpath(root, 'SConsopts'))

 all_isa_list.sort()
@@ -1025,7 +1028,7 @@
 def build_config_file(target, source, env):
     (variable, value) = [s.get_contents() for s in source]
     f = file(str(target[0]), 'w')
-    print >> f, '#define', variable, value
+    print('#define', variable, value, file=f)
     f.close()
     return None

@@ -1107,7 +1110,7 @@
     dp = os.path.relpath(os.path.realpath(dp),
                          os.path.realpath(env['BUILDDIR']))
     with open(path, 'w') as hdr:
-        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
+        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)

 switching_header_action = MakeAction(build_switching_header,
                                      Transform('GENERATE'))
@@ -1132,7 +1135,7 @@

 for variant_path in variant_paths:
     if not GetOption('silent'):
-        print "Building in", variant_path
+        print("Building in", variant_path)

     # Make a copy of the build-root environment to use for this config.
     env = main.Clone()
@@ -1151,7 +1154,7 @@
     if isfile(current_vars_file):
         sticky_vars.files.append(current_vars_file)
         if not GetOption('silent'):
-            print "Using saved variables file %s" % current_vars_file
+            print("Using saved variables file %s" % current_vars_file)
     elif variant_dir in ext_build_dirs:
         # Things in ext are built without a variant directory.
         continue
@@ -1177,12 +1180,12 @@
         if existing_files:
             default_vars_file = existing_files[0]
             sticky_vars.files.append(default_vars_file)
-            print "Variables file %s not found,\n  using defaults in %s" \
-                  % (current_vars_file, default_vars_file)
+            print("Variables file %s not found,\n  using defaults in %s"
+                  % (current_vars_file, default_vars_file))
         else:
-            print "Error: cannot find variables file %s or " \
-                  "default file(s) %s" \
-                  % (current_vars_file, ' or '.join(default_vars_files))
+            print("Error: cannot find variables file %s or "
+                  "default file(s) %s"
+                  % (current_vars_file, ' or '.join(default_vars_files)))
             Exit(1)

     # Apply current variable settings to env
@@ -1195,17 +1198,18 @@
     # Process variable settings.

     if not have_fenv and env['USE_FENV']:
-        print "Warning: <fenv.h> not available; " \
-              "forcing USE_FENV to False in", variant_dir + "."
+        print("Warning: <fenv.h> not available; "
+              "forcing USE_FENV to False in", variant_dir + ".")
         env['USE_FENV'] = False

     if not env['USE_FENV']:
- print "Warning: No IEEE FP rounding mode control in", variant_dir + "." - print " FP results may deviate slightly from other platforms."
+        print("Warning: No IEEE FP rounding mode control in",
+              variant_dir + ".")
+ print(" FP results may deviate slightly from other platforms.")

     if not have_png and env['USE_PNG']:
-        print "Warning: <png.h> not available; " \
-              "forcing USE_PNG to False in", variant_dir + "."
+        print("Warning: <png.h> not available; "
+              "forcing USE_PNG to False in", variant_dir + ".")
         env['USE_PNG'] = False

     if env['USE_PNG']:
@@ -1216,16 +1220,17 @@

     if env['USE_KVM']:
         if not have_kvm:
- print "Warning: Can not enable KVM, host seems to lack KVM support"
+            print("Warning: Can not enable KVM, host seems to "
+                  "lack KVM support")
             env['USE_KVM'] = False
         elif not is_isa_kvm_compatible(env['TARGET_ISA']):
- print "Info: KVM support disabled due to unsupported host and " \
-                "target ISA combination"
+            print("Info: KVM support disabled due to unsupported host and "
+                  "target ISA combination")
             env['USE_KVM'] = False

     if env['USE_TUNTAP']:
         if not have_tuntap:
-            print "Warning: Can't connect EtherTap with a tap device."
+            print("Warning: Can't connect EtherTap with a tap device.")
             env['USE_TUNTAP'] = False

     if env['BUILD_GPU']:
@@ -1234,9 +1239,9 @@
     # Warn about missing optional functionality
     if env['USE_KVM']:
         if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
-            print "Warning: perf_event headers lack support for the " \
-                "exclude_host attribute. KVM instruction counts will " \
-                "be inaccurate."
+            print("Warning: perf_event headers lack support for the "
+                  "exclude_host attribute. KVM instruction counts will "
+                  "be inaccurate.")

     # Save sticky variable settings back to current variables file
     sticky_vars.Save(current_vars_file, env)
diff --git a/ext/libelf/SConscript b/ext/libelf/SConscript
index 85820ac..45f809d 100644
--- a/ext/libelf/SConscript
+++ b/ext/libelf/SConscript
@@ -28,6 +28,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 import os, subprocess

 Import('main')
@@ -114,8 +116,8 @@
 # Check that m4 is available
 import SCons.Tool.m4
 if not SCons.Tool.m4.exists(m4env):
-   print "Error: Can't find version of M4 macro processor.  " + \
-         "Please install M4 and try again."
+   print("Error: Can't find version of M4 macro processor.  " +
+         "Please install M4 and try again.")
    Exit(1)

 m4env.Append(M4FLAGS=['-DSRCDIR=%s' % Dir('.').path])
diff --git a/ext/systemc/SConscript b/ext/systemc/SConscript
index c2e67ae..cb0c61d 100644
--- a/ext/systemc/SConscript
+++ b/ext/systemc/SConscript
@@ -23,6 +23,8 @@
 # Authors: Christian Menard
 #          Matthias Jung

+from __future__ import print_function
+
 import os
 from m5.util.terminal import get_termcap

@@ -57,8 +59,8 @@
     arch = 'x86_64'
 else:
     termcap = get_termcap(GetOption('use_colors'))
-    print termcap.Yellow + termcap.Bold + \
- "Warning: Unrecognized architecture for systemc." + termcap.Normal
+    print(termcap.Yellow + termcap.Bold +
+ "Warning: Unrecognized architecture for systemc." + termcap.Normal)

 conf.Finish()

diff --git a/ext/systemc/src/sysc/kernel/SConscript.sc b/ext/systemc/src/sysc/kernel/SConscript.sc
index 0db22a6..ac79c2f 100644
--- a/ext/systemc/src/sysc/kernel/SConscript.sc
+++ b/ext/systemc/src/sysc/kernel/SConscript.sc
@@ -23,6 +23,8 @@
 # Authors: Christian Menard
 #          Matthias Jung

+from __future__ import print_function
+
 Import('systemc', 'SystemCSource')

 SystemCSource(
@@ -63,5 +65,5 @@
 elif coroutine_lib == 'fiber':
     SystemCSource('sc_cor_fiber.cpp')
 else:
-    print 'Unrecognized threading implementation \'%s\'' % coroutine_lib
+    print('Unrecognized threading implementation \'%s\'' % coroutine_lib)
     Exit(1)
diff --git a/ext/systemc/src/sysc/qt/SConscript.sc b/ext/systemc/src/sysc/qt/SConscript.sc
index 5ffb0d3..c2e8baf 100644
--- a/ext/systemc/src/sysc/qt/SConscript.sc
+++ b/ext/systemc/src/sysc/qt/SConscript.sc
@@ -23,6 +23,8 @@
 # Authors: Christian Menard
 #          Matthias Jung

+from __future__ import print_function
+
 import os

 Import('systemc', 'SystemCSource')
@@ -32,11 +34,11 @@

     qt_arch = systemc.get('QT_ARCH', None)
     if not qt_arch:
-        print 'No architecture selected for the QT coroutine library.'
+        print('No architecture selected for the QT coroutine library.')
         Exit(1)

     if qt_arch in ('i386', 'iX86_64'):
         SystemCSource(os.path.join('md', qt_arch + '.s'))
     else:
-        print 'Don\'t know what to do for QT arch %s.' % qt_arch
+        print('Don\'t know what to do for QT arch %s.' % qt_arch)
         Exit(1)
diff --git a/src/SConscript b/src/SConscript
index 1c53160..339059d 100755
--- a/src/SConscript
+++ b/src/SConscript
@@ -28,6 +28,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 import array
 import bisect
 import functools
@@ -831,7 +833,7 @@
         # Add the C++ source file
         Source(proto.cc_file, tags=proto.tags)
 elif ProtoBuf.all:
-    print 'Got protobuf to build, but lacks support!'
+    print('Got protobuf to build, but lacks support!')
     Exit(1)

 #
@@ -1166,7 +1168,7 @@
     for target in ['opt', 'fast', 'prof', 'perf']:
         ccflags[target] += ['-O3']
 else:
-    print 'Unknown compiler, please fix compiler options'
+    print('Unknown compiler, please fix compiler options')
     Exit(1)


diff --git a/src/arch/hsail/gen.py b/src/arch/hsail/gen.py
index 515d7ed..bb60121 100755
--- a/src/arch/hsail/gen.py
+++ b/src/arch/hsail/gen.py
@@ -35,12 +35,14 @@
 #  Author: Steve Reinhardt
 #

+from __future__ import print_function
+
 import sys, re

 from m5.util import code_formatter

 if len(sys.argv) != 4:
-    print "Error: need 3 args (file names)"
+    print("Error: need 3 args (file names)")
     sys.exit(0)

 header_code = code_formatter()
diff --git a/src/arch/isa_parser.py b/src/arch/isa_parser.py
index fe95d06..6817349 100755
--- a/src/arch/isa_parser.py
+++ b/src/arch/isa_parser.py
@@ -39,7 +39,7 @@
 #
 # Authors: Steve Reinhardt

-from __future__ import with_statement
+from __future__ import with_statement, print_function
 import os
 import sys
 import re
@@ -1537,11 +1537,11 @@
         # select the different chunks. If no 'split' directives are used,
         # the cpp emissions have no effect.
         if re.search('-ns.cc.inc$', filename):
-            print >>f, '#if !defined(__SPLIT) || (__SPLIT == 1)'
+            print('#if !defined(__SPLIT) || (__SPLIT == 1)', file=f)
             self.splits[f] = 1
         # ensure requisite #include's
         elif filename == 'decoder-g.hh.inc':
-            print >>f, '#include "base/bitfield.hh"'
+            print('#include "base/bitfield.hh"', file=f)

         return f

@@ -1596,11 +1596,11 @@

                 fn = 'decoder-ns.cc.inc'
                 assert(fn in self.files)
-                print >>f, 'namespace %s {' % self.namespace
+                print('namespace %s {' % self.namespace, file=f)
                 if splits > 1:
-                    print >>f, '#define __SPLIT %u' % i
-                print >>f, '#include "%s"' % fn
-                print >>f, '}'
+                    print('#define __SPLIT %u' % i, file=f)
+                print('#include "%s"' % fn, file=f)
+                print('}', file=f)

         # instruction execution
         splits = self.splits[self.get_file('exec')]
@@ -1617,11 +1617,11 @@

                 fn = 'exec-ns.cc.inc'
                 assert(fn in self.files)
-                print >>f, 'namespace %s {' % self.namespace
+                print('namespace %s {' % self.namespace, file=f)
                 if splits > 1:
-                    print >>f, '#define __SPLIT %u' % i
-                print >>f, '#include "%s"' % fn
-                print >>f, '}'
+                    print('#define __SPLIT %u' % i, file=f)
+                print('#include "%s"' % fn, file=f)
+                print('}', file=f)

         # max_inst_regs.hh
         self.update('max_inst_regs.hh',
@@ -2019,7 +2019,7 @@
     def p_def_template(self, t):
         'def_template : DEF TEMPLATE ID CODELIT SEMI'
         if t[3] in self.templateMap:
-            print "warning: template %s already defined" % t[3]
+            print("warning: template %s already defined" % t[3])
         self.templateMap[t[3]] = Template(self, t[4])

     # An instruction format definition looks like
@@ -2604,9 +2604,9 @@
         try:
             self._parse_isa_desc(*args, **kwargs)
         except ISAParserError, e:
-            print backtrace(self.fileNameStack)
-            print "At %s:" % e.lineno
-            print e
+            print(backtrace(self.fileNameStack))
+            print("At %s:" % e.lineno)
+            print(e)
             sys.exit(1)

 # Called as script: get args from command line.
diff --git a/src/arch/micro_asm.py b/src/arch/micro_asm.py
index 4e5400c..263e73a 100644
--- a/src/arch/micro_asm.py
+++ b/src/arch/micro_asm.py
@@ -26,6 +26,8 @@
 #
 # Authors: Gabe Black

+from __future__ import print_function
+
 import os
 import sys
 import re
@@ -117,9 +119,9 @@
 ##########################################################################

 def print_error(message):
-    print
-    print "*** %s" % message
-    print
+    print()
+    print("*** %s" % message)
+    print()

 def handle_statement(parser, container, statement):
     if statement.is_microop:
@@ -153,7 +155,7 @@
                     statement.params, {}, parser.symbols)
         except:
             print_error("Error executing directive.")
-            print container.directives
+            print(container.directives)
             raise
     else:
raise Exception, "Didn't recognize the type of statement", statement
diff --git a/src/arch/micro_asm_test.py b/src/arch/micro_asm_test.py
index b074ecb..e5755f7 100755
--- a/src/arch/micro_asm_test.py
+++ b/src/arch/micro_asm_test.py
@@ -26,6 +26,8 @@
 #
 # Authors: Gabe Black

+from __future__ import print_function
+
from micro_asm import MicroAssembler, Combinational_Macroop, Rom_Macroop, Rom

 class Bah(object):
@@ -58,7 +60,7 @@
     def untweak(self):
         microops["bah"] = Bah
     def print_debug(self, message):
-        print message
+        print(message)

     def __init__(self, name):
         super(TestMacroop, self).__init__(name)
diff --git a/src/cpu/BaseCPU.py b/src/cpu/BaseCPU.py
index 096aa63..e02d367 100644
--- a/src/cpu/BaseCPU.py
+++ b/src/cpu/BaseCPU.py
@@ -42,6 +42,8 @@
 #          Andreas Hansson
 #          Glenn Bergmans

+from __future__ import print_function
+
 import sys

 from m5.SimObject import *
@@ -200,8 +202,8 @@
                 [], "Interrupt Controller")
         isa = VectorParam.RiscvISA([], "ISA instance")
     else:
-        print "Don't know what TLB to use for ISA %s" % \
-            buildEnv['TARGET_ISA']
+        print("Don't know what TLB to use for ISA %s" %
+              buildEnv['TARGET_ISA'])
         sys.exit(1)

     max_insts_all_threads = Param.Counter(0,
@@ -260,8 +262,8 @@
             self.interrupts = \
                 [RiscvInterrupts() for i in xrange(self.numThreads)]
         else:
- print "Don't know what Interrupt Controller to use for ISA %s" % \
-                buildEnv['TARGET_ISA']
+ print("Don't know what Interrupt Controller to use for ISA %s" %
+                  buildEnv['TARGET_ISA'])
             sys.exit(1)

     def connectCachedPorts(self, bus):
diff --git a/src/cpu/minor/MinorCPU.py b/src/cpu/minor/MinorCPU.py
index 5954f7b..87a3049 100644
--- a/src/cpu/minor/MinorCPU.py
+++ b/src/cpu/minor/MinorCPU.py
@@ -40,6 +40,8 @@
 #          Nathan Binkert
 #          Andrew Bardsley

+from __future__ import print_function
+
 from m5.defines import buildEnv
 from m5.params import *
 from m5.proxy import *
@@ -275,5 +277,5 @@
         numThreads = Parent.numThreads), "Branch Predictor")

     def addCheckerCpu(self):
-        print "Checker not yet supported by MinorCPU"
+        print("Checker not yet supported by MinorCPU")
         exit(1)
diff --git a/src/cpu/o3/O3CPU.py b/src/cpu/o3/O3CPU.py
index 8507ab6..b8152f6 100644
--- a/src/cpu/o3/O3CPU.py
+++ b/src/cpu/o3/O3CPU.py
@@ -38,6 +38,8 @@
 #
 # Authors: Kevin Lim

+from __future__ import print_function
+
 from m5.defines import buildEnv
 from m5.params import *
 from m5.proxy import *
@@ -173,5 +175,5 @@
             self.checker.cpu_id = self.cpu_id

         else:
-            print "ERROR: Checker only supported under ARM ISA!"
+            print("ERROR: Checker only supported under ARM ISA!")
             exit(1)
diff --git a/src/cpu/simple/BaseSimpleCPU.py b/src/cpu/simple/BaseSimpleCPU.py
index 7298724..b404584 100644
--- a/src/cpu/simple/BaseSimpleCPU.py
+++ b/src/cpu/simple/BaseSimpleCPU.py
@@ -26,6 +26,8 @@
 #
 # Authors: Gabe Black

+from __future__ import print_function
+
 from m5.defines import buildEnv
 from m5.params import *
 from BaseCPU import BaseCPU
@@ -45,7 +47,7 @@
             self.checker.itb = ArmTLB(size = self.itb.size)
             self.checker.dtb = ArmTLB(size = self.dtb.size)
         else:
-            print "ERROR: Checker only supported under ARM ISA!"
+            print("ERROR: Checker only supported under ARM ISA!")
             exit(1)

     branchPred = Param.BranchPredictor(NULL, "Branch Predictor")
diff --git a/src/mem/ruby/SConscript b/src/mem/ruby/SConscript
index 5cae880..64e798f 100644
--- a/src/mem/ruby/SConscript
+++ b/src/mem/ruby/SConscript
@@ -28,6 +28,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 import os
 import sys

@@ -101,7 +103,7 @@
 def MakeIncludeAction(target, source, env):
     f = file(str(target[0]), 'w')
     for s in source:
-        print >>f, '#include "%s"' % str(s.abspath)
+        print('#include "%s"' % str(s.abspath), file=f)
     f.close()

 def MakeInclude(source):
diff --git a/src/mem/slicc/main.py b/src/mem/slicc/main.py
index 0b528d8..05a5cdb 100644
--- a/src/mem/slicc/main.py
+++ b/src/mem/slicc/main.py
@@ -25,6 +25,8 @@
 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+from __future__ import print_function
+
 import os
 import sys

@@ -45,7 +47,7 @@
     if args:
         format = format % args

-    print >>sys.stderr, format
+    print(format, file=sys.stderr)

 def main(args=None):
     import optparse
@@ -79,7 +81,7 @@

     if opts.print_files:
         for i in sorted(slicc.files()):
-            print '    %s' % i
+            print('    %s' % i)
     else:
         output("Processing AST...")
         slicc.process()
diff --git a/src/mem/slicc/util.py b/src/mem/slicc/util.py
index 83badf4..3a0cf5f 100644
--- a/src/mem/slicc/util.py
+++ b/src/mem/slicc/util.py
@@ -24,6 +24,8 @@
 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+from __future__ import print_function
+
 import os
 import sys

@@ -66,7 +68,7 @@
         if args:
             message = message % args
         #raise Exception, "%s: Warning: %s" % (self, message)
-        print >>sys.stderr, "%s: Warning: %s" % (self, message)
+        print("%s: Warning: %s" % (self, message), file=sys.stderr)

     def error(self, message, *args):
         if args:
diff --git a/src/python/m5/SimObject.py b/src/python/m5/SimObject.py
index 919c0e8..6e61961 100644
--- a/src/python/m5/SimObject.py
+++ b/src/python/m5/SimObject.py
@@ -43,6 +43,8 @@
 #          Andreas Hansson
 #          Andreas Sandberg

+from __future__ import print_function
+
 import sys
 from types import FunctionType, MethodType, ModuleType
 from functools import wraps
@@ -768,8 +770,8 @@
         try:
             ptypes = [p.ptype for p in params]
         except:
-            print cls, p, p.ptype_str
-            print params
+            print(cls, p, p.ptype_str)
+            print(params)
             raise

         class_path = cls._value_dict['cxx_class'].split('::')
@@ -962,7 +964,7 @@
     def enumerateParams(self, flags_dict = {},
                         cmd_line_str = "", access_str = ""):
         if hasattr(self, "_paramEnumed"):
-            print "Cycle detected enumerating params"
+            print("Cycle detected enumerating params")
         else:
             self._paramEnumed = True
# Scan the children first to pick up all the objects in this SimObj
@@ -1334,8 +1336,8 @@
                 try:
                     value = value.unproxy(self)
                 except:
-                    print "Error in unproxying param '%s' of %s" % \
-                          (param, self.path())
+                    print("Error in unproxying param '%s' of %s" %
+                          (param, self.path()))
                     raise
                 setattr(self, param, value)

@@ -1349,30 +1351,31 @@
                 port.unproxy(self)

     def print_ini(self, ini_file):
- print >>ini_file, '[' + self.path() + ']' # .ini section header + print('[' + self.path() + ']', file=ini_file) # .ini section header

         instanceDict[self.path()] = self

         if hasattr(self, 'type'):
-            print >>ini_file, 'type=%s' % self.type
+            print('type=%s' % self.type, file=ini_file)

         if len(self._children.keys()):
-            print >>ini_file, 'children=%s' % \
-                  ' '.join(self._children[n].get_name() \
-                  for n in sorted(self._children.keys()))
+            print('children=%s' %
+                  ' '.join(self._children[n].get_name()
+                           for n in sorted(self._children.keys())),
+                  file=ini_file)

         for param in sorted(self._params.keys()):
             value = self._values.get(param)
             if value != None:
-                print >>ini_file, '%s=%s' % (param,
-                                             self._values[param].ini_str())
+                print('%s=%s' % (param, self._values[param].ini_str()),
+                      file=ini_file)

         for port_name in sorted(self._ports.keys()):
             port = self._port_refs.get(port_name, None)
             if port != None:
-                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
+                print('%s=%s' % (port_name, port.ini_str()), file=ini_file)

-        print >>ini_file        # blank line between objects
+        print(file=ini_file)        # blank line between objects

     # generate a tree of dictionaries expressing all the parameters in the
     # instantiated system for use by scripts that want to do power, thermal
diff --git a/src/python/m5/debug.py b/src/python/m5/debug.py
index 839c32d..f7e34a7 100644
--- a/src/python/m5/debug.py
+++ b/src/python/m5/debug.py
@@ -26,6 +26,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 from UserDict import DictMixin

 import _m5.debug
@@ -34,25 +36,25 @@
 from m5.util import printList

 def help():
-    print "Base Flags:"
+    print("Base Flags:")
     for name in sorted(flags):
         if name == 'All':
             continue
         flag = flags[name]
         children = [c for c in flag.kids() ]
         if not children:
-            print "    %s: %s" % (name, flag.desc())
-    print
-    print "Compound Flags:"
+            print("    %s: %s" % (name, flag.desc()))
+    print()
+    print("Compound Flags:")
     for name in sorted(flags):
         if name == 'All':
             continue
         flag = flags[name]
         children = [c for c in flag.kids() ]
         if children:
-            print "    %s: %s" % (name, flag.desc())
+            print("    %s: %s" % (name, flag.desc()))
             printList([ c.name() for c in children ], indent=8)
-    print
+    print()

 class AllFlags(DictMixin):
     def __init__(self):
diff --git a/src/python/m5/event.py b/src/python/m5/event.py
index 59d18b6..74863a9 100644
--- a/src/python/m5/event.py
+++ b/src/python/m5/event.py
@@ -40,6 +40,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 import m5
 import _m5.event

@@ -76,7 +78,7 @@
         self.eventq.schedule(self, m5.curTick() + self.period)

     def __call__(self):
-        print "Progress! Time now %fs" % (m5.curTick()/1e12)
+        print("Progress! Time now %fs" % (m5.curTick()/1e12))
         self.eventq.schedule(self, m5.curTick() + self.period)


diff --git a/src/python/m5/main.py b/src/python/m5/main.py
index ad45288..9d46d43 100644
--- a/src/python/m5/main.py
+++ b/src/python/m5/main.py
@@ -38,6 +38,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 import code
 import datetime
 import os
@@ -230,12 +232,12 @@

     # Print redirection notices here before doing any redirection
     if options.redirect_stdout and not options.redirect_stderr:
-        print "Redirecting stdout and stderr to", stdout_file
+        print("Redirecting stdout and stderr to", stdout_file)
     else:
         if options.redirect_stdout:
-            print "Redirecting stdout to", stdout_file
+            print("Redirecting stdout to", stdout_file)
         if options.redirect_stderr:
-            print "Redirecting stderr to", stderr_file
+            print("Redirecting stderr to", stderr_file)

     # Now redirect stdout/stderr as desired
     if options.redirect_stdout:
@@ -252,28 +254,28 @@

     if options.build_info:
         done = True
-        print 'Build information:'
-        print
-        print 'compiled %s' % defines.compileDate;
-        print 'build options:'
+        print('Build information:')
+        print()
+        print('compiled %s' % defines.compileDate)
+        print('build options:')
         keys = defines.buildEnv.keys()
         keys.sort()
         for key in keys:
             val = defines.buildEnv[key]
-            print '    %s = %s' % (key, val)
-        print
+            print('    %s = %s' % (key, val))
+        print()

     if options.copyright:
         done = True
-        print info.COPYING
-        print
+        print(info.COPYING)
+        print()

     if options.readme:
         done = True
-        print 'Readme:'
-        print
-        print info.README
-        print
+        print('Readme:')
+        print()
+        print(info.README)
+        print()

     if options.debug_help:
         done = True
@@ -283,23 +285,23 @@
     if options.list_sim_objects:
         import SimObject
         done = True
-        print "SimObjects:"
+        print("SimObjects:")
         objects = SimObject.allClasses.keys()
         objects.sort()
         for name in objects:
             obj = SimObject.allClasses[name]
-            print "    %s" % obj
+            print("    %s" % obj)
             params = obj._params.keys()
             params.sort()
             for pname in params:
                 param = obj._params[pname]
                 default = getattr(param, 'default', '')
-                print "        %s" % pname
+                print("        %s" % pname)
                 if default:
-                    print "            default: %s" % default
-                print "            desc: %s" % param.desc
-                print
-            print
+                    print("            default: %s" % default)
+                print("            desc: %s" % param.desc)
+                print()
+            print()

     if done:
         sys.exit(0)
@@ -310,26 +312,26 @@

     verbose = options.verbose - options.quiet
     if verbose >= 0:
-        print "gem5 Simulator System.  http://gem5.org";
-        print brief_copyright
-        print
+        print("gem5 Simulator System.  http://gem5.org";)
+        print(brief_copyright)
+        print()

-        print "gem5 compiled %s" % defines.compileDate;
+        print("gem5 compiled %s" % defines.compileDate)

-        print "gem5 started %s" % \
-            datetime.datetime.now().strftime("%b %e %Y %X")
-        print "gem5 executing on %s, pid %d" % \
-            (socket.gethostname(), os.getpid())
+        print("gem5 started %s" %
+              datetime.datetime.now().strftime("%b %e %Y %X"))
+        print("gem5 executing on %s, pid %d" %
+              (socket.gethostname(), os.getpid()))

         # in Python 3 pipes.quote() is moved to shlex.quote()
         import pipes
-        print "command line:", " ".join(map(pipes.quote, sys.argv))
-        print
+        print("command line:", " ".join(map(pipes.quote, sys.argv)))
+        print()

     # check to make sure we can find the listed script
     if not arguments or not os.path.isfile(arguments[0]):
         if arguments and not os.path.isfile(arguments[0]):
-            print "Script %s not found" % arguments[0]
+            print("Script %s not found" % arguments[0])

         options.usage(2)

@@ -375,7 +377,7 @@
                 off = True

             if flag not in debug.flags:
-                print >>sys.stderr, "invalid debug flag '%s'" % flag
+                print("invalid debug flag '%s'" % flag, file=sys.stderr)
                 sys.exit(1)

             if off:
@@ -420,11 +422,11 @@
         try:
             pdb.run(filecode, scope)
         except SystemExit:
-            print "The program exited via sys.exit(). Exit status: ",
-            print sys.exc_info()[1]
+ print("The program exited via sys.exit(). Exit status: ", end=' ')
+            print(sys.exc_info()[1])
         except:
             traceback.print_exc()
-            print "Uncaught exception. Entering post mortem debugging"
+            print("Uncaught exception. Entering post mortem debugging")
             t = sys.exc_info()[2]
             while t.tb_next is not None:
                 t = t.tb_next
@@ -441,9 +443,9 @@

     options, arguments = parse_options()

-    print 'opts:'
+    print('opts:')
     pprint(options, indent=4)
-    print
+    print()

-    print 'args:'
+    print('args:')
     pprint(arguments, indent=4)
diff --git a/src/python/m5/params.py b/src/python/m5/params.py
index 11a55e5..483e632 100644
--- a/src/python/m5/params.py
+++ b/src/python/m5/params.py
@@ -59,6 +59,8 @@
 #
 #####################################################################

+from __future__ import print_function
+
 import copy
 import datetime
 import re
@@ -311,7 +313,7 @@
                         cmd_line_str = "",
                         access_str = ""):
         if hasattr(self, "_paramEnumed"):
- print "Cycle detected enumerating params at %s?!" % (cmd_line_str) + print("Cycle detected enumerating params at %s?!" % (cmd_line_str))
         else:
             x = 0
             for vals in self:
@@ -1826,8 +1828,8 @@
             try:
                 realPeer = self.peer.unproxy(self.simobj)
             except:
-                print "Error in unproxying port '%s' of %s" % \
-                      (self.name, self.simobj.path())
+                print("Error in unproxying port '%s' of %s" %
+                      (self.name, self.simobj.path()))
                 raise
             self.connect(realPeer)

@@ -1856,9 +1858,9 @@
             connectPorts(self.simobj.getCCObject(), self.name, self.index,
                          peer.simobj.getCCObject(), peer.name, peer.index)
         except:
-            print "Error connecting port %s.%s to %s.%s" % \
+            print("Error connecting port %s.%s to %s.%s" %
                   (self.simobj.path(), self.name,
-                   peer.simobj.path(), peer.name)
+                   peer.simobj.path(), peer.name))
             raise
         self.ccConnected = True
         peer.ccConnected = True
diff --git a/src/python/m5/simulate.py b/src/python/m5/simulate.py
index c47dd22..0e1a67e 100644
--- a/src/python/m5/simulate.py
+++ b/src/python/m5/simulate.py
@@ -40,6 +40,8 @@
 # Authors: Nathan Binkert
 #          Steve Reinhardt

+from __future__ import print_function
+
 import atexit
 import os
 import sys
@@ -223,7 +225,7 @@

     drain()
     memWriteback(root)
-    print "Writing checkpoint"
+    print("Writing checkpoint")
     _m5.core.serializeAll(dir)

 def _changeMemoryMode(system, mode):
@@ -233,7 +235,7 @@
     if system.getMemoryMode() != mode:
         system.setMemoryMode(mode)
     else:
-        print "System already in target mode. Memory mode unchanged."
+        print("System already in target mode. Memory mode unchanged.")

 def switchCpus(system, cpuList, verbose=True):
     """Switch CPUs in a system.
@@ -248,7 +250,7 @@
     """

     if verbose:
-        print "switching cpus"
+        print("switching cpus")

     if not isinstance(cpuList, list):
         raise RuntimeError, "Must pass a list to this function"
diff --git a/src/python/m5/ticks.py b/src/python/m5/ticks.py
index ce9459f..582c65c 100644
--- a/src/python/m5/ticks.py
+++ b/src/python/m5/ticks.py
@@ -26,6 +26,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 import sys
 from m5.util import warn

@@ -39,7 +41,7 @@
     if not tps_fixed:
         tps_fixed = True
         _m5.core.setClockFrequency(int(tps))
-        print "Global frequency set at %d ticks per second" % int(tps)
+        print("Global frequency set at %d ticks per second" % int(tps))

 def setGlobalFrequency(ticksPerSecond):
     from m5.util import convert
diff --git a/src/python/m5/util/__init__.py b/src/python/m5/util/__init__.py
index 5736748..2ad9c56 100644
--- a/src/python/m5/util/__init__.py
+++ b/src/python/m5/util/__init__.py
@@ -39,6 +39,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 import os
 import re
 import sys
@@ -57,26 +59,26 @@
 # ever happen regardless of what the user does (i.e., an acutal m5
 # bug).
 def panic(fmt, *args):
-    print >>sys.stderr, 'panic:', fmt % args
+    print('panic:', fmt % args, file=sys.stderr)
     sys.exit(1)

 # fatal() should be called when the simulation cannot continue due to
 # some condition that is the user's fault (bad configuration, invalid
 # arguments, etc.) and not a simulator bug.
 def fatal(fmt, *args):
-    print >>sys.stderr, 'fatal:', fmt % args
+    print('fatal:', fmt % args, file=sys.stderr)
     sys.exit(1)

# warn() should be called when the user should be warned about some condition # that may or may not be the user's fault, but that they should be made aware
 # of as it may affect the simulation or results.
 def warn(fmt, *args):
-    print >>sys.stderr, 'warn:', fmt % args
+    print('warn:', fmt % args, file=sys.stderr)

 # inform() should be called when the user should be informed about some
 # condition that they may be interested in.
 def inform(fmt, *args):
-    print >>sys.stdout, 'info:', fmt % args
+    print('info:', fmt % args, file=sys.stdout)

 class Singleton(type):
     def __call__(cls, *args, **kwargs):
@@ -166,14 +168,14 @@
     line = ' ' * indent
     for i,item in enumerate(items):
         if len(line) + len(item) > 76:
-            print line
+            print(line)
             line = ' ' * indent

         if i < len(items) - 1:
             line += '%s, ' % item
         else:
             line += item
-            print line
+            print(line)

 def readCommand(cmd, **kwargs):
     """run the command cmd, read the results and return them
diff --git a/src/python/m5/util/attrdict.py b/src/python/m5/util/attrdict.py
index cb83e9e..d444d5d 100644
--- a/src/python/m5/util/attrdict.py
+++ b/src/python/m5/util/attrdict.py
@@ -26,6 +26,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 __all__ = [ 'attrdict', 'multiattrdict', 'optiondict' ]

 class attrdict(dict):
@@ -77,24 +79,24 @@
     x = attrdict()
     x.y = 1
     x['z'] = 2
-    print x['y'], x.y
-    print x['z'], x.z
-    print dir(x)
-    print x
+    print(x['y'], x.y)
+    print(x['z'], x.z)
+    print(dir(x))
+    print(x)

-    print
+    print()

     del x['y']
     del x.z
-    print dir(x)
+    print(dir(x))
     print(x)

-    print
-    print "multiattrdict"
+    print()
+    print("multiattrdict")
     x = multiattrdict()
     x.x.x.x = 9
     x.y.z = 9
-    print x
-    print x.y
-    print x.y.z
-    print x.z.z
+    print(x)
+    print(x.y)
+    print(x.y.z)
+    print(x.z.z)
diff --git a/src/python/m5/util/code_formatter.py b/src/python/m5/util/code_formatter.py
index 023e189..a11c9d3 100644
--- a/src/python/m5/util/code_formatter.py
+++ b/src/python/m5/util/code_formatter.py
@@ -24,6 +24,8 @@
 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+from __future__ import print_function
+
 import __builtin__
 import inspect
 import os
@@ -312,4 +314,4 @@
 }
 ''', 1, 9)

-    print f,
+    print(f, end=' ')
diff --git a/src/python/m5/util/jobfile.py b/src/python/m5/util/jobfile.py
index 9c59778..d8c09af 100644
--- a/src/python/m5/util/jobfile.py
+++ b/src/python/m5/util/jobfile.py
@@ -26,6 +26,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 import sys

 class Data(object):
@@ -69,12 +71,12 @@

     def printinfo(self):
         if self.name:
-            print 'name: %s' % self.name
+            print('name: %s' % self.name)
         if self.desc:
-            print 'desc: %s' % self.desc
+            print('desc: %s' % self.desc)
         try:
             if self.system:
-                print 'system: %s' % self.system
+                print('system: %s' % self.system)
         except AttributeError:
             pass

@@ -84,8 +86,8 @@
             if isinstance(val, dict):
                 import pprint
                 val = pprint.pformat(val)
-            print '%-20s = %s' % (key, val)
-        print
+            print('%-20s = %s' % (key, val))
+        print()

     def __contains__(self, attr):
         if attr.startswith('_'):
@@ -186,10 +188,10 @@
     def printinfo(self):
         super(Job, self).printinfo()
         if self._checkpoint:
-            print 'checkpoint: %s' % self._checkpoint.name
-        print 'config: %s' % self._config.name
-        print 'groups: %s' % [ g.name for g in self._groups ]
-        print 'options: %s' % [ o.name for o in self._options ]
+            print('checkpoint: %s' % self._checkpoint.name)
+        print('config: %s' % self._config.name)
+        print('groups: %s' % [ g.name for g in self._groups ])
+        print('options: %s' % [ o.name for o in self._options ])
         super(Job, self).printverbose()

 class SubOption(Data):
@@ -253,7 +255,7 @@

     def printinfo(self):
         super(Option, self).printinfo()
-        print 'config: %s' % self._config.name
+        print('config: %s' % self._config.name)
         super(Option, self).printverbose()

 class Group(Data):
@@ -283,8 +285,8 @@

     def printinfo(self):
         super(Group, self).printinfo()
-        print 'config: %s' % self._config.name
-        print 'options: %s' % [ o.name for o in self._options ]
+        print('config: %s' % self._config.name)
+        print('options: %s' % [ o.name for o in self._options ])
         super(Group, self).printverbose()

 class Configuration(Data):
@@ -397,7 +399,7 @@

     def printinfo(self):
         super(Configuration, self).printinfo()
-        print 'groups: %s' % [ g.name for g in self._groups ]
+        print('groups: %s' % [ g.name for g in self._groups ])
         super(Configuration, self).printverbose()

 def JobFile(jobfile):
@@ -466,7 +468,7 @@
             cpt = ''
             if job._checkpoint:
                 cpt = job._checkpoint.name
-            print job.name, cpt
+            print(job.name, cpt)

 if __name__ == '__main__':
     main()
diff --git a/src/python/m5/util/multidict.py b/src/python/m5/util/multidict.py
index b5cd700..d22b1cb 100644
--- a/src/python/m5/util/multidict.py
+++ b/src/python/m5/util/multidict.py
@@ -26,6 +26,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 __all__ = [ 'multidict' ]

 class multidict(object):
@@ -116,10 +118,10 @@
             return default

     def _dump(self):
-        print 'multidict dump'
+        print('multidict dump')
         node = self
         while isinstance(node, multidict):
-            print '    ', node.local
+            print('    ', node.local)
             node = node.parent

     def _dumpkey(self, key):
@@ -129,7 +131,7 @@
             if key in node.local:
                 values.append(node.local[key])
             node = node.parent
-        print key, values
+        print(key, values)

 if __name__ == '__main__':
     test1 = multidict()
@@ -150,33 +152,33 @@

     test2.setdefault('f', multidict)

-    print 'test1>', test1.items()
-    print 'test2>', test2.items()
-    #print test1['a']
-    print test1['b']
-    print test1['c']
-    print test1['d']
-    print test1['e']
+    print('test1>', test1.items())
+    print('test2>', test2.items())
+    #print(test1['a'])
+    print(test1['b'])
+    print(test1['c'])
+    print(test1['d'])
+    print(test1['e'])

-    print test2['a']
-    #print test2['b']
-    print test2['c']
-    print test2['d']
-    print test2['e']
+    print(test2['a'])
+    #print(test2['b'])
+    print(test2['c'])
+    print(test2['d'])
+    print(test2['e'])

     for key in test2.iterkeys():
-        print key
+        print(key)

     test2.get('g', 'foo')
     #test2.get('b')
     test2.get('b', 'bar')
     test2.setdefault('b', 'blah')
-    print test1
-    print test2
-    print `test2`
+    print(test1)
+    print(test2)
+    print(`test2`)

-    print len(test2)
+    print(len(test2))

     test3['a'] = [ 0, 1, 2, 3 ]

-    print test4
+    print(test4)
diff --git a/src/python/m5/util/sorteddict.py b/src/python/m5/util/sorteddict.py
index ef32be3..abe2837 100644
--- a/src/python/m5/util/sorteddict.py
+++ b/src/python/m5/util/sorteddict.py
@@ -24,6 +24,8 @@
 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+from __future__ import print_function
+
 from bisect import bisect_left, bisect_right

 class SortedDict(dict):
@@ -181,21 +183,21 @@

 if __name__ == '__main__':
     def display(d):
-        print d
-        print d.keys()
-        print list(d.iterkeys())
-        print d.values()
-        print list(d.itervalues())
-        print d.items()
-        print list(d.iteritems())
+        print(d)
+        print(d.keys())
+        print(list(d.iterkeys()))
+        print(d.values())
+        print(list(d.itervalues()))
+        print(d.items())
+        print(list(d.iteritems()))

     d = SortedDict(x=24,e=5,j=4,b=2,z=26,d=4)
     display(d)

-    print 'popitem', d.popitem()
+    print('popitem', d.popitem())
     display(d)

-    print 'pop j'
+    print('pop j')
     d.pop('j')
     display(d)

@@ -212,9 +214,9 @@
     d['y'] = 26
     display(d)

-    print `d`
+    print(`d`)

-    print d.copy()
+    print(d.copy())

     for k,v in d.itemrange('d', 'z', inclusive=True):
-        print k,v
+        print(k, v)
diff --git a/src/python/m5/util/terminal.py b/src/python/m5/util/terminal.py
index 6bf85f1..9dc5d98 100644
--- a/src/python/m5/util/terminal.py
+++ b/src/python/m5/util/terminal.py
@@ -26,6 +26,8 @@
 #
 # Author: Steve Reinhardt

+from __future__ import print_function
+
 import sys

 # Intended usage example:
@@ -36,7 +38,7 @@
 #    from m5.util.terminal import no_termcap as termcap
 # else:
 #    from m5.util.terminal import tty_termcap as termcap
-# print termcap.Blue + "This could be blue!" + termcap.Normal
+# print(termcap.Blue + "This could be blue!" + termcap.Normal)

 # ANSI color names in index order
 color_names = "Black Red Green Yellow Blue Magenta Cyan".split()
@@ -105,18 +107,18 @@
 def test_termcap(obj):
     for c_name in color_names:
         c_str = getattr(obj, c_name)
-        print c_str + c_name + obj.Normal
+        print(c_str + c_name + obj.Normal)
         for attr_name in capability_names:
             if attr_name == 'Normal':
                 continue
             attr_str = getattr(obj, attr_name)
-            print attr_str + c_str + attr_name + " " + c_name + obj.Normal
-        print obj.Bold + obj.Underline + \
-              c_name + "Bold Underline " + c + obj.Normal
+            print(attr_str + c_str + attr_name + " " + c_name + obj.Normal)
+        print(obj.Bold + obj.Underline +
+              c_name + "Bold Underline " + c + obj.Normal)

 if __name__ == '__main__':
-    print "=== termcap enabled ==="
+    print("=== termcap enabled ===")
     test_termcap(termcap)
-    print termcap.Normal
-    print "=== termcap disabled ==="
+    print(termcap.Normal)
+    print("=== termcap disabled ===")
     test_termcap(no_termcap)
diff --git a/src/unittest/genini.py b/src/unittest/genini.py
index 19e6442..5a4f345 100755
--- a/src/unittest/genini.py
+++ b/src/unittest/genini.py
@@ -27,6 +27,8 @@
 #
 # Authors: Nathan Binkert

+from __future__ import print_function
+
 import getopt, os, os.path, sys
 from os.path import join as joinpath, realpath

@@ -71,4 +73,4 @@
 if globals().has_key('root') and isinstance(root, Root):
     instantiate(root)
 else:
-    print "Instantiation skipped: no root object found."
+    print("Instantiation skipped: no root object found.")
diff --git a/tests/SConscript b/tests/SConscript
index 3ed3e24..b47315f 100644
--- a/tests/SConscript
+++ b/tests/SConscript
@@ -42,6 +42,8 @@
 #          Kevin Lim
 #          Andreas Sandberg

+from __future__ import print_function
+
 from SCons.Script.SConscript import SConsEnvironment
 import os
 import pickle
@@ -136,7 +138,7 @@
     if formatter:
         formatter.dump_suites([result])

-    print "***** %s: %s" % (source[0].dir, status)
+    print("***** %s: %s" % (source[0].dir, status))
     return 0

 printAction = env.Action(print_test, strfunction=None)
@@ -163,19 +165,19 @@
     result = result[0]

     if result.skipped():
-        print "*** %s: %s: Test skipped, not updating." % (
-            source[0].dir, color_message(termcap.Yellow, "WARNING"), )
+        print("*** %s: %s: Test skipped, not updating." %
+              (source[0].dir, color_message(termcap.Yellow, "WARNING")))
         return 0
     elif result:
-        print "*** %s: %s: Test successful, not updating." % (
-            source[0].dir, color_message(termcap.Green, "skipped"), )
+        print("*** %s: %s: Test successful, not updating." %
+              (source[0].dir, color_message(termcap.Green, "skipped")))
         return 0
     elif result.failed_run():
-        print "*** %s: %s: Test failed, not updating." % (
-            source[0].dir, color_message(termcap.Red, "ERROR"), )
+        print("*** %s: %s: Test failed, not updating." %
+              (source[0].dir, color_message(termcap.Red, "ERROR")))
         return 1

-    print "** Updating %s" % (test, )
+    print("** Updating %s" % test)
     test.update_ref()

     return 0
@@ -236,7 +238,7 @@
     with open(target[0].abspath, "w") as fout:
         for cat in categories:
             for test in env.Tests[cat]:
-                print >> fout,"/".join(test)
+                print("/".join(test), file=fout)

     return 0


--
To view, visit https://gem5-review.googlesource.com/8761
To unsubscribe, or for help writing mail filters, visit https://gem5-review.googlesource.com/settings

Gerrit-Project: public/gem5
Gerrit-Branch: master
Gerrit-Change-Id: I2de7dc3b1be756baad6f60574c47c8b7e80ea3b0
Gerrit-Change-Number: 8761
Gerrit-PatchSet: 2
Gerrit-Owner: Gabe Black <gabebl...@google.com>
Gerrit-Reviewer: Andreas Sandberg <andreas.sandb...@arm.com>
Gerrit-Reviewer: Anthony Gutierrez <anthony.gutier...@amd.com>
Gerrit-Reviewer: Brandon Potter <brandon.pot...@amd.com>
Gerrit-Reviewer: Gabe Black <gabebl...@google.com>
Gerrit-Reviewer: Jason Lowe-Power <ja...@lowepower.com>
Gerrit-Reviewer: Siddhesh Poyarekar <siddhesh.poyare...@gmail.com>
Gerrit-MessageType: merged
_______________________________________________
gem5-dev mailing list
gem5-dev@gem5.org
http://m5sim.org/mailman/listinfo/gem5-dev

Reply via email to