zturner created this revision.
zturner added a reviewer: tfiala.
zturner added a subscriber: lldb-commits.

    This patch was generating by running `2to3` on the files in the
    lldb/test directory.  This patch should be NFC, but it does
    introduce the `from __future__ import print_function` line, which
    will break future uses of the print statement.

    This patch does not address every python 2 / python 3
    incompatibility.  Some are more mechanical than others, so I
    plan to do this in stages.  The first pass fixes only print statements.
    Other incompatibilities will addressed in followup patches.
    

http://reviews.llvm.org/D13879

Files:
  test/dosep.py
  test/dotest.py
  test/lldbtest.py

Index: test/lldbtest.py
===================================================================
--- test/lldbtest.py
+++ test/lldbtest.py
@@ -31,6 +31,8 @@
 $ 
 """
 
+from __future__ import print_function
+
 import abc
 import gc
 import glob
@@ -247,9 +249,9 @@
         recordings to our session object.  And close the StringIO object, too.
         """
         if self.trace:
-            print >> sys.stderr, self.getvalue()
+            print(self.getvalue(), file=sys.stderr)
         if self.session:
-            print >> self.session, self.getvalue()
+            print(self.getvalue(), file=self.session)
         self.close()
 
 class _BaseProcess(object):
@@ -390,13 +392,13 @@
             trace = True
 
         with recording(test, trace) as sbuf:
-            print >> sbuf
-            print >> sbuf, "os command:", shellCommand
-            print >> sbuf, "with pid:", pid
-            print >> sbuf, "stdout:", this_output
-            print >> sbuf, "stderr:", this_error
-            print >> sbuf, "retcode:", retcode
-            print >> sbuf
+            print(file=sbuf)
+            print("os command:", shellCommand, file=sbuf)
+            print("with pid:", pid, file=sbuf)
+            print("stdout:", this_output, file=sbuf)
+            print("stderr:", this_error, file=sbuf)
+            print("retcode:", retcode, file=sbuf)
+            print(file=sbuf)
 
         if retcode:
             cmd = kwargs.get("args")
@@ -1235,7 +1237,7 @@
         if ("LLDB_TEST" in os.environ):
             full_dir = os.path.join(os.environ["LLDB_TEST"], cls.mydir)
             if traceAlways:
-                print >> sys.stderr, "Change dir to:", full_dir
+                print("Change dir to:", full_dir, file=sys.stderr)
             os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
 
         if debug_confirm_directory_exclusivity:
@@ -1251,7 +1253,7 @@
                 cls.dir_lock.acquire()
                 # read the previous owner from the lock file
                 lock_id = cls.dir_lock.handle.read()
-                print >> sys.stderr, "LOCK ERROR: {} wants to lock '{}' but it is already locked by '{}'".format(cls.__name__, full_dir, lock_id)
+                print("LOCK ERROR: {} wants to lock '{}' but it is already locked by '{}'".format(cls.__name__, full_dir, lock_id), file=sys.stderr)
                 raise ioerror
 
         # Set platform context.
@@ -1277,7 +1279,7 @@
             # Subclass might have specific cleanup function defined.
             if getattr(cls, "classCleanup", None):
                 if traceAlways:
-                    print >> sys.stderr, "Call class-specific cleanup function for class:", cls
+                    print("Call class-specific cleanup function for class:", cls, file=sys.stderr)
                 try:
                     cls.classCleanup()
                 except:
@@ -1290,7 +1292,7 @@
 
         # Restore old working directory.
         if traceAlways:
-            print >> sys.stderr, "Restore dir to:", cls.oldcwd
+            print("Restore dir to:", cls.oldcwd, file=sys.stderr)
         os.chdir(cls.oldcwd)
 
     @classmethod
@@ -1626,7 +1628,7 @@
         """
         if callable(hook):
             with recording(self, traceAlways) as sbuf:
-                print >> sbuf, "Adding tearDown hook:", getsource_if_available(hook)
+                print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf)
             self.hooks.append(hook)
         
         return self
@@ -1637,7 +1639,7 @@
         if self.child and self.child.isalive():
             import pexpect
             with recording(self, traceAlways) as sbuf:
-                print >> sbuf, "tearing down the child process...."
+                print("tearing down the child process....", file=sbuf)
             try:
                 if self.child_in_script_interpreter:
                     self.child.sendline('quit()')
@@ -1669,7 +1671,7 @@
         # Check and run any hook functions.
         for hook in reversed(self.hooks):
             with recording(self, traceAlways) as sbuf:
-                print >> sbuf, "Executing tearDown hook:", getsource_if_available(hook)
+                print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf)
             import inspect
             hook_argc = len(inspect.getargspec(hook).args)
             if hook_argc == 0 or getattr(hook,'im_self',None):
@@ -1703,7 +1705,7 @@
         with recording(self, False) as sbuf:
             # False because there's no need to write "ERROR" to the stderr twice.
             # Once by the Python unittest framework, and a second time by us.
-            print >> sbuf, "ERROR"
+            print("ERROR", file=sbuf)
 
     def markCleanupError(self):
         """Callback invoked when an error occurs while a test is cleaning up."""
@@ -1711,7 +1713,7 @@
         with recording(self, False) as sbuf:
             # False because there's no need to write "CLEANUP_ERROR" to the stderr twice.
             # Once by the Python unittest framework, and a second time by us.
-            print >> sbuf, "CLEANUP_ERROR"
+            print("CLEANUP_ERROR", file=sbuf)
 
     def markFailure(self):
         """Callback invoked when a failure (test assertion failure) occurred."""
@@ -1719,7 +1721,7 @@
         with recording(self, False) as sbuf:
             # False because there's no need to write "FAIL" to the stderr twice.
             # Once by the Python unittest framework, and a second time by us.
-            print >> sbuf, "FAIL"
+            print("FAIL", file=sbuf)
 
     def markExpectedFailure(self,err,bugnumber):
         """Callback invoked when an expected failure/error occurred."""
@@ -1729,9 +1731,9 @@
             # stderr twice.
             # Once by the Python unittest framework, and a second time by us.
             if bugnumber == None:
-                print >> sbuf, "expected failure"
+                print("expected failure", file=sbuf)
             else:
-                print >> sbuf, "expected failure (problem id:" + str(bugnumber) + ")"
+                print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf)
 
     def markSkippedTest(self):
         """Callback invoked when a test is skipped."""
@@ -1740,7 +1742,7 @@
             # False because there's no need to write "skipped test" to the
             # stderr twice.
             # Once by the Python unittest framework, and a second time by us.
-            print >> sbuf, "skipped test"
+            print("skipped test", file=sbuf)
 
     def markUnexpectedSuccess(self, bugnumber):
         """Callback invoked when an unexpected success occurred."""
@@ -1750,9 +1752,9 @@
             # stderr twice.
             # Once by the Python unittest framework, and a second time by us.
             if bugnumber == None:
-                print >> sbuf, "unexpected success"
+                print("unexpected success", file=sbuf)
             else:
-                print >> sbuf, "unexpected success (problem id:" + str(bugnumber) + ")"
+                print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf)
 
     def getRerunArgs(self):
         return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
@@ -1830,7 +1832,7 @@
         if not self.__unexpected__ and not self.__skipped__:
             for test, traceback in pairs:
                 if test is self:
-                    print >> self.session, traceback
+                    print(traceback, file=self.session)
 
         # put footer (timestamp/rerun instructions) into session
         testMethod = getattr(self, self._testMethodName)
@@ -1840,11 +1842,11 @@
             benchmarks = False
 
         import datetime
-        print >> self.session, "Session info generated @", datetime.datetime.now().ctime()
-        print >> self.session, "To rerun this test, issue the following command from the 'test' directory:\n"
-        print >> self.session, "./dotest.py %s -v %s %s" % (self.getRunOptions(),
+        print("Session info generated @", datetime.datetime.now().ctime(), file=self.session)
+        print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session)
+        print("./dotest.py %s -v %s %s" % (self.getRunOptions(),
                                                  ('+b' if benchmarks else '-t'),
-                                                 self.getRerunArgs())
+                                                 self.getRerunArgs()), file=self.session)
         self.session.close()
         del self.session
 
@@ -2072,7 +2074,7 @@
                  'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
                  'LD_EXTRAS' : "-L%s -lliblldb" % self.implib_dir}
         if self.TraceOn():
-            print "Building LLDB Driver (%s) from sources %s" % (exe_name, sources)
+            print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources))
 
         self.buildDefault(dictionary=d)
 
@@ -2100,7 +2102,7 @@
                  'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
                  'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.implib_dir}
         if self.TraceOn():
-            print "Building LLDB Library (%s) from sources %s" % (lib_name, sources)
+            print("Building LLDB Library (%s) from sources %s" % (lib_name, sources))
 
         self.buildDefault(dictionary=d)
     
@@ -2423,7 +2425,7 @@
                 return target
             self.dbg.CreateTarget = DecoratedCreateTarget
             if self.TraceOn():
-                print "self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget)
+                print("self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget))
 
         # We want our debugger to be synchronous.
         self.dbg.SetAsync(False)
@@ -2462,7 +2464,7 @@
                     lldb.remote_platform.Run(shell_cmd)
                 self.addTearDownHook(clean_working_directory)
             else:
-                print "error: making remote directory '%s': %s" % (remote_test_dir, error)
+                print("error: making remote directory '%s': %s" % (remote_test_dir, error))
     
     def registerSharedLibrariesWithTarget(self, target, shlibs):
         '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
@@ -2618,11 +2620,11 @@
                 target = atoms[-1]
                 # Now let's get the absolute pathname of our target.
                 abs_target = os.path.abspath(target)
-                print >> sbuf, "Found a file command, target (with absolute pathname)=%s" % abs_target
+                print("Found a file command, target (with absolute pathname)=%s" % abs_target, file=sbuf)
                 fpath, fname = os.path.split(abs_target)
                 parent_dir = os.path.split(fpath)[0]
                 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
-                print >> sbuf, "Insert this command to be run first: %s" % platform_target_install_command
+                print("Insert this command to be run first: %s" % platform_target_install_command, file=sbuf)
                 self.ci.HandleCommand(platform_target_install_command, self.res)
                 # And this is the file command we want to execute, instead.
                 #
@@ -2632,7 +2634,7 @@
                 #
                 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
                 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
-                print >> sbuf, "And this is the replaced file command: %s" % cmd
+                print("And this is the replaced file command: %s" % cmd, file=sbuf)
 
         running = (cmd.startswith("run") or cmd.startswith("process launch"))
 
@@ -2640,14 +2642,14 @@
             self.ci.HandleCommand(cmd, self.res, inHistory)
 
             with recording(self, trace) as sbuf:
-                print >> sbuf, "runCmd:", cmd
+                print("runCmd:", cmd, file=sbuf)
                 if not check:
-                    print >> sbuf, "check of return status not required"
+                    print("check of return status not required", file=sbuf)
                 if self.res.Succeeded():
-                    print >> sbuf, "output:", self.res.GetOutput()
+                    print("output:", self.res.GetOutput(), file=sbuf)
                 else:
-                    print >> sbuf, "runCmd failed!"
-                    print >> sbuf, self.res.GetError()
+                    print("runCmd failed!", file=sbuf)
+                    print(self.res.GetError(), file=sbuf)
 
             if self.res.Succeeded():
                 break
@@ -2655,7 +2657,7 @@
                 # For process launch, wait some time before possible next try.
                 time.sleep(self.timeWaitNextLaunch)
                 with recording(self, trace) as sbuf:
-                    print >> sbuf, "Command '" + cmd + "' failed!"
+                    print("Command '" + cmd + "' failed!", file=sbuf)
 
         if check:
             self.assertTrue(self.res.Succeeded(),
@@ -2684,7 +2686,7 @@
             # No execution required, just compare str against the golden input.
             output = str
             with recording(self, trace) as sbuf:
-                print >> sbuf, "looking at:", output
+                print("looking at:", output, file=sbuf)
 
         # The heading says either "Expecting" or "Not expecting".
         heading = "Expecting" if matching else "Not expecting"
@@ -2694,8 +2696,8 @@
             match_object = re.search(pattern, output)
             matched = bool(match_object)
             with recording(self, trace) as sbuf:
-                print >> sbuf, "%s pattern: %s" % (heading, pattern)
-                print >> sbuf, "Matched" if matched else "Not matched"
+                print("%s pattern: %s" % (heading, pattern), file=sbuf)
+                print("Matched" if matched else "Not matched", file=sbuf)
             if matched:
                 break
 
@@ -2749,7 +2751,7 @@
             else:
                 output = str
             with recording(self, trace) as sbuf:
-                print >> sbuf, "looking at:", output
+                print("looking at:", output, file=sbuf)
 
         # The heading says either "Expecting" or "Not expecting".
         heading = "Expecting" if matching else "Not expecting"
@@ -2760,16 +2762,16 @@
 
         if startstr:
             with recording(self, trace) as sbuf:
-                print >> sbuf, "%s start string: %s" % (heading, startstr)
-                print >> sbuf, "Matched" if matched else "Not matched"
+                print("%s start string: %s" % (heading, startstr), file=sbuf)
+                print("Matched" if matched else "Not matched", file=sbuf)
 
         # Look for endstr, if specified.
         keepgoing = matched if matching else not matched
         if endstr:
             matched = output.endswith(endstr)
             with recording(self, trace) as sbuf:
-                print >> sbuf, "%s end string: %s" % (heading, endstr)
-                print >> sbuf, "Matched" if matched else "Not matched"
+                print("%s end string: %s" % (heading, endstr), file=sbuf)
+                print("Matched" if matched else "Not matched", file=sbuf)
 
         # Look for sub strings, if specified.
         keepgoing = matched if matching else not matched
@@ -2777,8 +2779,8 @@
             for str in substrs:
                 matched = output.find(str) != -1
                 with recording(self, trace) as sbuf:
-                    print >> sbuf, "%s sub string: %s" % (heading, str)
-                    print >> sbuf, "Matched" if matched else "Not matched"
+                    print("%s sub string: %s" % (heading, str), file=sbuf)
+                    print("Matched" if matched else "Not matched", file=sbuf)
                 keepgoing = matched if matching else not matched
                 if not keepgoing:
                     break
@@ -2790,8 +2792,8 @@
                 # Match Objects always have a boolean value of True.
                 matched = bool(re.search(pattern, output))
                 with recording(self, trace) as sbuf:
-                    print >> sbuf, "%s pattern: %s" % (heading, pattern)
-                    print >> sbuf, "Matched" if matched else "Not matched"
+                    print("%s pattern: %s" % (heading, pattern), file=sbuf)
+                    print("Matched" if matched else "Not matched", file=sbuf)
                 keepgoing = matched if matching else not matched
                 if not keepgoing:
                     break
@@ -2809,7 +2811,7 @@
                         name + "is a method name of object: " + str(obj))
         result = method()
         with recording(self, trace) as sbuf:
-            print >> sbuf, str(method) + ":",  result
+            print(str(method) + ":",  result, file=sbuf)
         return result
 
     def build(self, architecture=None, compiler=None, dictionary=None, clean=True):
@@ -2869,7 +2871,7 @@
         if not traceAlways:
             return
 
-        print child
+        print(child)
 
     @classmethod
     def RemoveTempFile(cls, file):
Index: test/dotest.py
===================================================================
--- test/dotest.py
+++ test/dotest.py
@@ -20,6 +20,8 @@
 for available options.
 """
 
+from __future__ import print_function
+
 import atexit
 import commands
 import importlib
@@ -271,7 +273,7 @@
 def usage(parser):
     parser.print_help()
     if verbose > 0:
-        print """
+        print("""
 Examples:
 
 This is an example of using the -f option to pinpoint to a specific test class
@@ -379,7 +381,7 @@
   'process.gdb-remote' subsystem with a default option of 'packets' if
   GDB_REMOTE_LOG_OPTION is not defined.
 
-"""
+""")
     sys.exit(0)
 
 
@@ -405,9 +407,9 @@
         if category not in validCategories:
             category = unique_string_match(category, validCategories)
         if (category not in validCategories) or category == None:
-            print "fatal error: category '" + origCategory + "' is not a valid category"
-            print "if you have added a new category, please edit dotest.py, adding your new category to validCategories"
-            print "else, please specify one or more of the following: " + str(validCategories.keys())
+            print("fatal error: category '" + origCategory + "' is not a valid category")
+            print("if you have added a new category, please edit dotest.py, adding your new category to validCategories")
+            print("else, please specify one or more of the following: " + str(validCategories.keys()))
             sys.exit(1)
         result.append(category)
     return result
@@ -546,7 +548,7 @@
 
     # only print the args if being verbose (and parsable is off)
     if args.v and not args.q:
-        print sys.argv
+        print(sys.argv)
 
     if args.h:
         do_help = True
@@ -614,7 +616,7 @@
 
     if args.plus_a:
         if dont_do_python_api_test:
-            print "Warning: -a and +a can't both be specified! Using only -a"
+            print("Warning: -a and +a can't both be specified! Using only -a")
         else:
             just_do_python_api_test = True
 
@@ -626,7 +628,7 @@
             usage(parser)
         blacklistFile = args.b
         if not os.path.isfile(blacklistFile):
-            print 'Blacklist file:', blacklistFile, 'does not exist!'
+            print('Blacklist file:', blacklistFile, 'does not exist!')
             usage(parser)
         # Now read the blacklist contents and assign it to blacklist.
         execfile(blacklistFile, globals(), blacklistConfig)
@@ -637,7 +639,7 @@
             usage(parser)
         configFile = args.c
         if not os.path.isfile(configFile):
-            print 'Config file:', configFile, 'does not exist!'
+            print('Config file:', configFile, 'does not exist!')
             usage(parser)
 
     if args.d:
@@ -688,7 +690,7 @@
 
     if args.plus_m:
         if dont_do_lldbmi_test:
-            print "Warning: -m and +m can't both be specified! Using only -m"
+            print("Warning: -m and +m can't both be specified! Using only -m")
         else:
             just_do_lldbmi_test = True
 
@@ -723,7 +725,7 @@
         rdir = os.path.abspath(args.R)
         if os.path.exists(rdir):
             import shutil
-            print 'Removing tree:', rdir
+            print('Removing tree:', rdir)
             shutil.rmtree(rdir)
 
     if args.r:
@@ -731,7 +733,7 @@
             usage(parser)
         rdir = os.path.abspath(args.r)
         if os.path.exists(rdir):
-            print 'Relocated directory:', rdir, 'must not exist!'
+            print('Relocated directory:', rdir, 'must not exist!')
             usage(parser)
 
     if args.S:
@@ -917,12 +919,12 @@
         if "pre_flight" in config:
             pre_flight = config["pre_flight"]
             if not callable(pre_flight):
-                print "fatal error: pre_flight is not callable, exiting."
+                print("fatal error: pre_flight is not callable, exiting.")
                 sys.exit(1)
         if "post_flight" in config:
             post_flight = config["post_flight"]
             if not callable(post_flight):
-                print "fatal error: post_flight is not callable, exiting."
+                print("fatal error: post_flight is not callable, exiting.")
                 sys.exit(1)
         if "lldbtest_remote_sandbox" in config:
             lldbtest_remote_sandbox = config["lldbtest_remote_sandbox"]
@@ -1090,7 +1092,7 @@
     else:
         scriptPath = os.path.dirname(os.path.realpath(__file__))
     if not scriptPath.endswith('test'):
-        print "This script expects to reside in lldb's test directory."
+        print("This script expects to reside in lldb's test directory.")
         sys.exit(-1)
 
     if rdir:
@@ -1156,11 +1158,11 @@
         lldbtest_config.lldbExec = which('lldb')
 
     if lldbtest_config.lldbExec and not is_exe(lldbtest_config.lldbExec):
-        print "'{}' is not a path to a valid executable".format(lldbtest_config.lldbExec)
+        print("'{}' is not a path to a valid executable".format(lldbtest_config.lldbExec))
         lldbtest_config.lldbExec = None
 
     if not lldbtest_config.lldbExec:
-        print "The 'lldb' executable cannot be located.  Some of the tests may not be run as a result."
+        print("The 'lldb' executable cannot be located.  Some of the tests may not be run as a result.")
         sys.exit(-1)
 
     lldbLibDir = os.path.dirname(lldbtest_config.lldbExec)  # confusingly, this is the "bin" directory
@@ -1168,8 +1170,8 @@
     lldbImpLibDir = os.path.join(lldbLibDir, '..', 'lib') if sys.platform.startswith('win32') else lldbLibDir
     os.environ["LLDB_IMPLIB_DIR"] = lldbImpLibDir
     if not noHeaders:
-        print "LLDB library dir:", os.environ["LLDB_LIB_DIR"]
-        print "LLDB import library dir:", os.environ["LLDB_IMPLIB_DIR"]
+        print("LLDB library dir:", os.environ["LLDB_LIB_DIR"])
+        print("LLDB import library dir:", os.environ["LLDB_IMPLIB_DIR"])
         os.system('%s -v' % lldbtest_config.lldbExec)
 
     # Assume lldb-mi is in same place as lldb
@@ -1180,9 +1182,9 @@
     if not lldbMiExec:
         dont_do_lldbmi_test = True
         if just_do_lldbmi_test:
-            print "The 'lldb-mi' executable cannot be located.  The lldb-mi tests can not be run as a result."
+            print("The 'lldb-mi' executable cannot be located.  The lldb-mi tests can not be run as a result.")
         else:
-            print "The 'lldb-mi' executable cannot be located.  Some of the tests may not be run as a result."
+            print("The 'lldb-mi' executable cannot be located.  Some of the tests may not be run as a result.")
     else:
         os.environ["LLDBMI_EXEC"] = lldbMiExec
 
@@ -1195,7 +1197,7 @@
             pipe = subprocess.Popen([which("git"), "svn", "info", lldbRootDirectory], stdout = subprocess.PIPE)
             svn_info = pipe.stdout.read()
         if not noHeaders:
-            print svn_info
+            print(svn_info)
 
     global ignore
 
@@ -1205,7 +1207,7 @@
         if os.path.isfile(os.path.join(candidatePath, 'lldb/__init__.py')):
             lldbPythonDir = candidatePath
         if not lldbPythonDir:
-            print 'Resources/Python/lldb/__init__.py was not found in ' + lldbFrameworkPath
+            print('Resources/Python/lldb/__init__.py was not found in ' + lldbFrameworkPath)
             sys.exit(-1)
     else:
         # The '-i' option is used to skip looking for lldb.py in the build tree.
@@ -1251,19 +1253,19 @@
                         break
 
                 if not lldbPythonDir:
-                    print 'This script requires lldb.py to be in either ' + dbgPath + ',',
-                    print relPath + ', or ' + baiPath + '. Some tests might fail.'
+                    print('This script requires lldb.py to be in either ' + dbgPath + ',', end=' ')
+                    print(relPath + ', or ' + baiPath + '. Some tests might fail.')
             else:
-                print "Unable to load lldb extension module.  Possible reasons for this include:"
-                print "  1) LLDB was built with LLDB_DISABLE_PYTHON=1"
-                print "  2) PYTHONPATH and PYTHONHOME are not set correctly.  PYTHONHOME should refer to"
-                print "     the version of Python that LLDB built and linked against, and PYTHONPATH"
-                print "     should contain the Lib directory for the same python distro, as well as the"
-                print "     location of LLDB\'s site-packages folder."
-                print "  3) A different version of Python than that which was built against is exported in"
-                print "     the system\'s PATH environment variable, causing conflicts."
-                print "  4) The executable '%s' could not be found.  Please check " % lldbExecutable
-                print "     that it exists and is executable."
+                print("Unable to load lldb extension module.  Possible reasons for this include:")
+                print("  1) LLDB was built with LLDB_DISABLE_PYTHON=1")
+                print("  2) PYTHONPATH and PYTHONHOME are not set correctly.  PYTHONHOME should refer to")
+                print("     the version of Python that LLDB built and linked against, and PYTHONPATH")
+                print("     should contain the Lib directory for the same python distro, as well as the")
+                print("     location of LLDB\'s site-packages folder.")
+                print("  3) A different version of Python than that which was built against is exported in")
+                print("     the system\'s PATH environment variable, causing conflicts.")
+                print("  4) The executable '%s' could not be found.  Please check " % lldbExecutable)
+                print("     that it exists and is executable.")
 
     if lldbPythonDir:
         lldbPythonDir = os.path.normpath(lldbPythonDir)
@@ -1281,7 +1283,7 @@
         # This is to locate the lldb.py module.  Insert it right after sys.path[0].
         sys.path[1:1] = [lldbPythonDir]
         if dumpSysPath:
-            print "sys.path:", sys.path
+            print("sys.path:", sys.path)
 
 def visit(prefix, dir, names):
     """Visitor function for os.path.walk(path, visit, arg)."""
@@ -1427,10 +1429,10 @@
     pipe = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
     cmd_output = pipe.stdout.read()
     if cmd_output and "DBGFileMappedPaths = " in cmd_output:
-        print "%s =>" % ' '.join(cmd)
-        print cmd_output
-        print "Disable automatic lookup and caching of dSYMs before running the test suite!"
-        print "Exiting..."
+        print("%s =>" % ' '.join(cmd))
+        print(cmd_output)
+        print("Disable automatic lookup and caching of dSYMs before running the test suite!")
+        print("Exiting...")
         sys.exit(0)
 
 def exitTestSuite(exitCode = None):
@@ -1490,27 +1492,27 @@
     lldb.DBG = lldb.SBDebugger.Create()
 
     if lldb_platform_name:
-        print "Setting up remote platform '%s'" % (lldb_platform_name)
+        print("Setting up remote platform '%s'" % (lldb_platform_name))
         lldb.remote_platform = lldb.SBPlatform(lldb_platform_name)
         if not lldb.remote_platform.IsValid():
-            print "error: unable to create the LLDB platform named '%s'." % (lldb_platform_name)
+            print("error: unable to create the LLDB platform named '%s'." % (lldb_platform_name))
             exitTestSuite(1)
         if lldb_platform_url:
             # We must connect to a remote platform if a LLDB platform URL was specified
-            print "Connecting to remote platform '%s' at '%s'..." % (lldb_platform_name, lldb_platform_url)
+            print("Connecting to remote platform '%s' at '%s'..." % (lldb_platform_name, lldb_platform_url))
             lldb.platform_url = lldb_platform_url
             platform_connect_options = lldb.SBPlatformConnectOptions(lldb_platform_url)
             err = lldb.remote_platform.ConnectRemote(platform_connect_options)
             if err.Success():
-                print "Connected."
+                print("Connected.")
             else:
-                print "error: failed to connect to remote platform using URL '%s': %s" % (lldb_platform_url, err)
+                print("error: failed to connect to remote platform using URL '%s': %s" % (lldb_platform_url, err))
                 exitTestSuite(1)
         else:
             lldb.platform_url = None
 
         if lldb_platform_working_dir:
-            print "Setting remote platform working directory to '%s'..." % (lldb_platform_working_dir)
+            print("Setting remote platform working directory to '%s'..." % (lldb_platform_working_dir))
             lldb.remote_platform.SetWorkingDirectory(lldb_platform_working_dir)
     
         lldb.remote_platform_working_dir = lldb_platform_working_dir
@@ -1563,8 +1565,8 @@
             return repr(obj)
 
     if not noHeaders:
-        print "lldb.pre_flight:", getsource_if_available(lldb.pre_flight)
-        print "lldb.post_flight:", getsource_if_available(lldb.post_flight)
+        print("lldb.pre_flight:", getsource_if_available(lldb.pre_flight))
+        print("lldb.post_flight:", getsource_if_available(lldb.post_flight))
 
     # If either pre_flight or post_flight is defined, set lldb.test_remote to True.
     if lldb.pre_flight or lldb.post_flight:
@@ -1636,9 +1638,9 @@
     where_to_save_session = os.getcwd()
     fname = os.path.join(sdir_name, "TestStarted-%d" % os.getpid())
     with open(fname, "w") as f:
-        print >> f, "Test started at: %s\n" % timestamp_started
-        print >> f, svn_info
-        print >> f, "Command invoked: %s\n" % getMyCommandLine()
+        print("Test started at: %s\n" % timestamp_started, file=f)
+        print(svn_info, file=f)
+        print("Command invoked: %s\n" % getMyCommandLine(), file=f)
 
     #
     # Invoke the default TextTestRunner to run the test suite, possibly iterating
@@ -1670,17 +1672,17 @@
                 cmd_output = pipe.stdout.read()
                 if cmd_output:
                     if "not found" in cmd_output:
-                        print "dropping %s from the compilers used" % c
+                        print("dropping %s from the compilers used" % c)
                         compilers.remove(i)
                     else:
                         compilers[i] = cmd_output.split('\n')[0]
-                        print "'xcrun -find %s' returning %s" % (c, compilers[i])
+                        print("'xcrun -find %s' returning %s" % (c, compilers[i]))
 
     if not parsable:
-        print "compilers=%s" % str(compilers)
+        print("compilers=%s" % str(compilers))
 
     if not compilers or len(compilers) == 0:
-        print "No eligible compiler found, exiting."
+        print("No eligible compiler found, exiting.")
         exitTestSuite(1)
 
     if isinstance(compilers, list) and len(compilers) >= 1:
@@ -2054,12 +2056,12 @@
     os.chdir(where_to_save_session)
     fname = os.path.join(sdir_name, "TestFinished-%d" % os.getpid())
     with open(fname, "w") as f:
-        print >> f, "Test finished at: %s\n" % datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
+        print("Test finished at: %s\n" % datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S"), file=f)
 
     # Terminate the test suite if ${LLDB_TESTSUITE_FORCE_FINISH} is defined.
     # This should not be necessary now.
     if ("LLDB_TESTSUITE_FORCE_FINISH" in os.environ):
-        print "Terminating Test suite..."
+        print("Terminating Test suite...")
         subprocess.Popen(["/bin/sh", "-c", "kill %s; exit 0" % (os.getpid())])
 
     # Exiting.
Index: test/dosep.py
===================================================================
--- test/dosep.py
+++ test/dosep.py
@@ -32,6 +32,8 @@
 echo core.%p | sudo tee /proc/sys/kernel/core_pattern
 """
 
+from __future__ import print_function
+
 # system packages and modules
 import asyncore
 import distutils.version
@@ -104,10 +106,10 @@
     global output_lock
     with output_lock:
         if not (RESULTS_FORMATTER and RESULTS_FORMATTER.is_using_terminal()):
-            print >> sys.stderr
-            print >> sys.stderr, output
-            print >> sys.stderr, "[%s FAILED]" % name
-            print >> sys.stderr, "Command invoked: %s" % ' '.join(command)
+            print(file=sys.stderr)
+            print(output, file=sys.stderr)
+            print("[%s FAILED]" % name, file=sys.stderr)
+            print("Command invoked: %s" % ' '.join(command), file=sys.stderr)
         update_progress(name)
 
 
@@ -116,9 +118,9 @@
     with output_lock:
         if not (RESULTS_FORMATTER and RESULTS_FORMATTER.is_using_terminal()):
             if output_on_success:
-                print >> sys.stderr
-                print >> sys.stderr, output
-                print >> sys.stderr, "[%s PASSED]" % name
+                print(file=sys.stderr)
+                print(output, file=sys.stderr)
+                print("[%s PASSED]" % name, file=sys.stderr)
         update_progress(name)
 
 
@@ -414,7 +416,7 @@
     active_pid_set = collect_active_pids_from_pid_events(
         inferior_pid_events)
     for inferior_pid in active_pid_set:
-        print "killing inferior pid {}".format(inferior_pid)
+        print("killing inferior pid {}".format(inferior_pid))
         os.kill(inferior_pid, signal.SIGKILL)
 
 
@@ -432,7 +434,7 @@
     active_pid_set = collect_active_pids_from_pid_events(
         inferior_pid_events)
     for inferior_pid in active_pid_set:
-        print "killing inferior pid {}".format(inferior_pid)
+        print("killing inferior pid {}".format(inferior_pid))
         os.kill(inferior_pid, signal.SIGKILL)
 
     # We don't have a way to nuke the threads.  However, since we killed
@@ -485,8 +487,8 @@
     test_counter = multiprocessing.Value('i', 0)
     test_name_len = multiprocessing.Value('i', 0)
     if not (RESULTS_FORMATTER and RESULTS_FORMATTER.is_using_terminal()):
-        print >> sys.stderr, "Testing: %d test suites, %d thread%s" % (
-            total_tests, num_threads, (num_threads > 1) * "s")
+        print("Testing: %d test suites, %d thread%s" % (
+            total_tests, num_threads, (num_threads > 1) * "s"), file=sys.stderr)
     update_progress()
 
 
@@ -630,7 +632,7 @@
         name_index = len(key_name) - 1
     message = "\nHandling {} KeyboardInterrupt".format(key_name[name_index])
     with output_lock:
-        print message
+        print(message)
 
     if ctrl_c_count == 1:
         # Remove all outstanding items from the work queue so we stop
@@ -642,13 +644,13 @@
             except Queue.Empty:
                 pass
         with output_lock:
-            print "Stopped more work from being started."
+            print("Stopped more work from being started.")
     elif ctrl_c_count == 2:
         # Try to stop all inferiors, even the ones currently doing work.
         stop_all_inferiors_func(workers, inferior_pid_events)
     else:
         with output_lock:
-            print "All teardown activities kicked off, should finish soon."
+            print("All teardown activities kicked off, should finish soon.")
 
 
 def workers_and_async_done(workers, async_map):
@@ -1392,33 +1394,33 @@
             test_name = os.path.splitext(xtime)[0]
             touch(os.path.join(session_dir, "{}-{}".format(result, test_name)))
 
-    print
+    print()
     sys.stdout.write("Ran %d test suites" % num_test_files)
     if num_test_files > 0:
         sys.stdout.write(" (%d failed) (%f%%)" % (
             len(failed), 100.0 * len(failed) / num_test_files))
-    print
+    print()
     sys.stdout.write("Ran %d test cases" % num_test_cases)
     if num_test_cases > 0:
         sys.stdout.write(" (%d failed) (%f%%)" % (
             fail_count, 100.0 * fail_count / num_test_cases))
-    print
+    print()
     exit_code = 0
 
     if len(failed) > 0:
         failed.sort()
-        print "Failing Tests (%d)" % len(failed)
+        print("Failing Tests (%d)" % len(failed))
         for f in failed:
-            print "%s: LLDB (suite) :: %s (%s)" % (
+            print("%s: LLDB (suite) :: %s (%s)" % (
                 "TIMEOUT" if f in timed_out else "FAIL", f, system_info
-            )
+            ))
         exit_code = 1
 
     if len(unexpected_successes) > 0:
         unexpected_successes.sort()
-        print "\nUnexpected Successes (%d)" % len(unexpected_successes)
+        print("\nUnexpected Successes (%d)" % len(unexpected_successes))
         for u in unexpected_successes:
-            print "UNEXPECTED SUCCESS: LLDB (suite) :: %s (%s)" % (u, system_info)
+            print("UNEXPECTED SUCCESS: LLDB (suite) :: %s (%s)" % (u, system_info))
 
     sys.exit(exit_code)
 
_______________________________________________
lldb-commits mailing list
lldb-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits

Reply via email to