summaryrefslogtreecommitdiffstats
path: root/Lib/test
diff options
context:
space:
mode:
authorGuido van Rossum <guido@python.org>2007-02-09 05:37:30 (GMT)
committerGuido van Rossum <guido@python.org>2007-02-09 05:37:30 (GMT)
commitbe19ed77ddb047e02fe94d142181062af6d99dcc (patch)
tree70f214e06554046fcccbadeb78665f25e07ce965 /Lib/test
parent452bf519a70c3db0e7f0d2540b1bfb07d9085583 (diff)
downloadcpython-be19ed77ddb047e02fe94d142181062af6d99dcc.zip
cpython-be19ed77ddb047e02fe94d142181062af6d99dcc.tar.gz
cpython-be19ed77ddb047e02fe94d142181062af6d99dcc.tar.bz2
Fix most trivially-findable print statements.
There's one major and one minor category still unfixed: doctests are the major category (and I hope to be able to augment the refactoring tool to refactor bona fide doctests soon); other code generating print statements in strings is the minor category. (Oh, and I don't know if the compiler package works.)
Diffstat (limited to 'Lib/test')
-rw-r--r--Lib/test/badsyntax_future8.py2
-rw-r--r--Lib/test/badsyntax_future9.py2
-rw-r--r--Lib/test/crashers/bogus_sre_bytecode.py2
-rw-r--r--Lib/test/crashers/borrowed_ref_1.py2
-rw-r--r--Lib/test/crashers/borrowed_ref_2.py2
-rw-r--r--Lib/test/crashers/gc_inspection.py4
-rw-r--r--Lib/test/crashers/loosing_mro_ref.py2
-rw-r--r--Lib/test/crashers/modify_dict_attr.py2
-rw-r--r--Lib/test/crashers/nasty_eq_vs_dict.py2
-rw-r--r--Lib/test/inspect_fodder2.py2
-rw-r--r--Lib/test/list_tests.py2
-rw-r--r--Lib/test/pydocfodder.py6
-rwxr-xr-xLib/test/pystone.py10
-rwxr-xr-xLib/test/regrtest.py104
-rw-r--r--Lib/test/reperf.py4
-rw-r--r--Lib/test/sortperf.py10
-rwxr-xr-xLib/test/test_al.py4
-rwxr-xr-xLib/test/test_array.py2
-rw-r--r--Lib/test/test_ast.py8
-rw-r--r--Lib/test/test_atexit.py8
-rw-r--r--Lib/test/test_audioop.py56
-rw-r--r--Lib/test/test_bisect.py2
-rw-r--r--Lib/test/test_bool.py2
-rwxr-xr-xLib/test/test_bsddb.py24
-rw-r--r--Lib/test/test_bsddb3.py14
-rw-r--r--Lib/test/test_builtin.py12
-rw-r--r--Lib/test/test_capi.py4
-rwxr-xr-xLib/test/test_cd.py4
-rwxr-xr-xLib/test/test_cl.py4
-rw-r--r--Lib/test/test_class.py48
-rwxr-xr-xLib/test/test_cmath.py6
-rw-r--r--Lib/test/test_code.py4
-rw-r--r--Lib/test/test_codecs.py2
-rw-r--r--Lib/test/test_compiler.py9
-rw-r--r--Lib/test/test_complex.py2
-rwxr-xr-xLib/test/test_crypt.py2
-rw-r--r--Lib/test/test_csv.py2
-rw-r--r--Lib/test/test_curses.py2
-rw-r--r--Lib/test/test_datetime.py6
-rwxr-xr-xLib/test/test_dbm.py2
-rw-r--r--Lib/test/test_decimal.py6
-rw-r--r--Lib/test/test_defaultdict.py4
-rw-r--r--Lib/test/test_deque.py4
-rw-r--r--Lib/test/test_descr.py222
-rw-r--r--Lib/test/test_dis.py2
-rwxr-xr-xLib/test/test_dl.py8
-rw-r--r--Lib/test/test_doctest.py4
-rw-r--r--Lib/test/test_dummy_thread.py20
-rw-r--r--Lib/test/test_dummy_threading.py12
-rw-r--r--Lib/test/test_enumerate.py2
-rwxr-xr-xLib/test/test_errno.py4
-rw-r--r--Lib/test/test_extcall.py94
-rwxr-xr-xLib/test/test_fcntl.py6
-rw-r--r--Lib/test/test_file.py4
-rw-r--r--Lib/test/test_fileinput.py26
-rw-r--r--Lib/test/test_format.py28
-rw-r--r--Lib/test/test_funcattrs.py12
-rw-r--r--Lib/test/test_functools.py2
-rw-r--r--Lib/test/test_gc.py8
-rwxr-xr-xLib/test/test_gdbm.py2
-rw-r--r--Lib/test/test_generators.py12
-rw-r--r--Lib/test/test_genexps.py2
-rw-r--r--Lib/test/test_getopt.py14
-rwxr-xr-xLib/test/test_gl.py36
-rw-r--r--Lib/test/test_grammar.py74
-rw-r--r--Lib/test/test_heapq.py2
-rwxr-xr-xLib/test/test_imageop.py34
-rwxr-xr-xLib/test/test_imgfile.py20
-rw-r--r--Lib/test/test_import.py16
-rw-r--r--Lib/test/test_itertools.py2
-rw-r--r--Lib/test/test_largefile.py18
-rw-r--r--Lib/test/test_linuxaudiodev.py14
-rw-r--r--Lib/test/test_list.py2
-rw-r--r--Lib/test/test_locale.py24
-rw-r--r--Lib/test/test_long_future.py2
-rw-r--r--Lib/test/test_minidom.py40
-rw-r--r--Lib/test/test_module.py2
-rw-r--r--Lib/test/test_multibytecodec.py2
-rw-r--r--Lib/test/test_mutants.py14
-rw-r--r--Lib/test/test_normalization.py2
-rw-r--r--Lib/test/test_ntpath.py12
-rw-r--r--Lib/test/test_operations.py14
-rw-r--r--Lib/test/test_operator.py2
-rw-r--r--Lib/test/test_ossaudiodev.py8
-rw-r--r--Lib/test/test_peepholer.py2
-rw-r--r--Lib/test/test_pep247.py2
-rw-r--r--Lib/test/test_pep277.py4
-rw-r--r--Lib/test/test_pkg.py12
-rw-r--r--Lib/test/test_popen2.py10
-rw-r--r--Lib/test/test_pty.py2
-rw-r--r--Lib/test/test_pyclbr.py10
-rw-r--r--Lib/test/test_pyexpat.py86
-rw-r--r--Lib/test/test_queue.py4
-rw-r--r--Lib/test/test_random.py2
-rw-r--r--Lib/test/test_re.py28
-rw-r--r--Lib/test/test_rfc822.py4
-rw-r--r--Lib/test/test_rgbimg.py6
-rw-r--r--Lib/test/test_runpy.py32
-rw-r--r--Lib/test/test_sax.py4
-rw-r--r--Lib/test/test_scope.py8
-rw-r--r--Lib/test/test_select.py18
-rw-r--r--Lib/test/test_signal.py24
-rw-r--r--Lib/test/test_site.py10
-rw-r--r--Lib/test/test_socket_ssl.py12
-rw-r--r--Lib/test/test_socketserver.py23
-rw-r--r--Lib/test/test_softspace.py6
-rw-r--r--Lib/test/test_sort.py32
-rwxr-xr-xLib/test/test_strftime.py30
-rw-r--r--Lib/test/test_struct.py20
-rw-r--r--Lib/test/test_sundry.py2
-rw-r--r--Lib/test/test_support.py16
-rw-r--r--Lib/test/test_thread.py34
-rw-r--r--Lib/test/test_threaded_import.py8
-rw-r--r--Lib/test/test_threadedtempfile.py10
-rw-r--r--Lib/test/test_threading.py38
-rw-r--r--Lib/test/test_tokenize.py10
-rw-r--r--Lib/test/test_trace.py2
-rw-r--r--Lib/test/test_traceback.py8
-rw-r--r--Lib/test/test_unicode.py18
-rw-r--r--Lib/test/test_userdict.py2
-rw-r--r--Lib/test/test_uuid.py15
-rw-r--r--Lib/test/test_winreg.py10
-rw-r--r--Lib/test/test_xml_etree.py2
-rw-r--r--Lib/test/test_xml_etree_c.py2
-rw-r--r--Lib/test/test_zipfile64.py8
-rw-r--r--Lib/test/time_hashlib.py32
126 files changed, 878 insertions, 955 deletions
diff --git a/Lib/test/badsyntax_future8.py b/Lib/test/badsyntax_future8.py
index c167b09..ca45289 100644
--- a/Lib/test/badsyntax_future8.py
+++ b/Lib/test/badsyntax_future8.py
@@ -7,4 +7,4 @@ def f(x):
return x + y
return g
-print f(2)(4)
+print(f(2)(4))
diff --git a/Lib/test/badsyntax_future9.py b/Lib/test/badsyntax_future9.py
index cdce32a..916de06 100644
--- a/Lib/test/badsyntax_future9.py
+++ b/Lib/test/badsyntax_future9.py
@@ -7,4 +7,4 @@ def f(x):
return x + y
return g
-print f(2)(4)
+print(f(2)(4))
diff --git a/Lib/test/crashers/bogus_sre_bytecode.py b/Lib/test/crashers/bogus_sre_bytecode.py
index 4bfc730..7f006d9 100644
--- a/Lib/test/crashers/bogus_sre_bytecode.py
+++ b/Lib/test/crashers/bogus_sre_bytecode.py
@@ -38,7 +38,7 @@ ss = ["", "world", "x" * 500]
while 1:
code = [pick() for i in range(random.randrange(5, 25))]
- print code
+ print(code)
pat = _sre.compile(None, 0, code)
for s in ss:
try:
diff --git a/Lib/test/crashers/borrowed_ref_1.py b/Lib/test/crashers/borrowed_ref_1.py
index d16ede2..b82f464 100644
--- a/Lib/test/crashers/borrowed_ref_1.py
+++ b/Lib/test/crashers/borrowed_ref_1.py
@@ -8,7 +8,7 @@ class A(object):
class B(object):
def __del__(self):
- print 'hi'
+ print('hi')
del D.__missing__
class D(dict):
diff --git a/Lib/test/crashers/borrowed_ref_2.py b/Lib/test/crashers/borrowed_ref_2.py
index 1a7b3ff..f3ca350 100644
--- a/Lib/test/crashers/borrowed_ref_2.py
+++ b/Lib/test/crashers/borrowed_ref_2.py
@@ -10,7 +10,7 @@ class A(object):
class B(object):
def __del__(self):
- print "hi"
+ print("hi")
del C.d
class D(object):
diff --git a/Lib/test/crashers/gc_inspection.py b/Lib/test/crashers/gc_inspection.py
index 10caa79..ae85f97 100644
--- a/Lib/test/crashers/gc_inspection.py
+++ b/Lib/test/crashers/gc_inspection.py
@@ -25,8 +25,8 @@ def g():
yield marker
# now the marker is in the tuple being constructed
[tup] = [x for x in gc.get_referrers(marker) if type(x) is tuple]
- print tup
- print tup[1]
+ print(tup)
+ print(tup[1])
tuple(g())
diff --git a/Lib/test/crashers/loosing_mro_ref.py b/Lib/test/crashers/loosing_mro_ref.py
index f0b8047..5ecde63 100644
--- a/Lib/test/crashers/loosing_mro_ref.py
+++ b/Lib/test/crashers/loosing_mro_ref.py
@@ -32,5 +32,5 @@ class X(Base):
# there from the beginning :-)
locals()[MyKey()] = 5
-print X.mykey
+print(X.mykey)
# I get a segfault, or a slightly wrong assertion error in a debug build.
diff --git a/Lib/test/crashers/modify_dict_attr.py b/Lib/test/crashers/modify_dict_attr.py
index dfce467..2a8fce0 100644
--- a/Lib/test/crashers/modify_dict_attr.py
+++ b/Lib/test/crashers/modify_dict_attr.py
@@ -16,4 +16,4 @@ class MyClass(object):
if __name__ == '__main__':
del MyClass.__dict__ # if we set tp_dict to NULL,
- print MyClass # doing anything with MyClass segfaults
+ print(MyClass) # doing anything with MyClass segfaults
diff --git a/Lib/test/crashers/nasty_eq_vs_dict.py b/Lib/test/crashers/nasty_eq_vs_dict.py
index 3f3083d..85f7caf 100644
--- a/Lib/test/crashers/nasty_eq_vs_dict.py
+++ b/Lib/test/crashers/nasty_eq_vs_dict.py
@@ -44,4 +44,4 @@ dict = {y: "OK!"}
z = Yuck()
y.make_dangerous()
-print dict[z]
+print(dict[z])
diff --git a/Lib/test/inspect_fodder2.py b/Lib/test/inspect_fodder2.py
index 3d978cf..ef70c09 100644
--- a/Lib/test/inspect_fodder2.py
+++ b/Lib/test/inspect_fodder2.py
@@ -7,7 +7,7 @@ def wrap(foo=None):
# line 7
def replace(func):
def insteadfunc():
- print 'hello'
+ print('hello')
return insteadfunc
# line 13
diff --git a/Lib/test/list_tests.py b/Lib/test/list_tests.py
index 3867be5..507506e 100644
--- a/Lib/test/list_tests.py
+++ b/Lib/test/list_tests.py
@@ -54,7 +54,7 @@ class CommonTest(seq_tests.CommonTest):
d.append(400)
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, d,
+ print(d, end=' ', file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), repr(d))
diff --git a/Lib/test/pydocfodder.py b/Lib/test/pydocfodder.py
index becdf22..0ae013b 100644
--- a/Lib/test/pydocfodder.py
+++ b/Lib/test/pydocfodder.py
@@ -192,19 +192,19 @@ class FunkyProperties(object):
def __init__(self, attr):
self.attr = attr
def __call__(self, inst):
- print 'Get called', self, inst
+ print('Get called', self, inst)
return inst.desc[self.attr]
class set_desc:
def __init__(self, attr):
self.attr = attr
def __call__(self, inst, val):
- print 'Set called', self, inst, val
+ print('Set called', self, inst, val)
inst.desc[self.attr] = val
class del_desc:
def __init__(self, attr):
self.attr = attr
def __call__(self, inst):
- print 'Del called', self, inst
+ print('Del called', self, inst)
del inst.desc[self.attr]
x = property(get_desc('x'), set_desc('x'), del_desc('x'), 'prop x')
diff --git a/Lib/test/pystone.py b/Lib/test/pystone.py
index 0a25981..3ddb946 100755
--- a/Lib/test/pystone.py
+++ b/Lib/test/pystone.py
@@ -59,9 +59,9 @@ FALSE = 0
def main(loops=LOOPS):
benchtime, stones = pystones(loops)
- print "Pystone(%s) time for %d passes = %g" % \
- (__version__, loops, benchtime)
- print "This machine benchmarks at %g pystones/second" % stones
+ print("Pystone(%s) time for %d passes = %g" % \
+ (__version__, loops, benchtime))
+ print("This machine benchmarks at %g pystones/second" % stones)
def pystones(loops=LOOPS):
@@ -251,8 +251,8 @@ def Func3(EnumParIn):
if __name__ == '__main__':
import sys
def error(msg):
- print >>sys.stderr, msg,
- print >>sys.stderr, "usage: %s [number_of_loops]" % sys.argv[0]
+ print(msg, end=' ', file=sys.stderr)
+ print("usage: %s [number_of_loops]" % sys.argv[0], file=sys.stderr)
sys.exit(100)
nargs = len(sys.argv) - 1
if nargs > 1:
diff --git a/Lib/test/regrtest.py b/Lib/test/regrtest.py
index 4517c59..2efd391 100755
--- a/Lib/test/regrtest.py
+++ b/Lib/test/regrtest.py
@@ -171,8 +171,8 @@ RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb',
def usage(code, msg=''):
- print __doc__
- if msg: print msg
+ print(__doc__)
+ if msg: print(msg)
sys.exit(code)
@@ -253,7 +253,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
elif o in ('-R', '--huntrleaks'):
huntrleaks = a.split(':')
if len(huntrleaks) != 3:
- print a, huntrleaks
+ print(a, huntrleaks)
usage(2, '-R takes three colon-separated arguments')
if len(huntrleaks[0]) == 0:
huntrleaks[0] = 5
@@ -298,7 +298,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
try:
import gc
except ImportError:
- print 'No GC available, disabling findleaks.'
+ print('No GC available, disabling findleaks.')
findleaks = False
else:
# Uncomment the line below to report garbage that is not
@@ -355,7 +355,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
save_modules = sys.modules.keys()
for test in tests:
if not quiet:
- print test
+ print(test)
sys.stdout.flush()
if trace:
# If we're tracing code coverage, then we don't exit with status
@@ -368,7 +368,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
huntrleaks)
except KeyboardInterrupt:
# print a newline separate from the ^C
- print
+ print()
break
except:
raise
@@ -383,8 +383,8 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
if findleaks:
gc.collect()
if gc.garbage:
- print "Warning: test created", len(gc.garbage),
- print "uncollectable object(s)."
+ print("Warning: test created", len(gc.garbage), end=' ')
+ print("uncollectable object(s).")
# move the uncollectable objects somewhere so we don't see
# them again
found_garbage.extend(gc.garbage)
@@ -401,16 +401,16 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
if good and not quiet:
if not bad and not skipped and len(good) > 1:
- print "All",
- print count(len(good), "test"), "OK."
+ print("All", end=' ')
+ print(count(len(good), "test"), "OK.")
if verbose:
- print "CAUTION: stdout isn't compared in verbose mode:"
- print "a test that passes in verbose mode may fail without it."
+ print("CAUTION: stdout isn't compared in verbose mode:")
+ print("a test that passes in verbose mode may fail without it.")
if bad:
- print count(len(bad), "test"), "failed:"
+ print(count(len(bad), "test"), "failed:")
printlist(bad)
if skipped and not quiet:
- print count(len(skipped), "test"), "skipped:"
+ print(count(len(skipped), "test"), "skipped:")
printlist(skipped)
e = _ExpectedSkips()
@@ -418,19 +418,19 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
if e.isvalid():
surprise = set(skipped) - e.getexpected() - set(resource_denieds)
if surprise:
- print count(len(surprise), "skip"), \
- "unexpected on", plat + ":"
+ print(count(len(surprise), "skip"), \
+ "unexpected on", plat + ":")
printlist(surprise)
else:
- print "Those skips are all expected on", plat + "."
+ print("Those skips are all expected on", plat + ".")
else:
- print "Ask someone to teach regrtest.py about which tests are"
- print "expected to get skipped on", plat + "."
+ print("Ask someone to teach regrtest.py about which tests are")
+ print("expected to get skipped on", plat + ".")
if verbose2 and bad:
- print "Re-running failed tests in verbose mode"
+ print("Re-running failed tests in verbose mode")
for test in bad:
- print "Re-running test %r in verbose mode" % test
+ print("Re-running test %r in verbose mode" % test)
sys.stdout.flush()
try:
test_support.verbose = 1
@@ -438,7 +438,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
huntrleaks)
except KeyboardInterrupt:
# print a newline separate from the ^C
- print
+ print()
break
except:
raise
@@ -537,7 +537,7 @@ def runtest_inner(test, generate, verbose, quiet,
try:
if cfp:
sys.stdout = cfp
- print test # Output file starts with test name
+ print(test) # Output file starts with test name
if test.startswith('test.'):
abstest = test
else:
@@ -558,23 +558,23 @@ def runtest_inner(test, generate, verbose, quiet,
sys.stdout = save_stdout
except test_support.ResourceDenied as msg:
if not quiet:
- print test, "skipped --", msg
+ print(test, "skipped --", msg)
sys.stdout.flush()
return -2
except (ImportError, test_support.TestSkipped) as msg:
if not quiet:
- print test, "skipped --", msg
+ print(test, "skipped --", msg)
sys.stdout.flush()
return -1
except KeyboardInterrupt:
raise
except test_support.TestFailed as msg:
- print "test", test, "failed --", msg
+ print("test", test, "failed --", msg)
sys.stdout.flush()
return 0
except:
type, value = sys.exc_info()[:2]
- print "test", test, "crashed --", str(type) + ":", value
+ print("test", test, "crashed --", str(type) + ":", value)
sys.stdout.flush()
if verbose:
traceback.print_exc(file=sys.stdout)
@@ -590,8 +590,8 @@ def runtest_inner(test, generate, verbose, quiet,
# Write it since it already exists (and the contents
# may have changed), but let the user know it isn't
# needed:
- print "output file", outputfile, \
- "is no longer needed; consider removing it"
+ print("output file", outputfile, \
+ "is no longer needed; consider removing it")
else:
# We don't need it, so don't create it.
return 1
@@ -607,7 +607,7 @@ def runtest_inner(test, generate, verbose, quiet,
expected = test + "\n"
if output == expected or huntrleaks:
return 1
- print "test", test, "produced unexpected output:"
+ print("test", test, "produced unexpected output:")
sys.stdout.flush()
reportdiff(expected, output)
sys.stdout.flush()
@@ -637,12 +637,12 @@ def cleanup_test_droppings(testname, verbose):
"directory nor file" % name)
if verbose:
- print "%r left behind %s %r" % (testname, kind, name)
+ print("%r left behind %s %r" % (testname, kind, name))
try:
nuker(name)
except Exception as msg:
- print >> sys.stderr, ("%r left behind %s %r and it couldn't be "
- "removed: %s" % (testname, kind, name, msg))
+ print(("%r left behind %s %r and it couldn't be "
+ "removed: %s" % (testname, kind, name, msg)), file=sys.stderr)
def dash_R(the_module, test, indirect_test, huntrleaks):
# This code is hackish and inelegant, but it seems to do the job.
@@ -667,8 +667,8 @@ def dash_R(the_module, test, indirect_test, huntrleaks):
deltas = []
nwarmup, ntracked, fname = huntrleaks
repcount = nwarmup + ntracked
- print >> sys.stderr, "beginning", repcount, "repetitions"
- print >> sys.stderr, ("1234567890"*(repcount//10 + 1))[:repcount]
+ print("beginning", repcount, "repetitions", file=sys.stderr)
+ print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr)
dash_R_cleanup(fs, ps, pic)
for i in range(repcount):
rc = sys.gettotalrefcount()
@@ -677,11 +677,11 @@ def dash_R(the_module, test, indirect_test, huntrleaks):
dash_R_cleanup(fs, ps, pic)
if i >= nwarmup:
deltas.append(sys.gettotalrefcount() - rc - 2)
- print >> sys.stderr
+ print(file=sys.stderr)
if any(deltas):
- print >> sys.stderr, test, 'leaked', deltas, 'references'
+ print(test, 'leaked', deltas, 'references', file=sys.stderr)
refrep = open(fname, "a")
- print >> refrep, test, 'leaked', deltas, 'references'
+ print(test, 'leaked', deltas, 'references', file=refrep)
refrep.close()
def dash_R_cleanup(fs, ps, pic):
@@ -717,7 +717,7 @@ def dash_R_cleanup(fs, ps, pic):
def reportdiff(expected, output):
import difflib
- print "*" * 70
+ print("*" * 70)
a = expected.splitlines(1)
b = output.splitlines(1)
sm = difflib.SequenceMatcher(a=a, b=b)
@@ -736,26 +736,26 @@ def reportdiff(expected, output):
pass
elif op == 'delete':
- print "***", pair(a0, a1), "of expected output missing:"
+ print("***", pair(a0, a1), "of expected output missing:")
for line in a[a0:a1]:
- print "-", line,
+ print("-", line, end=' ')
elif op == 'replace':
- print "*** mismatch between", pair(a0, a1), "of expected", \
- "output and", pair(b0, b1), "of actual output:"
+ print("*** mismatch between", pair(a0, a1), "of expected", \
+ "output and", pair(b0, b1), "of actual output:")
for line in difflib.ndiff(a[a0:a1], b[b0:b1]):
- print line,
+ print(line, end=' ')
elif op == 'insert':
- print "***", pair(b0, b1), "of actual output doesn't appear", \
- "in expected output after line", str(a1)+":"
+ print("***", pair(b0, b1), "of actual output doesn't appear", \
+ "in expected output after line", str(a1)+":")
for line in b[b0:b1]:
- print "+", line,
+ print("+", line, end=' ')
else:
- print "get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1)
+ print("get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1))
- print "*" * 70
+ print("*" * 70)
def findtestdir():
if __name__ == '__main__':
@@ -786,8 +786,8 @@ def printlist(x, width=70, indent=4):
from textwrap import fill
blanks = ' ' * indent
- print fill(' '.join(map(str, x)), width,
- initial_indent=blanks, subsequent_indent=blanks)
+ print(fill(' '.join(map(str, x)), width,
+ initial_indent=blanks, subsequent_indent=blanks))
# Map sys.platform to a string containing the basenames of tests
# expected to be skipped on that platform.
@@ -1369,5 +1369,5 @@ if __name__ == '__main__':
if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
del sys.path[i]
if len(sys.path) == pathlen:
- print 'Could not find %r in sys.path to remove it' % mydir
+ print('Could not find %r in sys.path to remove it' % mydir)
main()
diff --git a/Lib/test/reperf.py b/Lib/test/reperf.py
index 68ac40f..7c68234 100644
--- a/Lib/test/reperf.py
+++ b/Lib/test/reperf.py
@@ -17,7 +17,7 @@ def timefunc(n, func, *args, **kw):
finally:
t1 = time.clock()
if n > 1:
- print n, "times",
- print func.__name__, "%.3f" % (t1-t0), "CPU seconds"
+ print(n, "times", end=' ')
+ print(func.__name__, "%.3f" % (t1-t0), "CPU seconds")
main()
diff --git a/Lib/test/sortperf.py b/Lib/test/sortperf.py
index 3c95b89..205ff87 100644
--- a/Lib/test/sortperf.py
+++ b/Lib/test/sortperf.py
@@ -38,7 +38,7 @@ def randfloats(n):
except os.error:
pass
except IOError as msg:
- print "can't write", fn, ":", msg
+ print("can't write", fn, ":", msg)
else:
result = marshal.load(fp)
fp.close()
@@ -60,7 +60,7 @@ def doit(L):
t0 = time.clock()
L.sort()
t1 = time.clock()
- print "%6.2f" % (t1-t0),
+ print("%6.2f" % (t1-t0), end=' ')
flush()
def tabulate(r):
@@ -84,11 +84,11 @@ def tabulate(r):
"""
cases = tuple([ch + "sort" for ch in r"*\/3+%~=!"])
fmt = ("%2s %7s" + " %6s"*len(cases))
- print fmt % (("i", "2**i") + cases)
+ print(fmt % (("i", "2**i") + cases))
for i in r:
n = 1 << i
L = randfloats(n)
- print "%2d %7d" % (i, n),
+ print("%2d %7d" % (i, n), end=' ')
flush()
doit(L) # *sort
L.reverse()
@@ -137,7 +137,7 @@ def tabulate(r):
# significantly faster if we leave tham as ints.
L = map(float, L)
doit(L) # !sort
- print
+ print()
def main():
"""Main program when invoked as a script.
diff --git a/Lib/test/test_al.py b/Lib/test/test_al.py
index 02876f0..e97ca65 100755
--- a/Lib/test/test_al.py
+++ b/Lib/test/test_al.py
@@ -14,10 +14,10 @@ alattrs = ['__doc__', '__name__', 'getdefault', 'getminmax', 'getname', 'getpara
def main():
# touch all the attributes of al without doing anything
if verbose:
- print 'Touching al module attributes...'
+ print('Touching al module attributes...')
for attr in alattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(al, attr)
main()
diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py
index 02215e5..6abfb90 100755
--- a/Lib/test/test_array.py
+++ b/Lib/test/test_array.py
@@ -975,7 +975,7 @@ def test_main(verbose=None):
test_support.run_unittest(*tests)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index 289b533..24394ed 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -117,11 +117,11 @@ eval_tests = [
if __name__=='__main__' and sys.argv[1:] == ['-g']:
for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
(eval_tests, "eval")):
- print kind+"_results = ["
+ print(kind+"_results = [")
for s in statements:
- print repr(to_tuple(compile(s, "?", kind, 0x400)))+","
- print "]"
- print "run_tests()"
+ print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
+ print("]")
+ print("run_tests()")
raise SystemExit
def test_order(ast_node, parent_pos):
diff --git a/Lib/test/test_atexit.py b/Lib/test/test_atexit.py
index 684d607..9d1e003 100644
--- a/Lib/test/test_atexit.py
+++ b/Lib/test/test_atexit.py
@@ -75,16 +75,16 @@ class TestCase(unittest.TestCase):
### helpers
def h1(self):
- print "h1"
+ print("h1")
def h2(self):
- print "h2"
+ print("h2")
def h3(self):
- print "h3"
+ print("h3")
def h4(self, *args, **kwargs):
- print "h4", args, kwargs
+ print("h4", args, kwargs)
def raise1(self):
raise TypeError
diff --git a/Lib/test/test_audioop.py b/Lib/test/test_audioop.py
index f585733..926a3cd 100644
--- a/Lib/test/test_audioop.py
+++ b/Lib/test/test_audioop.py
@@ -7,7 +7,7 @@ def gendata1():
def gendata2():
if verbose:
- print 'getsample'
+ print('getsample')
if audioop.getsample('\0\1', 2, 0) == 1:
return '\0\0\0\1\0\2'
else:
@@ -15,7 +15,7 @@ def gendata2():
def gendata4():
if verbose:
- print 'getsample'
+ print('getsample')
if audioop.getsample('\0\0\0\1', 4, 0) == 1:
return '\0\0\0\0\0\0\0\1\0\0\0\2'
else:
@@ -23,7 +23,7 @@ def gendata4():
def testmax(data):
if verbose:
- print 'max'
+ print('max')
if audioop.max(data[0], 1) != 2 or \
audioop.max(data[1], 2) != 2 or \
audioop.max(data[2], 4) != 2:
@@ -32,7 +32,7 @@ def testmax(data):
def testminmax(data):
if verbose:
- print 'minmax'
+ print('minmax')
if audioop.minmax(data[0], 1) != (0, 2) or \
audioop.minmax(data[1], 2) != (0, 2) or \
audioop.minmax(data[2], 4) != (0, 2):
@@ -41,7 +41,7 @@ def testminmax(data):
def testmaxpp(data):
if verbose:
- print 'maxpp'
+ print('maxpp')
if audioop.maxpp(data[0], 1) != 0 or \
audioop.maxpp(data[1], 2) != 0 or \
audioop.maxpp(data[2], 4) != 0:
@@ -50,7 +50,7 @@ def testmaxpp(data):
def testavg(data):
if verbose:
- print 'avg'
+ print('avg')
if audioop.avg(data[0], 1) != 1 or \
audioop.avg(data[1], 2) != 1 or \
audioop.avg(data[2], 4) != 1:
@@ -59,7 +59,7 @@ def testavg(data):
def testavgpp(data):
if verbose:
- print 'avgpp'
+ print('avgpp')
if audioop.avgpp(data[0], 1) != 0 or \
audioop.avgpp(data[1], 2) != 0 or \
audioop.avgpp(data[2], 4) != 0:
@@ -75,7 +75,7 @@ def testrms(data):
def testcross(data):
if verbose:
- print 'cross'
+ print('cross')
if audioop.cross(data[0], 1) != 0 or \
audioop.cross(data[1], 2) != 0 or \
audioop.cross(data[2], 4) != 0:
@@ -84,7 +84,7 @@ def testcross(data):
def testadd(data):
if verbose:
- print 'add'
+ print('add')
data2 = []
for d in data:
str = ''
@@ -99,7 +99,7 @@ def testadd(data):
def testbias(data):
if verbose:
- print 'bias'
+ print('bias')
# Note: this test assumes that avg() works
d1 = audioop.bias(data[0], 1, 100)
d2 = audioop.bias(data[1], 2, 100)
@@ -112,7 +112,7 @@ def testbias(data):
def testlin2lin(data):
if verbose:
- print 'lin2lin'
+ print('lin2lin')
# too simple: we test only the size
for d1 in data:
for d2 in data:
@@ -130,7 +130,7 @@ def testadpcm2lin(data):
def testlin2adpcm(data):
if verbose:
- print 'lin2adpcm'
+ print('lin2adpcm')
# Very cursory test
if audioop.lin2adpcm('\0\0\0\0', 1, None) != ('\0\0', (0,0)):
return 0
@@ -138,7 +138,7 @@ def testlin2adpcm(data):
def testlin2alaw(data):
if verbose:
- print 'lin2alaw'
+ print('lin2alaw')
if audioop.lin2alaw(data[0], 1) != '\xd5\xc5\xf5' or \
audioop.lin2alaw(data[1], 2) != '\xd5\xd5\xd5' or \
audioop.lin2alaw(data[2], 4) != '\xd5\xd5\xd5':
@@ -147,7 +147,7 @@ def testlin2alaw(data):
def testalaw2lin(data):
if verbose:
- print 'alaw2lin'
+ print('alaw2lin')
# Cursory
d = audioop.lin2alaw(data[0], 1)
if audioop.alaw2lin(d, 1) != data[0]:
@@ -156,7 +156,7 @@ def testalaw2lin(data):
def testlin2ulaw(data):
if verbose:
- print 'lin2ulaw'
+ print('lin2ulaw')
if audioop.lin2ulaw(data[0], 1) != '\xff\xe7\xdb' or \
audioop.lin2ulaw(data[1], 2) != '\xff\xff\xff' or \
audioop.lin2ulaw(data[2], 4) != '\xff\xff\xff':
@@ -165,7 +165,7 @@ def testlin2ulaw(data):
def testulaw2lin(data):
if verbose:
- print 'ulaw2lin'
+ print('ulaw2lin')
# Cursory
d = audioop.lin2ulaw(data[0], 1)
if audioop.ulaw2lin(d, 1) != data[0]:
@@ -174,7 +174,7 @@ def testulaw2lin(data):
def testmul(data):
if verbose:
- print 'mul'
+ print('mul')
data2 = []
for d in data:
str = ''
@@ -189,7 +189,7 @@ def testmul(data):
def testratecv(data):
if verbose:
- print 'ratecv'
+ print('ratecv')
state = None
d1, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state)
d2, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state)
@@ -199,14 +199,14 @@ def testratecv(data):
def testreverse(data):
if verbose:
- print 'reverse'
+ print('reverse')
if audioop.reverse(data[0], 1) != '\2\1\0':
return 0
return 1
def testtomono(data):
if verbose:
- print 'tomono'
+ print('tomono')
data2 = ''
for d in data[0]:
data2 = data2 + d + d
@@ -216,7 +216,7 @@ def testtomono(data):
def testtostereo(data):
if verbose:
- print 'tostereo'
+ print('tostereo')
data2 = ''
for d in data[0]:
data2 = data2 + d + d
@@ -226,28 +226,28 @@ def testtostereo(data):
def testfindfactor(data):
if verbose:
- print 'findfactor'
+ print('findfactor')
if audioop.findfactor(data[1], data[1]) != 1.0:
return 0
return 1
def testfindfit(data):
if verbose:
- print 'findfit'
+ print('findfit')
if audioop.findfit(data[1], data[1]) != (0, 1.0):
return 0
return 1
def testfindmax(data):
if verbose:
- print 'findmax'
+ print('findmax')
if audioop.findmax(data[1], 1) != 2:
return 0
return 1
def testgetsample(data):
if verbose:
- print 'getsample'
+ print('getsample')
for i in range(3):
if audioop.getsample(data[0], 1, i) != i or \
audioop.getsample(data[1], 2, i) != i or \
@@ -259,15 +259,15 @@ def testone(name, data):
try:
func = eval('test'+name)
except NameError:
- print 'No test found for audioop.'+name+'()'
+ print('No test found for audioop.'+name+'()')
return
try:
rv = func(data)
except 'xx':
- print 'Test FAILED for audioop.'+name+'() (with an exception)'
+ print('Test FAILED for audioop.'+name+'() (with an exception)')
return
if not rv:
- print 'Test FAILED for audioop.'+name+'()'
+ print('Test FAILED for audioop.'+name+'()')
def testall():
data = [gendata1(), gendata2(), gendata4()]
diff --git a/Lib/test/test_bisect.py b/Lib/test/test_bisect.py
index 772e808..1d62352 100644
--- a/Lib/test/test_bisect.py
+++ b/Lib/test/test_bisect.py
@@ -252,7 +252,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_bool.py b/Lib/test/test_bool.py
index 954423f..1d9a60b 100644
--- a/Lib/test/test_bool.py
+++ b/Lib/test/test_bool.py
@@ -27,7 +27,7 @@ class BoolTest(unittest.TestCase):
def test_print(self):
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, False, True
+ print(False, True, file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), 'False True\n')
diff --git a/Lib/test/test_bsddb.py b/Lib/test/test_bsddb.py
index 91c1cca..3b33c48 100755
--- a/Lib/test/test_bsddb.py
+++ b/Lib/test/test_bsddb.py
@@ -147,42 +147,42 @@ class TestBSDDB(unittest.TestCase):
# in pybsddb's _DBWithCursor this causes an internal DBCursor
# object is created. Other test_ methods in this class could
# inadvertently cause the deadlock but an explicit test is needed.
- if debug: print "A"
+ if debug: print("A")
k,v = self.f.first()
- if debug: print "B", k
+ if debug: print("B", k)
self.f[k] = "deadlock. do not pass go. do not collect $200."
- if debug: print "C"
+ if debug: print("C")
# if the bsddb implementation leaves the DBCursor open during
# the database write and locking+threading support is enabled
# the cursor's read lock will deadlock the write lock request..
# test the iterator interface (if present)
if hasattr(self.f, 'iteritems'):
- if debug: print "D"
+ if debug: print("D")
i = self.f.iteritems()
k,v = i.next()
- if debug: print "E"
+ if debug: print("E")
self.f[k] = "please don't deadlock"
- if debug: print "F"
+ if debug: print("F")
while 1:
try:
k,v = i.next()
except StopIteration:
break
- if debug: print "F2"
+ if debug: print("F2")
i = iter(self.f)
- if debug: print "G"
+ if debug: print("G")
while i:
try:
- if debug: print "H"
+ if debug: print("H")
k = i.next()
- if debug: print "I"
+ if debug: print("I")
self.f[k] = "deadlocks-r-us"
- if debug: print "J"
+ if debug: print("J")
except StopIteration:
i = None
- if debug: print "K"
+ if debug: print("K")
# test the legacy cursor interface mixed with writes
self.assert_(self.f.first()[0] in self.d)
diff --git a/Lib/test/test_bsddb3.py b/Lib/test/test_bsddb3.py
index 166ad03..69e99c0 100644
--- a/Lib/test/test_bsddb3.py
+++ b/Lib/test/test_bsddb3.py
@@ -65,12 +65,12 @@ def test_main():
# For invocation as a script
if __name__ == '__main__':
from bsddb import db
- print '-=' * 38
- print db.DB_VERSION_STRING
- print 'bsddb.db.version(): %s' % (db.version(),)
- print 'bsddb.db.__version__: %s' % db.__version__
- print 'bsddb.db.cvsid: %s' % db.cvsid
- print 'python version: %s' % sys.version
- print '-=' * 38
+ print('-=' * 38)
+ print(db.DB_VERSION_STRING)
+ print('bsddb.db.version(): %s' % (db.version(),))
+ print('bsddb.db.__version__: %s' % db.__version__)
+ print('bsddb.db.cvsid: %s' % db.cvsid)
+ print('python version: %s' % sys.version)
+ print('-=' * 38)
unittest.main(defaultTest='suite')
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index 56417a3..ab9dfc8 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -204,15 +204,15 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(TypeError, cmp)
def test_compile(self):
- compile('print 1\n', '', 'exec')
+ compile('print(1)\n', '', 'exec')
bom = '\xef\xbb\xbf'
- compile(bom + 'print 1\n', '', 'exec')
+ compile(bom + 'print(1)\n', '', 'exec')
self.assertRaises(TypeError, compile)
- self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode')
- self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff)
+ self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
+ self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
if have_unicode:
- compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
+ compile(unicode('print(u"\xc3\xa5")\n', 'utf8'), '', 'exec')
self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
@@ -1659,7 +1659,7 @@ def test_main(verbose=None):
run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
diff --git a/Lib/test/test_capi.py b/Lib/test/test_capi.py
index cdd84bb..074f581 100644
--- a/Lib/test/test_capi.py
+++ b/Lib/test/test_capi.py
@@ -11,7 +11,7 @@ def test_main():
if name.startswith('test_'):
test = getattr(_testcapi, name)
if test_support.verbose:
- print "internal", name
+ print("internal", name)
try:
test()
except _testcapi.error:
@@ -23,7 +23,7 @@ def test_main():
import time
if test_support.verbose:
- print "auto-thread-state"
+ print("auto-thread-state")
idents = []
diff --git a/Lib/test/test_cd.py b/Lib/test/test_cd.py
index d856211..217b38b 100755
--- a/Lib/test/test_cd.py
+++ b/Lib/test/test_cd.py
@@ -17,10 +17,10 @@ cdattrs = ['BLOCKSIZE', 'CDROM', 'DATASIZE', 'ERROR', 'NODISC', 'PAUSED', 'PLAYI
def main():
# touch all the attributes of cd without doing anything
if verbose:
- print 'Touching cd module attributes...'
+ print('Touching cd module attributes...')
for attr in cdattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(cd, attr)
main()
diff --git a/Lib/test/test_cl.py b/Lib/test/test_cl.py
index abfe3c1..0df7f6f 100755
--- a/Lib/test/test_cl.py
+++ b/Lib/test/test_cl.py
@@ -69,10 +69,10 @@ clattrs = ['ADDED_ALGORITHM_ERROR', 'ALAW', 'ALGORITHM_ID',
def main():
# touch all the attributes of al without doing anything
if verbose:
- print 'Touching cl module attributes...'
+ print('Touching cl module attributes...')
for attr in clattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(cl, attr)
main()
diff --git a/Lib/test/test_class.py b/Lib/test/test_class.py
index c450c80..221fd48 100644
--- a/Lib/test/test_class.py
+++ b/Lib/test/test_class.py
@@ -65,63 +65,63 @@ testmeths = [
class AllTests:
def __hash__(self, *args):
- print "__hash__:", args
+ print("__hash__:", args)
return hash(id(self))
def __str__(self, *args):
- print "__str__:", args
+ print("__str__:", args)
return "AllTests"
def __repr__(self, *args):
- print "__repr__:", args
+ print("__repr__:", args)
return "AllTests"
def __int__(self, *args):
- print "__int__:", args
+ print("__int__:", args)
return 1
def __float__(self, *args):
- print "__float__:", args
+ print("__float__:", args)
return 1.0
def __oct__(self, *args):
- print "__oct__:", args
+ print("__oct__:", args)
return '01'
def __hex__(self, *args):
- print "__hex__:", args
+ print("__hex__:", args)
return '0x1'
def __cmp__(self, *args):
- print "__cmp__:", args
+ print("__cmp__:", args)
return 0
def __eq__(self, *args):
- print "__eq__:", args
+ print("__eq__:", args)
return True
def __ne__(self, *args):
- print "__ne__:", args
+ print("__ne__:", args)
return False
def __lt__(self, *args):
- print "__lt__:", args
+ print("__lt__:", args)
return False
def __le__(self, *args):
- print "__le__:", args
+ print("__le__:", args)
return True
def __gt__(self, *args):
- print "__gt__:", args
+ print("__gt__:", args)
return False
def __ge__(self, *args):
- print "__ge__:", args
+ print("__ge__:", args)
return True
def __del__(self, *args):
- print "__del__:", args
+ print("__del__:", args)
# Synthesize AllTests methods from the names in testmeths.
@@ -186,7 +186,7 @@ class Empty: pass
try:
1 in Empty()
- print 'failed, should have raised TypeError'
+ print('failed, should have raised TypeError')
except TypeError:
pass
@@ -224,9 +224,9 @@ if sys.platform[:4] != 'java':
else:
# This works under Jython, but the actual slice values are
# different.
- print "__getitem__: (slice(0, 42, None),)"
- print "__setitem__: (slice(0, 42, None), 'The Answer')"
- print "__delitem__: (slice(0, 42, None),)"
+ print("__getitem__: (slice(0, 42, None),)")
+ print("__setitem__: (slice(0, 42, None), 'The Answer')")
+ print("__delitem__: (slice(0, 42, None),)")
# Unary operations
@@ -265,14 +265,14 @@ if sys.platform[:4] == 'java':
class ExtraTests:
def __getattr__(self, *args):
- print "__getattr__:", args
+ print("__getattr__:", args)
return "SomeVal"
def __setattr__(self, *args):
- print "__setattr__:", args
+ print("__setattr__:", args)
def __delattr__(self, *args):
- print "__delattr__:", args
+ print("__delattr__:", args)
testme = ExtraTests()
testme.spam
@@ -349,7 +349,7 @@ try:
A().a # Raised AttributeError: A instance has no attribute 'a'
except AttributeError as x:
if str(x) != "booh":
- print "attribute error for A().a got masked:", str(x)
+ print("attribute error for A().a got masked:", str(x))
class E:
__eq__ = property(booh)
@@ -362,7 +362,7 @@ try:
except AttributeError as x:
pass
else:
- print "attribute error for I.__init__ got masked"
+ print("attribute error for I.__init__ got masked")
# Test comparison and hash of methods
diff --git a/Lib/test/test_cmath.py b/Lib/test/test_cmath.py
index 6e39292..fd3a6bf 100755
--- a/Lib/test/test_cmath.py
+++ b/Lib/test/test_cmath.py
@@ -43,10 +43,10 @@ for func in testdict.keys():
f = getattr(cmath, func)
r = f(testdict[func])
if verbose:
- print 'Calling %s(%f) = %f' % (func, testdict[func], abs(r))
+ print('Calling %s(%f) = %f' % (func, testdict[func], abs(r)))
p = cmath.pi
e = cmath.e
if verbose:
- print 'PI = ', abs(p)
- print 'E = ', abs(e)
+ print('PI = ', abs(p))
+ print('E = ', abs(e))
diff --git a/Lib/test/test_code.py b/Lib/test/test_code.py
index 6e0a181..13ec254 100644
--- a/Lib/test/test_code.py
+++ b/Lib/test/test_code.py
@@ -115,8 +115,8 @@ def dump(co):
"""Print out a text representation of a code object."""
for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames",
"cellvars", "freevars", "nlocals", "flags"]:
- print "%s: %s" % (attr, getattr(co, "co_" + attr))
- print "consts:", tuple(consts(co.co_consts))
+ print("%s: %s" % (attr, getattr(co, "co_" + attr)))
+ print("consts:", tuple(consts(co.co_consts)))
def test_main(verbose=None):
from test.test_support import run_doctest
diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py
index 0711923..44ce8eb 100644
--- a/Lib/test/test_codecs.py
+++ b/Lib/test/test_codecs.py
@@ -548,7 +548,7 @@ punycode_testcases = [
for i in punycode_testcases:
if len(i)!=2:
- print repr(i)
+ print(repr(i))
class PunycodeTest(unittest.TestCase):
def test_encode(self):
diff --git a/Lib/test/test_compiler.py b/Lib/test/test_compiler.py
index 7320368..ab9a660 100644
--- a/Lib/test/test_compiler.py
+++ b/Lib/test/test_compiler.py
@@ -30,8 +30,7 @@ class CompilerTest(unittest.TestCase):
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, \
- ' testCompileLibrary still working, be patient...'
+ print(' testCompileLibrary still working, be patient...', file=sys.__stdout__)
sys.__stdout__.flush()
if not basename.endswith(".py"):
@@ -40,7 +39,7 @@ class CompilerTest(unittest.TestCase):
continue
path = os.path.join(dir, basename)
if test.test_support.verbose:
- print "compiling", path
+ print("compiling", path)
f = open(path, "U")
buf = f.read()
f.close()
@@ -94,7 +93,7 @@ class CompilerTest(unittest.TestCase):
try:
self._check_lineno(node)
except AssertionError:
- print node.__class__, node.lineno
+ print(node.__class__, node.lineno)
raise
def _check_lineno(self, node):
@@ -217,7 +216,7 @@ else:
a, b = b, a
try:
- print yo
+ print(yo)
except:
yo = 3
else:
diff --git a/Lib/test/test_complex.py b/Lib/test/test_complex.py
index afc7cae..91f074b 100644
--- a/Lib/test/test_complex.py
+++ b/Lib/test/test_complex.py
@@ -315,7 +315,7 @@ class ComplexTest(unittest.TestCase):
fo = None
try:
fo = open(test_support.TESTFN, "wb")
- print >>fo, a, b
+ print(a, b, file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), "%s %s\n" % (a, b))
diff --git a/Lib/test/test_crypt.py b/Lib/test/test_crypt.py
index dfbcbdf..7336711 100755
--- a/Lib/test/test_crypt.py
+++ b/Lib/test/test_crypt.py
@@ -8,4 +8,4 @@ import crypt
c = crypt.crypt('mypassword', 'ab')
if verbose:
- print 'Test encryption: ', c
+ print('Test encryption: ', c)
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index feb6ddf..46361c8 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -894,7 +894,7 @@ Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back
self.assertEqual(dialect.quotechar, "'")
if not hasattr(sys, "gettotalrefcount"):
- if test_support.verbose: print "*** skipping leakage tests ***"
+ if test_support.verbose: print("*** skipping leakage tests ***")
else:
class NUL:
def write(s, *args):
diff --git a/Lib/test/test_curses.py b/Lib/test/test_curses.py
index 4022149..fd8e6ed 100644
--- a/Lib/test/test_curses.py
+++ b/Lib/test/test_curses.py
@@ -228,7 +228,7 @@ def unit_tests():
('\x8a', '!^J'), ('\xc1', '!A'),
]:
if ascii.unctrl(ch) != expected:
- print 'curses.unctrl fails on character', repr(ch)
+ print('curses.unctrl fails on character', repr(ch))
def test_userptr_without_set(stdscr):
diff --git a/Lib/test/test_datetime.py b/Lib/test/test_datetime.py
index b32017e..70b00a4 100644
--- a/Lib/test/test_datetime.py
+++ b/Lib/test/test_datetime.py
@@ -3287,11 +3287,11 @@ def test_main():
gc.garbage)
if hasattr(sys, 'gettotalrefcount'):
thisrc = sys.gettotalrefcount()
- print >> sys.stderr, '*' * 10, 'total refs:', thisrc,
+ print('*' * 10, 'total refs:', thisrc, end=' ', file=sys.stderr)
if lastrc:
- print >> sys.stderr, 'delta:', thisrc - lastrc
+ print('delta:', thisrc - lastrc, file=sys.stderr)
else:
- print >> sys.stderr
+ print(file=sys.stderr)
lastrc = thisrc
if __name__ == "__main__":
diff --git a/Lib/test/test_dbm.py b/Lib/test/test_dbm.py
index 0a9db4e..a3b7716 100755
--- a/Lib/test/test_dbm.py
+++ b/Lib/test/test_dbm.py
@@ -31,7 +31,7 @@ def test_keys():
d.keys()
if 'a' in d:
if verbose:
- print 'Test dbm keys: ', d.keys()
+ print('Test dbm keys: ', d.keys())
d.close()
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
index 4a53122..c39a8e3 100644
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -143,8 +143,8 @@ class DecimalTest(unittest.TestCase):
try:
t = self.eval_line(line)
except InvalidOperation:
- print 'Error in test cases:'
- print line
+ print('Error in test cases:')
+ print(line)
continue
except DecimalException as exception:
#Exception raised where there shoudn't have been one.
@@ -271,7 +271,7 @@ class DecimalTest(unittest.TestCase):
except Signals as error:
self.fail("Raised %s in %s" % (error, s))
except: #Catch any error long enough to state the test case.
- print "ERROR:", s
+ print("ERROR:", s)
raise
myexceptions = self.getexceptions()
diff --git a/Lib/test/test_defaultdict.py b/Lib/test/test_defaultdict.py
index 602e0d9..03900de 100644
--- a/Lib/test/test_defaultdict.py
+++ b/Lib/test/test_defaultdict.py
@@ -81,8 +81,8 @@ class TestDefaultDict(unittest.TestCase):
try:
f = open(tfn, "w+")
try:
- print >>f, d1
- print >>f, d2
+ print(d1, file=f)
+ print(d2, file=f)
f.seek(0)
self.assertEqual(f.readline(), repr(d1) + "\n")
self.assertEqual(f.readline(), repr(d2) + "\n")
diff --git a/Lib/test/test_deque.py b/Lib/test/test_deque.py
index a98339b..9f7caec 100644
--- a/Lib/test/test_deque.py
+++ b/Lib/test/test_deque.py
@@ -245,7 +245,7 @@ class TestBasic(unittest.TestCase):
d.append(d)
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, d,
+ print(d, end=' ', file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), repr(d))
@@ -622,7 +622,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
# doctests
from test import test_deque
diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py
index bcfadf7..aab3331 100644
--- a/Lib/test/test_descr.py
+++ b/Lib/test/test_descr.py
@@ -13,7 +13,7 @@ def veris(a, b):
raise TestFailed, "%r is %r" % (a, b)
def testunop(a, res, expr="len(a)", meth="__len__"):
- if verbose: print "checking", expr
+ if verbose: print("checking", expr)
dict = {'a': a}
vereq(eval(expr, dict), res)
t = type(a)
@@ -26,7 +26,7 @@ def testunop(a, res, expr="len(a)", meth="__len__"):
vereq(bm(), res)
def testbinop(a, b, res, expr="a+b", meth="__add__"):
- if verbose: print "checking", expr
+ if verbose: print("checking", expr)
dict = {'a': a, 'b': b}
vereq(eval(expr, dict), res)
@@ -40,7 +40,7 @@ def testbinop(a, b, res, expr="a+b", meth="__add__"):
vereq(bm(b), res)
def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
- if verbose: print "checking", expr
+ if verbose: print("checking", expr)
dict = {'a': a, 'b': b, 'c': c}
vereq(eval(expr, dict), res)
t = type(a)
@@ -53,7 +53,7 @@ def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
vereq(bm(b, c), res)
def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
- if verbose: print "checking", stmt
+ if verbose: print("checking", stmt)
dict = {'a': deepcopy(a), 'b': b}
exec(stmt, dict)
vereq(dict['a'], res)
@@ -71,7 +71,7 @@ def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
vereq(dict['a'], res)
def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
- if verbose: print "checking", stmt
+ if verbose: print("checking", stmt)
dict = {'a': deepcopy(a), 'b': b, 'c': c}
exec(stmt, dict)
vereq(dict['a'], res)
@@ -89,7 +89,7 @@ def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
vereq(dict['a'], res)
def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
- if verbose: print "checking", stmt
+ if verbose: print("checking", stmt)
dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
exec(stmt, dict)
vereq(dict['a'], res)
@@ -135,7 +135,7 @@ def class_docstrings():
verify(NewDynamic2.__doc__ is None)
def lists():
- if verbose: print "Testing list operations..."
+ if verbose: print("Testing list operations...")
testbinop([1], [2], [1,2], "a+b", "__add__")
testbinop([1,2,3], 2, 1, "b in a", "__contains__")
testbinop([1,2,3], 4, 0, "b in a", "__contains__")
@@ -150,7 +150,7 @@ def lists():
testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
def dicts():
- if verbose: print "Testing dict operations..."
+ if verbose: print("Testing dict operations...")
##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
@@ -175,7 +175,7 @@ def dicts():
def dict_constructor():
if verbose:
- print "Testing dict constructor ..."
+ print("Testing dict constructor ...")
d = dict()
vereq(d, {})
d = dict({})
@@ -258,7 +258,7 @@ def dict_constructor():
def test_dir():
if verbose:
- print "Testing dir() ..."
+ print("Testing dir() ...")
junk = 12
vereq(dir(), ['junk'])
del junk
@@ -413,7 +413,7 @@ def numops(a, b, skip=[]):
testunop(a, res, expr, name)
def ints():
- if verbose: print "Testing int operations..."
+ if verbose: print("Testing int operations...")
numops(100, 3)
# The following crashes in Python 2.2
vereq((1).__bool__(), True)
@@ -431,15 +431,15 @@ def ints():
raise TestFailed, "NotImplemented should have caused TypeError"
def longs():
- if verbose: print "Testing long operations..."
+ if verbose: print("Testing long operations...")
numops(100, 3)
def floats():
- if verbose: print "Testing float operations..."
+ if verbose: print("Testing float operations...")
numops(100.0, 3.0)
def complexes():
- if verbose: print "Testing complex operations..."
+ if verbose: print("Testing complex operations...")
numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
class Number(complex):
__slots__ = ['prec']
@@ -469,7 +469,7 @@ def complexes():
vereq(a.prec, 12)
def spamlists():
- if verbose: print "Testing spamlist operations..."
+ if verbose: print("Testing spamlist operations...")
import copy, xxsubtype as spam
def spamlist(l, memo=None):
import xxsubtype as spam
@@ -505,7 +505,7 @@ def spamlists():
vereq(a.getstate(), 42)
def spamdicts():
- if verbose: print "Testing spamdict operations..."
+ if verbose: print("Testing spamdict operations...")
import copy, xxsubtype as spam
def spamdict(d, memo=None):
import xxsubtype as spam
@@ -550,7 +550,7 @@ def spamdicts():
vereq(a.getstate(), 100)
def pydicts():
- if verbose: print "Testing Python subclass of dict..."
+ if verbose: print("Testing Python subclass of dict...")
verify(issubclass(dict, dict))
verify(isinstance({}, dict))
d = dict()
@@ -591,7 +591,7 @@ def pydicts():
vereq(a[42], 0)
a[42] = 24
vereq(a[42], 24)
- if verbose: print "pydict stress test ..."
+ if verbose: print("pydict stress test ...")
N = 50
for i in range(N):
a[i] = C()
@@ -602,7 +602,7 @@ def pydicts():
vereq(a[i][j], i*j)
def pylists():
- if verbose: print "Testing Python subclass of list..."
+ if verbose: print("Testing Python subclass of list...")
class C(list):
def __getitem__(self, i):
return list.__getitem__(self, i) + 100
@@ -616,7 +616,7 @@ def pylists():
vereq(a[100:200], (100,200))
def metaclass():
- if verbose: print "Testing __metaclass__..."
+ if verbose: print("Testing __metaclass__...")
class C:
__metaclass__ = type
def __init__(self):
@@ -778,7 +778,7 @@ def metaclass():
else: raise TestFailed, "calling object w/o call method should raise TypeError"
def pymods():
- if verbose: print "Testing Python subclass of module..."
+ if verbose: print("Testing Python subclass of module...")
log = []
import sys
MT = type(sys)
@@ -803,7 +803,7 @@ def pymods():
("delattr", "foo")])
def multi():
- if verbose: print "Testing multiple inheritance..."
+ if verbose: print("Testing multiple inheritance...")
class C(object):
def __init__(self):
self.__state = 0
@@ -844,7 +844,7 @@ def multi():
vereq(int(Frag()), 42)
def diamond():
- if verbose: print "Testing multiple inheritance special cases..."
+ if verbose: print("Testing multiple inheritance special cases...")
class A(object):
def spam(self): return "A"
vereq(A().spam(), "A")
@@ -882,7 +882,7 @@ def diamond():
# see thread python-dev/2002-October/029035.html
def ex5():
- if verbose: print "Testing ex5 from C3 switch discussion..."
+ if verbose: print("Testing ex5 from C3 switch discussion...")
class A(object): pass
class B(object): pass
class C(object): pass
@@ -894,7 +894,7 @@ def ex5():
# see "A Monotonic Superclass Linearization for Dylan",
# by Kim Barrett et al. (OOPSLA 1996)
def monotonicity():
- if verbose: print "Testing MRO monotonicity..."
+ if verbose: print("Testing MRO monotonicity...")
class Boat(object): pass
class DayBoat(Boat): pass
class WheelBoat(Boat): pass
@@ -917,7 +917,7 @@ def monotonicity():
# see "A Monotonic Superclass Linearization for Dylan",
# by Kim Barrett et al. (OOPSLA 1996)
def consistency_with_epg():
- if verbose: print "Testing consistentcy with EPG..."
+ if verbose: print("Testing consistentcy with EPG...")
class Pane(object): pass
class ScrollingMixin(object): pass
class EditingMixin(object): pass
@@ -933,7 +933,7 @@ mro_err_msg = """Cannot create a consistent method resolution
order (MRO) for bases """
def mro_disagreement():
- if verbose: print "Testing error messages for MRO disagreement..."
+ if verbose: print("Testing error messages for MRO disagreement...")
def raises(exc, expected, callable, *args):
try:
callable(*args)
@@ -963,7 +963,7 @@ def mro_disagreement():
type, "ConfusedGrid", (HVGrid, VHGrid), {})
def objects():
- if verbose: print "Testing object class..."
+ if verbose: print("Testing object class...")
a = object()
vereq(a.__class__, object)
vereq(type(a), object)
@@ -987,7 +987,7 @@ def objects():
vereq(x.__dict__, {'foo': 1})
def slots():
- if verbose: print "Testing __slots__..."
+ if verbose: print("Testing __slots__...")
class C0(object):
__slots__ = []
x = C0()
@@ -1152,7 +1152,7 @@ def slots():
sys.stderr = save_stderr
def slotspecials():
- if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
+ if verbose: print("Testing __dict__ and __weakref__ in __slots__...")
class D(object):
__slots__ = ["__dict__"]
@@ -1199,7 +1199,7 @@ def slotspecials():
# __slots__ = []
def dynamics():
- if verbose: print "Testing class attribute propagation..."
+ if verbose: print("Testing class attribute propagation...")
class D(object):
pass
class E(D):
@@ -1278,7 +1278,7 @@ def dynamics():
verify(someclass != object)
def errors():
- if verbose: print "Testing errors..."
+ if verbose: print("Testing errors...")
try:
class C(list, dict):
@@ -1323,7 +1323,7 @@ def errors():
verify(0, "__slots__ = [1] should be illegal")
def classmethods():
- if verbose: print "Testing class methods..."
+ if verbose: print("Testing class methods...")
class C(object):
def foo(*a): return a
goo = classmethod(foo)
@@ -1369,7 +1369,7 @@ def classmethods():
raise TestFailed, "classmethod shouldn't accept keyword args"
def classmethods_in_c():
- if verbose: print "Testing C-based class methods..."
+ if verbose: print("Testing C-based class methods...")
import xxsubtype as spam
a = (1, 2, 3)
d = {'abc': 123}
@@ -1383,7 +1383,7 @@ def classmethods_in_c():
vereq(d, d1)
def staticmethods():
- if verbose: print "Testing static methods..."
+ if verbose: print("Testing static methods...")
class C(object):
def foo(*a): return a
goo = staticmethod(foo)
@@ -1400,7 +1400,7 @@ def staticmethods():
vereq(D.foo(d, 1), (d, 1))
def staticmethods_in_c():
- if verbose: print "Testing C-based static methods..."
+ if verbose: print("Testing C-based static methods...")
import xxsubtype as spam
a = (1, 2, 3)
d = {"abc": 123}
@@ -1414,7 +1414,7 @@ def staticmethods_in_c():
vereq(d, d1)
def classic():
- if verbose: print "Testing classic classes..."
+ if verbose: print("Testing classic classes...")
class C:
def foo(*a): return a
goo = classmethod(foo)
@@ -1435,7 +1435,7 @@ def classic():
verify(repr(C.foo.__get__(C())).startswith("<bound method "))
def compattr():
- if verbose: print "Testing computed attributes..."
+ if verbose: print("Testing computed attributes...")
class C(object):
class computed_attribute(object):
def __init__(self, get, set=None, delete=None):
@@ -1469,7 +1469,7 @@ def compattr():
vereq(hasattr(a, 'x'), 0)
def newslot():
- if verbose: print "Testing __new__ slot override..."
+ if verbose: print("Testing __new__ slot override...")
class C(list):
def __new__(cls):
self = list.__new__(cls)
@@ -1487,7 +1487,7 @@ def newslot():
verify(b.__class__ is D)
def altmro():
- if verbose: print "Testing mro() and overriding it..."
+ if verbose: print("Testing mro() and overriding it...")
class A(object):
def f(self): return "A"
class B(A):
@@ -1542,7 +1542,7 @@ def altmro():
def overloading():
- if verbose: print "Testing operator overloading..."
+ if verbose: print("Testing operator overloading...")
class B(object):
"Intermediate class because object doesn't have a __setattr__"
@@ -1599,7 +1599,7 @@ def overloading():
vereq(a.delslice, (0, 10))
def methods():
- if verbose: print "Testing methods..."
+ if verbose: print("Testing methods...")
class C(object):
def __init__(self, x):
self.x = x
@@ -1621,7 +1621,7 @@ def methods():
def specials():
# Test operators like __hash__ for which a built-in default exists
- if verbose: print "Testing special operators..."
+ if verbose: print("Testing special operators...")
# Test the default behavior for static classes
class C(object):
def __getitem__(self, i):
@@ -1782,7 +1782,7 @@ def specials():
sys.stdout = get_original_stdout()
try:
# nothing should actually be printed, this should raise an exception
- print Letter('w')
+ print(Letter('w'))
except RuntimeError:
pass
else:
@@ -1790,7 +1790,7 @@ def specials():
sys.stdout = test_stdout
def weakrefs():
- if verbose: print "Testing weak references..."
+ if verbose: print("Testing weak references...")
import weakref
class C(object):
pass
@@ -1819,7 +1819,7 @@ def weakrefs():
del r
def properties():
- if verbose: print "Testing property..."
+ if verbose: print("Testing property...")
class C(object):
def getx(self):
return self.__x
@@ -1902,7 +1902,7 @@ def properties():
def supers():
- if verbose: print "Testing super..."
+ if verbose: print("Testing super...")
class A(object):
def meth(self, a):
@@ -2018,7 +2018,7 @@ def supers():
raise TestFailed, "super shouldn't accept keyword args"
def inherits():
- if verbose: print "Testing inheritance from basic types..."
+ if verbose: print("Testing inheritance from basic types...")
class hexint(int):
def __repr__(self):
@@ -2362,7 +2362,7 @@ def inherits():
def keywords():
if verbose:
- print "Testing keyword args to basic type constructors ..."
+ print("Testing keyword args to basic type constructors ...")
vereq(int(x=1), 1)
vereq(float(x=2), 2.0)
vereq(int(x=3), 3)
@@ -2388,7 +2388,7 @@ def restricted():
return
import rexec
if verbose:
- print "Testing interaction with restricted execution ..."
+ print("Testing interaction with restricted execution ...")
sandbox = rexec.RExec()
@@ -2428,7 +2428,7 @@ f = t(%r, 'w') # rexec can't catch this by itself
def str_subclass_as_dict_key():
if verbose:
- print "Testing a str subclass used as dict key .."
+ print("Testing a str subclass used as dict key ..")
class cistr(str):
"""Sublcass of str that computes __eq__ case-insensitively.
@@ -2460,11 +2460,11 @@ def str_subclass_as_dict_key():
vereq(d.get(cistr('thrEE')), 3)
def classic_comparisons():
- if verbose: print "Testing classic comparisons..."
+ if verbose: print("Testing classic comparisons...")
class classic:
pass
for base in (classic, int, object):
- if verbose: print " (base = %s)" % base
+ if verbose: print(" (base = %s)" % base)
class C(base):
def __init__(self, value):
self.value = int(value)
@@ -2521,7 +2521,7 @@ def classic_comparisons():
def rich_comparisons():
if verbose:
- print "Testing rich comparisons..."
+ print("Testing rich comparisons...")
class Z(complex):
pass
z = Z(1)
@@ -2540,7 +2540,7 @@ def rich_comparisons():
class classic:
pass
for base in (classic, int, object, list):
- if verbose: print " (base = %s)" % base
+ if verbose: print(" (base = %s)" % base)
class C(base):
def __init__(self, value):
self.value = int(value)
@@ -2598,14 +2598,14 @@ def rich_comparisons():
"x=%d, y=%d" % (x, y))
def descrdoc():
- if verbose: print "Testing descriptor doc strings..."
+ if verbose: print("Testing descriptor doc strings...")
def check(descr, what):
vereq(descr.__doc__, what)
check(file.closed, "True if the file is closed") # getset descriptor
check(file.name, "file name") # member descriptor
def setclass():
- if verbose: print "Testing __class__ assignment..."
+ if verbose: print("Testing __class__ assignment...")
class C(object): pass
class D(object): pass
class E(object): pass
@@ -2647,7 +2647,7 @@ def setclass():
del o
def setdict():
- if verbose: print "Testing __dict__ assignment..."
+ if verbose: print("Testing __dict__ assignment...")
class C(object): pass
a = C()
a.__dict__ = {'b': 1}
@@ -2668,7 +2668,7 @@ def setdict():
def pickles():
if verbose:
- print "Testing pickling and copying new-style classes and objects..."
+ print("Testing pickling and copying new-style classes and objects...")
import pickle
try:
import cPickle
@@ -2733,7 +2733,7 @@ def pickles():
continue # cPickle not found -- skip it
for bin in 0, 1:
if verbose:
- print p.__name__, ["text", "binary"][bin]
+ print(p.__name__, ["text", "binary"][bin])
for cls in C, C1, C2:
s = p.dumps(cls, bin)
@@ -2751,8 +2751,8 @@ def pickles():
vereq(repr(x), repr(a))
vereq(repr(y), repr(b))
if verbose:
- print "a = x =", a
- print "b = y =", b
+ print("a = x =", a)
+ print("b = y =", b)
# Test for __getstate__ and __setstate__ on new style class
u = C3(42)
s = p.dumps(u, bin)
@@ -2769,7 +2769,7 @@ def pickles():
# Testing copy.deepcopy()
if verbose:
- print "deepcopy"
+ print("deepcopy")
import copy
for cls in C, C1, C2:
cls2 = copy.deepcopy(cls)
@@ -2785,11 +2785,11 @@ def pickles():
vereq(repr(x), repr(a))
vereq(repr(y), repr(b))
if verbose:
- print "a = x =", a
- print "b = y =", b
+ print("a = x =", a)
+ print("b = y =", b)
def pickleslots():
- if verbose: print "Testing pickling of classes with __slots__ ..."
+ if verbose: print("Testing pickling of classes with __slots__ ...")
import pickle, pickle as cPickle
# Pickling of classes with __slots__ but without __getstate__ should fail
global B, C, D, E
@@ -2876,7 +2876,7 @@ def pickleslots():
vereq(y.b, x.b)
def copies():
- if verbose: print "Testing copy.copy() and copy.deepcopy()..."
+ if verbose: print("Testing copy.copy() and copy.deepcopy()...")
import copy
class C(object):
pass
@@ -2897,7 +2897,7 @@ def copies():
vereq(d.bar, [1,2,3])
def binopoverride():
- if verbose: print "Testing overrides of binary operations..."
+ if verbose: print("Testing overrides of binary operations...")
class I(int):
def __repr__(self):
return "I(%r)" % int(self)
@@ -2927,7 +2927,7 @@ def binopoverride():
return self.lower() == other.lower()
def subclasspropagation():
- if verbose: print "Testing propagation of slot functions to subclasses..."
+ if verbose: print("Testing propagation of slot functions to subclasses...")
class A(object):
pass
class B(A):
@@ -3000,7 +3000,7 @@ def buffer_inherit():
import binascii
# SF bug [#470040] ParseTuple t# vs subclasses.
if verbose:
- print "Testing that buffer interface is inherited ..."
+ print("Testing that buffer interface is inherited ...")
class MyStr(str):
pass
@@ -3032,7 +3032,7 @@ def str_of_str_subclass():
import cStringIO
if verbose:
- print "Testing __str__ defined in subclass of str ..."
+ print("Testing __str__ defined in subclass of str ...")
class octetstring(str):
def __str__(self):
@@ -3052,13 +3052,13 @@ def str_of_str_subclass():
capture = cStringIO.StringIO()
# Calling str() or not exercises different internal paths.
- print >> capture, o
- print >> capture, str(o)
+ print(o, file=capture)
+ print(str(o), file=capture)
vereq(capture.getvalue(), '41\n41\n')
capture.close()
def kwdargs():
- if verbose: print "Testing keyword arguments to __init__, __call__..."
+ if verbose: print("Testing keyword arguments to __init__, __call__...")
def f(a): return a
vereq(f.__call__(a=42), 42)
a = []
@@ -3066,8 +3066,8 @@ def kwdargs():
vereq(a, [0, 1, 2])
def recursive__call__():
- if verbose: print ("Testing recursive __call__() by setting to instance of "
- "class ...")
+ if verbose: print(("Testing recursive __call__() by setting to instance of "
+ "class ..."))
class A(object):
pass
@@ -3081,7 +3081,7 @@ def recursive__call__():
"__call__()")
def delhook():
- if verbose: print "Testing __del__ hook..."
+ if verbose: print("Testing __del__ hook...")
log = []
class C(object):
def __del__(self):
@@ -3098,7 +3098,7 @@ def delhook():
else: raise TestFailed, "invalid del() didn't raise TypeError"
def hashinherit():
- if verbose: print "Testing hash of mutable subclasses..."
+ if verbose: print("Testing hash of mutable subclasses...")
class mydict(dict):
pass
@@ -3167,7 +3167,7 @@ def strops():
vereq('%c' % '5', '5')
def deepcopyrecursive():
- if verbose: print "Testing deepcopy of recursive objects..."
+ if verbose: print("Testing deepcopy of recursive objects...")
class Node:
pass
a = Node()
@@ -3177,7 +3177,7 @@ def deepcopyrecursive():
z = deepcopy(a) # This blew up before
def modules():
- if verbose: print "Testing uninitialized module objects..."
+ if verbose: print("Testing uninitialized module objects...")
from types import ModuleType as M
m = M.__new__(M)
str(m)
@@ -3192,7 +3192,7 @@ def dictproxyiterkeys():
class C(object):
def meth(self):
pass
- if verbose: print "Testing dict-proxy iterkeys..."
+ if verbose: print("Testing dict-proxy iterkeys...")
keys = [ key for key in C.__dict__.iterkeys() ]
keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
@@ -3201,7 +3201,7 @@ def dictproxyitervalues():
class C(object):
def meth(self):
pass
- if verbose: print "Testing dict-proxy itervalues..."
+ if verbose: print("Testing dict-proxy itervalues...")
values = [ values for values in C.__dict__.itervalues() ]
vereq(len(values), 5)
@@ -3209,13 +3209,13 @@ def dictproxyiteritems():
class C(object):
def meth(self):
pass
- if verbose: print "Testing dict-proxy iteritems..."
+ if verbose: print("Testing dict-proxy iteritems...")
keys = [ key for (key, value) in C.__dict__.iteritems() ]
keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
def funnynew():
- if verbose: print "Testing __new__ returning something unexpected..."
+ if verbose: print("Testing __new__ returning something unexpected...")
class C(object):
def __new__(cls, arg):
if isinstance(arg, str): return [1, 2, 3]
@@ -3237,7 +3237,7 @@ def funnynew():
def imulbug():
# SF bug 544647
- if verbose: print "Testing for __imul__ problems..."
+ if verbose: print("Testing for __imul__ problems...")
class C(object):
def __imul__(self, other):
return (self, other)
@@ -3263,7 +3263,7 @@ def imulbug():
def docdescriptor():
# SF bug 542984
- if verbose: print "Testing __doc__ descriptor..."
+ if verbose: print("Testing __doc__ descriptor...")
class DocDescr(object):
def __get__(self, object, otype):
if object:
@@ -3282,7 +3282,7 @@ def docdescriptor():
def copy_setstate():
if verbose:
- print "Testing that copy.*copy() correctly uses __setstate__..."
+ print("Testing that copy.*copy() correctly uses __setstate__...")
import copy
class C(object):
def __init__(self, foo=None):
@@ -3310,7 +3310,7 @@ def copy_setstate():
def slices():
if verbose:
- print "Testing cases with slices and overridden __getitem__ ..."
+ print("Testing cases with slices and overridden __getitem__ ...")
# Strings
vereq("hello"[:4], "hell")
vereq("hello"[slice(4)], "hell")
@@ -3354,7 +3354,7 @@ def slices():
def subtype_resurrection():
if verbose:
- print "Testing resurrection of new-style instance..."
+ print("Testing resurrection of new-style instance...")
class C(object):
container = []
@@ -3384,7 +3384,7 @@ def subtype_resurrection():
def slottrash():
# Deallocating deeply nested slotted trash caused stack overflows
if verbose:
- print "Testing slot trash..."
+ print("Testing slot trash...")
class trash(object):
__slots__ = ['x']
def __init__(self, x):
@@ -3410,7 +3410,7 @@ def slotmultipleinheritance():
def testrmul():
# SF patch 592646
if verbose:
- print "Testing correct invocation of __rmul__..."
+ print("Testing correct invocation of __rmul__...")
class C(object):
def __mul__(self, other):
return "mul"
@@ -3425,7 +3425,7 @@ def testrmul():
def testipow():
# [SF bug 620179]
if verbose:
- print "Testing correct invocation of __ipow__..."
+ print("Testing correct invocation of __ipow__...")
class C(object):
def __ipow__(self, other):
pass
@@ -3434,7 +3434,7 @@ def testipow():
def do_this_first():
if verbose:
- print "Testing SF bug 551412 ..."
+ print("Testing SF bug 551412 ...")
# This dumps core when SF bug 551412 isn't fixed --
# but only when test_descr.py is run separately.
# (That can't be helped -- as soon as PyType_Ready()
@@ -3448,14 +3448,14 @@ def do_this_first():
pass
if verbose:
- print "Testing SF bug 570483..."
+ print("Testing SF bug 570483...")
# Another segfault only when run early
# (before PyType_Ready(tuple) is called)
type.mro(tuple)
def test_mutable_bases():
if verbose:
- print "Testing mutable bases..."
+ print("Testing mutable bases...")
# stuff that should work:
class C(object):
pass
@@ -3545,7 +3545,7 @@ def test_mutable_bases():
def test_mutable_bases_with_failing_mro():
if verbose:
- print "Testing mutable bases with failing mro..."
+ print("Testing mutable bases with failing mro...")
class WorkOnce(type):
def __new__(self, name, bases, ns):
self.flag = 0
@@ -3600,7 +3600,7 @@ def test_mutable_bases_with_failing_mro():
def test_mutable_bases_catch_mro_conflict():
if verbose:
- print "Testing mutable bases catch mro conflict..."
+ print("Testing mutable bases catch mro conflict...")
class A(object):
pass
@@ -3625,7 +3625,7 @@ def test_mutable_bases_catch_mro_conflict():
def mutable_names():
if verbose:
- print "Testing mutable names..."
+ print("Testing mutable names...")
class C(object):
pass
@@ -3640,7 +3640,7 @@ def mutable_names():
def subclass_right_op():
if verbose:
- print "Testing correct dispatch of subclass overloading __r<op>__..."
+ print("Testing correct dispatch of subclass overloading __r<op>__...")
# This code tests various cases where right-dispatch of a subclass
# should be preferred over left-dispatch of a base class.
@@ -3692,7 +3692,7 @@ def subclass_right_op():
def dict_type_with_metaclass():
if verbose:
- print "Testing type of __dict__ when __metaclass__ set..."
+ print("Testing type of __dict__ when __metaclass__ set...")
class B(object):
pass
@@ -3706,7 +3706,7 @@ def dict_type_with_metaclass():
def meth_class_get():
# Full coverage of descrobject.c::classmethod_get()
if verbose:
- print "Testing __get__ method of METH_CLASS C methods..."
+ print("Testing __get__ method of METH_CLASS C methods...")
# Baseline
arg = [1, 2, 3]
res = {1: None, 2: None, 3: None}
@@ -3745,7 +3745,7 @@ def meth_class_get():
def isinst_isclass():
if verbose:
- print "Testing proxy isinstance() and isclass()..."
+ print("Testing proxy isinstance() and isclass()...")
class Proxy(object):
def __init__(self, obj):
self.__obj = obj
@@ -3785,7 +3785,7 @@ def isinst_isclass():
def proxysuper():
if verbose:
- print "Testing super() for a proxy object..."
+ print("Testing super() for a proxy object...")
class Proxy(object):
def __init__(self, obj):
self.__obj = obj
@@ -3809,7 +3809,7 @@ def proxysuper():
def carloverre():
if verbose:
- print "Testing prohibition of Carlo Verre's hack..."
+ print("Testing prohibition of Carlo Verre's hack...")
try:
object.__setattr__(str, "foo", 42)
except TypeError:
@@ -3826,7 +3826,7 @@ def carloverre():
def weakref_segfault():
# SF 742911
if verbose:
- print "Testing weakref segfault..."
+ print("Testing weakref segfault...")
import weakref
@@ -3854,7 +3854,7 @@ def wrapper_segfault():
# Fix SF #762455, segfault when sys.stdout is changed in getattr
def filefault():
if verbose:
- print "Testing sys.stdout is changed in getattr..."
+ print("Testing sys.stdout is changed in getattr...")
import sys
class StdoutGuard:
def __getattr__(self, attr):
@@ -3862,7 +3862,7 @@ def filefault():
raise RuntimeError("Premature access to sys.stdout.%s" % attr)
sys.stdout = StdoutGuard()
try:
- print "Oops!"
+ print("Oops!")
except RuntimeError:
pass
@@ -3871,7 +3871,7 @@ def vicious_descriptor_nonsense():
# python-dev 2003-04-17, turned into an example & fixed by Michael
# Hudson just less than four months later...
if verbose:
- print "Testing vicious_descriptor_nonsense..."
+ print("Testing vicious_descriptor_nonsense...")
class Evil(object):
def __hash__(self):
@@ -3910,7 +3910,7 @@ def test_init():
def methodwrapper():
# <type 'method-wrapper'> did not support any reflection before 2.5
if verbose:
- print "Testing method-wrapper objects..."
+ print("Testing method-wrapper objects...")
return # XXX should methods really support __eq__?
@@ -3938,7 +3938,7 @@ def methodwrapper():
def notimplemented():
# all binary methods should be able to return a NotImplemented
if verbose:
- print "Testing NotImplemented..."
+ print("Testing NotImplemented...")
import sys
import types
@@ -4098,7 +4098,7 @@ def test_main():
methodwrapper()
notimplemented()
- if verbose: print "All OK"
+ if verbose: print("All OK")
if __name__ == "__main__":
test_main()
diff --git a/Lib/test/test_dis.py b/Lib/test/test_dis.py
index f9a6a07..3916c32 100644
--- a/Lib/test/test_dis.py
+++ b/Lib/test/test_dis.py
@@ -8,7 +8,7 @@ import StringIO
import unittest
def _f(a):
- print a
+ print(a)
return 1
dis_f = """\
diff --git a/Lib/test/test_dl.py b/Lib/test/test_dl.py
index 9c70427..ba5d8bd 100755
--- a/Lib/test/test_dl.py
+++ b/Lib/test/test_dl.py
@@ -16,19 +16,19 @@ sharedlibs = [
for s, func in sharedlibs:
try:
if verbose:
- print 'trying to open:', s,
+ print('trying to open:', s, end=' ')
l = dl.open(s)
except dl.error as err:
if verbose:
- print 'failed', repr(str(err))
+ print('failed', repr(str(err)))
pass
else:
if verbose:
- print 'succeeded...',
+ print('succeeded...', end=' ')
l.call(func)
l.close()
if verbose:
- print 'worked!'
+ print('worked!')
break
else:
raise TestSkipped, 'Could not open any shared libraries'
diff --git a/Lib/test/test_doctest.py b/Lib/test/test_doctest.py
index 56c2449..ac9d00d 100644
--- a/Lib/test/test_doctest.py
+++ b/Lib/test/test_doctest.py
@@ -143,7 +143,7 @@ class _FakeInput:
def readline(self):
line = self.lines.pop(0)
- print line
+ print(line)
return line+'\n'
######################################################################
@@ -2407,7 +2407,7 @@ def test_coverage(coverdir):
trace=0, count=1)
tracer.run('reload(doctest); test_main()')
r = tracer.results()
- print 'Writing coverage results...'
+ print('Writing coverage results...')
r.write_results(show_missing=True, summary=True,
coverdir=coverdir)
diff --git a/Lib/test/test_dummy_thread.py b/Lib/test/test_dummy_thread.py
index f274e0a..288b621 100644
--- a/Lib/test/test_dummy_thread.py
+++ b/Lib/test/test_dummy_thread.py
@@ -72,13 +72,13 @@ class LockTests(unittest.TestCase):
start_time = int(time.time())
_thread.start_new_thread(delay_unlock,(self.lock, DELAY))
if test_support.verbose:
- print
- print "*** Waiting for thread to release the lock "\
- "(approx. %s sec.) ***" % DELAY
+ print()
+ print("*** Waiting for thread to release the lock "\
+ "(approx. %s sec.) ***" % DELAY)
self.lock.acquire()
end_time = int(time.time())
if test_support.verbose:
- print "done"
+ print("done")
self.failUnless((end_time - start_time) >= DELAY,
"Blocking by unconditional acquiring failed.")
@@ -150,9 +150,9 @@ class ThreadTests(unittest.TestCase):
thread_count = 5
testing_queue = Queue.Queue(thread_count)
if test_support.verbose:
- print
- print "*** Testing multiple thread creation "\
- "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)
+ print()
+ print("*** Testing multiple thread creation "\
+ "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count))
for count in xrange(thread_count):
if DELAY:
local_delay = round(random.random(), 1)
@@ -162,7 +162,7 @@ class ThreadTests(unittest.TestCase):
(testing_queue, local_delay))
time.sleep(DELAY)
if test_support.verbose:
- print 'done'
+ print('done')
self.failUnless(testing_queue.qsize() == thread_count,
"Not all %s threads executed properly after %s sec." %
(thread_count, DELAY))
@@ -173,8 +173,8 @@ def test_main(imported_module=None):
_thread = imported_module
DELAY = 2
if test_support.verbose:
- print
- print "*** Using %s as _thread module ***" % _thread
+ print()
+ print("*** Using %s as _thread module ***" % _thread)
test_support.run_unittest(LockTests, MiscTests, ThreadTests)
if __name__ == '__main__':
diff --git a/Lib/test/test_dummy_threading.py b/Lib/test/test_dummy_threading.py
index 3724f1e..90bf6e0 100644
--- a/Lib/test/test_dummy_threading.py
+++ b/Lib/test/test_dummy_threading.py
@@ -17,20 +17,20 @@ class TestThread(_threading.Thread):
#delay = random.random() * 2
delay = 0
if verbose:
- print 'task', self.getName(), 'will run for', delay, 'sec'
+ print('task', self.getName(), 'will run for', delay, 'sec')
sema.acquire()
mutex.acquire()
running = running + 1
if verbose:
- print running, 'tasks are running'
+ print(running, 'tasks are running')
mutex.release()
time.sleep(delay)
if verbose:
- print 'task', self.getName(), 'done'
+ print('task', self.getName(), 'done')
mutex.acquire()
running = running - 1
if verbose:
- print self.getName(), 'is finished.', running, 'tasks are running'
+ print(self.getName(), 'is finished.', running, 'tasks are running')
mutex.release()
sema.release()
@@ -61,11 +61,11 @@ def test_main():
starttasks()
if verbose:
- print 'waiting for all tasks to complete'
+ print('waiting for all tasks to complete')
for t in threads:
t.join()
if verbose:
- print 'all tasks done'
+ print('all tasks done')
diff --git a/Lib/test/test_enumerate.py b/Lib/test/test_enumerate.py
index 4ee8680..6290070 100644
--- a/Lib/test/test_enumerate.py
+++ b/Lib/test/test_enumerate.py
@@ -208,7 +208,7 @@ def test_main(verbose=None):
for i in xrange(len(counts)):
test_support.run_unittest(*testclasses)
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_errno.py b/Lib/test/test_errno.py
index 6b02e25..25937dc 100755
--- a/Lib/test/test_errno.py
+++ b/Lib/test/test_errno.py
@@ -43,7 +43,7 @@ for error in errors:
a = getattr(errno, error)
except AttributeError:
if verbose:
- print '%s: not found' % error
+ print('%s: not found' % error)
else:
if verbose:
- print '%s: %d' % (error, a)
+ print('%s: %d' % (error, a))
diff --git a/Lib/test/test_extcall.py b/Lib/test/test_extcall.py
index 11cf43a..e67b3f8 100644
--- a/Lib/test/test_extcall.py
+++ b/Lib/test/test_extcall.py
@@ -2,16 +2,16 @@ from test.test_support import verify, verbose, TestFailed, sortdict
from UserList import UserList
def e(a, b):
- print a, b
+ print(a, b)
def f(*a, **k):
- print a, sortdict(k)
+ print(a, sortdict(k))
def g(x, *y, **z):
- print x, y, sortdict(z)
+ print(x, y, sortdict(z))
def h(j=1, a=2, h=3):
- print j, a, h
+ print(j, a, h)
f()
f(1)
@@ -31,28 +31,28 @@ try:
except TypeError:
pass
else:
- print "should raise TypeError: e() got an unexpected keyword argument 'c'"
+ print("should raise TypeError: e() got an unexpected keyword argument 'c'")
try:
g()
except TypeError as err:
- print "TypeError:", err
+ print("TypeError:", err)
else:
- print "should raise TypeError: not enough arguments; expected 1, got 0"
+ print("should raise TypeError: not enough arguments; expected 1, got 0")
try:
g(*())
except TypeError as err:
- print "TypeError:", err
+ print("TypeError:", err)
else:
- print "should raise TypeError: not enough arguments; expected 1, got 0"
+ print("should raise TypeError: not enough arguments; expected 1, got 0")
try:
g(*(), **{})
except TypeError as err:
- print "TypeError:", err
+ print("TypeError:", err)
else:
- print "should raise TypeError: not enough arguments; expected 1, got 0"
+ print("should raise TypeError: not enough arguments; expected 1, got 0")
g(1)
g(1, 2)
@@ -64,7 +64,7 @@ try:
except TypeError as attr:
pass
else:
- print "should raise TypeError"
+ print("should raise TypeError")
class Nothing:
def __len__(self):
@@ -74,7 +74,7 @@ try:
except TypeError as attr:
pass
else:
- print "should raise TypeError"
+ print("should raise TypeError")
class Nothing:
def __len__(self):
@@ -96,7 +96,7 @@ try:
except TypeError as attr:
pass
else:
- print "should raise TypeError"
+ print("should raise TypeError")
class Nothing:
def __init__(self):
@@ -116,8 +116,8 @@ d = {'a': 1, 'b': 2, 'c': 3}
d2 = d.copy()
verify(d == d2)
g(1, d=4, **d)
-print sortdict(d)
-print sortdict(d2)
+print(sortdict(d))
+print(sortdict(d2))
verify(d == d2, "function call modified dictionary")
# what about willful misconduct?
@@ -133,79 +133,79 @@ del kw['x']
try:
g(1, 2, 3, **{'x':4, 'y':5})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: keyword parameter redefined"
+ print("should raise TypeError: keyword parameter redefined")
try:
g(1, 2, 3, a=4, b=5, *(6, 7), **{'a':8, 'b':9})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: keyword parameter redefined"
+ print("should raise TypeError: keyword parameter redefined")
try:
f(**{1:2})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: keywords must be strings"
+ print("should raise TypeError: keywords must be strings")
try:
h(**{'e': 2})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: unexpected keyword argument: e"
+ print("should raise TypeError: unexpected keyword argument: e")
try:
h(*h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: * argument must be a tuple"
+ print("should raise TypeError: * argument must be a tuple")
try:
dir(*h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: * argument must be a tuple"
+ print("should raise TypeError: * argument must be a tuple")
try:
None(*h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: * argument must be a tuple"
+ print("should raise TypeError: * argument must be a tuple")
try:
h(**h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: ** argument must be a dictionary"
+ print("should raise TypeError: ** argument must be a dictionary")
try:
dir(**h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: ** argument must be a dictionary"
+ print("should raise TypeError: ** argument must be a dictionary")
try:
None(**h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: ** argument must be a dictionary"
+ print("should raise TypeError: ** argument must be a dictionary")
try:
dir(b=1,**{'b':1})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: dir() got multiple values for keyword argument 'b'"
+ print("should raise TypeError: dir() got multiple values for keyword argument 'b'")
def f2(*a, **b):
return a, b
@@ -215,27 +215,27 @@ for i in range(512):
key = 'k%d' % i
d[key] = i
a, b = f2(1, *(2, 3), **d)
-print len(a), len(b), b == d
+print(len(a), len(b), b == d)
class Foo:
def method(self, arg1, arg2):
return arg1 + arg2
x = Foo()
-print Foo.method(*(x, 1, 2))
-print Foo.method(x, *(1, 2))
+print(Foo.method(*(x, 1, 2)))
+print(Foo.method(x, *(1, 2)))
try:
- print Foo.method(*(1, 2, 3))
+ print(Foo.method(*(1, 2, 3)))
except TypeError as err:
pass
else:
- print 'expected a TypeError for unbound method call'
+ print('expected a TypeError for unbound method call')
try:
- print Foo.method(1, *(2, 3))
+ print(Foo.method(1, *(2, 3)))
except TypeError as err:
pass
else:
- print 'expected a TypeError for unbound method call'
+ print('expected a TypeError for unbound method call')
# A PyCFunction that takes only positional parameters should allow an
# empty keyword dictionary to pass without a complaint, but raise a
@@ -274,6 +274,6 @@ for name in ['za', 'zade', 'zabk', 'zabdv', 'zabdevk']:
for kwargs in ['', 'a', 'd', 'ad', 'abde']:
kwdict = {}
for k in kwargs: kwdict[k] = k + k
- print func.func_name, args, sortdict(kwdict), '->',
+ print(func.func_name, args, sortdict(kwdict), '->', end=' ')
try: func(*args, **kwdict)
- except TypeError as err: print err
+ except TypeError as err: print(err)
diff --git a/Lib/test/test_fcntl.py b/Lib/test/test_fcntl.py
index 2d800b2..f544f1f 100755
--- a/Lib/test/test_fcntl.py
+++ b/Lib/test/test_fcntl.py
@@ -41,18 +41,18 @@ else:
lockdata = struct.pack('hh'+start_len+'hh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
if lockdata:
if verbose:
- print 'struct.pack: ', repr(lockdata)
+ print('struct.pack: ', repr(lockdata))
# the example from the library docs
f = open(filename, 'w')
rv = fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
if verbose:
- print 'Status from fcntl with O_NONBLOCK: ', rv
+ print('Status from fcntl with O_NONBLOCK: ', rv)
if sys.platform not in ['os2emx']:
rv = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, lockdata)
if verbose:
- print 'String from fcntl with F_SETLKW: ', repr(rv)
+ print('String from fcntl with F_SETLKW: ', repr(rv))
f.close()
os.unlink(filename)
diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py
index 52c4a02..91f6e76 100644
--- a/Lib/test/test_file.py
+++ b/Lib/test/test_file.py
@@ -142,9 +142,9 @@ class OtherFileTests(unittest.TestCase):
if sys.platform != 'osf1V5':
self.assertRaises(IOError, sys.stdin.seek, -1)
else:
- print >>sys.__stdout__, (
+ print((
' Skipping sys.stdin.seek(-1), it may crash the interpreter.'
- ' Test manually.')
+ ' Test manually.'), file=sys.__stdout__)
self.assertRaises(IOError, sys.stdin.truncate)
def testUnicodeOpen(self):
diff --git a/Lib/test/test_fileinput.py b/Lib/test/test_fileinput.py
index 301769e..2b7b255 100644
--- a/Lib/test/test_fileinput.py
+++ b/Lib/test/test_fileinput.py
@@ -34,7 +34,7 @@ def remove_tempfiles(*names):
def runTests(t1, t2, t3, t4, bs=0, round=0):
start = 1 + round*6
if verbose:
- print '%s. Simple iteration (bs=%s)' % (start+0, bs)
+ print('%s. Simple iteration (bs=%s)' % (start+0, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
lines = list(fi)
fi.close()
@@ -45,7 +45,7 @@ def runTests(t1, t2, t3, t4, bs=0, round=0):
verify(fi.filename() == t4)
if verbose:
- print '%s. Status variables (bs=%s)' % (start+1, bs)
+ print('%s. Status variables (bs=%s)' % (start+1, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
s = "x"
while s and s != 'Line 6 of file 2\n':
@@ -57,14 +57,14 @@ def runTests(t1, t2, t3, t4, bs=0, round=0):
verify(not fi.isstdin())
if verbose:
- print '%s. Nextfile (bs=%s)' % (start+2, bs)
+ print('%s. Nextfile (bs=%s)' % (start+2, bs))
fi.nextfile()
verify(fi.readline() == 'Line 1 of file 3\n')
verify(fi.lineno() == 22)
fi.close()
if verbose:
- print '%s. Stdin (bs=%s)' % (start+3, bs)
+ print('%s. Stdin (bs=%s)' % (start+3, bs))
fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs)
savestdin = sys.stdin
try:
@@ -78,7 +78,7 @@ def runTests(t1, t2, t3, t4, bs=0, round=0):
sys.stdin = savestdin
if verbose:
- print '%s. Boundary conditions (bs=%s)' % (start+4, bs)
+ print('%s. Boundary conditions (bs=%s)' % (start+4, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
verify(fi.lineno() == 0)
verify(fi.filename() == None)
@@ -87,13 +87,13 @@ def runTests(t1, t2, t3, t4, bs=0, round=0):
verify(fi.filename() == None)
if verbose:
- print '%s. Inplace (bs=%s)' % (start+5, bs)
+ print('%s. Inplace (bs=%s)' % (start+5, bs))
savestdout = sys.stdout
try:
fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs)
for line in fi:
line = line[:-1].upper()
- print line
+ print(line)
fi.close()
finally:
sys.stdout = savestdout
@@ -124,7 +124,7 @@ for round, bs in (0, 0), (1, 30):
# Next, check for proper behavior with 0-byte files.
if verbose:
- print "13. 0-byte files"
+ print("13. 0-byte files")
try:
t1 = writeTmp(1, [""])
t2 = writeTmp(2, [""])
@@ -146,7 +146,7 @@ finally:
remove_tempfiles(t1, t2, t3, t4)
if verbose:
- print "14. Files that don't end with newline"
+ print("14. Files that don't end with newline")
try:
t1 = writeTmp(1, ["A\nB\nC"])
t2 = writeTmp(2, ["D\nE\nF"])
@@ -159,7 +159,7 @@ finally:
remove_tempfiles(t1, t2)
if verbose:
- print "15. Unicode filenames"
+ print("15. Unicode filenames")
try:
t1 = writeTmp(1, ["A\nB"])
encoding = sys.getfilesystemencoding()
@@ -172,7 +172,7 @@ finally:
remove_tempfiles(t1)
if verbose:
- print "16. fileno()"
+ print("16. fileno()")
try:
t1 = writeTmp(1, ["A\nB"])
t2 = writeTmp(2, ["C\nD"])
@@ -188,7 +188,7 @@ finally:
remove_tempfiles(t1, t2)
if verbose:
- print "17. Specify opening mode"
+ print("17. Specify opening mode")
try:
# invalid mode, should raise ValueError
fi = FileInput(mode="w")
@@ -205,7 +205,7 @@ finally:
remove_tempfiles(t1)
if verbose:
- print "18. Test file opening hook"
+ print("18. Test file opening hook")
try:
# cannot use openhook and inplace mode
fi = FileInput(inplace=1, openhook=lambda f,m: None)
diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py
index df78a32..658a302 100644
--- a/Lib/test/test_format.py
+++ b/Lib/test/test_format.py
@@ -11,26 +11,26 @@ overflowok = 1
def testformat(formatstr, args, output=None):
if verbose:
if output:
- print "%s %% %s =? %s ..." %\
- (repr(formatstr), repr(args), repr(output)),
+ print("%s %% %s =? %s ..." %\
+ (repr(formatstr), repr(args), repr(output)), end=' ')
else:
- print "%s %% %s works? ..." % (repr(formatstr), repr(args)),
+ print("%s %% %s works? ..." % (repr(formatstr), repr(args)), end=' ')
try:
result = formatstr % args
except OverflowError:
if not overflowok:
raise
if verbose:
- print 'overflow (this is fine)'
+ print('overflow (this is fine)')
else:
if output and result != output:
if verbose:
- print 'no'
- print "%s %% %s == %s != %s" %\
- (repr(formatstr), repr(args), repr(result), repr(output))
+ print('no')
+ print("%s %% %s == %s != %s" %\
+ (repr(formatstr), repr(args), repr(result), repr(output)))
else:
if verbose:
- print 'yes'
+ print('yes')
def testboth(formatstr, *args):
testformat(formatstr, *args)
@@ -194,7 +194,7 @@ testboth("%o", -042, "-42")
# Test exception for unknown format characters
if verbose:
- print 'Testing exceptions'
+ print('Testing exceptions')
def test_exc(formatstr, args, exception, excmsg):
try:
@@ -202,13 +202,13 @@ def test_exc(formatstr, args, exception, excmsg):
except exception as exc:
if str(exc) == excmsg:
if verbose:
- print "yes"
+ print("yes")
else:
- if verbose: print 'no'
- print 'Unexpected ', exception, ':', repr(str(exc))
+ if verbose: print('no')
+ print('Unexpected ', exception, ':', repr(str(exc)))
except:
- if verbose: print 'no'
- print 'Unexpected exception'
+ if verbose: print('no')
+ print('Unexpected exception')
raise
else:
raise TestFailed, 'did not get expected exception: %s' % excmsg
diff --git a/Lib/test/test_funcattrs.py b/Lib/test/test_funcattrs.py
index 930c851..2f4b67a 100644
--- a/Lib/test/test_funcattrs.py
+++ b/Lib/test/test_funcattrs.py
@@ -204,7 +204,7 @@ def bar():
pass
def temp():
- print 1
+ print(1)
if foo==bar:
raise TestFailed
@@ -235,7 +235,7 @@ def cantset(obj, name, value, exception=(AttributeError, TypeError)):
def test_func_closure():
a = 12
- def f(): print a
+ def f(): print(a)
c = f.func_closure
verify(isinstance(c, tuple))
verify(len(c) == 1)
@@ -284,10 +284,10 @@ def test_func_name():
def test_func_code():
a = b = 24
def f(): pass
- def g(): print 12
- def f1(): print a
- def g1(): print b
- def f2(): print a, b
+ def g(): print(12)
+ def f1(): print(a)
+ def g1(): print(b)
+ def f2(): print(a, b)
verify(type(f.func_code) is types.CodeType)
f.func_code = g.func_code
cantset(f, "func_code", None)
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index 828331e..2d5e33c 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -356,7 +356,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == '__main__':
test_main(verbose=True)
diff --git a/Lib/test/test_gc.py b/Lib/test/test_gc.py
index 675b988..8068b35 100644
--- a/Lib/test/test_gc.py
+++ b/Lib/test/test_gc.py
@@ -14,10 +14,10 @@ def expect_nonzero(actual, name):
def run_test(name, thunk):
if verbose:
- print "testing %s..." % name,
+ print("testing %s..." % name, end=' ')
thunk()
if verbose:
- print "ok"
+ print("ok")
def test_list():
l = []
@@ -612,7 +612,7 @@ def test_all():
def test():
if verbose:
- print "disabling automatic collection"
+ print("disabling automatic collection")
enabled = gc.isenabled()
gc.disable()
verify(not gc.isenabled())
@@ -625,7 +625,7 @@ def test():
gc.set_debug(debug)
# test gc.enable() even if GC is disabled by default
if verbose:
- print "restoring automatic collection"
+ print("restoring automatic collection")
# make sure to always test gc.enable()
gc.enable()
verify(gc.isenabled())
diff --git a/Lib/test/test_gdbm.py b/Lib/test/test_gdbm.py
index a689576..ae76e39 100755
--- a/Lib/test/test_gdbm.py
+++ b/Lib/test/test_gdbm.py
@@ -15,7 +15,7 @@ g['a'] = 'b'
g['12345678910'] = '019237410982340912840198242'
a = g.keys()
if verbose:
- print 'Test gdbm file keys: ', a
+ print('Test gdbm file keys: ', a)
'a' in g
g.close()
diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py
index a40d8ea..39d016c 100644
--- a/Lib/test/test_generators.py
+++ b/Lib/test/test_generators.py
@@ -1082,12 +1082,12 @@ class Queens:
n = self.n
assert n == len(row2col)
sep = "+" + "-+" * n
- print sep
+ print(sep)
for i in range(n):
squares = [" " for j in range(n)]
squares[row2col[i]] = "Q"
- print "|" + "|".join(squares) + "|"
- print sep
+ print("|" + "|".join(squares) + "|")
+ print(sep)
# A conjoin-based Knight's Tour solver. This is pretty sophisticated
# (e.g., when used with flat_conjoin above, and passing hard=1 to the
@@ -1279,11 +1279,11 @@ class Knights:
k += 1
sep = "+" + ("-" * w + "+") * n
- print sep
+ print(sep)
for i in range(m):
row = squares[i]
- print "|" + "|".join(row) + "|"
- print sep
+ print("|" + "|".join(row) + "|")
+ print(sep)
conjoin_tests = """
diff --git a/Lib/test/test_genexps.py b/Lib/test/test_genexps.py
index 2598a79..5fd9c7b 100644
--- a/Lib/test/test_genexps.py
+++ b/Lib/test/test_genexps.py
@@ -274,7 +274,7 @@ def test_main(verbose=None):
test_support.run_doctest(test_genexps, verbose)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_getopt.py b/Lib/test/test_getopt.py
index f565d23..10bd256 100644
--- a/Lib/test/test_getopt.py
+++ b/Lib/test/test_getopt.py
@@ -21,14 +21,14 @@ if old_posixly_correct is not None:
del os.environ["POSIXLY_CORRECT"]
if verbose:
- print 'Running tests on getopt.short_has_arg'
+ print('Running tests on getopt.short_has_arg')
verify(getopt.short_has_arg('a', 'a:'))
verify(not getopt.short_has_arg('a', 'a'))
expectException("tmp = getopt.short_has_arg('a', 'b')", GetoptError)
expectException("tmp = getopt.short_has_arg('a', '')", GetoptError)
if verbose:
- print 'Running tests on getopt.long_has_args'
+ print('Running tests on getopt.long_has_args')
has_arg, option = getopt.long_has_args('abc', ['abc='])
verify(has_arg)
verify(option == 'abc')
@@ -47,7 +47,7 @@ expectException("has_arg, option = " + \
GetoptError)
if verbose:
- print 'Running tests on getopt.do_shorts'
+ print('Running tests on getopt.do_shorts')
opts, args = getopt.do_shorts([], 'a', 'a', [])
verify(opts == [('-a', '')])
verify(args == [])
@@ -69,7 +69,7 @@ expectException("opts, args = getopt.do_shorts([], 'a', 'a:', [])",
GetoptError)
if verbose:
- print 'Running tests on getopt.do_longs'
+ print('Running tests on getopt.do_longs')
opts, args = getopt.do_longs([], 'abc', ['abc'], [])
verify(opts == [('--abc', '')])
verify(args == [])
@@ -99,7 +99,7 @@ cmdline = ['-a', '1', '-b', '--alpha=2', '--beta', '-a', '3', '-a', '',
'--beta', 'arg1', 'arg2']
if verbose:
- print 'Running tests on getopt.getopt'
+ print('Running tests on getopt.getopt')
opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta'])
verify(opts == [('-a', '1'), ('-b', ''), ('--alpha', '2'), ('--beta', ''),
('-a', '3'), ('-a', ''), ('--beta', '')] )
@@ -113,7 +113,7 @@ expectException(
# Test handling of GNU style scanning mode.
if verbose:
- print 'Running tests on getopt.gnu_getopt'
+ print('Running tests on getopt.gnu_getopt')
cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2']
# GNU style
opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
@@ -177,4 +177,4 @@ run_doctest(sys.modules[__name__], verbose)
#------------------------------------------------------------------------------
if verbose:
- print "Module getopt: tests completed successfully."
+ print("Module getopt: tests completed successfully.")
diff --git a/Lib/test/test_gl.py b/Lib/test/test_gl.py
index c9cce77..adae10e 100755
--- a/Lib/test/test_gl.py
+++ b/Lib/test/test_gl.py
@@ -91,60 +91,60 @@ def main():
# touch all the attributes of gl without doing anything
if verbose:
- print 'Touching gl module attributes...'
+ print('Touching gl module attributes...')
for attr in glattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(gl, attr)
# create a small 'Crisscross' window
if verbose:
- print 'Creating a small "CrissCross" window...'
- print 'foreground'
+ print('Creating a small "CrissCross" window...')
+ print('foreground')
gl.foreground()
if verbose:
- print 'prefposition'
+ print('prefposition')
gl.prefposition(500, 900, 500, 900)
if verbose:
- print 'winopen "CrissCross"'
+ print('winopen "CrissCross"')
w = gl.winopen('CrissCross')
if verbose:
- print 'clear'
+ print('clear')
gl.clear()
if verbose:
- print 'ortho2'
+ print('ortho2')
gl.ortho2(0.0, 400.0, 0.0, 400.0)
if verbose:
- print 'color WHITE'
+ print('color WHITE')
gl.color(GL.WHITE)
if verbose:
- print 'color RED'
+ print('color RED')
gl.color(GL.RED)
if verbose:
- print 'bgnline'
+ print('bgnline')
gl.bgnline()
if verbose:
- print 'v2f'
+ print('v2f')
gl.v2f(0.0, 0.0)
gl.v2f(400.0, 400.0)
if verbose:
- print 'endline'
+ print('endline')
gl.endline()
if verbose:
- print 'bgnline'
+ print('bgnline')
gl.bgnline()
if verbose:
- print 'v2i'
+ print('v2i')
gl.v2i(400, 0)
gl.v2i(0, 400)
if verbose:
- print 'endline'
+ print('endline')
gl.endline()
if verbose:
- print 'Displaying window for 2 seconds...'
+ print('Displaying window for 2 seconds...')
time.sleep(2)
if verbose:
- print 'winclose'
+ print('winclose')
gl.winclose(w)
main()
diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py
index 33bfd32..4a480aa 100644
--- a/Lib/test/test_grammar.py
+++ b/Lib/test/test_grammar.py
@@ -351,7 +351,7 @@ class GrammarTests(unittest.TestCase):
x = 1; pass; del x;
foo()
- ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
+ ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
# Tested below
def testExprStmt(self):
@@ -367,76 +367,6 @@ class GrammarTests(unittest.TestCase):
check_syntax_error(self, "x + 1 = 1")
check_syntax_error(self, "a + 1 = b + 2")
- def testPrintStmt(self):
- # 'print' (test ',')* [test]
- import StringIO
-
- # Can't test printing to real stdout without comparing output
- # which is not available in unittest.
- save_stdout = sys.stdout
- sys.stdout = StringIO.StringIO()
-
- print 1, 2, 3
- print 1, 2, 3,
- print
- print 0 or 1, 0 or 1,
- print 0 or 1
-
- # 'print' '>>' test ','
- print >> sys.stdout, 1, 2, 3
- print >> sys.stdout, 1, 2, 3,
- print >> sys.stdout
- print >> sys.stdout, 0 or 1, 0 or 1,
- print >> sys.stdout, 0 or 1
-
- # test printing to an instance
- class Gulp:
- def write(self, msg): pass
-
- gulp = Gulp()
- print >> gulp, 1, 2, 3
- print >> gulp, 1, 2, 3,
- print >> gulp
- print >> gulp, 0 or 1, 0 or 1,
- print >> gulp, 0 or 1
-
- # test print >> None
- def driver():
- oldstdout = sys.stdout
- sys.stdout = Gulp()
- try:
- tellme(Gulp())
- tellme()
- finally:
- sys.stdout = oldstdout
-
- # we should see this once
- def tellme(file=sys.stdout):
- print >> file, 'hello world'
-
- driver()
-
- # we should not see this at all
- def tellme(file=None):
- print >> file, 'goodbye universe'
-
- driver()
-
- self.assertEqual(sys.stdout.getvalue(), '''\
-1 2 3
-1 2 3
-1 1 1
-1 2 3
-1 2 3
-1 1 1
-hello world
-''')
- sys.stdout = save_stdout
-
- # syntax errors
- check_syntax_error(self, 'print ,')
- check_syntax_error(self, 'print >> x,')
-
def testDelStmt(self):
# 'del' exprlist
abc = [1,2,3]
@@ -902,7 +832,7 @@ hello world
# Test ifelse expressions in various cases
def _checkeval(msg, ret):
"helper to check that evaluation of expressions is done correctly"
- print x
+ print(x)
return ret
self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py
index b652d41..934f7b6 100644
--- a/Lib/test/test_heapq.py
+++ b/Lib/test/test_heapq.py
@@ -281,7 +281,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_imageop.py b/Lib/test/test_imageop.py
index b01e83f..d079473 100755
--- a/Lib/test/test_imageop.py
+++ b/Lib/test/test_imageop.py
@@ -28,7 +28,7 @@ def main(use_rgbimg=1):
# Return the selected part of image, which should by width by height
# in size and consist of pixels of psize bytes.
if verbose:
- print 'crop'
+ print('crop')
newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1)
# Return image scaled to size newwidth by newheight. No interpolation
@@ -36,7 +36,7 @@ def main(use_rgbimg=1):
# Therefore, computer-generated images or dithered images will
# not look nice after scaling.
if verbose:
- print 'scale'
+ print('scale')
scaleimage = imageop.scale(image, 4, width, height, 1, 1)
# Run a vertical low-pass filter over an image. It does so by computing
@@ -44,34 +44,34 @@ def main(use_rgbimg=1):
# pixels. The main use of this routine is to forestall excessive flicker
# if the image two vertically-aligned source pixels, hence the name.
if verbose:
- print 'tovideo'
+ print('tovideo')
videoimage = imageop.tovideo (image, 4, width, height)
# Convert an rgb image to an 8 bit rgb
if verbose:
- print 'rgb2rgb8'
+ print('rgb2rgb8')
greyimage = imageop.rgb2rgb8(image, width, height)
# Convert an 8 bit rgb image to a 24 bit rgb image
if verbose:
- print 'rgb82rgb'
+ print('rgb82rgb')
image = imageop.rgb82rgb(greyimage, width, height)
# Convert an rgb image to an 8 bit greyscale image
if verbose:
- print 'rgb2grey'
+ print('rgb2grey')
greyimage = imageop.rgb2grey(image, width, height)
# Convert an 8 bit greyscale image to a 24 bit rgb image
if verbose:
- print 'grey2rgb'
+ print('grey2rgb')
image = imageop.grey2rgb(greyimage, width, height)
# Convert a 8-bit deep greyscale image to a 1-bit deep image by
# thresholding all the pixels. The resulting image is tightly packed
# and is probably only useful as an argument to mono2grey.
if verbose:
- print 'grey2mono'
+ print('grey2mono')
monoimage = imageop.grey2mono (greyimage, width, height, 0)
# monoimage, width, height = getimage('monotest.rgb')
@@ -81,42 +81,42 @@ def main(use_rgbimg=1):
# monochrome black-and-white image to greyscale pass the values 0 and
# 255 respectively.
if verbose:
- print 'mono2grey'
+ print('mono2grey')
greyimage = imageop.mono2grey (monoimage, width, height, 0, 255)
# Convert an 8-bit greyscale image to a 1-bit monochrome image using a
# (simple-minded) dithering algorithm.
if verbose:
- print 'dither2mono'
+ print('dither2mono')
monoimage = imageop.dither2mono (greyimage, width, height)
# Convert an 8-bit greyscale image to a 4-bit greyscale image without
# dithering.
if verbose:
- print 'grey2grey4'
+ print('grey2grey4')
grey4image = imageop.grey2grey4 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image without
# dithering.
if verbose:
- print 'grey2grey2'
+ print('grey2grey2')
grey2image = imageop.grey2grey2 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image with
# dithering. As for dither2mono, the dithering algorithm is currently
# very simple.
if verbose:
- print 'dither2grey2'
+ print('dither2grey2')
grey2image = imageop.dither2grey2 (greyimage, width, height)
# Convert a 4-bit greyscale image to an 8-bit greyscale image.
if verbose:
- print 'grey42grey'
+ print('grey42grey')
greyimage = imageop.grey42grey (grey4image, width, height)
# Convert a 2-bit greyscale image to an 8-bit greyscale image.
if verbose:
- print 'grey22grey'
+ print('grey22grey')
image = imageop.grey22grey (grey2image, width, height)
# Cleanup
@@ -134,7 +134,7 @@ def getrgbimage(name):
name = get_qualified_path(name)
sizes = rgbimg.sizeofimage(name)
if verbose:
- print 'rgbimg opening test image: %s, sizes: %s' % (name, str(sizes))
+ print('rgbimg opening test image: %s, sizes: %s' % (name, str(sizes)))
image = rgbimg.longimagedata(name)
return (image, sizes[0], sizes[1])
@@ -152,7 +152,7 @@ def getimage(name):
name = get_qualified_path(name)
sizes = imgfile.getsizes(name)
if verbose:
- print 'imgfile opening test image: %s, sizes: %s' % (name, str(sizes))
+ print('imgfile opening test image: %s, sizes: %s' % (name, str(sizes)))
image = imgfile.read(name)
return (image, sizes[0], sizes[1])
diff --git a/Lib/test/test_imgfile.py b/Lib/test/test_imgfile.py
index bdfd796..4e31cb1 100755
--- a/Lib/test/test_imgfile.py
+++ b/Lib/test/test_imgfile.py
@@ -51,7 +51,7 @@ def testimage(name):
name = os.sep.join(parts)
sizes = imgfile.getsizes(name)
if verbose:
- print 'Opening test image: %s, sizes: %s' % (name, str(sizes))
+ print('Opening test image: %s, sizes: %s' % (name, str(sizes)))
# This function reads and decodes the image on the specified file,
# and returns it as a python string. The string has either 1 byte
# greyscale pixels or 4 byte RGBA pixels. The bottom left pixel
@@ -65,12 +65,12 @@ def testimage(name):
# are stored as 4 byte values of which only the lower three
# bytes are used). These are the formats returned by gl.lrectread.
if verbose:
- print 'Writing output file'
+ print('Writing output file')
imgfile.write (outputfile, image, sizes[0], sizes[1], sizes[2])
if verbose:
- print 'Opening scaled test image: %s, sizes: %s' % (name, str(sizes))
+ print('Opening scaled test image: %s, sizes: %s' % (name, str(sizes)))
# This function is identical to read but it returns an image that
# is scaled to the given x and y sizes. If the filter and blur
# parameters are omitted scaling is done by simply dropping
@@ -84,7 +84,7 @@ def testimage(name):
# makes no attempt to keep the aspect ratio correct, so that
# is the users' responsibility.
if verbose:
- print 'Filtering with "impulse"'
+ print('Filtering with "impulse"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'impulse', 2.0)
# This function sets a global flag which defines whether the
@@ -92,23 +92,23 @@ def testimage(name):
# top (flag is zero, compatible with SGI GL) or from top to
# bottom(flag is one, compatible with X). The default is zero.
if verbose:
- print 'Switching to X compatibility'
+ print('Switching to X compatibility')
imgfile.ttob (1)
if verbose:
- print 'Filtering with "triangle"'
+ print('Filtering with "triangle"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'triangle', 3.0)
if verbose:
- print 'Switching back to SGI compatibility'
+ print('Switching back to SGI compatibility')
imgfile.ttob (0)
- if verbose: print 'Filtering with "quadratic"'
+ if verbose: print('Filtering with "quadratic"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'quadratic')
- if verbose: print 'Filtering with "gaussian"'
+ if verbose: print('Filtering with "gaussian"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'gaussian', 1.0)
if verbose:
- print 'Writing output file'
+ print('Writing output file')
imgfile.write (outputfile, simage, sizes[0]/2, sizes[1]/2, sizes[2])
os.unlink(outputfile)
diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py
index f3d1d49..a8f912f 100644
--- a/Lib/test/test_import.py
+++ b/Lib/test/test_import.py
@@ -45,11 +45,11 @@ class ImportTest(unittest.TestCase):
pyc = TESTFN + os.extsep + "pyc"
f = open(source, "w")
- print >> f, "# This tests Python's ability to import a", ext, "file."
+ print("# This tests Python's ability to import a", ext, "file.", file=f)
a = random.randrange(1000)
b = random.randrange(1000)
- print >> f, "a =", a
- print >> f, "b =", b
+ print("a =", a, file=f)
+ print("b =", b, file=f)
f.close()
try:
@@ -130,7 +130,7 @@ class ImportTest(unittest.TestCase):
def test_failing_import_sticks(self):
source = TESTFN + os.extsep + "py"
f = open(source, "w")
- print >> f, "a = 1/0"
+ print("a = 1/0", file=f)
f.close()
# New in 2.4, we shouldn't be able to import that no matter how often
@@ -153,8 +153,8 @@ class ImportTest(unittest.TestCase):
# A failing reload should leave the module object in sys.modules.
source = TESTFN + os.extsep + "py"
f = open(source, "w")
- print >> f, "a = 1"
- print >> f, "b = 2"
+ print("a = 1", file=f)
+ print("b = 2", file=f)
f.close()
sys.path.insert(0, os.curdir)
@@ -172,8 +172,8 @@ class ImportTest(unittest.TestCase):
# Now damage the module.
f = open(source, "w")
- print >> f, "a = 10"
- print >> f, "b = 20//0"
+ print("a = 10", file=f)
+ print("b = 20//0", file=f)
f.close()
self.assertRaises(ZeroDivisionError, reload, mod)
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index 0b9f165..5a1d4a1 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -965,7 +965,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
# doctest the examples in the library reference
test_support.run_doctest(sys.modules[__name__], verbose)
diff --git a/Lib/test/test_largefile.py b/Lib/test/test_largefile.py
index d7ed1b3..f4b51ff 100644
--- a/Lib/test/test_largefile.py
+++ b/Lib/test/test_largefile.py
@@ -52,22 +52,22 @@ else:
def expect(got_this, expect_this):
if test_support.verbose:
- print '%r =?= %r ...' % (got_this, expect_this),
+ print('%r =?= %r ...' % (got_this, expect_this), end=' ')
if got_this != expect_this:
if test_support.verbose:
- print 'no'
+ print('no')
raise test_support.TestFailed, 'got %r, but expected %r' %\
(got_this, expect_this)
else:
if test_support.verbose:
- print 'yes'
+ print('yes')
# test that each file function works as expected for a large (i.e. >2GB, do
# we have to check >4GB) files
if test_support.verbose:
- print 'create large file via seek (may be sparse file) ...'
+ print('create large file via seek (may be sparse file) ...')
f = open(name, 'wb')
try:
f.write('z')
@@ -76,16 +76,16 @@ try:
f.write('a')
f.flush()
if test_support.verbose:
- print 'check file size with os.fstat'
+ print('check file size with os.fstat')
expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
finally:
f.close()
if test_support.verbose:
- print 'check file size with os.stat'
+ print('check file size with os.stat')
expect(os.stat(name)[stat.ST_SIZE], size+1)
if test_support.verbose:
- print 'play around with seek() and read() with the built largefile'
+ print('play around with seek() and read() with the built largefile')
f = open(name, 'rb')
try:
expect(f.tell(), 0)
@@ -119,7 +119,7 @@ finally:
f.close()
if test_support.verbose:
- print 'play around with os.lseek() with the built largefile'
+ print('play around with os.lseek() with the built largefile')
f = open(name, 'rb')
try:
expect(os.lseek(f.fileno(), 0, 0), 0)
@@ -136,7 +136,7 @@ finally:
if hasattr(f, 'truncate'):
if test_support.verbose:
- print 'try truncate'
+ print('try truncate')
f = open(name, 'r+b')
try:
f.seek(0, 2)
diff --git a/Lib/test/test_linuxaudiodev.py b/Lib/test/test_linuxaudiodev.py
index 05e4041..eac204f 100644
--- a/Lib/test/test_linuxaudiodev.py
+++ b/Lib/test/test_linuxaudiodev.py
@@ -22,7 +22,7 @@ def play_sound_file(path):
fp.close()
if enc != SND_FORMAT_MULAW_8:
- print "Expect .au file with 8-bit mu-law samples"
+ print("Expect .au file with 8-bit mu-law samples")
return
try:
@@ -63,27 +63,27 @@ def test_errors():
try:
a.setparameters(-1, size, nchannels, fmt)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, -2, nchannels, fmt)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, size, 3, fmt)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, size, nchannels, 177)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, 16, nchannels, fmt)
except ValueError as msg:
- print msg
+ print(msg)
def test():
play_sound_file(findfile('audiotest.au'))
diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py
index 711ac4b..5d9983f 100644
--- a/Lib/test/test_list.py
+++ b/Lib/test/test_list.py
@@ -30,7 +30,7 @@ def test_main(verbose=None):
test_support.run_unittest(ListTest)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
diff --git a/Lib/test/test_locale.py b/Lib/test/test_locale.py
index 9e264b9..ba7d653 100644
--- a/Lib/test/test_locale.py
+++ b/Lib/test/test_locale.py
@@ -23,19 +23,19 @@ else:
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format):
if verbose:
if output:
- print "%s %% %s =? %s ..." %\
- (repr(formatstr), repr(value), repr(output)),
+ print("%s %% %s =? %s ..." %\
+ (repr(formatstr), repr(value), repr(output)), end=' ')
else:
- print "%s %% %s works? ..." % (repr(formatstr), repr(value)),
+ print("%s %% %s works? ..." % (repr(formatstr), repr(value)), end=' ')
result = func(formatstr, value, grouping = grouping)
if output and result != output:
if verbose:
- print 'no'
- print "%s %% %s == %s != %s" %\
- (repr(formatstr), repr(value), repr(result), repr(output))
+ print('no')
+ print("%s %% %s == %s != %s" %\
+ (repr(formatstr), repr(value), repr(result), repr(output)))
else:
if verbose:
- print "yes"
+ print("yes")
try:
# On Solaris 10, the thousands_sep is the empty string
@@ -80,15 +80,15 @@ finally:
# Test BSD Rune locale's bug for isctype functions.
def teststrop(s, method, output):
if verbose:
- print "%s.%s() =? %s ..." % (repr(s), method, repr(output)),
+ print("%s.%s() =? %s ..." % (repr(s), method, repr(output)), end=' ')
result = getattr(s, method)()
if result != output:
if verbose:
- print "no"
- print "%s.%s() == %s != %s" % (repr(s), method, repr(result),
- repr(output))
+ print("no")
+ print("%s.%s() == %s != %s" % (repr(s), method, repr(result),
+ repr(output)))
elif verbose:
- print "yes"
+ print("yes")
try:
if sys.platform == 'sunos5':
diff --git a/Lib/test/test_long_future.py b/Lib/test/test_long_future.py
index 3f137d6..fc01001 100644
--- a/Lib/test/test_long_future.py
+++ b/Lib/test/test_long_future.py
@@ -7,7 +7,7 @@ from test.test_support import TestFailed, verify, verbose
def test_true_division():
if verbose:
- print "long true division"
+ print("long true division")
huge = 1 << 40000
mhuge = -huge
verify(huge / huge == 1.0)
diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py
index a6d309f..d0a99a7 100644
--- a/Lib/test/test_minidom.py
+++ b/Lib/test/test_minidom.py
@@ -24,7 +24,7 @@ del base
def confirm(test, testname = "Test"):
if not test:
- print "Failed " + testname
+ print("Failed " + testname)
raise Exception
def testParseFromFile():
@@ -140,29 +140,29 @@ def testLegalChildren():
try: dom.appendChild(text)
except xml.dom.HierarchyRequestErr: pass
else:
- print "dom.appendChild didn't raise HierarchyRequestErr"
+ print("dom.appendChild didn't raise HierarchyRequestErr")
dom.appendChild(elem)
try: dom.insertBefore(text, elem)
except xml.dom.HierarchyRequestErr: pass
else:
- print "dom.appendChild didn't raise HierarchyRequestErr"
+ print("dom.appendChild didn't raise HierarchyRequestErr")
try: dom.replaceChild(text, elem)
except xml.dom.HierarchyRequestErr: pass
else:
- print "dom.appendChild didn't raise HierarchyRequestErr"
+ print("dom.appendChild didn't raise HierarchyRequestErr")
nodemap = elem.attributes
try: nodemap.setNamedItem(text)
except xml.dom.HierarchyRequestErr: pass
else:
- print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr"
+ print("NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr")
try: nodemap.setNamedItemNS(text)
except xml.dom.HierarchyRequestErr: pass
else:
- print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr"
+ print("NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr")
elem.appendChild(text)
dom.unlink()
@@ -457,8 +457,8 @@ def testTooManyDocumentElements():
except xml.dom.HierarchyRequestErr:
pass
else:
- print "Failed to catch expected exception when" \
- " adding extra document element."
+ print("Failed to catch expected exception when" \
+ " adding extra document element.")
elem.unlink()
doc.unlink()
@@ -896,7 +896,7 @@ def testEncodings():
except UnicodeDecodeError:
pass
else:
- print 'parsing with bad encoding should raise a UnicodeDecodeError'
+ print('parsing with bad encoding should raise a UnicodeDecodeError')
doc.unlink()
@@ -1008,7 +1008,7 @@ def testRenameAttribute():
except xml.dom.NamespaceErr:
pass
else:
- print "expected NamespaceErr"
+ print("expected NamespaceErr")
checkRenameNodeSharedConstraints(doc, attr)
doc.unlink()
@@ -1063,7 +1063,7 @@ def checkRenameNodeSharedConstraints(doc, node):
except xml.dom.NamespaceErr:
pass
else:
- print "expected NamespaceErr"
+ print("expected NamespaceErr")
doc2 = parseString("<doc/>")
try:
@@ -1071,7 +1071,7 @@ def checkRenameNodeSharedConstraints(doc, node):
except xml.dom.WrongDocumentErr:
pass
else:
- print "expected WrongDocumentErr"
+ print("expected WrongDocumentErr")
def testRenameOther():
# We have to create a comment node explicitly since not all DOM
@@ -1084,7 +1084,7 @@ def testRenameOther():
except xml.dom.NotSupportedErr:
pass
else:
- print "expected NotSupportedErr when renaming comment node"
+ print("expected NotSupportedErr when renaming comment node")
doc.unlink()
def checkWholeText(node, s):
@@ -1368,13 +1368,13 @@ else:
confirm(len(Node.allnodes) == 0,
"assertion: len(Node.allnodes) == 0")
if len(Node.allnodes):
- print "Garbage left over:"
+ print("Garbage left over:")
if verbose:
- print Node.allnodes.items()[0:10]
+ print(Node.allnodes.items()[0:10])
else:
# Don't print specific nodes if repeatable results
# are needed
- print len(Node.allnodes)
+ print(len(Node.allnodes))
Node.allnodes = {}
for name in names:
@@ -1385,13 +1385,13 @@ for name in names:
check_allnodes()
except:
failed.append(name)
- print "Test Failed: ", name
+ print("Test Failed: ", name)
sys.stdout.flush()
traceback.print_exception(*sys.exc_info())
- print repr(sys.exc_info()[1])
+ print(repr(sys.exc_info()[1]))
Node.allnodes = {}
if failed:
- print "\n\n\n**** Check for failures in these tests:"
+ print("\n\n\n**** Check for failures in these tests:")
for name in failed:
- print " " + name
+ print(" " + name)
diff --git a/Lib/test/test_module.py b/Lib/test/test_module.py
index 2b35a53..7911a0e 100644
--- a/Lib/test/test_module.py
+++ b/Lib/test/test_module.py
@@ -45,4 +45,4 @@ vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc", "bar": 42})
verify(foo.__dict__ is d)
if verbose:
- print "All OK"
+ print("All OK")
diff --git a/Lib/test/test_multibytecodec.py b/Lib/test/test_multibytecodec.py
index fb7f82d..2ac7061 100644
--- a/Lib/test/test_multibytecodec.py
+++ b/Lib/test/test_multibytecodec.py
@@ -48,7 +48,7 @@ class Test_MultibyteCodec(unittest.TestCase):
def test_codingspec(self):
try:
for enc in ALL_CJKENCODINGS:
- print >> open(TESTFN, 'w'), '# coding:', enc
+ print('# coding:', enc, file=open(TESTFN, 'w'))
execfile(TESTFN)
finally:
os.unlink(TESTFN)
diff --git a/Lib/test/test_mutants.py b/Lib/test/test_mutants.py
index 6215226..a710248 100644
--- a/Lib/test/test_mutants.py
+++ b/Lib/test/test_mutants.py
@@ -135,13 +135,13 @@ def test_one(n):
# same size.
mutate = 1
if verbose:
- print "trying w/ lengths", len(dict1), len(dict2),
+ print("trying w/ lengths", len(dict1), len(dict2), end=' ')
while dict1 and len(dict1) == len(dict2):
if verbose:
- print ".",
+ print(".", end=' ')
c = dict1 == dict2
if verbose:
- print
+ print()
# Run test_one n times. At the start (before the bugs were fixed), 20
# consecutive runs of this test each blew up on or before the sixth time
@@ -186,7 +186,7 @@ class Parent:
# the expected-output file doesn't need to change.
f = open(TESTFN, "w")
-print >> f, Parent().__dict__
+print(Parent().__dict__, file=f)
f.close()
os.unlink(TESTFN)
@@ -207,7 +207,7 @@ class Machiavelli:
# Michael sez: "doesn't crash without this. don't know why."
# Tim sez: "luck of the draw; crashes with or without for me."
- print >> f
+ print(file=f)
return repr("machiavelli")
@@ -216,7 +216,7 @@ class Machiavelli:
dict[Machiavelli()] = Machiavelli()
-print >> f, str(dict)
+print(str(dict), file=f)
f.close()
os.unlink(TESTFN)
del f, dict
@@ -280,7 +280,7 @@ dict[Machiavelli3(2)] = Machiavelli3(0)
f = open(TESTFN, "w")
try:
try:
- print >> f, dict[Machiavelli3(2)]
+ print(dict[Machiavelli3(2)], file=f)
except KeyError:
pass
finally:
diff --git a/Lib/test/test_normalization.py b/Lib/test/test_normalization.py
index 81bdfbd..d890067 100644
--- a/Lib/test/test_normalization.py
+++ b/Lib/test/test_normalization.py
@@ -58,7 +58,7 @@ def test_main():
continue
if verbose:
- print line
+ print(line)
# Perform tests
verify(c2 == NFC(c1) == NFC(c2) == NFC(c3), line)
diff --git a/Lib/test/test_ntpath.py b/Lib/test/test_ntpath.py
index 6bc2a05..939886d 100644
--- a/Lib/test/test_ntpath.py
+++ b/Lib/test/test_ntpath.py
@@ -9,11 +9,11 @@ def tester(fn, wantResult):
fn = fn.replace("\\", "\\\\")
gotResult = eval(fn)
if wantResult != gotResult:
- print "error!"
- print "evaluated: " + str(fn)
- print "should be: " + str(wantResult)
- print " returned: " + str(gotResult)
- print ""
+ print("error!")
+ print("evaluated: " + str(fn))
+ print("should be: " + str(wantResult))
+ print(" returned: " + str(gotResult))
+ print("")
errors = errors + 1
tester('ntpath.splitext("foo.ext")', ('foo', '.ext'))
@@ -152,4 +152,4 @@ else:
if errors:
raise TestFailed(str(errors) + " errors.")
elif verbose:
- print "No errors. Thank your lucky stars."
+ print("No errors. Thank your lucky stars.")
diff --git a/Lib/test/test_operations.py b/Lib/test/test_operations.py
index 8baef4c..e8b1ae8 100644
--- a/Lib/test/test_operations.py
+++ b/Lib/test/test_operations.py
@@ -1,11 +1,11 @@
# Python test set -- part 3, built-in operations.
-print '3. Operations'
-print 'XXX Mostly not yet implemented'
+print('3. Operations')
+print('XXX Mostly not yet implemented')
-print '3.1 Dictionary lookups fail if __cmp__() raises an exception'
+print('3.1 Dictionary lookups fail if __cmp__() raises an exception')
class BadDictKey:
@@ -14,7 +14,7 @@ class BadDictKey:
def __eq__(self, other):
if isinstance(other, self.__class__):
- print "raising error"
+ print("raising error")
raise RuntimeError, "gotcha"
return other
@@ -32,9 +32,9 @@ for stmt in ['d[x2] = 2',
try:
exec(stmt)
except RuntimeError:
- print "%s: caught the RuntimeError outside" % (stmt,)
+ print("%s: caught the RuntimeError outside" % (stmt,))
else:
- print "%s: No exception passed through!" % (stmt,) # old CPython behavior
+ print("%s: No exception passed through!" % (stmt,)) # old CPython behavior
# Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
@@ -74,4 +74,4 @@ d[X()] = 5
resizing = True
d[9] = 6
-print 'resize bugs not triggered.'
+print('resize bugs not triggered.')
diff --git a/Lib/test/test_operator.py b/Lib/test/test_operator.py
index c71a4e6..2183508 100644
--- a/Lib/test/test_operator.py
+++ b/Lib/test/test_operator.py
@@ -468,7 +468,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_ossaudiodev.py b/Lib/test/test_ossaudiodev.py
index 0377e9c..e97e788 100644
--- a/Lib/test/test_ossaudiodev.py
+++ b/Lib/test/test_ossaudiodev.py
@@ -33,7 +33,7 @@ def read_sound_file(path):
fp.close()
if enc != SND_FORMAT_MULAW_8:
- print "Expect .au file with 8-bit mu-law samples"
+ print("Expect .au file with 8-bit mu-law samples")
return
# Convert the data to 16-bit signed.
@@ -78,8 +78,8 @@ def play_sound_file(data, rate, ssize, nchannels):
# set parameters based on .au file headers
dsp.setparameters(AFMT_S16_NE, nchannels, rate)
- print ("playing test sound file (expected running time: %.2f sec)"
- % expected_time)
+ print(("playing test sound file (expected running time: %.2f sec)"
+ % expected_time))
t1 = time.time()
dsp.write(data)
dsp.close()
@@ -143,7 +143,7 @@ def test_bad_setparameters(dsp):
result = dsp.setparameters(fmt, channels, rate, True)
raise AssertionError("setparameters: expected OSSAudioError")
except ossaudiodev.OSSAudioError as err:
- print "setparameters: got OSSAudioError as expected"
+ print("setparameters: got OSSAudioError as expected")
def test():
(data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au'))
diff --git a/Lib/test/test_peepholer.py b/Lib/test/test_peepholer.py
index 779a20a..213edd2 100644
--- a/Lib/test/test_peepholer.py
+++ b/Lib/test/test_peepholer.py
@@ -211,7 +211,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_pep247.py b/Lib/test/test_pep247.py
index 88f2461..cbd071b 100644
--- a/Lib/test/test_pep247.py
+++ b/Lib/test/test_pep247.py
@@ -41,7 +41,7 @@ def check_hash_module(module, key=None):
hd2 += "%02x" % ord(byte)
assert hd2 == hexdigest, "hexdigest doesn't appear correct"
- print 'Module', module.__name__, 'seems to comply with PEP 247'
+ print('Module', module.__name__, 'seems to comply with PEP 247')
if __name__ == '__main__':
diff --git a/Lib/test/test_pep277.py b/Lib/test/test_pep277.py
index ff71bf2..8efa50a 100644
--- a/Lib/test/test_pep277.py
+++ b/Lib/test/test_pep277.py
@@ -83,7 +83,7 @@ class UnicodeFileTests(unittest.TestCase):
f2 = os.listdir(unicode(test_support.TESTFN,
sys.getfilesystemencoding()))
f2.sort()
- print f2
+ print(f2)
def test_rename(self):
for name in self.files:
@@ -99,7 +99,7 @@ class UnicodeFileTests(unittest.TestCase):
f = open(filename, 'w')
f.write((filename + '\n').encode("utf-8"))
f.close()
- print repr(filename)
+ print(repr(filename))
os.access(filename,os.R_OK)
os.remove(filename)
os.chdir(oldwd)
diff --git a/Lib/test/test_pkg.py b/Lib/test/test_pkg.py
index c365742..79c9098 100644
--- a/Lib/test/test_pkg.py
+++ b/Lib/test/test_pkg.py
@@ -18,7 +18,7 @@ def mkhier(root, descr):
if contents is None:
mkdir(fullname)
else:
- if verbose: print "write", fullname
+ if verbose: print("write", fullname)
f = open(fullname, "w")
f.write(contents)
if contents and contents[-1] != '\n':
@@ -26,7 +26,7 @@ def mkhier(root, descr):
f.close()
def mkdir(x):
- if verbose: print "mkdir", x
+ if verbose: print("mkdir", x)
os.mkdir(x)
def cleanout(root):
@@ -40,7 +40,7 @@ def cleanout(root):
rmdir(root)
def rmdir(x):
- if verbose: print "rmdir", x
+ if verbose: print("rmdir", x)
os.rmdir(x)
def fixdir(lst):
@@ -61,7 +61,7 @@ def runtest(hier, code):
os.close(fd)
try:
sys.path.insert(0, root)
- if verbose: print "sys.path =", sys.path
+ if verbose: print("sys.path =", sys.path)
try:
execfile(fname, globals(), {})
except:
@@ -242,9 +242,9 @@ if __name__ == '__main__':
for name, hier, code in tests:
if args and name not in args:
- print "skipping test", name
+ print("skipping test", name)
continue
- print "running test", name
+ print("running test", name)
runtest(hier, code)
# Test
diff --git a/Lib/test/test_popen2.py b/Lib/test/test_popen2.py
index 2d54eb0..008a67a 100644
--- a/Lib/test/test_popen2.py
+++ b/Lib/test/test_popen2.py
@@ -13,7 +13,7 @@ from test.test_support import TestSkipped, reap_children
# subprocess.
def main():
- print "Test popen2 module:"
+ print("Test popen2 module:")
if (sys.platform[:4] == 'beos' or sys.platform[:6] == 'atheos') \
and __name__ != '__main__':
# Locks get messed up or something. Generally we're supposed
@@ -33,7 +33,7 @@ def main():
def _test():
# same test as popen2._test(), but using the os.popen*() API
- print "Testing os module:"
+ print("Testing os module:")
import popen2
# When the test runs, there shouldn't be any open pipes
popen2._cleanup()
@@ -46,14 +46,14 @@ def _test():
# sometimes adding an extra newline at the start or the
# end. So we strip whitespace off both ends for comparison.
expected = teststr.strip()
- print "testing popen2..."
+ print("testing popen2...")
w, r = os.popen2(cmd)
w.write(teststr)
w.close()
got = r.read()
if got.strip() != expected:
raise ValueError("wrote %r read %r" % (teststr, got))
- print "testing popen3..."
+ print("testing popen3...")
try:
w, r, e = os.popen3([cmd])
except:
@@ -71,7 +71,7 @@ def _test():
popen2._cleanup()
if popen2._active:
raise ValueError("_active not empty")
- print "All OK"
+ print("All OK")
main()
_test()
diff --git a/Lib/test/test_pty.py b/Lib/test/test_pty.py
index 02290be..123c3f8 100644
--- a/Lib/test/test_pty.py
+++ b/Lib/test/test_pty.py
@@ -6,7 +6,7 @@ TEST_STRING_2 = "For my pet fish, Eric.\n"
if verbose:
def debug(msg):
- print msg
+ print(msg)
else:
def debug(msg):
pass
diff --git a/Lib/test/test_pyclbr.py b/Lib/test/test_pyclbr.py
index a03daa9..478083e 100644
--- a/Lib/test/test_pyclbr.py
+++ b/Lib/test/test_pyclbr.py
@@ -28,13 +28,13 @@ class PyclbrTest(TestCase):
''' succeed iff {l1} - {ignore} == {l2} - {ignore} '''
missing = (set(l1) ^ set(l2)) - set(ignore)
if missing:
- print >>sys.stderr, "l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore)
+ print("l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore), file=sys.stderr)
self.fail("%r missing" % missing.pop())
def assertHasattr(self, obj, attr, ignore):
''' succeed iff hasattr(obj,attr) or attr in ignore. '''
if attr in ignore: return
- if not hasattr(obj, attr): print "???", attr
+ if not hasattr(obj, attr): print("???", attr)
self.failUnless(hasattr(obj, attr),
'expected hasattr(%r, %r)' % (obj, attr))
@@ -43,7 +43,7 @@ class PyclbrTest(TestCase):
''' succeed iff key in obj or key in ignore. '''
if key in ignore: return
if key not in obj:
- print >>sys.stderr, "***",key
+ print("***",key, file=sys.stderr)
self.failUnless(key in obj)
def assertEqualsOrIgnored(self, a, b, ignore):
@@ -110,7 +110,7 @@ class PyclbrTest(TestCase):
try:
self.assertListEq(real_bases, pyclbr_bases, ignore)
except:
- print >>sys.stderr, "class=%s" % py_item
+ print("class=%s" % py_item, file=sys.stderr)
raise
actualMethods = []
@@ -132,7 +132,7 @@ class PyclbrTest(TestCase):
ignore)
# can't check file or lineno
except:
- print >>sys.stderr, "class=%s" % py_item
+ print("class=%s" % py_item, file=sys.stderr)
raise
# Now check for missing stuff.
diff --git a/Lib/test/test_pyexpat.py b/Lib/test/test_pyexpat.py
index 73092c1..fed1a9c 100644
--- a/Lib/test/test_pyexpat.py
+++ b/Lib/test/test_pyexpat.py
@@ -10,50 +10,50 @@ from test.test_support import sortdict, TestFailed
class Outputter:
def StartElementHandler(self, name, attrs):
- print 'Start element:\n\t', repr(name), sortdict(attrs)
+ print('Start element:\n\t', repr(name), sortdict(attrs))
def EndElementHandler(self, name):
- print 'End element:\n\t', repr(name)
+ print('End element:\n\t', repr(name))
def CharacterDataHandler(self, data):
data = data.strip()
if data:
- print 'Character data:'
- print '\t', repr(data)
+ print('Character data:')
+ print('\t', repr(data))
def ProcessingInstructionHandler(self, target, data):
- print 'PI:\n\t', repr(target), repr(data)
+ print('PI:\n\t', repr(target), repr(data))
def StartNamespaceDeclHandler(self, prefix, uri):
- print 'NS decl:\n\t', repr(prefix), repr(uri)
+ print('NS decl:\n\t', repr(prefix), repr(uri))
def EndNamespaceDeclHandler(self, prefix):
- print 'End of NS decl:\n\t', repr(prefix)
+ print('End of NS decl:\n\t', repr(prefix))
def StartCdataSectionHandler(self):
- print 'Start of CDATA section'
+ print('Start of CDATA section')
def EndCdataSectionHandler(self):
- print 'End of CDATA section'
+ print('End of CDATA section')
def CommentHandler(self, text):
- print 'Comment:\n\t', repr(text)
+ print('Comment:\n\t', repr(text))
def NotationDeclHandler(self, *args):
name, base, sysid, pubid = args
- print 'Notation declared:', args
+ print('Notation declared:', args)
def UnparsedEntityDeclHandler(self, *args):
entityName, base, systemId, publicId, notationName = args
- print 'Unparsed entity decl:\n\t', args
+ print('Unparsed entity decl:\n\t', args)
def NotStandaloneHandler(self, userData):
- print 'Not standalone'
+ print('Not standalone')
return 1
def ExternalEntityRefHandler(self, *args):
context, base, sysId, pubId = args
- print 'External entity ref:', args[1:]
+ print('External entity ref:', args[1:])
return 1
def DefaultHandler(self, userData):
@@ -65,9 +65,9 @@ class Outputter:
def confirm(ok):
if ok:
- print "OK."
+ print("OK.")
else:
- print "Not OK."
+ print("Not OK.")
out = Outputter()
parser = expat.ParserCreate(namespace_separator='!')
@@ -131,10 +131,10 @@ parser.returns_unicode = 0
try:
parser.Parse(data, 1)
except expat.error:
- print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)
- print '** Line', parser.ErrorLineNumber
- print '** Column', parser.ErrorColumnNumber
- print '** Byte', parser.ErrorByteIndex
+ print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
+ print('** Line', parser.ErrorLineNumber)
+ print('** Column', parser.ErrorColumnNumber)
+ print('** Byte', parser.ErrorByteIndex)
# Try the parse again, this time producing Unicode output
parser = expat.ParserCreate(namespace_separator='!')
@@ -145,10 +145,10 @@ for name in HANDLER_NAMES:
try:
parser.Parse(data, 1)
except expat.error:
- print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)
- print '** Line', parser.ErrorLineNumber
- print '** Column', parser.ErrorColumnNumber
- print '** Byte', parser.ErrorByteIndex
+ print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
+ print('** Line', parser.ErrorLineNumber)
+ print('** Column', parser.ErrorColumnNumber)
+ print('** Byte', parser.ErrorByteIndex)
# Try parsing a file
parser = expat.ParserCreate(namespace_separator='!')
@@ -161,35 +161,35 @@ file = StringIO.StringIO(data)
try:
parser.ParseFile(file)
except expat.error:
- print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)
- print '** Line', parser.ErrorLineNumber
- print '** Column', parser.ErrorColumnNumber
- print '** Byte', parser.ErrorByteIndex
+ print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
+ print('** Line', parser.ErrorLineNumber)
+ print('** Column', parser.ErrorColumnNumber)
+ print('** Byte', parser.ErrorByteIndex)
# Tests that make sure we get errors when the namespace_separator value
# is illegal, and that we don't for good values:
-print
-print "Testing constructor for proper handling of namespace_separator values:"
+print()
+print("Testing constructor for proper handling of namespace_separator values:")
expat.ParserCreate()
expat.ParserCreate(namespace_separator=None)
expat.ParserCreate(namespace_separator=' ')
-print "Legal values tested o.k."
+print("Legal values tested o.k.")
try:
expat.ParserCreate(namespace_separator=42)
except TypeError as e:
- print "Caught expected TypeError:"
- print e
+ print("Caught expected TypeError:")
+ print(e)
else:
- print "Failed to catch expected TypeError."
+ print("Failed to catch expected TypeError.")
try:
expat.ParserCreate(namespace_separator='too long')
except ValueError as e:
- print "Caught expected ValueError:"
- print e
+ print("Caught expected ValueError:")
+ print(e)
else:
- print "Failed to catch expected ValueError."
+ print("Failed to catch expected ValueError.")
# ParserCreate() needs to accept a namespace_separator of zero length
# to satisfy the requirements of RDF applications that are required
@@ -211,12 +211,12 @@ p.EndElementHandler = collector
p.Parse("<e> <e/> <e></e> </e>", 1)
tag = L[0]
if len(L) != 6:
- print "L should only contain 6 entries; found", len(L)
+ print("L should only contain 6 entries; found", len(L))
for entry in L:
if tag is not entry:
- print "expected L to contain many references to the same string",
- print "(it didn't)"
- print "L =", repr(L)
+ print("expected L to contain many references to the same string", end=' ')
+ print("(it didn't)")
+ print("L =", repr(L))
break
# Tests of the buffer_text attribute.
@@ -323,9 +323,9 @@ try:
parser.Parse("<a><b><c/></b></a>", 1)
except RuntimeError as e:
if e.args[0] != "a":
- print "Expected RuntimeError for element 'a'; found %r" % e.args[0]
+ print("Expected RuntimeError for element 'a'; found %r" % e.args[0])
else:
- print "Expected RuntimeError for 'a'"
+ print("Expected RuntimeError for 'a'")
# Test Current* members:
class PositionTest:
diff --git a/Lib/test/test_queue.py b/Lib/test/test_queue.py
index 66977e6..ac382c1 100644
--- a/Lib/test/test_queue.py
+++ b/Lib/test/test_queue.py
@@ -271,11 +271,11 @@ def test():
SimpleQueueTest(q)
SimpleQueueTest(q)
if verbose:
- print "Simple Queue tests seemed to work"
+ print("Simple Queue tests seemed to work")
q = FailingQueue(QUEUE_SIZE)
FailingQueueTest(q)
FailingQueueTest(q)
if verbose:
- print "Failing Queue tests seemed to work"
+ print("Failing Queue tests seemed to work")
test()
diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py
index 5a76b1e..e4a2792 100644
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -547,7 +547,7 @@ def test_main(verbose=None):
for i in xrange(len(counts)):
test_support.run_unittest(*testclasses)
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py
index dafd82e..bb97433 100644
--- a/Lib/test/test_re.py
+++ b/Lib/test/test_re.py
@@ -603,7 +603,7 @@ class ReTests(unittest.TestCase):
def run_re_tests():
from test.re_tests import benchmarks, tests, SUCCEED, FAIL, SYNTAX_ERROR
if verbose:
- print 'Running re_tests test suite'
+ print('Running re_tests test suite')
else:
# To save time, only run the first and last 10 tests
#tests = tests[:10] + tests[-10:]
@@ -624,23 +624,23 @@ def run_re_tests():
except re.error:
if outcome == SYNTAX_ERROR: pass # Expected a syntax error
else:
- print '=== Syntax error:', t
+ print('=== Syntax error:', t)
except KeyboardInterrupt: raise KeyboardInterrupt
except:
- print '*** Unexpected error ***', t
+ print('*** Unexpected error ***', t)
if verbose:
traceback.print_exc(file=sys.stdout)
else:
try:
result = obj.search(s)
except re.error as msg:
- print '=== Unexpected exception', t, repr(msg)
+ print('=== Unexpected exception', t, repr(msg))
if outcome == SYNTAX_ERROR:
# This should have been a syntax error; forget it.
pass
elif outcome == FAIL:
if result is None: pass # No match, as expected
- else: print '=== Succeeded incorrectly', t
+ else: print('=== Succeeded incorrectly', t)
elif outcome == SUCCEED:
if result is not None:
# Matched, as expected, so now we compute the
@@ -668,17 +668,17 @@ def run_re_tests():
vardict[i] = gi
repl = eval(repl, vardict)
if repl != expected:
- print '=== grouping error', t,
- print repr(repl) + ' should be ' + repr(expected)
+ print('=== grouping error', t, end=' ')
+ print(repr(repl) + ' should be ' + repr(expected))
else:
- print '=== Failed incorrectly', t
+ print('=== Failed incorrectly', t)
# Try the match on a unicode string, and check that it
# still succeeds.
try:
result = obj.search(unicode(s, "latin-1"))
if result is None:
- print '=== Fails on unicode match', t
+ print('=== Fails on unicode match', t)
except NameError:
continue # 1.5.2
except TypeError:
@@ -689,7 +689,7 @@ def run_re_tests():
obj=re.compile(unicode(pattern, "latin-1"))
result = obj.search(s)
if result is None:
- print '=== Fails on unicode pattern match', t
+ print('=== Fails on unicode pattern match', t)
# Try the match with the search area limited to the extent
# of the match and see if it still succeeds. \B will
@@ -701,28 +701,28 @@ def run_re_tests():
obj = re.compile(pattern)
result = obj.search(s, result.start(0), result.end(0) + 1)
if result is None:
- print '=== Failed on range-limited match', t
+ print('=== Failed on range-limited match', t)
# Try the match with IGNORECASE enabled, and check that it
# still succeeds.
obj = re.compile(pattern, re.IGNORECASE)
result = obj.search(s)
if result is None:
- print '=== Fails on case-insensitive match', t
+ print('=== Fails on case-insensitive match', t)
# Try the match with LOCALE enabled, and check that it
# still succeeds.
obj = re.compile(pattern, re.LOCALE)
result = obj.search(s)
if result is None:
- print '=== Fails on locale-sensitive match', t
+ print('=== Fails on locale-sensitive match', t)
# Try the match with UNICODE locale enabled, and check
# that it still succeeds.
obj = re.compile(pattern, re.UNICODE)
result = obj.search(s)
if result is None:
- print '=== Fails on unicode-sensitive match', t
+ print('=== Fails on unicode-sensitive match', t)
def test_main():
run_unittest(ReTests)
diff --git a/Lib/test/test_rfc822.py b/Lib/test/test_rfc822.py
index d59e743..91e694a 100644
--- a/Lib/test/test_rfc822.py
+++ b/Lib/test/test_rfc822.py
@@ -42,7 +42,7 @@ class MessageTestCase(unittest.TestCase):
try:
mn, ma = results[i][0], results[i][1]
except IndexError:
- print 'extra parsed address:', repr(n), repr(a)
+ print('extra parsed address:', repr(n), repr(a))
continue
i = i + 1
self.assertEqual(mn, n,
@@ -52,7 +52,7 @@ class MessageTestCase(unittest.TestCase):
if mn == n and ma == a:
pass
else:
- print 'not found:', repr(n), repr(a)
+ print('not found:', repr(n), repr(a))
out = m.getdate('date')
if out:
diff --git a/Lib/test/test_rgbimg.py b/Lib/test/test_rgbimg.py
index 650c02a..65a0f42 100644
--- a/Lib/test/test_rgbimg.py
+++ b/Lib/test/test_rgbimg.py
@@ -14,7 +14,7 @@ from test.test_support import verbose, unlink, findfile
class error(Exception):
pass
-print 'RGBimg test suite:'
+print('RGBimg test suite:')
def testimg(rgb_file, raw_file):
rgb_file = findfile(rgb_file)
@@ -40,11 +40,11 @@ for source, target in table:
source = findfile(source)
target = findfile(target)
if verbose:
- print "uudecoding", source, "->", target, "..."
+ print("uudecoding", source, "->", target, "...")
uu.decode(source, target)
if verbose:
- print "testing..."
+ print("testing...")
ttob = rgbimg.ttob(0)
if ttob != 0:
diff --git a/Lib/test/test_runpy.py b/Lib/test/test_runpy.py
index a37ee7b..e0fdabc 100644
--- a/Lib/test/test_runpy.py
+++ b/Lib/test/test_runpy.py
@@ -92,22 +92,22 @@ class RunModuleTest(unittest.TestCase):
init_fname = "__init__"+os.extsep+"py"
test_fname = "runpy_test"+os.extsep+"py"
pkg_dir = sub_dir = tempfile.mkdtemp()
- if verbose: print " Package tree in:", sub_dir
+ if verbose: print(" Package tree in:", sub_dir)
sys.path.insert(0, pkg_dir)
- if verbose: print " Updated sys.path:", sys.path[0]
+ if verbose: print(" Updated sys.path:", sys.path[0])
for i in range(depth):
sub_dir = os.path.join(sub_dir, pkg_name)
os.mkdir(sub_dir)
- if verbose: print " Next level in:", sub_dir
+ if verbose: print(" Next level in:", sub_dir)
pkg_fname = os.path.join(sub_dir, init_fname)
pkg_file = open(pkg_fname, "w")
pkg_file.close()
- if verbose: print " Created:", pkg_fname
+ if verbose: print(" Created:", pkg_fname)
mod_fname = os.path.join(sub_dir, test_fname)
mod_file = open(mod_fname, "w")
mod_file.write(source)
mod_file.close()
- if verbose: print " Created:", mod_fname
+ if verbose: print(" Created:", mod_fname)
mod_name = (pkg_name+".")*depth + "runpy_test"
return pkg_dir, mod_fname, mod_name
@@ -118,49 +118,49 @@ class RunModuleTest(unittest.TestCase):
try:
del sys.modules[entry]
except KeyError as ex:
- if verbose: print ex # Persist with cleaning up
- if verbose: print " Removed sys.modules entries"
+ if verbose: print(ex) # Persist with cleaning up
+ if verbose: print(" Removed sys.modules entries")
del sys.path[0]
- if verbose: print " Removed sys.path entry"
+ if verbose: print(" Removed sys.path entry")
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
try:
os.remove(os.path.join(root, name))
except OSError as ex:
- if verbose: print ex # Persist with cleaning up
+ if verbose: print(ex) # Persist with cleaning up
for name in dirs:
fullname = os.path.join(root, name)
try:
os.rmdir(fullname)
except OSError as ex:
- if verbose: print ex # Persist with cleaning up
+ if verbose: print(ex) # Persist with cleaning up
try:
os.rmdir(top)
- if verbose: print " Removed package tree"
+ if verbose: print(" Removed package tree")
except OSError as ex:
- if verbose: print ex # Persist with cleaning up
+ if verbose: print(ex) # Persist with cleaning up
def _check_module(self, depth):
pkg_dir, mod_fname, mod_name = (
self._make_pkg("x=1\n", depth))
try:
- if verbose: print "Running from source:", mod_name
+ if verbose: print("Running from source:", mod_name)
d1 = run_module(mod_name) # Read from source
self.failUnless(d1["x"] == 1)
del d1 # Ensure __loader__ entry doesn't keep file open
__import__(mod_name)
os.remove(mod_fname)
- if verbose: print "Running from compiled:", mod_name
+ if verbose: print("Running from compiled:", mod_name)
d2 = run_module(mod_name) # Read from bytecode
self.failUnless(d2["x"] == 1)
del d2 # Ensure __loader__ entry doesn't keep file open
finally:
self._del_pkg(pkg_dir, depth, mod_name)
- if verbose: print "Module executed successfully"
+ if verbose: print("Module executed successfully")
def test_run_module(self):
for depth in range(4):
- if verbose: print "Testing package depth:", depth
+ if verbose: print("Testing package depth:", depth)
self._check_module(depth)
diff --git a/Lib/test/test_sax.py b/Lib/test/test_sax.py
index d3939c0..5715d67 100644
--- a/Lib/test/test_sax.py
+++ b/Lib/test/test_sax.py
@@ -27,7 +27,7 @@ def confirm(outcome, name):
tests = tests + 1
if outcome:
if verbose:
- print "Passed", name
+ print("Passed", name)
else:
failures.append(name)
@@ -745,7 +745,7 @@ for (name, value) in items:
del items
if verbose:
- print "%d tests, %d failures" % (tests, len(failures))
+ print("%d tests, %d failures" % (tests, len(failures)))
if failures:
raise TestFailed("%d of %d tests failed: %s"
% (len(failures), tests, ", ".join(failures)))
diff --git a/Lib/test/test_scope.py b/Lib/test/test_scope.py
index 777e85a..31e57e5 100644
--- a/Lib/test/test_scope.py
+++ b/Lib/test/test_scope.py
@@ -269,7 +269,7 @@ def noproblem3():
def testUnboundLocal(self):
def errorInOuter():
- print y
+ print(y)
def inner():
return y
y = 1
@@ -530,18 +530,18 @@ self.assert_(X.passed)
def testListCompLocalVars(self):
try:
- print bad
+ print(bad)
except NameError:
pass
else:
- print "bad should not be defined"
+ print("bad should not be defined")
def x():
[bad for s in 'a b' for bad in s.split()]
x()
try:
- print bad
+ print(bad)
except NameError:
pass
diff --git a/Lib/test/test_select.py b/Lib/test/test_select.py
index d341324..fd76674 100644
--- a/Lib/test/test_select.py
+++ b/Lib/test/test_select.py
@@ -9,7 +9,7 @@ try:
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
class Nope:
pass
@@ -23,47 +23,47 @@ try:
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
try:
rfd, wfd, xfd = select.select([Almost()], [], [])
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
try:
rfd, wfd, xfd = select.select([], [], [], 'not a number')
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
def test():
import sys
if sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'):
if verbose:
- print "Can't test select easily on", sys.platform
+ print("Can't test select easily on", sys.platform)
return
cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done'
p = os.popen(cmd, 'r')
for tout in (0, 1, 2, 4, 8, 16) + (None,)*10:
if verbose:
- print 'timeout =', tout
+ print('timeout =', tout)
rfd, wfd, xfd = select.select([p], [], [], tout)
if (rfd, wfd, xfd) == ([], [], []):
continue
if (rfd, wfd, xfd) == ([p], [], []):
line = p.readline()
if verbose:
- print repr(line)
+ print(repr(line))
if not line:
if verbose:
- print 'EOF'
+ print('EOF')
break
continue
- print 'Unexpected return values from select():', rfd, wfd, xfd
+ print('Unexpected return values from select():', rfd, wfd, xfd)
p.close()
reap_children()
diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py
index 13d02bb..9093965 100644
--- a/Lib/test/test_signal.py
+++ b/Lib/test/test_signal.py
@@ -15,7 +15,7 @@ else:
pid = os.getpid()
if verbose:
- print "test runner's pid is", pid
+ print("test runner's pid is", pid)
# Shell script that will send us asynchronous signals
script = """
@@ -36,7 +36,7 @@ def handlerA(*args):
global a_called
a_called = True
if verbose:
- print "handlerA invoked", args
+ print("handlerA invoked", args)
class HandlerBCalled(Exception):
pass
@@ -45,7 +45,7 @@ def handlerB(*args):
global b_called
b_called = True
if verbose:
- print "handlerB invoked", args
+ print("handlerB invoked", args)
raise HandlerBCalled, args
# Set up a child to send signals to us (the parent) after waiting long
@@ -69,10 +69,10 @@ def force_test_exit():
# time for the normal sequence of events to occur. This is
# just a stop-gap to try to prevent the test from hanging.
time.sleep(MAX_DURATION + 5)
- print >> sys.__stdout__, ' child should not have to kill parent'
+ print(' child should not have to kill parent', file=sys.__stdout__)
for signame in "SIGHUP", "SIGUSR1", "SIGUSR2", "SIGALRM":
os.kill(pid, getattr(signal, signame))
- print >> sys.__stdout__, " child sent", signame, "to", pid
+ print(" child sent", signame, "to", pid, file=sys.__stdout__)
time.sleep(1)
finally:
os._exit(0)
@@ -126,27 +126,27 @@ try:
# KeyboardInterrupt, finally getting us out of the loop.
os.system(script)
try:
- print "starting pause() loop..."
+ print("starting pause() loop...")
while 1:
try:
if verbose:
- print "call pause()..."
+ print("call pause()...")
signal.pause()
if verbose:
- print "pause() returned"
+ print("pause() returned")
except HandlerBCalled:
if verbose:
- print "HandlerBCalled exception caught"
+ print("HandlerBCalled exception caught")
except KeyboardInterrupt:
if verbose:
- print "KeyboardInterrupt (the alarm() went off)"
+ print("KeyboardInterrupt (the alarm() went off)")
if not a_called:
- print 'HandlerA not called'
+ print('HandlerA not called')
if not b_called:
- print 'HandlerB not called'
+ print('HandlerB not called')
finally:
# Forcibly kill the child we created to ping us if there was a test error.
diff --git a/Lib/test/test_site.py b/Lib/test/test_site.py
index d379ab5..6f32fca 100644
--- a/Lib/test/test_site.py
+++ b/Lib/test/test_site.py
@@ -119,11 +119,11 @@ class PthFile(object):
"""
FILE = open(self.file_path, 'w')
try:
- print>>FILE, "#import @bad module name"
- print>>FILE, "\n"
- print>>FILE, "import %s" % self.imported
- print>>FILE, self.good_dirname
- print>>FILE, self.bad_dirname
+ print("#import @bad module name", file=FILE)
+ print("\n", file=FILE)
+ print("import %s" % self.imported, file=FILE)
+ print(self.good_dirname, file=FILE)
+ print(self.bad_dirname, file=FILE)
finally:
FILE.close()
os.mkdir(self.good_dir_path)
diff --git a/Lib/test/test_socket_ssl.py b/Lib/test/test_socket_ssl.py
index 5d308c5..b04effe 100644
--- a/Lib/test/test_socket_ssl.py
+++ b/Lib/test/test_socket_ssl.py
@@ -16,7 +16,7 @@ def test_basic():
import urllib
if test_support.verbose:
- print "test_basic ..."
+ print("test_basic ...")
socket.RAND_status()
try:
@@ -24,7 +24,7 @@ def test_basic():
except TypeError:
pass
else:
- print "didn't raise TypeError"
+ print("didn't raise TypeError")
socket.RAND_add("this is a random string", 75.0)
f = urllib.urlopen('https://sf.net')
@@ -35,14 +35,14 @@ def test_timeout():
test_support.requires('network')
def error_msg(extra_msg):
- print >> sys.stderr, """\
+ print("""\
WARNING: an attempt to connect to %r %s, in
test_timeout. That may be legitimate, but is not the outcome we hoped
for. If this message is seen often, test_timeout should be changed to
- use a more reliable address.""" % (ADDR, extra_msg)
+ use a more reliable address.""" % (ADDR, extra_msg), file=sys.stderr)
if test_support.verbose:
- print "test_timeout ..."
+ print("test_timeout ...")
# A service which issues a welcome banner (without need to write
# anything).
@@ -73,7 +73,7 @@ def test_timeout():
def test_rude_shutdown():
if test_support.verbose:
- print "test_rude_shutdown ..."
+ print("test_rude_shutdown ...")
try:
import threading
diff --git a/Lib/test/test_socketserver.py b/Lib/test/test_socketserver.py
index 202f2da..062be65 100644
--- a/Lib/test/test_socketserver.py
+++ b/Lib/test/test_socketserver.py
@@ -77,16 +77,16 @@ class ServerThread(threading.Thread):
def run(self):
class svrcls(MyMixinServer, self.__svrcls):
pass
- if verbose: print "thread: creating server"
+ if verbose: print("thread: creating server")
svr = svrcls(self.__addr, self.__hdlrcls)
# pull the address out of the server in case it changed
# this can happen if another process is using the port
addr = getattr(svr, 'server_address')
if addr:
self.__addr = addr
- if verbose: print "thread: serving three times"
+ if verbose: print("thread: serving three times")
svr.serve_a_few()
- if verbose: print "thread: done"
+ if verbose: print("thread: done")
seed = 0
def pickport():
@@ -129,19 +129,19 @@ def testloop(proto, servers, hdlrcls, testfunc):
for svrcls in servers:
addr = pickaddr(proto)
if verbose:
- print "ADDR =", addr
- print "CLASS =", svrcls
+ print("ADDR =", addr)
+ print("CLASS =", svrcls)
t = ServerThread(addr, svrcls, hdlrcls)
- if verbose: print "server created"
+ if verbose: print("server created")
t.start()
- if verbose: print "server running"
+ if verbose: print("server running")
for i in range(NREQ):
time.sleep(DELAY)
- if verbose: print "test client", i
+ if verbose: print("test client", i)
testfunc(proto, addr)
- if verbose: print "waiting for server"
+ if verbose: print("waiting for server")
t.join()
- if verbose: print "done"
+ if verbose: print("done")
class ForgivingTCPServer(TCPServer):
# prevent errors if another process is using the port we want
@@ -159,8 +159,7 @@ class ForgivingTCPServer(TCPServer):
(err, msg) = e
if err != errno.EADDRINUSE:
raise
- print >>sys.__stderr__, \
- ' WARNING: failed to listen on port %d, trying another' % port
+ print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__)
tcpservers = [ForgivingTCPServer, ThreadingTCPServer]
if hasattr(os, 'fork') and os.name not in ('os2',):
diff --git a/Lib/test/test_softspace.py b/Lib/test/test_softspace.py
index 5405ba3..c0b4e8f 100644
--- a/Lib/test/test_softspace.py
+++ b/Lib/test/test_softspace.py
@@ -5,10 +5,10 @@ import StringIO
f = StringIO.StringIO()
class C:
def __str__(self):
- print >> f, 'a'
+ print('a', file=f)
return 'b'
-print >> f, C(), 'c ', 'd\t', 'e'
-print >> f, 'f', 'g'
+print(C(), 'c ', 'd\t', 'e', file=f)
+print('f', 'g', file=f)
# In 2.2 & earlier, this printed ' a\nbc d\te\nf g\n'
test_support.vereq(f.getvalue(), 'a\nb c d\te\nf g\n')
diff --git a/Lib/test/test_sort.py b/Lib/test/test_sort.py
index 031780a..ad3a817 100644
--- a/Lib/test/test_sort.py
+++ b/Lib/test/test_sort.py
@@ -10,7 +10,7 @@ def check(tag, expected, raw, compare=None):
global nerrors
if verbose:
- print " checking", tag
+ print(" checking", tag)
orig = raw[:] # save input in case of error
if compare:
@@ -19,22 +19,22 @@ def check(tag, expected, raw, compare=None):
raw.sort()
if len(expected) != len(raw):
- print "error in", tag
- print "length mismatch;", len(expected), len(raw)
- print expected
- print orig
- print raw
+ print("error in", tag)
+ print("length mismatch;", len(expected), len(raw))
+ print(expected)
+ print(orig)
+ print(raw)
nerrors += 1
return
for i, good in enumerate(expected):
maybe = raw[i]
if good is not maybe:
- print "error in", tag
- print "out of order at index", i, good, maybe
- print expected
- print orig
- print raw
+ print("error in", tag)
+ print("out of order at index", i, good, maybe)
+ print(expected)
+ print(orig)
+ print(raw)
nerrors += 1
return
@@ -56,7 +56,7 @@ class TestBase(unittest.TestCase):
def __lt__(self, other):
if Complains.maybe_complain and random.random() < 0.001:
if verbose:
- print " complaining at", self, other
+ print(" complaining at", self, other)
raise RuntimeError
return self.i < other.i
@@ -77,7 +77,7 @@ class TestBase(unittest.TestCase):
for n in sizes:
x = range(n)
if verbose:
- print "Testing size", n
+ print("Testing size", n)
s = x[:]
check("identity", x, s)
@@ -96,8 +96,8 @@ class TestBase(unittest.TestCase):
check("reversed via function", y, s, lambda a, b: cmp(b, a))
if verbose:
- print " Checking against an insane comparison function."
- print " If the implementation isn't careful, this may segfault."
+ print(" Checking against an insane comparison function.")
+ print(" If the implementation isn't careful, this may segfault.")
s = x[:]
s.sort(lambda a, b: int(random.random() * 3) - 1)
check("an insane function left some permutation", x, s)
@@ -285,7 +285,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_strftime.py b/Lib/test/test_strftime.py
index 26bae1b..c6db3dd 100755
--- a/Lib/test/test_strftime.py
+++ b/Lib/test/test_strftime.py
@@ -40,7 +40,7 @@ def escapestr(text, ampm):
def strftest(now):
if verbose:
- print "strftime test for", time.ctime(now)
+ print("strftime test for", time.ctime(now))
nowsecs = str(int(now))[:-1]
gmt = time.gmtime(now)
now = time.localtime(now)
@@ -113,42 +113,42 @@ def strftest(now):
)
if verbose:
- print "Strftime test, platform: %s, Python version: %s" % \
- (sys.platform, sys.version.split()[0])
+ print("Strftime test, platform: %s, Python version: %s" % \
+ (sys.platform, sys.version.split()[0]))
for e in expectations:
try:
result = time.strftime(e[0], now)
except ValueError as error:
- print "Standard '%s' format gave error:" % e[0], error
+ print("Standard '%s' format gave error:" % e[0], error)
continue
if re.match(escapestr(e[1], ampm), result): continue
if not result or result[0] == '%':
- print "Does not support standard '%s' format (%s)" % (e[0], e[2])
+ print("Does not support standard '%s' format (%s)" % (e[0], e[2]))
else:
- print "Conflict for %s (%s):" % (e[0], e[2])
- print " Expected %s, but got %s" % (e[1], result)
+ print("Conflict for %s (%s):" % (e[0], e[2]))
+ print(" Expected %s, but got %s" % (e[1], result))
for e in nonstandard_expectations:
try:
result = time.strftime(e[0], now)
except ValueError as result:
if verbose:
- print "Error for nonstandard '%s' format (%s): %s" % \
- (e[0], e[2], str(result))
+ print("Error for nonstandard '%s' format (%s): %s" % \
+ (e[0], e[2], str(result)))
continue
if re.match(escapestr(e[1], ampm), result):
if verbose:
- print "Supports nonstandard '%s' format (%s)" % (e[0], e[2])
+ print("Supports nonstandard '%s' format (%s)" % (e[0], e[2]))
elif not result or result[0] == '%':
if verbose:
- print "Does not appear to support '%s' format (%s)" % (e[0],
- e[2])
+ print("Does not appear to support '%s' format (%s)" % (e[0],
+ e[2]))
else:
if verbose:
- print "Conflict for nonstandard '%s' format (%s):" % (e[0],
- e[2])
- print " Expected %s, but got %s" % (e[1], result)
+ print("Conflict for nonstandard '%s' format (%s):" % (e[0],
+ e[2]))
+ print(" Expected %s, but got %s" % (e[1], result))
def fixasctime(s):
if s[8] == ' ':
diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py
index e0f0971..21cba89 100644
--- a/Lib/test/test_struct.py
+++ b/Lib/test/test_struct.py
@@ -114,7 +114,7 @@ for prefix in ('', '@', '<', '>', '=', '!'):
for format in ('xcbhilfdt', 'xcBHILfdt'):
format = prefix + format
if verbose:
- print "trying:", format
+ print("trying:", format)
s = struct.pack(format, c, b, h, i, l, f, d, t)
cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s)
if (cp != c or bp != b or hp != h or ip != i or lp != l or
@@ -169,7 +169,7 @@ tests = [
for fmt, arg, big, lil, asy in tests:
if verbose:
- print "%r %r %r %r" % (fmt, arg, big, lil)
+ print("%r %r %r %r" % (fmt, arg, big, lil))
for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
('='+fmt, ISBIGENDIAN and big or lil)]:
res = struct.pack(xfmt, arg)
@@ -195,7 +195,7 @@ except struct.error:
has_native_qQ = 0
if verbose:
- print "Platform has native q/Q?", has_native_qQ and "Yes." or "No."
+ print("Platform has native q/Q?", has_native_qQ and "Yes." or "No.")
any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless
simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless
@@ -258,7 +258,7 @@ class IntTester:
unpack=struct.unpack,
unhexlify=binascii.unhexlify):
if verbose:
- print "trying std", self.formatpair, "on", x, "==", hex(x)
+ print("trying std", self.formatpair, "on", x, "==", hex(x))
# Try signed.
code = self.signed_code
@@ -313,7 +313,7 @@ class IntTester:
# x is out of range -- verify pack realizes that.
if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK:
if verbose:
- print "Skipping buggy range check for code", code
+ print("Skipping buggy range check for code", code)
else:
deprecated_err(pack, ">" + code, x)
deprecated_err(pack, "<" + code, x)
@@ -368,7 +368,7 @@ class IntTester:
# x is out of range -- verify pack realizes that.
if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK:
if verbose:
- print "Skipping buggy range check for code", code
+ print("Skipping buggy range check for code", code)
else:
deprecated_err(pack, ">" + code, x)
deprecated_err(pack, "<" + code, x)
@@ -627,13 +627,13 @@ def test_bool():
falseFormat = prefix + 't' * len(false)
if verbose:
- print 'trying bool pack/unpack on', false, 'using format', falseFormat
+ print('trying bool pack/unpack on', false, 'using format', falseFormat)
packedFalse = struct.pack(falseFormat, *false)
unpackedFalse = struct.unpack(falseFormat, packedFalse)
trueFormat = prefix + 't' * len(true)
if verbose:
- print 'trying bool pack/unpack on', true, 'using format', trueFormat
+ print('trying bool pack/unpack on', true, 'using format', trueFormat)
packedTrue = struct.pack(trueFormat, *true)
unpackedTrue = struct.unpack(trueFormat, packedTrue)
@@ -650,7 +650,7 @@ def test_bool():
raise TestFailed('%r did not unpack as false' % t)
if prefix and verbose:
- print 'trying size of bool with format %r' % (prefix+'t')
+ print('trying size of bool with format %r' % (prefix+'t'))
packed = struct.pack(prefix+'t', 1)
if len(packed) != struct.calcsize(prefix+'t'):
@@ -659,7 +659,7 @@ def test_bool():
if len(packed) != 1 and prefix:
raise TestFailed('encoded bool is not one byte: %r' % packed)
elif not prefix and verbose:
- print 'size of bool in native format is %i' % (len(packed))
+ print('size of bool in native format is %i' % (len(packed)))
for c in '\x01\x7f\xff\x0f\xf0':
if struct.unpack('>t', c)[0] is not True:
diff --git a/Lib/test/test_sundry.py b/Lib/test/test_sundry.py
index f19467c..dcc21ac 100644
--- a/Lib/test/test_sundry.py
+++ b/Lib/test/test_sundry.py
@@ -68,7 +68,7 @@ try:
import tty # not available on Windows
except ImportError:
if verbose:
- print "skipping tty"
+ print("skipping tty")
# Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
# can screw up all sorts of things (esp. if it prints!).
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py
index 0b37306..6cc52ea 100644
--- a/Lib/test/test_support.py
+++ b/Lib/test/test_support.py
@@ -106,8 +106,7 @@ def bind_port(sock, host='', preferred_port=54321):
(err, msg) = e
if err != errno.EADDRINUSE:
raise
- print >>sys.__stderr__, \
- ' WARNING: failed to listen on port %d, trying another' % port
+ print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__)
raise TestFailed, 'unable to find port to listen on'
FUZZ = 1e-6
@@ -178,10 +177,9 @@ else:
except UnicodeEncodeError:
pass
else:
- print \
- 'WARNING: The filename %r CAN be encoded by the filesystem. ' \
+ print('WARNING: The filename %r CAN be encoded by the filesystem. ' \
'Unicode filename tests may not be effective' \
- % TESTFN_UNICODE_UNENCODEABLE
+ % TESTFN_UNICODE_UNENCODEABLE)
# Make sure we can write to TESTFN, try in /tmp if we can't
fp = None
@@ -194,8 +192,8 @@ except IOError:
TESTFN = TMP_TESTFN
del TMP_TESTFN
except IOError:
- print ('WARNING: tests will fail, unable to write to: %s or %s' %
- (TESTFN, TMP_TESTFN))
+ print(('WARNING: tests will fail, unable to write to: %s or %s' %
+ (TESTFN, TMP_TESTFN)))
if fp is not None:
fp.close()
unlink(TESTFN)
@@ -267,7 +265,7 @@ def open_urlresource(url):
return open(fn)
requires('urlfetch')
- print >> get_original_stdout(), '\tfetching %s ...' % url
+ print('\tfetching %s ...' % url, file=get_original_stdout())
fn, _ = urllib.urlretrieve(url, filename)
return open(fn)
@@ -514,7 +512,7 @@ def run_doctest(module, verbosity=None):
finally:
sys.stdout = save_stdout
if verbose:
- print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
+ print('doctest (%s) ... %d tests with zero failures' % (module.__name__, t))
return f, t
#=======================================================================
diff --git a/Lib/test/test_thread.py b/Lib/test/test_thread.py
index c4c21fe..5705798 100644
--- a/Lib/test/test_thread.py
+++ b/Lib/test/test_thread.py
@@ -21,10 +21,10 @@ def task(ident):
delay = random.random() * numtasks
rmutex.release()
if verbose:
- print 'task', ident, 'will run for', round(delay, 1), 'sec'
+ print('task', ident, 'will run for', round(delay, 1), 'sec')
time.sleep(delay)
if verbose:
- print 'task', ident, 'done'
+ print('task', ident, 'done')
mutex.acquire()
running = running - 1
if running == 0:
@@ -37,7 +37,7 @@ def newtask():
mutex.acquire()
next_ident = next_ident + 1
if verbose:
- print 'creating task', next_ident
+ print('creating task', next_ident)
thread.start_new_thread(task, (next_ident,))
running = running + 1
mutex.release()
@@ -45,9 +45,9 @@ def newtask():
for i in range(numtasks):
newtask()
-print 'waiting for all tasks to complete'
+print('waiting for all tasks to complete')
done.acquire()
-print 'all tasks done'
+print('all tasks done')
class barrier:
def __init__(self, n):
@@ -89,13 +89,13 @@ def task2(ident):
delay = random.random() * numtasks
rmutex.release()
if verbose:
- print 'task', ident, 'will run for', round(delay, 1), 'sec'
+ print('task', ident, 'will run for', round(delay, 1), 'sec')
time.sleep(delay)
if verbose:
- print 'task', ident, 'entering barrier', i
+ print('task', ident, 'entering barrier', i)
bar.enter()
if verbose:
- print 'task', ident, 'leaving barrier', i
+ print('task', ident, 'leaving barrier', i)
mutex.acquire()
running -= 1
# Must release mutex before releasing done, else the main thread can
@@ -106,7 +106,7 @@ def task2(ident):
if finished:
done.release()
-print '\n*** Barrier Test ***'
+print('\n*** Barrier Test ***')
if done.acquire(0):
raise ValueError, "'done' should have remained acquired"
bar = barrier(numtasks)
@@ -114,10 +114,10 @@ running = numtasks
for i in range(numtasks):
thread.start_new_thread(task2, (i,))
done.acquire()
-print 'all tasks done'
+print('all tasks done')
# not all platforms support changing thread stack size
-print '\n*** Changing thread stack size ***'
+print('\n*** Changing thread stack size ***')
if thread.stack_size() != 0:
raise ValueError, "initial stack_size not 0"
@@ -132,10 +132,10 @@ if os_name in ("nt", "os2", "posix"):
try:
thread.stack_size(4096)
except ValueError:
- print 'caught expected ValueError setting stack_size(4096)'
+ print('caught expected ValueError setting stack_size(4096)')
except thread.error:
tss_supported = 0
- print 'platform does not support changing thread stack size'
+ print('platform does not support changing thread stack size')
if tss_supported:
failed = lambda s, e: s != e
@@ -144,17 +144,17 @@ if os_name in ("nt", "os2", "posix"):
thread.stack_size(tss)
if failed(thread.stack_size(), tss):
raise ValueError, fail_msg % tss
- print 'successfully set stack_size(%d)' % tss
+ print('successfully set stack_size(%d)' % tss)
for tss in (262144, 0x100000):
- print 'trying stack_size = %d' % tss
+ print('trying stack_size = %d' % tss)
next_ident = 0
for i in range(numtasks):
newtask()
- print 'waiting for all tasks to complete'
+ print('waiting for all tasks to complete')
done.acquire()
- print 'all tasks done'
+ print('all tasks done')
# reset stack size to default
thread.stack_size(0)
diff --git a/Lib/test/test_threaded_import.py b/Lib/test/test_threaded_import.py
index 602ad2a..41a2b90 100644
--- a/Lib/test/test_threaded_import.py
+++ b/Lib/test/test_threaded_import.py
@@ -28,14 +28,14 @@ def task():
def test_import_hangers():
import sys
if verbose:
- print "testing import hangers ...",
+ print("testing import hangers ...", end=' ')
import test.threaded_import_hangers
try:
if test.threaded_import_hangers.errors:
raise TestFailed(test.threaded_import_hangers.errors)
elif verbose:
- print "OK."
+ print("OK.")
finally:
# In case this test is run again, make sure the helper module
# gets loaded from scratch again.
@@ -61,12 +61,12 @@ def test_main(): # magic name! see above
done.acquire()
for N in (20, 50) * 3:
if verbose:
- print "Trying", N, "threads ...",
+ print("Trying", N, "threads ...", end=' ')
for i in range(N):
thread.start_new_thread(task, ())
done.acquire()
if verbose:
- print "OK."
+ print("OK.")
done.release()
test_import_hangers()
diff --git a/Lib/test/test_threadedtempfile.py b/Lib/test/test_threadedtempfile.py
index 974333b..75d719d 100644
--- a/Lib/test/test_threadedtempfile.py
+++ b/Lib/test/test_threadedtempfile.py
@@ -50,26 +50,26 @@ def test_main():
threads = []
thread_info = threading_setup()
- print "Creating"
+ print("Creating")
for i in range(NUM_THREADS):
t = TempFileGreedy()
threads.append(t)
t.start()
- print "Starting"
+ print("Starting")
startEvent.set()
- print "Reaping"
+ print("Reaping")
ok = errors = 0
for t in threads:
t.join()
ok += t.ok_count
errors += t.error_count
if t.error_count:
- print '%s errors:\n%s' % (t.getName(), t.errors.getvalue())
+ print('%s errors:\n%s' % (t.getName(), t.errors.getvalue()))
msg = "Done: errors %d ok %d" % (errors, ok)
- print msg
+ print(msg)
if errors:
raise TestFailed(msg)
diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
index 8614ecb..95557c0 100644
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -30,27 +30,27 @@ class TestThread(threading.Thread):
def run(self):
delay = random.random() * 2
if verbose:
- print 'task', self.getName(), 'will run for', delay, 'sec'
+ print('task', self.getName(), 'will run for', delay, 'sec')
self.sema.acquire()
self.mutex.acquire()
self.nrunning.inc()
if verbose:
- print self.nrunning.get(), 'tasks are running'
+ print(self.nrunning.get(), 'tasks are running')
self.testcase.assert_(self.nrunning.get() <= 3)
self.mutex.release()
time.sleep(delay)
if verbose:
- print 'task', self.getName(), 'done'
+ print('task', self.getName(), 'done')
self.mutex.acquire()
self.nrunning.dec()
self.testcase.assert_(self.nrunning.get() >= 0)
if verbose:
- print self.getName(), 'is finished.', self.nrunning.get(), \
- 'tasks are running'
+ print(self.getName(), 'is finished.', self.nrunning.get(), \
+ 'tasks are running')
self.mutex.release()
self.sema.release()
@@ -77,23 +77,23 @@ class ThreadTests(unittest.TestCase):
t.start()
if verbose:
- print 'waiting for all tasks to complete'
+ print('waiting for all tasks to complete')
for t in threads:
t.join(NUMTASKS)
self.assert_(not t.isAlive())
if verbose:
- print 'all tasks done'
+ print('all tasks done')
self.assertEqual(numrunning.get(), 0)
# run with a small(ish) thread stack size (256kB)
def test_various_ops_small_stack(self):
if verbose:
- print 'with 256kB thread stack size...'
+ print('with 256kB thread stack size...')
try:
threading.stack_size(262144)
except thread.error:
if verbose:
- print 'platform does not support changing thread stack size'
+ print('platform does not support changing thread stack size')
return
self.test_various_ops()
threading.stack_size(0)
@@ -101,12 +101,12 @@ class ThreadTests(unittest.TestCase):
# run with a large thread stack size (1MB)
def test_various_ops_large_stack(self):
if verbose:
- print 'with 1MB thread stack size...'
+ print('with 1MB thread stack size...')
try:
threading.stack_size(0x100000)
except thread.error:
if verbose:
- print 'platform does not support changing thread stack size'
+ print('platform does not support changing thread stack size')
return
self.test_various_ops()
threading.stack_size(0)
@@ -138,7 +138,7 @@ class ThreadTests(unittest.TestCase):
import ctypes
except ImportError:
if verbose:
- print "test_PyThreadState_SetAsyncExc can't import ctypes"
+ print("test_PyThreadState_SetAsyncExc can't import ctypes")
return # can't do anything
set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
@@ -172,31 +172,31 @@ class ThreadTests(unittest.TestCase):
t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
t.start()
if verbose:
- print " started worker thread"
+ print(" started worker thread")
# Try a thread id that doesn't make sense.
if verbose:
- print " trying nonsensical thread id"
+ print(" trying nonsensical thread id")
result = set_async_exc(ctypes.c_long(-1), exception)
self.assertEqual(result, 0) # no thread states modified
# Now raise an exception in the worker thread.
if verbose:
- print " waiting for worker thread to get started"
+ print(" waiting for worker thread to get started")
worker_started.wait()
if verbose:
- print " verifying worker hasn't exited"
+ print(" verifying worker hasn't exited")
self.assert_(not t.finished)
if verbose:
- print " attempting to raise asynch exception in worker"
+ print(" attempting to raise asynch exception in worker")
result = set_async_exc(ctypes.c_long(t.id), exception)
self.assertEqual(result, 1) # one thread state modified
if verbose:
- print " waiting for worker to say it caught the exception"
+ print(" waiting for worker to say it caught the exception")
worker_saw_exception.wait(timeout=10)
self.assert_(t.finished)
if verbose:
- print " all OK -- joining worker"
+ print(" all OK -- joining worker")
if t.finished:
t.join()
# else the thread is still running, and we have no way to kill it
diff --git a/Lib/test/test_tokenize.py b/Lib/test/test_tokenize.py
index de6e888..7d6a818 100644
--- a/Lib/test/test_tokenize.py
+++ b/Lib/test/test_tokenize.py
@@ -118,12 +118,12 @@ def dump_tokens(s):
if type == ENDMARKER:
break
type = tok_name[type]
- print "%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals()
+ print("%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals())
def roundtrip(s):
f = StringIO(s)
source = untokenize(generate_tokens(f.readline))
- print source,
+ print(source, end=' ')
# This is an example from the docs, set up as a doctest.
def decistmt(s):
@@ -165,7 +165,7 @@ def decistmt(s):
def test_main():
if verbose:
- print 'starting...'
+ print('starting...')
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
@@ -191,7 +191,7 @@ def test_main():
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, ' test_main still working, be patient...'
+ print(' test_main still working, be patient...', file=sys.__stdout__)
sys.__stdout__.flush()
test_roundtrip(f)
@@ -217,7 +217,7 @@ def foo():
run_doctest(test_tokenize, verbose)
if verbose:
- print 'finished'
+ print('finished')
def test_rarrow():
"""
diff --git a/Lib/test/test_trace.py b/Lib/test/test_trace.py
index 42d1a4a..7b5ac7d 100644
--- a/Lib/test/test_trace.py
+++ b/Lib/test/test_trace.py
@@ -309,7 +309,7 @@ class RaisingTraceFuncTestCase(unittest.TestCase):
def test_trash_stack(self):
def f():
for i in range(5):
- print i # line tracing will raise an exception at this line
+ print(i) # line tracing will raise an exception at this line
def g(frame, why, extra):
if (why == 'line' and
diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py
index 5c8a4e4..1ccb2b2 100644
--- a/Lib/test/test_traceback.py
+++ b/Lib/test/test_traceback.py
@@ -60,9 +60,9 @@ class TracebackCases(unittest.TestCase):
try:
sys.path.insert(0, testdir)
testfile = os.path.join(testdir, 'test_bug737473.py')
- print >> open(testfile, 'w'), """
+ print("""
def test():
- raise ValueError"""
+ raise ValueError""", file=open(testfile, 'w'))
if 'test_bug737473' in sys.modules:
del sys.modules['test_bug737473']
@@ -82,9 +82,9 @@ def test():
# three seconds are needed for this test to pass reliably :-(
time.sleep(4)
- print >> open(testfile, 'w'), """
+ print("""
def test():
- raise NotImplementedError"""
+ raise NotImplementedError""", file=open(testfile, 'w'))
reload(test_bug737473)
try:
test_bug737473.test()
diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py
index 5c70df1..bb3338b 100644
--- a/Lib/test/test_unicode.py
+++ b/Lib/test/test_unicode.py
@@ -732,15 +732,15 @@ class UnicodeTest(
pass
out = BitBucket()
- print >>out, u'abc'
- print >>out, u'abc', u'def'
- print >>out, u'abc', 'def'
- print >>out, 'abc', u'def'
- print >>out, u'abc\n'
- print >>out, u'abc\n',
- print >>out, u'abc\n',
- print >>out, u'def\n'
- print >>out, u'def\n'
+ print(u'abc', file=out)
+ print(u'abc', u'def', file=out)
+ print(u'abc', 'def', file=out)
+ print('abc', u'def', file=out)
+ print(u'abc\n', file=out)
+ print(u'abc\n', end=' ', file=out)
+ print(u'abc\n', end=' ', file=out)
+ print(u'def\n', file=out)
+ print(u'def\n', file=out)
def test_ucs4(self):
if sys.maxunicode == 0xFFFF:
diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py
index 25aa307..a7fc60a 100644
--- a/Lib/test/test_userdict.py
+++ b/Lib/test/test_userdict.py
@@ -79,7 +79,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
self.assertEqual(u2b, u2c)
class MyUserDict(UserDict.UserDict):
- def display(self): print self
+ def display(self): print(self)
m2 = MyUserDict(u2)
m2a = m2.copy()
diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py
index f1d1d1c..3e5f77d 100644
--- a/Lib/test/test_uuid.py
+++ b/Lib/test/test_uuid.py
@@ -307,9 +307,8 @@ class TestUUID(TestCase):
def test_ifconfig_getnode(self):
import sys
- print >>sys.__stdout__, \
-""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms.
- It is disabled until the code and/or test can be fixed properly."""
+ print(""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms.
+ It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__)
return
import os
@@ -336,9 +335,8 @@ class TestUUID(TestCase):
def test_unixdll_getnode(self):
import sys
- print >>sys.__stdout__, \
-""" WARNING: uuid._unixdll_getnode is unreliable on many platforms.
- It is disabled until the code and/or test can be fixed properly."""
+ print(""" WARNING: uuid._unixdll_getnode is unreliable on many platforms.
+ It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__)
return
import os
@@ -352,9 +350,8 @@ class TestUUID(TestCase):
def test_getnode(self):
import sys
- print >>sys.__stdout__, \
-""" WARNING: uuid.getnode is unreliable on many platforms.
- It is disabled until the code and/or test can be fixed properly."""
+ print(""" WARNING: uuid.getnode is unreliable on many platforms.
+ It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__)
return
node1 = uuid.getnode()
diff --git a/Lib/test/test_winreg.py b/Lib/test/test_winreg.py
index 81bd760..08de67c 100644
--- a/Lib/test/test_winreg.py
+++ b/Lib/test/test_winreg.py
@@ -133,7 +133,7 @@ def TestAll(root_key):
# Test on my local machine.
TestAll(HKEY_CURRENT_USER)
-print "Local registry tests worked"
+print("Local registry tests worked")
try:
remote_name = sys.argv[sys.argv.index("--remote")+1]
except (IndexError, ValueError):
@@ -143,14 +143,14 @@ if remote_name is not None:
try:
remote_key = ConnectRegistry(remote_name, HKEY_CURRENT_USER)
except EnvironmentError as exc:
- print "Could not connect to the remote machine -", exc.strerror
+ print("Could not connect to the remote machine -", exc.strerror)
remote_key = None
if remote_key is not None:
TestAll(remote_key)
- print "Remote registry tests worked"
+ print("Remote registry tests worked")
else:
- print "Remote registry calls can be tested using",
- print "'test_winreg.py --remote \\\\machine_name'"
+ print("Remote registry calls can be tested using", end=' ')
+ print("'test_winreg.py --remote \\\\machine_name'")
# perform minimal ConnectRegistry test which just invokes it
h = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
h.Close()
diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py
index 78adb42..6df19c4 100644
--- a/Lib/test/test_xml_etree.py
+++ b/Lib/test/test_xml_etree.py
@@ -37,7 +37,7 @@ def sanity():
def check_method(method):
if not callable(method):
- print method, "not callable"
+ print(method, "not callable")
def serialize(ET, elem, encoding=None):
import StringIO
diff --git a/Lib/test/test_xml_etree_c.py b/Lib/test/test_xml_etree_c.py
index 250f791..75b5a82 100644
--- a/Lib/test/test_xml_etree_c.py
+++ b/Lib/test/test_xml_etree_c.py
@@ -35,7 +35,7 @@ def sanity():
def check_method(method):
if not callable(method):
- print method, "not callable"
+ print(method, "not callable")
def serialize(ET, elem, encoding=None):
import StringIO
diff --git a/Lib/test/test_zipfile64.py b/Lib/test/test_zipfile64.py
index 449cf39..445e23d 100644
--- a/Lib/test/test_zipfile64.py
+++ b/Lib/test/test_zipfile64.py
@@ -57,9 +57,9 @@ class TestsWithSourceFile(unittest.TestCase):
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, (
+ print((
' zipTest still writing %d of %d, be patient...' %
- (num, filecount))
+ (num, filecount)), file=sys.__stdout__)
sys.__stdout__.flush()
zipfp.close()
@@ -70,9 +70,9 @@ class TestsWithSourceFile(unittest.TestCase):
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, (
+ print((
' zipTest still reading %d of %d, be patient...' %
- (num, filecount))
+ (num, filecount)), file=sys.__stdout__)
sys.__stdout__.flush()
zipfp.close()
diff --git a/Lib/test/time_hashlib.py b/Lib/test/time_hashlib.py
index de25cfd..c210bd2 100644
--- a/Lib/test/time_hashlib.py
+++ b/Lib/test/time_hashlib.py
@@ -18,7 +18,7 @@ def test_scaled_msg(scale, name):
x = localCF(longStr).digest()
end = time.time()
- print ('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name
+ print(('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name)
def test_create():
start = time.time()
@@ -26,7 +26,7 @@ def test_create():
d = creatorFunc()
end = time.time()
- print ('%2.2f' % (end-start)), "seconds", '[20000 creations]'
+ print(('%2.2f' % (end-start)), "seconds", '[20000 creations]')
def test_zero():
start = time.time()
@@ -34,7 +34,7 @@ def test_zero():
x = creatorFunc().digest()
end = time.time()
- print ('%2.2f' % (end-start)), "seconds", '[20000 "" digests]'
+ print(('%2.2f' % (end-start)), "seconds", '[20000 "" digests]')
@@ -46,33 +46,33 @@ hName = sys.argv[1]
if hName in ('_md5', '_sha'):
exec('import '+hName)
exec('creatorFunc = '+hName+'.new')
- print "testing speed of old", hName, "legacy interface"
+ print("testing speed of old", hName, "legacy interface")
elif hName == '_hashlib' and len(sys.argv) > 3:
import _hashlib
exec('creatorFunc = _hashlib.%s' % sys.argv[2])
- print "testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])
+ print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2]))
elif hName == '_hashlib' and len(sys.argv) == 3:
import _hashlib
exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2])
- print "testing speed of _hashlib.new(%r)" % sys.argv[2]
+ print("testing speed of _hashlib.new(%r)" % sys.argv[2])
elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)):
creatorFunc = getattr(hashlib, hName)
- print "testing speed of hashlib."+hName, getattr(hashlib, hName)
+ print("testing speed of hashlib."+hName, getattr(hashlib, hName))
else:
exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName)
- print "testing speed of hashlib.new(%r)" % hName
+ print("testing speed of hashlib.new(%r)" % hName)
try:
test_create()
except ValueError:
- print
- print "pass argument(s) naming the hash to run a speed test on:"
- print " '_md5' and '_sha' test the legacy builtin md5 and sha"
- print " '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib"
- print " '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)"
- print " 'hName' tests the hashlib.hName() implementation if it exists"
- print " otherwise it uses hashlib.new(hName)."
- print
+ print()
+ print("pass argument(s) naming the hash to run a speed test on:")
+ print(" '_md5' and '_sha' test the legacy builtin md5 and sha")
+ print(" '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib")
+ print(" '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)")
+ print(" 'hName' tests the hashlib.hName() implementation if it exists")
+ print(" otherwise it uses hashlib.new(hName).")
+ print()
raise
test_zero()