tools: use print() function on both Python 2 and 3

PR-URL: https://github.com/nodejs/node/pull/24486
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Refael Ackermann <refack@gmail.com>
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
This commit is contained in:
cclauss 2018-11-19 06:09:40 -05:00 committed by Refael Ackermann
parent f2432a4761
commit b507783bc1
7 changed files with 120 additions and 113 deletions

View File

@ -7,13 +7,14 @@
# ustack helper. # ustack helper.
# #
from __future__ import print_function
import re import re
import subprocess import subprocess
import sys import sys
import errno import errno
if len(sys.argv) != 3: if len(sys.argv) != 3:
print "usage: objsym.py outfile libv8_base.a" print("usage: objsym.py outfile libv8_base.a")
sys.exit(2); sys.exit(2);
outfile = file(sys.argv[1], 'w'); outfile = file(sys.argv[1], 'w');
@ -22,13 +23,13 @@ try:
bufsize=-1, stdout=subprocess.PIPE).stdout; bufsize=-1, stdout=subprocess.PIPE).stdout;
except OSError, e: except OSError, e:
if e.errno == errno.ENOENT: if e.errno == errno.ENOENT:
print ''' print('''
Node.js compile error: could not find objdump Node.js compile error: could not find objdump
Check that GNU binutils are installed and included in PATH Check that GNU binutils are installed and included in PATH
''' ''')
else: else:
print 'problem running objdump: ', e.strerror print('problem running objdump: ', e.strerror)
sys.exit() sys.exit()

View File

@ -1,4 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
from __future__ import print_function
import os import os
import sys import sys
@ -52,7 +53,7 @@ def run_gyp(args):
rc = gyp.main(args) rc = gyp.main(args)
if rc != 0: if rc != 0:
print 'Error running GYP' print('Error running GYP')
sys.exit(rc) sys.exit(rc)

View File

@ -11,6 +11,7 @@
# Usage: # Usage:
# Use "-h" to get help options. # Use "-h" to get help options.
from __future__ import print_function
import sys import sys
import shutil import shutil
# for utf-8 # for utf-8
@ -79,54 +80,54 @@ optVars = vars(options)
for opt in [ "datfile", "filterfile", "tmpdir", "outfile" ]: for opt in [ "datfile", "filterfile", "tmpdir", "outfile" ]:
if optVars[opt] is None: if optVars[opt] is None:
print "Missing required option: %s" % opt print("Missing required option: %s" % opt)
sys.exit(1) sys.exit(1)
if options.verbose>0: if options.verbose>0:
print "Options: "+str(options) print("Options: "+str(options))
if (os.path.isdir(options.tmpdir) and options.deltmpdir): if (os.path.isdir(options.tmpdir) and options.deltmpdir):
if options.verbose>1: if options.verbose>1:
print "Deleting tmp dir %s.." % (options.tmpdir) print("Deleting tmp dir %s.." % (options.tmpdir))
shutil.rmtree(options.tmpdir) shutil.rmtree(options.tmpdir)
if not (os.path.isdir(options.tmpdir)): if not (os.path.isdir(options.tmpdir)):
os.mkdir(options.tmpdir) os.mkdir(options.tmpdir)
else: else:
print "Please delete tmpdir %s before beginning." % options.tmpdir print("Please delete tmpdir %s before beginning." % options.tmpdir)
sys.exit(1) sys.exit(1)
if options.endian not in ("big","little","host"): if options.endian not in ("big","little","host"):
print "Unknown endianness: %s" % options.endian print("Unknown endianness: %s" % options.endian)
sys.exit(1) sys.exit(1)
if options.endian is "host": if options.endian is "host":
options.endian = endian options.endian = endian
if not os.path.isdir(options.tmpdir): if not os.path.isdir(options.tmpdir):
print "Error, tmpdir not a directory: %s" % (options.tmpdir) print("Error, tmpdir not a directory: %s" % (options.tmpdir))
sys.exit(1) sys.exit(1)
if not os.path.isfile(options.filterfile): if not os.path.isfile(options.filterfile):
print "Filterfile doesn't exist: %s" % (options.filterfile) print("Filterfile doesn't exist: %s" % (options.filterfile))
sys.exit(1) sys.exit(1)
if not os.path.isfile(options.datfile): if not os.path.isfile(options.datfile):
print "Datfile doesn't exist: %s" % (options.datfile) print("Datfile doesn't exist: %s" % (options.datfile))
sys.exit(1) sys.exit(1)
if not options.datfile.endswith(".dat"): if not options.datfile.endswith(".dat"):
print "Datfile doesn't end with .dat: %s" % (options.datfile) print("Datfile doesn't end with .dat: %s" % (options.datfile))
sys.exit(1) sys.exit(1)
outfile = os.path.join(options.tmpdir, options.outfile) outfile = os.path.join(options.tmpdir, options.outfile)
if os.path.isfile(outfile): if os.path.isfile(outfile):
print "Error, output file does exist: %s" % (outfile) print("Error, output file does exist: %s" % (outfile))
sys.exit(1) sys.exit(1)
if not options.outfile.endswith(".dat"): if not options.outfile.endswith(".dat"):
print "Outfile doesn't end with .dat: %s" % (options.outfile) print("Outfile doesn't end with .dat: %s" % (options.outfile))
sys.exit(1) sys.exit(1)
dataname=options.outfile[0:-4] dataname=options.outfile[0:-4]
@ -140,11 +141,11 @@ def runcmd(tool, cmd, doContinue=False):
cmd = tool + " " + cmd cmd = tool + " " + cmd
if(options.verbose>4): if(options.verbose>4):
print "# " + cmd print("# " + cmd)
rc = os.system(cmd) rc = os.system(cmd)
if rc is not 0 and not doContinue: if rc is not 0 and not doContinue:
print "FAILED: %s" % cmd print("FAILED: %s" % cmd)
sys.exit(1) sys.exit(1)
return rc return rc
@ -161,10 +162,10 @@ if (options.locales):
config["variables"]["locales"]["only"] = options.locales.split(',') config["variables"]["locales"]["only"] = options.locales.split(',')
if (options.verbose > 6): if (options.verbose > 6):
print config print(config)
if(config.has_key("comment")): if(config.has_key("comment")):
print "%s: %s" % (options.filterfile, config["comment"]) print("%s: %s" % (options.filterfile, config["comment"]))
## STEP 1 - copy the data file, swapping endianness ## STEP 1 - copy the data file, swapping endianness
## The first letter of endian_letter will be 'b' or 'l' for big or little ## The first letter of endian_letter will be 'b' or 'l' for big or little
@ -184,7 +185,7 @@ fi.close()
itemset = set(items) itemset = set(items)
if (options.verbose>1): if (options.verbose>1):
print "input file: %d items" % (len(items)) print("input file: %d items" % (len(items)))
# list of all trees # list of all trees
trees = {} trees = {}
@ -211,23 +212,23 @@ def queueForRemoval(tree):
return return
mytree = trees[tree] mytree = trees[tree]
if(options.verbose>0): if(options.verbose>0):
print "* %s: %d items" % (tree, len(mytree["locs"])) print("* %s: %d items" % (tree, len(mytree["locs"])))
# do varible substitution for this tree here # do varible substitution for this tree here
if type(config["trees"][tree]) == str or type(config["trees"][tree]) == unicode: if type(config["trees"][tree]) == str or type(config["trees"][tree]) == unicode:
treeStr = config["trees"][tree] treeStr = config["trees"][tree]
if(options.verbose>5): if(options.verbose>5):
print " Substituting $%s for tree %s" % (treeStr, tree) print(" Substituting $%s for tree %s" % (treeStr, tree))
if(not config.has_key("variables") or not config["variables"].has_key(treeStr)): if(not config.has_key("variables") or not config["variables"].has_key(treeStr)):
print " ERROR: no variable: variables.%s for tree %s" % (treeStr, tree) print(" ERROR: no variable: variables.%s for tree %s" % (treeStr, tree))
sys.exit(1) sys.exit(1)
config["trees"][tree] = config["variables"][treeStr] config["trees"][tree] = config["variables"][treeStr]
myconfig = config["trees"][tree] myconfig = config["trees"][tree]
if(options.verbose>4): if(options.verbose>4):
print " Config: %s" % (myconfig) print(" Config: %s" % (myconfig))
# Process this tree # Process this tree
if(len(myconfig)==0 or len(mytree["locs"])==0): if(len(myconfig)==0 or len(mytree["locs"])==0):
if(options.verbose>2): if(options.verbose>2):
print " No processing for %s - skipping" % (tree) print(" No processing for %s - skipping" % (tree))
else: else:
only = None only = None
if myconfig.has_key("only"): if myconfig.has_key("only"):
@ -236,22 +237,22 @@ def queueForRemoval(tree):
thePool = "%spool.res" % (mytree["treeprefix"]) thePool = "%spool.res" % (mytree["treeprefix"])
if (thePool in itemset): if (thePool in itemset):
if(options.verbose>0): if(options.verbose>0):
print "Removing %s because tree %s is empty." % (thePool, tree) print("Removing %s because tree %s is empty." % (thePool, tree))
remove.add(thePool) remove.add(thePool)
else: else:
print "tree %s - no ONLY" print("tree %s - no ONLY")
for l in range(len(mytree["locs"])): for l in range(len(mytree["locs"])):
loc = mytree["locs"][l] loc = mytree["locs"][l]
if (only is not None) and not loc in only: if (only is not None) and not loc in only:
# REMOVE loc # REMOVE loc
toRemove = "%s%s%s" % (mytree["treeprefix"], loc, mytree["extension"]) toRemove = "%s%s%s" % (mytree["treeprefix"], loc, mytree["extension"])
if(options.verbose>6): if(options.verbose>6):
print "Queueing for removal: %s" % toRemove print("Queueing for removal: %s" % toRemove)
remove.add(toRemove) remove.add(toRemove)
def addTreeByType(tree, mytree): def addTreeByType(tree, mytree):
if(options.verbose>1): if(options.verbose>1):
print "(considering %s): %s" % (tree, mytree) print("(considering %s): %s" % (tree, mytree))
trees[tree] = mytree trees[tree] = mytree
mytree["locs"]=[] mytree["locs"]=[]
for i in range(len(items)): for i in range(len(items)):
@ -278,7 +279,7 @@ for i in range(len(items)):
else: else:
tree = treeprefix[0:-1] tree = treeprefix[0:-1]
if(options.verbose>6): if(options.verbose>6):
print "procesing %s" % (tree) print("procesing %s" % (tree))
trees[tree] = { "extension": ".res", "treeprefix": treeprefix, "hasIndex": True } trees[tree] = { "extension": ".res", "treeprefix": treeprefix, "hasIndex": True }
# read in the resource list for the tree # read in the resource list for the tree
treelistfile = os.path.join(options.tmpdir,"%s.lst" % tree) treelistfile = os.path.join(options.tmpdir,"%s.lst" % tree)
@ -288,7 +289,7 @@ for i in range(len(items)):
trees[tree]["locs"] = [treeitems[i].strip() for i in range(len(treeitems))] trees[tree]["locs"] = [treeitems[i].strip() for i in range(len(treeitems))]
fi.close() fi.close()
if(not config.has_key("trees") or not config["trees"].has_key(tree)): if(not config.has_key("trees") or not config["trees"].has_key(tree)):
print " Warning: filter file %s does not mention trees.%s - will be kept as-is" % (options.filterfile, tree) print(" Warning: filter file %s does not mention trees.%s - will be kept as-is" % (options.filterfile, tree))
else: else:
queueForRemoval(tree) queueForRemoval(tree)
@ -297,22 +298,22 @@ def removeList(count=0):
global remove global remove
remove = remove - keep remove = remove - keep
if(count > 10): if(count > 10):
print "Giving up - %dth attempt at removal." % count print("Giving up - %dth attempt at removal." % count)
sys.exit(1) sys.exit(1)
if(options.verbose>1): if(options.verbose>1):
print "%d items to remove - try #%d" % (len(remove),count) print("%d items to remove - try #%d" % (len(remove),count))
if(len(remove)>0): if(len(remove)>0):
oldcount = len(remove) oldcount = len(remove)
hackerrfile=os.path.join(options.tmpdir, "REMOVE.err") hackerrfile=os.path.join(options.tmpdir, "REMOVE.err")
removefile = os.path.join(options.tmpdir, "REMOVE.lst") removefile = os.path.join(options.tmpdir, "REMOVE.lst")
fi = open(removefile, 'wb') fi = open(removefile, 'wb')
for i in remove: for i in remove:
print >>fi, i print(i, file=fi)
fi.close() fi.close()
rc = runcmd("icupkg","-r %s %s 2> %s" % (removefile,outfile,hackerrfile),True) rc = runcmd("icupkg","-r %s %s 2> %s" % (removefile,outfile,hackerrfile),True)
if rc is not 0: if rc is not 0:
if(options.verbose>5): if(options.verbose>5):
print "## Damage control, trying to parse stderr from icupkg.." print("## Damage control, trying to parse stderr from icupkg..")
fi = open(hackerrfile, 'rb') fi = open(hackerrfile, 'rb')
erritems = fi.readlines() erritems = fi.readlines()
fi.close() fi.close()
@ -324,15 +325,15 @@ def removeList(count=0):
if m: if m:
toDelete = m.group(1) toDelete = m.group(1)
if(options.verbose > 5): if(options.verbose > 5):
print "<< %s added to delete" % toDelete print("<< %s added to delete" % toDelete)
remove.add(toDelete) remove.add(toDelete)
else: else:
print "ERROR: could not match errline: %s" % line print("ERROR: could not match errline: %s" % line)
sys.exit(1) sys.exit(1)
if(options.verbose > 5): if(options.verbose > 5):
print " now %d items to remove" % len(remove) print(" now %d items to remove" % len(remove))
if(oldcount == len(remove)): if(oldcount == len(remove)):
print " ERROR: could not add any mor eitems to remove. Fail." print(" ERROR: could not add any mor eitems to remove. Fail.")
sys.exit(1) sys.exit(1)
removeList(count+1) removeList(count+1)

View File

@ -1,4 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
from __future__ import print_function
import optparse import optparse
import os import os
import re import re
@ -29,11 +30,11 @@ parser.add_option('--icutmp',
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
if os.path.isdir(options.icusmall): if os.path.isdir(options.icusmall):
print 'Deleting existing icusmall %s' % (options.icusmall) print('Deleting existing icusmall %s' % (options.icusmall))
shutil.rmtree(options.icusmall) shutil.rmtree(options.icusmall)
if not os.path.isdir(options.icusrc): if not os.path.isdir(options.icusrc):
print 'Missing source ICU dir --icusrc=%s' % (options.icusrc) print('Missing source ICU dir --icusrc=%s' % (options.icusrc))
sys.exit(1) sys.exit(1)
@ -73,7 +74,7 @@ def icu_ignore(dir, files):
def icu_info(icu_full_path): def icu_info(icu_full_path):
uvernum_h = os.path.join(icu_full_path, 'source/common/unicode/uvernum.h') uvernum_h = os.path.join(icu_full_path, 'source/common/unicode/uvernum.h')
if not os.path.isfile(uvernum_h): if not os.path.isfile(uvernum_h):
print ' Error: could not load %s - is ICU installed?' % uvernum_h print(' Error: could not load %s - is ICU installed?' % uvernum_h)
sys.exit(1) sys.exit(1)
icu_ver_major = None icu_ver_major = None
matchVerExp = r'^\s*#define\s+U_ICU_VERSION_SHORT\s+"([^"]*)".*' matchVerExp = r'^\s*#define\s+U_ICU_VERSION_SHORT\s+"([^"]*)".*'
@ -83,25 +84,25 @@ def icu_info(icu_full_path):
if m: if m:
icu_ver_major = m.group(1) icu_ver_major = m.group(1)
if not icu_ver_major: if not icu_ver_major:
print ' Could not read U_ICU_VERSION_SHORT version from %s' % uvernum_h print(' Could not read U_ICU_VERSION_SHORT version from %s' % uvernum_h)
sys.exit(1) sys.exit(1)
icu_endianness = sys.byteorder[0]; # TODO(srl295): EBCDIC should be 'e' icu_endianness = sys.byteorder[0]; # TODO(srl295): EBCDIC should be 'e'
return (icu_ver_major, icu_endianness) return (icu_ver_major, icu_endianness)
(icu_ver_major, icu_endianness) = icu_info(options.icusrc) (icu_ver_major, icu_endianness) = icu_info(options.icusrc)
print "icudt%s%s" % (icu_ver_major, icu_endianness) print("icudt%s%s" % (icu_ver_major, icu_endianness))
src_datafile = os.path.join(options.icutmp, "icusmdt%s.dat" % (icu_ver_major)) src_datafile = os.path.join(options.icutmp, "icusmdt%s.dat" % (icu_ver_major))
dst_datafile = os.path.join(options.icusmall, "source","data","in", "icudt%s%s.dat" % (icu_ver_major, icu_endianness)) dst_datafile = os.path.join(options.icusmall, "source","data","in", "icudt%s%s.dat" % (icu_ver_major, icu_endianness))
if not os.path.isfile(src_datafile): if not os.path.isfile(src_datafile):
print "Could not find source datafile %s - did you build small-icu node?" % src_datafile print("Could not find source datafile %s - did you build small-icu node?" % src_datafile)
sys.exit(1) sys.exit(1)
else: else:
print "will use small datafile %s" % (src_datafile) print("will use small datafile %s" % (src_datafile))
print '%s --> %s' % (options.icusrc, options.icusmall) print('%s --> %s' % (options.icusrc, options.icusmall))
shutil.copytree(options.icusrc, options.icusmall, ignore=icu_ignore) shutil.copytree(options.icusrc, options.icusmall, ignore=icu_ignore)
print '%s --> %s' % (src_datafile, dst_datafile) print('%s --> %s' % (src_datafile, dst_datafile))
# now, make the data dir (since we ignored it) # now, make the data dir (since we ignored it)
os.mkdir(os.path.join(os.path.join(options.icusmall, "source", "data"))) os.mkdir(os.path.join(os.path.join(options.icusmall, "source", "data")))
@ -114,13 +115,13 @@ shutil.copy(src_datafile, dst_datafile)
readme_name = os.path.join(options.icusmall, "README-SMALL-ICU.txt" ) readme_name = os.path.join(options.icusmall, "README-SMALL-ICU.txt" )
fi = open(readme_name, 'wb') fi = open(readme_name, 'wb')
print >>fi, "Small ICU sources - auto generated by shrink-icu-src.py" print("Small ICU sources - auto generated by shrink-icu-src.py", file=fi)
print >>fi, "" print("", file=fi)
print >>fi, "This directory contains the ICU subset used by --with-intl=small-icu (the default)" print("This directory contains the ICU subset used by --with-intl=small-icu (the default)", file=fi)
print >>fi, "It is a strict subset of ICU %s source files with the following exception(s):" % (icu_ver_major) print("It is a strict subset of ICU %s source files with the following exception(s):" % (icu_ver_major), file=fi)
print >>fi, "* %s : Reduced-size data file" % (dst_datafile) print("* %s : Reduced-size data file" % (dst_datafile), file=fi)
print >>fi, "" print("", file=fi)
print >>fi, "" print("", file=fi)
print >>fi, "To rebuild this directory, see ../../tools/icu/README.md" print("To rebuild this directory, see ../../tools/icu/README.md", file=fi)
print >>fi, "" print("", file=fi)
fi.close() fi.close()

View File

@ -27,6 +27,7 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import print_function
from os import path from os import path
import subprocess import subprocess
import sys import sys
@ -40,12 +41,12 @@ VALGRIND_ARGUMENTS = [
] ]
if len(sys.argv) < 2: if len(sys.argv) < 2:
print 'Please provide an executable to analyze.' print('Please provide an executable to analyze.')
sys.exit(1) sys.exit(1)
executable = path.join(NODE_ROOT, sys.argv[1]) executable = path.join(NODE_ROOT, sys.argv[1])
if not path.exists(executable): if not path.exists(executable):
print 'Cannot find the file specified: %s' % executable print('Cannot find the file specified: %s' % executable)
sys.exit(1) sys.exit(1)
# Compute the command line. # Compute the command line.

View File

@ -6,11 +6,12 @@
# Specialize node.d for given flavor (`freebsd`) and arch (`x64` or `ia32`) # Specialize node.d for given flavor (`freebsd`) and arch (`x64` or `ia32`)
# #
from __future__ import print_function
import re import re
import sys import sys
if len(sys.argv) != 5: if len(sys.argv) != 5:
print "usage: specialize_node_d.py outfile src/node.d flavor arch" print("usage: specialize_node_d.py outfile src/node.d flavor arch")
sys.exit(2); sys.exit(2);
outfile = file(sys.argv[1], 'w'); outfile = file(sys.argv[1], 'w');

View File

@ -28,6 +28,7 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import print_function
import imp import imp
import logging import logging
import optparse import optparse
@ -87,11 +88,11 @@ class ProgressIndicator(object):
negative_marker = '[negative] ' negative_marker = '[negative] '
else: else:
negative_marker = '' negative_marker = ''
print "=== %(label)s %(negative)s===" % { print("=== %(label)s %(negative)s===" % {
'label': test.GetLabel(), 'label': test.GetLabel(),
'negative': negative_marker 'negative': negative_marker
} })
print "Path: %s" % "/".join(test.path) print("Path: %s" % "/".join(test.path))
def Run(self, tasks): def Run(self, tasks):
self.Starting() self.Starting()
@ -182,40 +183,40 @@ def EscapeCommand(command):
class SimpleProgressIndicator(ProgressIndicator): class SimpleProgressIndicator(ProgressIndicator):
def Starting(self): def Starting(self):
print 'Running %i tests' % len(self.cases) print('Running %i tests' % len(self.cases))
def Done(self): def Done(self):
print print()
for failed in self.failed: for failed in self.failed:
self.PrintFailureHeader(failed.test) self.PrintFailureHeader(failed.test)
if failed.output.stderr: if failed.output.stderr:
print "--- stderr ---" print("--- stderr ---")
print failed.output.stderr.strip() print(failed.output.stderr.strip())
if failed.output.stdout: if failed.output.stdout:
print "--- stdout ---" print("--- stdout ---")
print failed.output.stdout.strip() print(failed.output.stdout.strip())
print "Command: %s" % EscapeCommand(failed.command) print("Command: %s" % EscapeCommand(failed.command))
if failed.HasCrashed(): if failed.HasCrashed():
print "--- %s ---" % PrintCrashed(failed.output.exit_code) print("--- %s ---" % PrintCrashed(failed.output.exit_code))
if failed.HasTimedOut(): if failed.HasTimedOut():
print "--- TIMEOUT ---" print("--- TIMEOUT ---")
if len(self.failed) == 0: if len(self.failed) == 0:
print "===" print("===")
print "=== All tests succeeded" print("=== All tests succeeded")
print "===" print("===")
else: else:
print print()
print "===" print("===")
print "=== %i tests failed" % len(self.failed) print("=== %i tests failed" % len(self.failed))
if self.crashed > 0: if self.crashed > 0:
print "=== %i tests CRASHED" % self.crashed print("=== %i tests CRASHED" % self.crashed)
print "===" print("===")
class VerboseProgressIndicator(SimpleProgressIndicator): class VerboseProgressIndicator(SimpleProgressIndicator):
def AboutToRun(self, case): def AboutToRun(self, case):
print 'Starting %s...' % case.GetLabel() print('Starting %s...' % case.GetLabel())
sys.stdout.flush() sys.stdout.flush()
def HasRun(self, output): def HasRun(self, output):
@ -226,7 +227,7 @@ class VerboseProgressIndicator(SimpleProgressIndicator):
outcome = 'FAIL' outcome = 'FAIL'
else: else:
outcome = 'pass' outcome = 'pass'
print 'Done running %s: %s' % (output.test.GetLabel(), outcome) print('Done running %s: %s' % (output.test.GetLabel(), outcome))
class DotsProgressIndicator(SimpleProgressIndicator): class DotsProgressIndicator(SimpleProgressIndicator):
@ -362,9 +363,9 @@ class DeoptsCheckProgressIndicator(SimpleProgressIndicator):
("because:" in line or "reason:" in line): ("because:" in line or "reason:" in line):
if not printed_file: if not printed_file:
printed_file = True printed_file = True
print '==== %s ====' % command print('==== %s ====' % command)
self.failed.append(output) self.failed.append(output)
print ' %s' % line print(' %s' % line)
def Done(self): def Done(self):
pass pass
@ -393,15 +394,15 @@ class CompactProgressIndicator(ProgressIndicator):
self.PrintFailureHeader(output.test) self.PrintFailureHeader(output.test)
stdout = output.output.stdout.strip() stdout = output.output.stdout.strip()
if len(stdout): if len(stdout):
print self.templates['stdout'] % stdout print(self.templates['stdout'] % stdout)
stderr = output.output.stderr.strip() stderr = output.output.stderr.strip()
if len(stderr): if len(stderr):
print self.templates['stderr'] % stderr print(self.templates['stderr'] % stderr)
print "Command: %s" % EscapeCommand(output.command) print("Command: %s" % EscapeCommand(output.command))
if output.HasCrashed(): if output.HasCrashed():
print "--- %s ---" % PrintCrashed(output.output.exit_code) print("--- %s ---" % PrintCrashed(output.output.exit_code))
if output.HasTimedOut(): if output.HasTimedOut():
print "--- TIMEOUT ---" print("--- TIMEOUT ---")
def Truncate(self, str, length): def Truncate(self, str, length):
if length and (len(str) > (length - 3)): if length and (len(str) > (length - 3)):
@ -422,7 +423,7 @@ class CompactProgressIndicator(ProgressIndicator):
} }
status = self.Truncate(status, 78) status = self.Truncate(status, 78)
self.last_status_length = len(status) self.last_status_length = len(status)
print status, print(status, end=' ')
sys.stdout.flush() sys.stdout.flush()
@ -437,7 +438,7 @@ class ColorProgressIndicator(CompactProgressIndicator):
super(ColorProgressIndicator, self).__init__(cases, flaky_tests_mode, templates) super(ColorProgressIndicator, self).__init__(cases, flaky_tests_mode, templates)
def ClearLine(self, last_line_length): def ClearLine(self, last_line_length):
print "\033[1K\r", print("\033[1K\r", end=' ')
class MonochromeProgressIndicator(CompactProgressIndicator): class MonochromeProgressIndicator(CompactProgressIndicator):
@ -453,7 +454,7 @@ class MonochromeProgressIndicator(CompactProgressIndicator):
super(MonochromeProgressIndicator, self).__init__(cases, flaky_tests_mode, templates) super(MonochromeProgressIndicator, self).__init__(cases, flaky_tests_mode, templates)
def ClearLine(self, last_line_length): def ClearLine(self, last_line_length):
print ("\r" + (" " * last_line_length) + "\r"), print(("\r" + (" " * last_line_length) + "\r"), end=' ')
PROGRESS_INDICATORS = { PROGRESS_INDICATORS = {
@ -616,7 +617,7 @@ def KillTimedOutProcess(context, pid):
def RunProcess(context, timeout, args, **rest): def RunProcess(context, timeout, args, **rest):
if context.verbose: print "#", " ".join(args) if context.verbose: print("#", " ".join(args))
popen_args = args popen_args = args
prev_error_mode = SEM_INVALID_VALUE; prev_error_mode = SEM_INVALID_VALUE;
if utils.IsWindows(): if utils.IsWindows():
@ -1181,15 +1182,15 @@ def ParseCondition(expr):
"""Parses a logical expression into an Expression object""" """Parses a logical expression into an Expression object"""
tokens = Tokenizer(expr).Tokenize() tokens = Tokenizer(expr).Tokenize()
if not tokens: if not tokens:
print "Malformed expression: '%s'" % expr print("Malformed expression: '%s'" % expr)
return None return None
scan = Scanner(tokens) scan = Scanner(tokens)
ast = ParseLogicalExpression(scan) ast = ParseLogicalExpression(scan)
if not ast: if not ast:
print "Malformed expression: '%s'" % expr print("Malformed expression: '%s'" % expr)
return None return None
if scan.HasMore(): if scan.HasMore():
print "Malformed expression: '%s'" % expr print("Malformed expression: '%s'" % expr)
return None return None
return ast return ast
@ -1387,19 +1388,19 @@ def ProcessOptions(options):
if options.run == [""]: if options.run == [""]:
options.run = None options.run = None
elif len(options.run) != 2: elif len(options.run) != 2:
print "The run argument must be two comma-separated integers." print("The run argument must be two comma-separated integers.")
return False return False
else: else:
try: try:
options.run = map(int, options.run) options.run = map(int, options.run)
except ValueError: except ValueError:
print "Could not parse the integers from the run argument." print("Could not parse the integers from the run argument.")
return False return False
if options.run[0] < 0 or options.run[1] < 0: if options.run[0] < 0 or options.run[1] < 0:
print "The run argument cannot have negative integers." print("The run argument cannot have negative integers.")
return False return False
if options.run[0] >= options.run[1]: if options.run[0] >= options.run[1]:
print "The test group to run (n) must be smaller than number of groups (m)." print("The test group to run (n) must be smaller than number of groups (m).")
return False return False
if options.J: if options.J:
# inherit JOBS from environment if provided. some virtualised systems # inherit JOBS from environment if provided. some virtualised systems
@ -1407,7 +1408,7 @@ def ProcessOptions(options):
cores = os.environ.get('JOBS') cores = os.environ.get('JOBS')
options.j = int(cores) if cores is not None else multiprocessing.cpu_count() options.j = int(cores) if cores is not None else multiprocessing.cpu_count()
if options.flaky_tests not in [RUN, SKIP, DONTCARE]: if options.flaky_tests not in [RUN, SKIP, DONTCARE]:
print "Unknown flaky-tests mode %s" % options.flaky_tests print("Unknown flaky-tests mode %s" % options.flaky_tests)
return False return False
return True return True
@ -1606,13 +1607,13 @@ def Main():
for mode in options.mode: for mode in options.mode:
vm = context.GetVm(arch, mode) vm = context.GetVm(arch, mode)
if not exists(vm): if not exists(vm):
print "Can't find shell executable: '%s'" % vm print("Can't find shell executable: '%s'" % vm)
continue continue
archEngineContext = Execute([vm, "-p", "process.arch"], context) archEngineContext = Execute([vm, "-p", "process.arch"], context)
vmArch = archEngineContext.stdout.rstrip() vmArch = archEngineContext.stdout.rstrip()
if archEngineContext.exit_code is not 0 or vmArch == "undefined": if archEngineContext.exit_code is not 0 or vmArch == "undefined":
print "Can't determine the arch of: '%s'" % vm print("Can't determine the arch of: '%s'" % vm)
print archEngineContext.stderr.rstrip() print(archEngineContext.stderr.rstrip())
continue continue
env = { env = {
'mode': mode, 'mode': mode,
@ -1649,15 +1650,15 @@ def Main():
if key in visited: if key in visited:
continue continue
visited.add(key) visited.add(key)
print "--- begin source: %s ---" % test.GetLabel() print("--- begin source: %s ---" % test.GetLabel())
source = test.GetSource().strip() source = test.GetSource().strip()
print source print(source)
print "--- end source: %s ---" % test.GetLabel() print("--- end source: %s ---" % test.GetLabel())
return 0 return 0
if options.warn_unused: if options.warn_unused:
for rule in globally_unused_rules: for rule in globally_unused_rules:
print "Rule for '%s' was not used." % '/'.join([str(s) for s in rule.path]) print("Rule for '%s' was not used." % '/'.join([str(s) for s in rule.path]))
tempdir = os.environ.get('NODE_TEST_DIR') or options.temp_dir tempdir = os.environ.get('NODE_TEST_DIR') or options.temp_dir
if tempdir: if tempdir:
@ -1666,7 +1667,7 @@ def Main():
os.makedirs(tempdir) os.makedirs(tempdir)
except OSError as exception: except OSError as exception:
if exception.errno != errno.EEXIST: if exception.errno != errno.EEXIST:
print "Could not create the temporary directory", options.temp_dir print("Could not create the temporary directory", options.temp_dir)
sys.exit(1) sys.exit(1)
def should_keep(case): def should_keep(case):
@ -1700,7 +1701,7 @@ def Main():
len(cases_to_run), len(cases_to_run),
options.run[1]) ] options.run[1]) ]
if len(cases_to_run) == 0: if len(cases_to_run) == 0:
print "No tests to run." print("No tests to run.")
return 1 return 1
else: else:
try: try:
@ -1711,13 +1712,13 @@ def Main():
result = 1 result = 1
duration = time.time() - start duration = time.time() - start
except KeyboardInterrupt: except KeyboardInterrupt:
print "Interrupted" print("Interrupted")
return 1 return 1
if options.time: if options.time:
# Write the times to stderr to make it easy to separate from the # Write the times to stderr to make it easy to separate from the
# test output. # test output.
print print()
sys.stderr.write("--- Total time: %s ---\n" % FormatTime(duration)) sys.stderr.write("--- Total time: %s ---\n" % FormatTime(duration))
timed_tests = [ t for t in cases_to_run if not t.duration is None ] timed_tests = [ t for t in cases_to_run if not t.duration is None ]
timed_tests.sort(lambda a, b: a.CompareTime(b)) timed_tests.sort(lambda a, b: a.CompareTime(b))