]> granicus.if.org Git - python/commitdiff
Fix most trivially-findable print statements.
authorGuido van Rossum <guido@python.org>
Fri, 9 Feb 2007 05:37:30 +0000 (05:37 +0000)
committerGuido van Rossum <guido@python.org>
Fri, 9 Feb 2007 05:37:30 +0000 (05:37 +0000)
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.)

331 files changed:
Lib/BaseHTTPServer.py
Lib/Bastion.py
Lib/Cookie.py
Lib/DocXMLRPCServer.py
Lib/SimpleXMLRPCServer.py
Lib/SocketServer.py
Lib/StringIO.py
Lib/aifc.py
Lib/asyncore.py
Lib/atexit.py
Lib/audiodev.py
Lib/base64.py
Lib/bdb.py
Lib/bsddb/dbtables.py
Lib/bsddb/test/test_all.py
Lib/bsddb/test/test_associate.py
Lib/bsddb/test/test_basics.py
Lib/bsddb/test/test_compat.py
Lib/bsddb/test/test_dbshelve.py
Lib/bsddb/test/test_dbtables.py
Lib/bsddb/test/test_join.py
Lib/bsddb/test/test_lock.py
Lib/bsddb/test/test_queue.py
Lib/bsddb/test/test_recno.py
Lib/bsddb/test/test_thread.py
Lib/cProfile.py
Lib/calendar.py
Lib/cgi.py
Lib/code.py
Lib/compileall.py
Lib/compiler/future.py
Lib/compiler/pyassem.py
Lib/compiler/pycodegen.py
Lib/compiler/symbols.py
Lib/compiler/syntax.py
Lib/compiler/transformer.py
Lib/compiler/visitor.py
Lib/copy.py
Lib/ctypes/test/__init__.py
Lib/ctypes/test/test_byteswap.py
Lib/ctypes/test/test_find.py
Lib/ctypes/test/test_keeprefs.py
Lib/ctypes/test/test_loading.py
Lib/ctypes/test/test_numbers.py
Lib/ctypes/test/test_strings.py
Lib/ctypes/util.py
Lib/curses/has_key.py
Lib/curses/textpad.py
Lib/difflib.py
Lib/dis.py
Lib/distutils/bcppcompiler.py
Lib/distutils/ccompiler.py
Lib/distutils/cmd.py
Lib/distutils/command/bdist_rpm.py
Lib/distutils/command/config.py
Lib/distutils/command/install.py
Lib/distutils/command/register.py
Lib/distutils/command/upload.py
Lib/distutils/core.py
Lib/distutils/dist.py
Lib/distutils/fancy_getopt.py
Lib/distutils/filelist.py
Lib/distutils/log.py
Lib/distutils/mwerkscompiler.py
Lib/distutils/spawn.py
Lib/distutils/tests/test_dist.py
Lib/distutils/text_file.py
Lib/doctest.py
Lib/email/generator.py
Lib/email/iterators.py
Lib/email/test/test_email.py
Lib/email/test/test_email_renamed.py
Lib/filecmp.py
Lib/fileinput.py
Lib/formatter.py
Lib/fpformat.py
Lib/ftplib.py
Lib/getopt.py
Lib/getpass.py
Lib/gopherlib.py
Lib/gzip.py
Lib/heapq.py
Lib/hotshot/log.py
Lib/hotshot/stones.py
Lib/htmllib.py
Lib/httplib.py
Lib/idlelib/CallTips.py
Lib/idlelib/ColorDelegator.py
Lib/idlelib/Delegator.py
Lib/idlelib/EditorWindow.py
Lib/idlelib/FileList.py
Lib/idlelib/GrepDialog.py
Lib/idlelib/MultiCall.py
Lib/idlelib/Percolator.py
Lib/idlelib/PyShell.py
Lib/idlelib/ScrolledList.py
Lib/idlelib/UndoDelegator.py
Lib/idlelib/WidgetRedirector.py
Lib/idlelib/WindowList.py
Lib/idlelib/configHandler.py
Lib/idlelib/configHelpSourceEdit.py
Lib/idlelib/configSectionNameDialog.py
Lib/idlelib/keybindingDialog.py
Lib/idlelib/rpc.py
Lib/idlelib/run.py
Lib/ihooks.py
Lib/imaplib.py
Lib/imghdr.py
Lib/imputil.py
Lib/lib-tk/Dialog.py
Lib/lib-tk/FileDialog.py
Lib/lib-tk/SimpleDialog.py
Lib/lib-tk/Tkinter.py
Lib/lib-tk/tkColorChooser.py
Lib/lib-tk/tkFileDialog.py
Lib/lib-tk/tkFont.py
Lib/lib-tk/tkMessageBox.py
Lib/lib-tk/tkSimpleDialog.py
Lib/locale.py
Lib/logging/handlers.py
Lib/macurl2path.py
Lib/mailcap.py
Lib/mhlib.py
Lib/mimetypes.py
Lib/mimify.py
Lib/modulefinder.py
Lib/msilib/__init__.py
Lib/netrc.py
Lib/nntplib.py
Lib/optparse.py
Lib/pdb.py
Lib/pickletools.py
Lib/pipes.py
Lib/plat-irix5/cddb.py
Lib/plat-irix5/cdplayer.py
Lib/plat-irix5/flp.py
Lib/plat-irix5/panel.py
Lib/plat-irix6/cddb.py
Lib/plat-irix6/cdplayer.py
Lib/plat-irix6/flp.py
Lib/plat-irix6/panel.py
Lib/plat-mac/Audio_mac.py
Lib/plat-mac/EasyDialogs.py
Lib/plat-mac/FrameWork.py
Lib/plat-mac/MiniAEFrame.py
Lib/plat-mac/aetools.py
Lib/plat-mac/applesingle.py
Lib/plat-mac/argvemulator.py
Lib/plat-mac/bundlebuilder.py
Lib/plat-mac/findertools.py
Lib/plat-mac/gensuitemodule.py
Lib/plat-mac/ic.py
Lib/plat-mac/macresource.py
Lib/plat-mac/pimp.py
Lib/plat-mac/videoreader.py
Lib/plat-os2emx/_emx_link.py
Lib/plat-riscos/rourl2path.py
Lib/platform.py
Lib/popen2.py
Lib/poplib.py
Lib/pprint.py
Lib/profile.py
Lib/pstats.py
Lib/pyclbr.py
Lib/pydoc.py
Lib/quopri.py
Lib/random.py
Lib/rexec.py
Lib/rfc822.py
Lib/robotparser.py
Lib/runpy.py
Lib/sgmllib.py
Lib/shlex.py
Lib/site.py
Lib/smtpd.py
Lib/smtplib.py
Lib/sndhdr.py
Lib/sqlite3/test/dbapi.py
Lib/sre_constants.py
Lib/sre_parse.py
Lib/subprocess.py
Lib/sunaudio.py
Lib/symtable.py
Lib/tabnanny.py
Lib/tarfile.py
Lib/telnetlib.py
Lib/test/badsyntax_future8.py
Lib/test/badsyntax_future9.py
Lib/test/crashers/bogus_sre_bytecode.py
Lib/test/crashers/borrowed_ref_1.py
Lib/test/crashers/borrowed_ref_2.py
Lib/test/crashers/gc_inspection.py
Lib/test/crashers/loosing_mro_ref.py
Lib/test/crashers/modify_dict_attr.py
Lib/test/crashers/nasty_eq_vs_dict.py
Lib/test/inspect_fodder2.py
Lib/test/list_tests.py
Lib/test/pydocfodder.py
Lib/test/pystone.py
Lib/test/regrtest.py
Lib/test/reperf.py
Lib/test/sortperf.py
Lib/test/test_al.py
Lib/test/test_array.py
Lib/test/test_ast.py
Lib/test/test_atexit.py
Lib/test/test_audioop.py
Lib/test/test_bisect.py
Lib/test/test_bool.py
Lib/test/test_bsddb.py
Lib/test/test_bsddb3.py
Lib/test/test_builtin.py
Lib/test/test_capi.py
Lib/test/test_cd.py
Lib/test/test_cl.py
Lib/test/test_class.py
Lib/test/test_cmath.py
Lib/test/test_code.py
Lib/test/test_codecs.py
Lib/test/test_compiler.py
Lib/test/test_complex.py
Lib/test/test_crypt.py
Lib/test/test_csv.py
Lib/test/test_curses.py
Lib/test/test_datetime.py
Lib/test/test_dbm.py
Lib/test/test_decimal.py
Lib/test/test_defaultdict.py
Lib/test/test_deque.py
Lib/test/test_descr.py
Lib/test/test_dis.py
Lib/test/test_dl.py
Lib/test/test_doctest.py
Lib/test/test_dummy_thread.py
Lib/test/test_dummy_threading.py
Lib/test/test_enumerate.py
Lib/test/test_errno.py
Lib/test/test_extcall.py
Lib/test/test_fcntl.py
Lib/test/test_file.py
Lib/test/test_fileinput.py
Lib/test/test_format.py
Lib/test/test_funcattrs.py
Lib/test/test_functools.py
Lib/test/test_gc.py
Lib/test/test_gdbm.py
Lib/test/test_generators.py
Lib/test/test_genexps.py
Lib/test/test_getopt.py
Lib/test/test_gl.py
Lib/test/test_grammar.py
Lib/test/test_heapq.py
Lib/test/test_imageop.py
Lib/test/test_imgfile.py
Lib/test/test_import.py
Lib/test/test_itertools.py
Lib/test/test_largefile.py
Lib/test/test_linuxaudiodev.py
Lib/test/test_list.py
Lib/test/test_locale.py
Lib/test/test_long_future.py
Lib/test/test_minidom.py
Lib/test/test_module.py
Lib/test/test_multibytecodec.py
Lib/test/test_mutants.py
Lib/test/test_normalization.py
Lib/test/test_ntpath.py
Lib/test/test_operations.py
Lib/test/test_operator.py
Lib/test/test_ossaudiodev.py
Lib/test/test_peepholer.py
Lib/test/test_pep247.py
Lib/test/test_pep277.py
Lib/test/test_pkg.py
Lib/test/test_popen2.py
Lib/test/test_pty.py
Lib/test/test_pyclbr.py
Lib/test/test_pyexpat.py
Lib/test/test_queue.py
Lib/test/test_random.py
Lib/test/test_re.py
Lib/test/test_rfc822.py
Lib/test/test_rgbimg.py
Lib/test/test_runpy.py
Lib/test/test_sax.py
Lib/test/test_scope.py
Lib/test/test_select.py
Lib/test/test_signal.py
Lib/test/test_site.py
Lib/test/test_socket_ssl.py
Lib/test/test_socketserver.py
Lib/test/test_softspace.py
Lib/test/test_sort.py
Lib/test/test_strftime.py
Lib/test/test_struct.py
Lib/test/test_sundry.py
Lib/test/test_support.py
Lib/test/test_thread.py
Lib/test/test_threaded_import.py
Lib/test/test_threadedtempfile.py
Lib/test/test_threading.py
Lib/test/test_tokenize.py
Lib/test/test_trace.py
Lib/test/test_traceback.py
Lib/test/test_unicode.py
Lib/test/test_userdict.py
Lib/test/test_uuid.py
Lib/test/test_winreg.py
Lib/test/test_xml_etree.py
Lib/test/test_xml_etree_c.py
Lib/test/test_zipfile64.py
Lib/test/time_hashlib.py
Lib/textwrap.py
Lib/this.py
Lib/threading.py
Lib/timeit.py
Lib/tokenize.py
Lib/trace.py
Lib/unittest.py
Lib/urllib.py
Lib/urlparse.py
Lib/uu.py
Lib/warnings.py
Lib/webbrowser.py
Lib/whichdb.py
Lib/wsgiref/simple_server.py
Lib/xml/dom/pulldom.py
Lib/xml/sax/handler.py
Lib/xmllib.py
Lib/xmlrpclib.py
Lib/zipfile.py

index ae916b6c96f34585f615567df9a34fb25ee3bcb6..982c9d2c0f3ad2adbca6957d4ccd7f0f62c01483 100644 (file)
@@ -570,7 +570,7 @@ def test(HandlerClass = BaseHTTPRequestHandler,
     httpd = ServerClass(server_address, HandlerClass)
 
     sa = httpd.socket.getsockname()
-    print "Serving HTTP on", sa[0], "port", sa[1], "..."
+    print("Serving HTTP on", sa[0], "port", sa[1], "...")
     httpd.serve_forever()
 
 
index 2127f46dbaff00e45a6306d9ed12c064b3e5e3c4..6a5cb5c60551499b73ed617b145955b9cde784f8 100644 (file)
@@ -165,7 +165,7 @@ def _test():
         print "accessible"
     \n"""
     exec(testcode)
-    print '='*20, "Using rexec:", '='*20
+    print('='*20, "Using rexec:", '='*20)
     import rexec
     r = rexec.RExec()
     m = r.add_module('__main__')
index 46ef3ea61c77cf5a670a01d83ba8f5c54dcfe67d..fb06840de9f834c41916a7e2a42ff89865cbc4d8 100644 (file)
@@ -80,9 +80,9 @@ attributes by using the .output() function
    >>> C = Cookie.SmartCookie()
    >>> C["rocky"] = "road"
    >>> C["rocky"]["path"] = "/cookie"
-   >>> print C.output(header="Cookie:")
+   >>> print(C.output(header="Cookie:"))
    Cookie: rocky=road; Path=/cookie
-   >>> print C.output(attrs=[], header="Cookie:")
+   >>> print(C.output(attrs=[], header="Cookie:"))
    Cookie: rocky=road
 
 The load() method of a Cookie extracts cookies from a string.  In a
@@ -100,7 +100,7 @@ such trickeries do not confuse it.
 
    >>> C = Cookie.SmartCookie()
    >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
-   >>> print C
+   >>> print(C)
    Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
 
 Each element of the Cookie also supports all of the RFC 2109
@@ -110,7 +110,7 @@ attribute.
    >>> C = Cookie.SmartCookie()
    >>> C["oreo"] = "doublestuff"
    >>> C["oreo"]["path"] = "/"
-   >>> print C
+   >>> print(C)
    Set-Cookie: oreo=doublestuff; Path=/
 
 Each dictionary element has a 'value' attribute, which gives you
@@ -198,7 +198,7 @@ it is still possible to use Cookie.Cookie() to create a Cookie.  In
 fact, this simply returns a SmartCookie.
 
    >>> C = Cookie.Cookie()
-   >>> print C.__class__.__name__
+   >>> print(C.__class__.__name__)
    SmartCookie
 
 
index ddd56047d4d4e8b201098dd2eb73a92fa8c8f84d..fd3b2c9d18b016c165fe8b3abded852719e184b3 100644 (file)
@@ -270,9 +270,9 @@ class DocCGIXMLRPCRequestHandler(   CGIXMLRPCRequestHandler,
 
         response = self.generate_html_documentation()
 
-        print 'Content-Type: text/html'
-        print 'Content-Length: %d' % len(response)
-        print
+        print('Content-Type: text/html')
+        print('Content-Length: %d' % len(response))
+        print()
         sys.stdout.write(response)
 
     def __init__(self):
index 0a62b47fe505f368560b0d3de3f9261ad4eb1a55..814ede1025413b456b573869615533682278ecff 100644 (file)
@@ -543,9 +543,9 @@ class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
 
         response = self._marshaled_dispatch(request_text)
 
-        print 'Content-Type: text/xml'
-        print 'Content-Length: %d' % len(response)
-        print
+        print('Content-Type: text/xml')
+        print('Content-Length: %d' % len(response))
+        print()
         sys.stdout.write(response)
 
     def handle_get(self):
@@ -565,10 +565,10 @@ class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
              'message' : message,
              'explain' : explain
             }
-        print 'Status: %d %s' % (code, message)
-        print 'Content-Type: text/html'
-        print 'Content-Length: %d' % len(response)
-        print
+        print('Status: %d %s' % (code, message))
+        print('Content-Type: text/html')
+        print('Content-Length: %d' % len(response))
+        print()
         sys.stdout.write(response)
 
     def handle_request(self, request_text = None):
@@ -590,7 +590,7 @@ class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
             self.handle_xmlrpc(request_text)
 
 if __name__ == '__main__':
-    print 'Running XML-RPC server on port 8000'
+    print('Running XML-RPC server on port 8000')
     server = SimpleXMLRPCServer(("localhost", 8000))
     server.register_function(pow)
     server.register_function(lambda x,y: x+y, 'add')
index 3a74c444ba182ed01edf50bbe4a78c7108906bf3..eedb25149a1cea42b67d9df8e6323f5ebfa0e45e 100644 (file)
@@ -263,12 +263,12 @@ class BaseServer:
         The default is to print a traceback and continue.
 
         """
-        print '-'*40
-        print 'Exception happened during processing of request from',
-        print client_address
+        print('-'*40)
+        print('Exception happened during processing of request from', end=' ')
+        print(client_address)
         import traceback
         traceback.print_exc() # XXX But this goes to stderr!
-        print '-'*40
+        print('-'*40)
 
 
 class TCPServer(BaseServer):
index 9394360fa784195a45e466f58c0ba0c6c2655743..a6b0ea4061d93b0ffb6b1d892b747d5e565ba497 100644 (file)
@@ -291,14 +291,14 @@ def test():
     if f.getvalue() != text:
         raise RuntimeError, 'write failed'
     length = f.tell()
-    print 'File length =', length
+    print('File length =', length)
     f.seek(len(lines[0]))
     f.write(lines[1])
     f.seek(0)
-    print 'First line =', repr(f.readline())
-    print 'Position =', f.tell()
+    print('First line =', repr(f.readline()))
+    print('Position =', f.tell())
     line = f.readline()
-    print 'Second line =', repr(line)
+    print('Second line =', repr(line))
     f.seek(-len(line), 1)
     line2 = f.read(len(line))
     if line != line2:
@@ -310,13 +310,13 @@ def test():
     line2 = f.read()
     if line != line2:
         raise RuntimeError, 'bad result after seek back from EOF'
-    print 'Read', len(list), 'more lines'
-    print 'File length =', f.tell()
+    print('Read', len(list), 'more lines')
+    print('File length =', f.tell())
     if f.tell() != length:
         raise RuntimeError, 'bad length'
     f.truncate(length/2)
     f.seek(0, 2)
-    print 'Truncated length =', f.tell()
+    print('Truncated length =', f.tell())
     if f.tell() != length/2:
         raise RuntimeError, 'truncate did not adjust length'
     f.close()
index e28c5c0b9f8bab4cf3604ede38ac2768daef5865..bc82f48dc8b34dadd163648f1d68d0e830e09dfc 100644 (file)
@@ -453,7 +453,7 @@ class Aifc_read:
             kludge = 0
             if chunk.chunksize == 18:
                 kludge = 1
-                print 'Warning: bad COMM chunk size'
+                print('Warning: bad COMM chunk size')
                 chunk.chunksize = 23
             #DEBUG end
             self._comptype = chunk.read(4)
@@ -518,11 +518,11 @@ class Aifc_read:
                     # a position 0 and name ''
                     self._markers.append((id, pos, name))
         except EOFError:
-            print 'Warning: MARK chunk contains only',
-            print len(self._markers),
-            if len(self._markers) == 1: print 'marker',
-            else: print 'markers',
-            print 'instead of', nmarkers
+            print('Warning: MARK chunk contains only', end=' ')
+            print(len(self._markers), end=' ')
+            if len(self._markers) == 1: print('marker', end=' ')
+            else: print('markers', end=' ')
+            print('instead of', nmarkers)
 
 class Aifc_write:
     # Variables used in this class:
@@ -939,16 +939,16 @@ if __name__ == '__main__':
         sys.argv.append('/usr/demos/data/audio/bach.aiff')
     fn = sys.argv[1]
     f = open(fn, 'r')
-    print "Reading", fn
-    print "nchannels =", f.getnchannels()
-    print "nframes   =", f.getnframes()
-    print "sampwidth =", f.getsampwidth()
-    print "framerate =", f.getframerate()
-    print "comptype  =", f.getcomptype()
-    print "compname  =", f.getcompname()
+    print("Reading", fn)
+    print("nchannels =", f.getnchannels())
+    print("nframes   =", f.getnframes())
+    print("sampwidth =", f.getsampwidth())
+    print("framerate =", f.getframerate())
+    print("comptype  =", f.getcomptype())
+    print("compname  =", f.getcompname())
     if sys.argv[2:]:
         gn = sys.argv[2]
-        print "Writing", gn
+        print("Writing", gn)
         g = open(gn, 'w')
         g.setparams(f.getparams())
         while 1:
@@ -958,4 +958,4 @@ if __name__ == '__main__':
             g.writeframes(data)
         g.close()
         f.close()
-        print "Done."
+        print("Done.")
index 9eb6d7f2e24affb41d51565fc01251cffbf65234..fc110c9ef29c29651357eb1f07be6d2292cd03cf 100644 (file)
@@ -373,7 +373,7 @@ class dispatcher:
 
     def log_info(self, message, type='info'):
         if __debug__ or type != 'info':
-            print '%s: %s' % (type, message)
+            print('%s: %s' % (type, message))
 
     def handle_read_event(self):
         if self.accepting:
index 93fddf7f99a4473f971474745a74330059150010..51a153e7e918e1e784e48abf6fd32d113cc7764f 100644 (file)
@@ -26,7 +26,7 @@ def _run_exitfuncs():
             exc_info = sys.exc_info()
         except:
             import traceback
-            print >> sys.stderr, "Error in atexit._run_exitfuncs:"
+            print("Error in atexit._run_exitfuncs:", file=sys.stderr)
             traceback.print_exc()
             exc_info = sys.exc_info()
 
@@ -53,11 +53,11 @@ sys.exitfunc = _run_exitfuncs
 
 if __name__ == "__main__":
     def x1():
-        print "running x1"
+        print("running x1")
     def x2(n):
-        print "running x2(%r)" % (n,)
+        print("running x2(%r)" % (n,))
     def x3(n, kwd=None):
-        print "running x3(%r, kwd=%r)" % (n, kwd)
+        print("running x3(%r, kwd=%r)" % (n, kwd))
 
     register(x1)
     register(x2, 12)
index 8945c983c21a1f4996a5037f369cc08d95a10720..0585bcfb59a28b39fb413c0ded7309660e2ad30a 100644 (file)
@@ -240,7 +240,7 @@ def test(fn = None):
         fn = 'f:just samples:just.aif'
     import aifc
     af = aifc.open(fn, 'r')
-    print fn, af.getparams()
+    print(fn, af.getparams())
     p = AudioDev()
     p.setoutrate(af.getframerate())
     p.setsampwidth(af.getsampwidth())
@@ -249,7 +249,7 @@ def test(fn = None):
     while 1:
         data = af.readframes(BUFSIZ)
         if not data: break
-        print len(data)
+        print(len(data))
         p.writeframes(data)
     p.wait()
 
index dbcccd849ab982ea6d5c294b2c40d64b7aa221a0..19de5143b085ef051a578973c06847064358b1f3 100755 (executable)
@@ -330,11 +330,11 @@ def test():
         opts, args = getopt.getopt(sys.argv[1:], 'deut')
     except getopt.error as msg:
         sys.stdout = sys.stderr
-        print msg
-        print """usage: %s [-d|-e|-u|-t] [file|-]
+        print(msg)
+        print("""usage: %s [-d|-e|-u|-t] [file|-]
         -d, -u: decode
         -e: encode (default)
-        -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
+        -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])
         sys.exit(2)
     func = encode
     for o, a in opts:
@@ -352,7 +352,7 @@ def test1():
     s0 = "Aladdin:open sesame"
     s1 = encodestring(s0)
     s2 = decodestring(s1)
-    print s0, repr(s1), s2
+    print(s0, repr(s1), s2)
 
 
 if __name__ == '__main__':
index 11cce42397bb193ec765315bf89177a034eafb22..d49e7e385d5ce15c465905baa8332a00cf9ec107 100644 (file)
@@ -58,7 +58,7 @@ class Bdb:
             return self.trace_dispatch
         if event == 'c_return':
             return self.trace_dispatch
-        print 'bdb.Bdb.dispatch: unknown debugging event:', repr(event)
+        print('bdb.Bdb.dispatch: unknown debugging event:', repr(event))
         return self.trace_dispatch
 
     def dispatch_line(self, frame):
@@ -483,17 +483,17 @@ class Breakpoint:
             disp = disp + 'yes  '
         else:
             disp = disp + 'no   '
-        print >>out, '%-4dbreakpoint   %s at %s:%d' % (self.number, disp,
-                                                       self.file, self.line)
+        print('%-4dbreakpoint   %s at %s:%d' % (self.number, disp,
+                                                       self.file, self.line), file=out)
         if self.cond:
-            print >>out, '\tstop only if %s' % (self.cond,)
+            print('\tstop only if %s' % (self.cond,), file=out)
         if self.ignore:
-            print >>out, '\tignore next %d hits' % (self.ignore)
+            print('\tignore next %d hits' % (self.ignore), file=out)
         if (self.hits):
             if (self.hits > 1): ss = 's'
             else: ss = ''
-            print >>out, ('\tbreakpoint already hit %d time%s' %
-                          (self.hits, ss))
+            print(('\tbreakpoint already hit %d time%s' %
+                          (self.hits, ss)), file=out)
 
 # -----------end of Breakpoint class----------
 
@@ -582,27 +582,27 @@ class Tdb(Bdb):
     def user_call(self, frame, args):
         name = frame.f_code.co_name
         if not name: name = '???'
-        print '+++ call', name, args
+        print('+++ call', name, args)
     def user_line(self, frame):
         import linecache
         name = frame.f_code.co_name
         if not name: name = '???'
         fn = self.canonic(frame.f_code.co_filename)
         line = linecache.getline(fn, frame.f_lineno)
-        print '+++', fn, frame.f_lineno, name, ':', line.strip()
+        print('+++', fn, frame.f_lineno, name, ':', line.strip())
     def user_return(self, frame, retval):
-        print '+++ return', retval
+        print('+++ return', retval)
     def user_exception(self, frame, exc_stuff):
-        print '+++ exception', exc_stuff
+        print('+++ exception', exc_stuff)
         self.set_continue()
 
 def foo(n):
-    print 'foo(', n, ')'
+    print('foo(', n, ')')
     x = bar(n*10)
-    print 'bar returned', x
+    print('bar returned', x)
 
 def bar(a):
-    print 'bar(', a, ')'
+    print('bar(', a, ')')
     return a/2
 
 def test():
index 704c4d205722b81dfb2d1af0d7ab271ce744d950..5359de8a665b96e533812096ed3ad19931770cda 100644 (file)
@@ -208,12 +208,12 @@ class bsdTableDB :
 
     def _db_print(self) :
         """Print the database to stdout for debugging"""
-        print "******** Printing raw database for debugging ********"
+        print("******** Printing raw database for debugging ********")
         cur = self.db.cursor()
         try:
             key, data = cur.first()
             while 1:
-                print repr({key: data})
+                print(repr({key: data}))
                 next = cur.next()
                 if next:
                     key, data = next
index 0b132f49cc4b28bf25c6e0f3a4032de6cc8dc241..b3ef5b92992e40aeabb3aef3f004f5373689c4fa 100644 (file)
@@ -22,15 +22,15 @@ if 'silent' in sys.argv:  # take care of old flag, just in case
 
 
 def print_versions():
-    print
-    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 'My pid:               %s' % os.getpid()
-    print '-=' * 38
+    print()
+    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('My pid:               %s' % os.getpid())
+    print('-=' * 38)
 
 
 class PrintInfoFakeTest(unittest.TestCase):
index 7ae7c53ff80a4a9c945a940543f37741bae60509..857cd3d0ae1d6ef62fb9b442f6eafc0ed74177e5 100644 (file)
@@ -114,9 +114,9 @@ class AssociateErrorTestCase(unittest.TestCase):
 
     def test00_associateDBError(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test00_associateDBError..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test00_associateDBError..." % \
+                  self.__class__.__name__)
 
         dupDB = db.DB(self.env)
         dupDB.set_flags(db.DB_DUP)
@@ -207,9 +207,9 @@ class AssociateTestCase(unittest.TestCase):
 
     def test01_associateWithDB(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test01_associateWithDB..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test01_associateWithDB..." % \
+                  self.__class__.__name__)
 
         self.createDB()
 
@@ -227,9 +227,9 @@ class AssociateTestCase(unittest.TestCase):
 
     def test02_associateAfterDB(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test02_associateAfterDB..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test02_associateAfterDB..." % \
+                  self.__class__.__name__)
 
         self.createDB()
         self.addDataToDB(self.getDB())
@@ -257,7 +257,7 @@ class AssociateTestCase(unittest.TestCase):
         vals[1].index('unknown')
 
         if verbose:
-            print "Primary key traversal:"
+            print("Primary key traversal:")
         self.cur = self.getDB().cursor(txn)
         count = 0
         rec = self.cur.first()
@@ -268,13 +268,13 @@ class AssociateTestCase(unittest.TestCase):
                 assert rec[0] and type(rec[0]) == type(0)
             count = count + 1
             if verbose:
-                print rec
+                print(rec)
             rec = self.cur.next()
         assert count == len(musicdata) # all items accounted for
 
 
         if verbose:
-            print "Secondary key traversal:"
+            print("Secondary key traversal:")
         self.cur = secDB.cursor(txn)
         count = 0
 
@@ -294,7 +294,7 @@ class AssociateTestCase(unittest.TestCase):
         while rec is not None:
             count = count + 1
             if verbose:
-                print rec
+                print(rec)
             rec = self.cur.next()
         # all items accounted for EXCEPT for 1 with "Blues" genre
         assert count == len(musicdata)-1
@@ -304,7 +304,7 @@ class AssociateTestCase(unittest.TestCase):
     def getGenre(self, priKey, priData):
         assert type(priData) == type("")
         if verbose:
-            print 'getGenre key: %r data: %r' % (priKey, priData)
+            print('getGenre key: %r data: %r' % (priKey, priData))
         genre = string.split(priData, '|')[2]
         if genre == 'Blues':
             return db.DB_DONOTINDEX
@@ -343,9 +343,9 @@ class AssociateBTreeTxnTestCase(AssociateBTreeTestCase):
 
     def test13_associate_in_transaction(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test13_associateAutoCommit..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test13_associateAutoCommit..." % \
+                  self.__class__.__name__)
 
         txn = self.env.txn_begin()
         try:
@@ -389,7 +389,7 @@ class ShelveAssociateTestCase(AssociateTestCase):
     def getGenre(self, priKey, priData):
         assert type(priData) == type(())
         if verbose:
-            print 'getGenre key: %r data: %r' % (priKey, priData)
+            print('getGenre key: %r data: %r' % (priKey, priData))
         genre = priData[2]
         if genre == 'Blues':
             return db.DB_DONOTINDEX
index 281e9428a90aa7bd353dcbc0bfdfb3dd53aba5eb..a9d7be0c4cb283637694ec756e900abb906690da 100644 (file)
@@ -31,10 +31,10 @@ class VersionTestCase(unittest.TestCase):
     def test00_version(self):
         info = db.version()
         if verbose:
-            print '\n', '-=' * 20
-            print 'bsddb.db.version(): %s' % (info, )
-            print db.DB_VERSION_STRING
-            print '-=' * 20
+            print('\n', '-=' * 20)
+            print('bsddb.db.version(): %s' % (info, ))
+            print(db.DB_VERSION_STRING)
+            print('-=' * 20)
         assert info == (db.DB_VERSION_MAJOR, db.DB_VERSION_MINOR,
                         db.DB_VERSION_PATCH)
 
@@ -131,7 +131,7 @@ class BasicTestCase(unittest.TestCase):
 
         num = len(d)
         if verbose:
-            print "created %d records" % num
+            print("created %d records" % num)
 
 
     def makeData(self, key):
@@ -145,13 +145,13 @@ class BasicTestCase(unittest.TestCase):
         d = self.d
 
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test01_GetsAndPuts..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test01_GetsAndPuts..." % self.__class__.__name__)
 
         for key in ['0001', '0100', '0400', '0700', '0999']:
             data = d.get(key)
             if verbose:
-                print data
+                print(data)
 
         assert d.get('0321') == '0321-0321-0321-0321-0321'
 
@@ -164,7 +164,7 @@ class BasicTestCase(unittest.TestCase):
             d.delete('abcd')
         except db.DBNotFoundError as val:
             assert val[0] == db.DB_NOTFOUND
-            if verbose: print val
+            if verbose: print(val)
         else:
             self.fail("expected exception")
 
@@ -183,7 +183,7 @@ class BasicTestCase(unittest.TestCase):
             d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE)
         except db.DBKeyExistError as val:
             assert val[0] == db.DB_KEYEXIST
-            if verbose: print val
+            if verbose: print(val)
         else:
             self.fail("expected exception")
 
@@ -212,7 +212,7 @@ class BasicTestCase(unittest.TestCase):
 
         rec = d.get_both('0555', '0555-0555-0555-0555-0555')
         if verbose:
-            print rec
+            print(rec)
 
         assert d.get_both('0555', 'bad data') == None
 
@@ -227,7 +227,7 @@ class BasicTestCase(unittest.TestCase):
         s = d.stat()
         assert type(s) == type({})
         if verbose:
-            print 'd.stat() returned this dictionary:'
+            print('d.stat() returned this dictionary:')
             pprint(s)
 
 
@@ -237,15 +237,15 @@ class BasicTestCase(unittest.TestCase):
         d = self.d
 
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test02_DictionaryMethods..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test02_DictionaryMethods..." % \
+                  self.__class__.__name__)
 
         for key in ['0002', '0101', '0401', '0701', '0998']:
             data = d[key]
             assert data == self.makeData(key)
             if verbose:
-                print data
+                print(data)
 
         assert len(d) == self._numKeys
         keys = d.keys()
@@ -263,7 +263,7 @@ class BasicTestCase(unittest.TestCase):
         assert len(keys) == self._numKeys+1
 
         if verbose:
-            print "the first 10 keys are:"
+            print("the first 10 keys are:")
             pprint(keys[:10])
 
         assert d['new record'] == 'a replacement record'
@@ -278,7 +278,7 @@ class BasicTestCase(unittest.TestCase):
         assert len(items[0]) == 2
 
         if verbose:
-            print "the first 10 items are:"
+            print("the first 10 items are:")
             pprint(items[:10])
 
         values = d.values()
@@ -286,7 +286,7 @@ class BasicTestCase(unittest.TestCase):
         assert type(values) == type([])
 
         if verbose:
-            print "the first 10 values are:"
+            print("the first 10 values are:")
             pprint(values[:10])
 
 
@@ -295,9 +295,9 @@ class BasicTestCase(unittest.TestCase):
 
     def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \
-                  (self.__class__.__name__, get_raises_error, set_raises_error)
+            print('\n', '-=' * 30)
+            print("Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \
+                  (self.__class__.__name__, get_raises_error, set_raises_error))
 
         if self.env and self.dbopenflags & db.DB_AUTO_COMMIT:
             txn = self.env.txn_begin()
@@ -310,13 +310,13 @@ class BasicTestCase(unittest.TestCase):
         while rec is not None:
             count = count + 1
             if verbose and count % 100 == 0:
-                print rec
+                print(rec)
             try:
                 rec = c.next()
             except db.DBNotFoundError as val:
                 if get_raises_error:
                     assert val[0] == db.DB_NOTFOUND
-                    if verbose: print val
+                    if verbose: print(val)
                     rec = None
                 else:
                     self.fail("unexpected DBNotFoundError")
@@ -330,13 +330,13 @@ class BasicTestCase(unittest.TestCase):
         while rec is not None:
             count = count + 1
             if verbose and count % 100 == 0:
-                print rec
+                print(rec)
             try:
                 rec = c.prev()
             except db.DBNotFoundError as val:
                 if get_raises_error:
                     assert val[0] == db.DB_NOTFOUND
-                    if verbose: print val
+                    if verbose: print(val)
                     rec = None
                 else:
                     self.fail("unexpected DBNotFoundError")
@@ -359,7 +359,7 @@ class BasicTestCase(unittest.TestCase):
             n = c.set('bad key')
         except db.DBNotFoundError as val:
             assert val[0] == db.DB_NOTFOUND
-            if verbose: print val
+            if verbose: print(val)
         else:
             if set_raises_error:
                 self.fail("expected exception")
@@ -373,7 +373,7 @@ class BasicTestCase(unittest.TestCase):
             n = c.get_both('0404', 'bad data')
         except db.DBNotFoundError as val:
             assert val[0] == db.DB_NOTFOUND
-            if verbose: print val
+            if verbose: print(val)
         else:
             if get_raises_error:
                 self.fail("expected exception")
@@ -383,16 +383,16 @@ class BasicTestCase(unittest.TestCase):
         if self.d.get_type() == db.DB_BTREE:
             rec = c.set_range('011')
             if verbose:
-                print "searched for '011', found: ", rec
+                print("searched for '011', found: ", rec)
 
             rec = c.set_range('011',dlen=0,doff=0)
             if verbose:
-                print "searched (partial) for '011', found: ", rec
+                print("searched (partial) for '011', found: ", rec)
             if rec[1] != '': self.fail('expected empty data portion')
 
             ev = c.set_range('empty value')
             if verbose:
-                print "search for 'empty value' returned", ev
+                print("search for 'empty value' returned", ev)
             if ev[1] != '': self.fail('empty value lookup failed')
 
         c.set('0499')
@@ -402,7 +402,7 @@ class BasicTestCase(unittest.TestCase):
         except db.DBKeyEmptyError as val:
             if get_raises_error:
                 assert val[0] == db.DB_KEYEMPTY
-                if verbose: print val
+                if verbose: print(val)
             else:
                 self.fail("unexpected DBKeyEmptyError")
         else:
@@ -441,13 +441,13 @@ class BasicTestCase(unittest.TestCase):
         for method, args in methods_to_test.items():
             try:
                 if verbose:
-                    print "attempting to use a closed cursor's %s method" % \
-                          method
+                    print("attempting to use a closed cursor's %s method" % \
+                          method)
                 # a bug may cause a NULL pointer dereference...
                 getattr(c, method)(*args)
             except db.DBError as val:
                 assert val[0] == 0
-                if verbose: print val
+                if verbose: print(val)
             else:
                 self.fail("no exception raised when using a buggy cursor's"
                           "%s method" % method)
@@ -466,9 +466,9 @@ class BasicTestCase(unittest.TestCase):
     def test03b_SimpleCursorWithoutGetReturnsNone0(self):
         # same test but raise exceptions instead of returning None
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
+                  self.__class__.__name__)
 
         old = self.d.set_get_returns_none(0)
         assert old == 2
@@ -477,9 +477,9 @@ class BasicTestCase(unittest.TestCase):
     def test03b_SimpleCursorWithGetReturnsNone1(self):
         # same test but raise exceptions instead of returning None
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
+                  self.__class__.__name__)
 
         old = self.d.set_get_returns_none(1)
         self.test03_SimpleCursorStuff(get_raises_error=0, set_raises_error=1)
@@ -488,9 +488,9 @@ class BasicTestCase(unittest.TestCase):
     def test03c_SimpleCursorGetReturnsNone2(self):
         # same test but raise exceptions instead of returning None
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \
+                  self.__class__.__name__)
 
         old = self.d.set_get_returns_none(1)
         assert old == 2
@@ -503,9 +503,9 @@ class BasicTestCase(unittest.TestCase):
     def test04_PartialGetAndPut(self):
         d = self.d
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test04_PartialGetAndPut..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test04_PartialGetAndPut..." % \
+                  self.__class__.__name__)
 
         key = "partialTest"
         data = "1" * 1000 + "2" * 1000
@@ -533,8 +533,8 @@ class BasicTestCase(unittest.TestCase):
     def test05_GetSize(self):
         d = self.d
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test05_GetSize..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test05_GetSize..." % self.__class__.__name__)
 
         for i in range(1, 50000, 500):
             key = "size%s" % i
@@ -553,8 +553,8 @@ class BasicTestCase(unittest.TestCase):
 
         d = self.d
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test99_Truncate..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test99_Truncate..." % self.__class__.__name__)
 
         d.put("abcde", "ABCDE");
         num = d.truncate()
@@ -598,8 +598,8 @@ class BasicWithEnvTestCase(BasicTestCase):
             return
 
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__)
 
         # can't rename or remove an open DB
         self.d.close()
@@ -647,8 +647,8 @@ class BasicTransactionTestCase(BasicTestCase):
     def test06_Transactions(self):
         d = self.d
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test06_Transactions..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test06_Transactions..." % self.__class__.__name__)
 
         assert d.get('new rec', txn=self.txn) == None
         d.put('new rec', 'this is a new record', self.txn)
@@ -671,7 +671,7 @@ class BasicTransactionTestCase(BasicTestCase):
         while rec is not None:
             count = count + 1
             if verbose and count % 100 == 0:
-                print rec
+                print(rec)
             rec = c.next()
         assert count == self._numKeys+1
 
@@ -696,7 +696,7 @@ class BasicTransactionTestCase(BasicTestCase):
         assert logs != None
         for log in logs:
             if verbose:
-                print 'log file: ' + log
+                print('log file: ' + log)
         if db.version() >= (4,2):
             logs = self.env.log_archive(db.DB_ARCH_REMOVE)
             assert not logs
@@ -712,8 +712,8 @@ class BasicTransactionTestCase(BasicTestCase):
 
         d = self.d
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test07_TxnTruncate..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test07_TxnTruncate..." % self.__class__.__name__)
 
         d.put("abcde", "ABCDE");
         txn = self.env.txn_begin()
@@ -762,21 +762,21 @@ class BTreeRecnoTestCase(BasicTestCase):
     def test07_RecnoInBTree(self):
         d = self.d
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test07_RecnoInBTree..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test07_RecnoInBTree..." % self.__class__.__name__)
 
         rec = d.get(200)
         assert type(rec) == type(())
         assert len(rec) == 2
         if verbose:
-            print "Record #200 is ", rec
+            print("Record #200 is ", rec)
 
         c = d.cursor()
         c.set('0200')
         num = c.get_recno()
         assert type(num) == type(1)
         if verbose:
-            print "recno of d['0200'] is ", num
+            print("recno of d['0200'] is ", num)
 
         rec = c.current()
         assert c.set_recno(num) == rec
@@ -796,9 +796,9 @@ class BasicDUPTestCase(BasicTestCase):
     def test08_DuplicateKeys(self):
         d = self.d
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test08_DuplicateKeys..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test08_DuplicateKeys..." % \
+                  self.__class__.__name__)
 
         d.put("dup0", "before")
         for x in "The quick brown fox jumped over the lazy dog.".split():
@@ -808,7 +808,7 @@ class BasicDUPTestCase(BasicTestCase):
         data = d.get("dup1")
         assert data == "The"
         if verbose:
-            print data
+            print(data)
 
         c = d.cursor()
         rec = c.set("dup1")
@@ -827,14 +827,14 @@ class BasicDUPTestCase(BasicTestCase):
         rec = c.set('dup1')
         while rec is not None:
             if verbose:
-                print rec
+                print(rec)
             rec = c.next_dup()
 
         c.set('dup1')
         rec = c.next_nodup()
         assert rec[0] != 'dup1'
         if verbose:
-            print rec
+            print(rec)
 
         c.close()
 
@@ -869,8 +869,8 @@ class BasicMultiDBTestCase(BasicTestCase):
     def test09_MultiDB(self):
         d1 = self.d
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test09_MultiDB..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test09_MultiDB..." % self.__class__.__name__)
 
         d2 = db.DB(self.env)
         d2.open(self.filename, "second", self.dbtype,
@@ -910,7 +910,7 @@ class BasicMultiDBTestCase(BasicTestCase):
         while rec is not None:
             count = count + 1
             if verbose and (count % 50) == 0:
-                print rec
+                print(rec)
             rec = c1.next()
         assert count == self._numKeys
 
@@ -919,7 +919,7 @@ class BasicMultiDBTestCase(BasicTestCase):
         while rec is not None:
             count = count + 1
             if verbose:
-                print rec
+                print(rec)
             rec = c2.next()
         assert count == 9
 
@@ -928,7 +928,7 @@ class BasicMultiDBTestCase(BasicTestCase):
         while rec is not None:
             count = count + 1
             if verbose:
-                print rec
+                print(rec)
             rec = c3.next()
         assert count == 52
 
index af9e128904db0cd423e196e503cc36adc958b293..7561f9f01d03dd977ed2aeed4088f04fcb971423 100644 (file)
@@ -37,7 +37,7 @@ class CompatibilityTestCase(unittest.TestCase):
     def test03_rnopen(self):
         data = string.split("The quick brown fox jumped over the lazy dog.")
         if verbose:
-            print "\nTesting: rnopen"
+            print("\nTesting: rnopen")
 
         f = rnopen(self.filename, 'c')
         for x in range(len(data)):
@@ -45,7 +45,7 @@ class CompatibilityTestCase(unittest.TestCase):
 
         getTest = (f[1], f[2], f[3])
         if verbose:
-            print '%s %s %s' % getTest
+            print('%s %s %s' % getTest)
 
         assert getTest[1] == 'quick', 'data mismatch!'
 
@@ -73,7 +73,7 @@ class CompatibilityTestCase(unittest.TestCase):
         rec = f.first()
         while rec:
             if verbose:
-                print rec
+                print(rec)
             try:
                 rec = f.next()
             except KeyError:
@@ -89,17 +89,17 @@ class CompatibilityTestCase(unittest.TestCase):
 
     def do_bthash_test(self, factory, what):
         if verbose:
-            print '\nTesting: ', what
+            print('\nTesting: ', what)
 
         f = factory(self.filename, 'c')
         if verbose:
-            print 'creation...'
+            print('creation...')
 
         # truth test
         if f:
-            if verbose: print "truth test: true"
+            if verbose: print("truth test: true")
         else:
-            if verbose: print "truth test: false"
+            if verbose: print("truth test: false")
 
         f['0'] = ''
         f['a'] = 'Guido'
@@ -109,10 +109,10 @@ class CompatibilityTestCase(unittest.TestCase):
         # 'e' intentionally left out
         f['f'] = 'Python'
         if verbose:
-            print '%s %s %s' % (f['a'], f['b'], f['c'])
+            print('%s %s %s' % (f['a'], f['b'], f['c']))
 
         if verbose:
-            print 'key ordering...'
+            print('key ordering...')
         start = f.set_location(f.first()[0])
         if start != ('0', ''):
             self.fail("incorrect first() result: "+repr(start))
@@ -124,7 +124,7 @@ class CompatibilityTestCase(unittest.TestCase):
                 f.previous()
                 break
             if verbose:
-                print rec
+                print(rec)
 
         assert f.has_key('f'), 'Error, missing key!'
 
@@ -147,9 +147,9 @@ class CompatibilityTestCase(unittest.TestCase):
         # truth test
         try:
             if f:
-                if verbose: print "truth test: true"
+                if verbose: print("truth test: true")
             else:
-                if verbose: print "truth test: false"
+                if verbose: print("truth test: false")
         except db.DBError:
             pass
         else:
@@ -158,16 +158,16 @@ class CompatibilityTestCase(unittest.TestCase):
         del f
 
         if verbose:
-            print 'modification...'
+            print('modification...')
         f = factory(self.filename, 'w')
         f['d'] = 'discovered'
 
         if verbose:
-            print 'access...'
+            print('access...')
         for key in f.keys():
             word = f[key]
             if verbose:
-                print word
+                print(word)
 
         def noRec(f):
             rec = f['no such key']
index 1da6546a55a008d01fa799ebb32d2620a147fda8..e75e9c8caf2875be14fdb4c299f0f4c0b9a27213 100644 (file)
@@ -79,8 +79,8 @@ class DBShelveTestCase(unittest.TestCase):
 
     def test01_basics(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test01_basics..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test01_basics..." % self.__class__.__name__)
 
         self.populateDB(self.d)
         self.d.sync()
@@ -94,9 +94,9 @@ class DBShelveTestCase(unittest.TestCase):
         f = d.fd()
 
         if verbose:
-            print "length:", l
-            print "keys:", k
-            print "stats:", s
+            print("length:", l)
+            print("keys:", k)
+            print("stats:", s)
 
         assert 0 == d.has_key('bad key')
         assert 1 == d.has_key('IA')
@@ -113,7 +113,7 @@ class DBShelveTestCase(unittest.TestCase):
             value = d[key]
             values.append(value)
             if verbose:
-                print "%s: %s" % (key, value)
+                print("%s: %s" % (key, value))
             self.checkrec(key, value)
 
         dbvalues = sorted(d.values(), key=lambda x: (str(type(x)), x))
@@ -144,8 +144,8 @@ class DBShelveTestCase(unittest.TestCase):
 
     def test02_cursors(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test02_cursors..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test02_cursors..." % self.__class__.__name__)
 
         self.populateDB(self.d)
         d = self.d
@@ -156,7 +156,7 @@ class DBShelveTestCase(unittest.TestCase):
         while rec is not None:
             count = count + 1
             if verbose:
-                print rec
+                print(rec)
             key, value = rec
             self.checkrec(key, value)
             rec = c.next()
@@ -170,7 +170,7 @@ class DBShelveTestCase(unittest.TestCase):
         while rec is not None:
             count = count + 1
             if verbose:
-                print rec
+                print(rec)
             key, value = rec
             self.checkrec(key, value)
             rec = c.prev()
index a31fcec910c7d15e1f0b9b24e744b02c324a6e0d..c476e5561a4163739c165c232334a9f59378ca91 100644 (file)
@@ -110,7 +110,7 @@ class TableDBTestCase(unittest.TestCase):
             assert values[1]['Species'] == 'Penguin'
         else :
             if verbose:
-                print "values= %r" % (values,)
+                print("values= %r" % (values,))
             raise "Wrong values returned!"
 
     def test03(self):
@@ -120,15 +120,15 @@ class TableDBTestCase(unittest.TestCase):
         except dbtables.TableDBError:
             pass
         if verbose:
-            print '...before CreateTable...'
+            print('...before CreateTable...')
             self.tdb._db_print()
         self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e'])
         if verbose:
-            print '...after CreateTable...'
+            print('...after CreateTable...')
             self.tdb._db_print()
         self.tdb.Drop(tabname)
         if verbose:
-            print '...after Drop...'
+            print('...after Drop...')
             self.tdb._db_print()
         self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e'])
 
index 5e307aead757bafd1e0301d06f690a8c6526e0e3..67507eabebfc6ee860a7ec77dbcc8275b6389316 100644 (file)
@@ -65,9 +65,9 @@ class JoinTestCase(unittest.TestCase):
 
     def test01_join(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test01_join..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test01_join..." % \
+                  self.__class__.__name__)
 
         # create and populate primary index
         priDB = db.DB(self.env)
index 61bdae8b7604e84f9713bb420334cdc4b49400dd..e44bf214a642f6f49f50ca385bd8f791aa333b7b 100644 (file)
@@ -49,27 +49,27 @@ class LockingTestCase(unittest.TestCase):
 
     def test01_simple(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test01_simple..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test01_simple..." % self.__class__.__name__)
 
         anID = self.env.lock_id()
         if verbose:
-            print "locker ID: %s" % anID
+            print("locker ID: %s" % anID)
         lock = self.env.lock_get(anID, "some locked thing", db.DB_LOCK_WRITE)
         if verbose:
-            print "Aquired lock: %s" % lock
+            print("Aquired lock: %s" % lock)
         time.sleep(1)
         self.env.lock_put(lock)
         if verbose:
-            print "Released lock: %s" % lock
+            print("Released lock: %s" % lock)
 
 
 
 
     def test02_threaded(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test02_threaded..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test02_threaded..." % self.__class__.__name__)
 
         threads = []
         threads.append(Thread(target = self.theThread,
@@ -113,17 +113,17 @@ class LockingTestCase(unittest.TestCase):
 
         anID = self.env.lock_id()
         if verbose:
-            print "%s: locker ID: %s" % (name, anID)
+            print("%s: locker ID: %s" % (name, anID))
 
         lock = self.env.lock_get(anID, "some locked thing", lockType)
         if verbose:
-            print "%s: Aquired %s lock: %s" % (name, lt, lock)
+            print("%s: Aquired %s lock: %s" % (name, lt, lock))
 
         time.sleep(sleepTime)
 
         self.env.lock_put(lock)
         if verbose:
-            print "%s: Released %s lock: %s" % (name, lt, lock)
+            print("%s: Released %s lock: %s" % (name, lt, lock))
 
 
 #----------------------------------------------------------------------
index 4226c9e1e8d6edd9c3e6260ebb79cf4ae35e20ea..9f80b4362ffcbdf0f2628146a6d58af97acba4b8 100644 (file)
@@ -34,15 +34,15 @@ class SimpleQueueTestCase(unittest.TestCase):
         # Basic Queue tests using the deprecated DBCursor.consume method.
 
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test01_basic..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test01_basic..." % self.__class__.__name__)
 
         d = db.DB()
         d.set_re_len(40)  # Queues must be fixed length
         d.open(self.filename, db.DB_QUEUE, db.DB_CREATE)
 
         if verbose:
-            print "before appends" + '-' * 30
+            print("before appends" + '-' * 30)
             pprint(d.stat())
 
         for x in string.letters:
@@ -58,7 +58,7 @@ class SimpleQueueTestCase(unittest.TestCase):
         assert len(d) == 55
 
         if verbose:
-            print "before close" + '-' * 30
+            print("before close" + '-' * 30)
             pprint(d.stat())
 
         d.close()
@@ -67,25 +67,25 @@ class SimpleQueueTestCase(unittest.TestCase):
         d.open(self.filename)
 
         if verbose:
-            print "after open" + '-' * 30
+            print("after open" + '-' * 30)
             pprint(d.stat())
 
         d.append("one more")
         c = d.cursor()
 
         if verbose:
-            print "after append" + '-' * 30
+            print("after append" + '-' * 30)
             pprint(d.stat())
 
         rec = c.consume()
         while rec:
             if verbose:
-                print rec
+                print(rec)
             rec = c.consume()
         c.close()
 
         if verbose:
-            print "after consume loop" + '-' * 30
+            print("after consume loop" + '-' * 30)
             pprint(d.stat())
 
         assert len(d) == 0, \
@@ -101,12 +101,12 @@ class SimpleQueueTestCase(unittest.TestCase):
         # (No cursor needed)
 
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test02_basicPost32..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test02_basicPost32..." % self.__class__.__name__)
 
         if db.version() < (3, 2, 0):
             if verbose:
-                print "Test not run, DB not new enough..."
+                print("Test not run, DB not new enough...")
             return
 
         d = db.DB()
@@ -114,7 +114,7 @@ class SimpleQueueTestCase(unittest.TestCase):
         d.open(self.filename, db.DB_QUEUE, db.DB_CREATE)
 
         if verbose:
-            print "before appends" + '-' * 30
+            print("before appends" + '-' * 30)
             pprint(d.stat())
 
         for x in string.letters:
@@ -130,7 +130,7 @@ class SimpleQueueTestCase(unittest.TestCase):
         assert len(d) == 55
 
         if verbose:
-            print "before close" + '-' * 30
+            print("before close" + '-' * 30)
             pprint(d.stat())
 
         d.close()
@@ -140,23 +140,23 @@ class SimpleQueueTestCase(unittest.TestCase):
         #d.set_get_returns_none(true)
 
         if verbose:
-            print "after open" + '-' * 30
+            print("after open" + '-' * 30)
             pprint(d.stat())
 
         d.append("one more")
 
         if verbose:
-            print "after append" + '-' * 30
+            print("after append" + '-' * 30)
             pprint(d.stat())
 
         rec = d.consume()
         while rec:
             if verbose:
-                print rec
+                print(rec)
             rec = d.consume()
 
         if verbose:
-            print "after consume loop" + '-' * 30
+            print("after consume loop" + '-' * 30)
             pprint(d.stat())
 
         d.close()
index 7bf3695dfa2a1d077e95a92063a2e91754478be7..8baf8438ee81a48bf89e10b03b861b70959f9aaa 100644 (file)
@@ -45,9 +45,9 @@ class SimpleRecnoTestCase(unittest.TestCase):
             assert type(recno) == type(0)
             assert recno >= 1
             if verbose:
-                print recno,
+                print(recno, end=' ')
 
-        if verbose: print
+        if verbose: print()
 
         stat = d.stat()
         if verbose:
@@ -56,7 +56,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
         for recno in range(1, len(d)+1):
             data = d[recno]
             if verbose:
-                print data
+                print(data)
 
             assert type(data) == type("")
             assert data == d.get(recno)
@@ -65,7 +65,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
             data = d[0]  # This should raise a KeyError!?!?!
         except db.DBInvalidArgError as val:
             assert val[0] == db.EINVAL
-            if verbose: print val
+            if verbose: print(val)
         else:
             self.fail("expected exception")
 
@@ -94,7 +94,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
 
         keys = d.keys()
         if verbose:
-            print keys
+            print(keys)
         assert type(keys) == type([])
         assert type(keys[0]) == type(123)
         assert len(keys) == len(d)
@@ -120,23 +120,23 @@ class SimpleRecnoTestCase(unittest.TestCase):
         data = d.get_both(26, "z" * 60)
         assert data == "z" * 60
         if verbose:
-            print data
+            print(data)
 
         fd = d.fd()
         if verbose:
-            print fd
+            print(fd)
 
         c = d.cursor()
         rec = c.first()
         while rec:
             if verbose:
-                print rec
+                print(rec)
             rec = c.next()
 
         c.set(50)
         rec = c.current()
         if verbose:
-            print rec
+            print(rec)
 
         c.put(-1, "a replacement record", db.DB_CURRENT)
 
@@ -144,18 +144,18 @@ class SimpleRecnoTestCase(unittest.TestCase):
         rec = c.current()
         assert rec == (50, "a replacement record")
         if verbose:
-            print rec
+            print(rec)
 
         rec = c.set_range(30)
         if verbose:
-            print rec
+            print(rec)
 
         # test that non-existant key lookups work (and that
         # DBC_set_range doesn't have a memleak under valgrind)
         rec = c.set_range(999999)
         assert rec == None
         if verbose:
-            print rec
+            print(rec)
 
         c.close()
         d.close()
@@ -182,7 +182,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
                 self.fail("unexpected DBKeyEmptyError exception")
             else:
                 assert val[0] == db.DB_KEYEMPTY
-                if verbose: print val
+                if verbose: print(val)
         else:
             if not get_returns_none:
                 self.fail("expected exception")
@@ -190,7 +190,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
         rec = c.set(40)
         while rec:
             if verbose:
-                print rec
+                print(rec)
             rec = c.next()
 
         c.close()
@@ -227,9 +227,9 @@ class SimpleRecnoTestCase(unittest.TestCase):
         text = open(source, 'r').read()
         text = text.strip()
         if verbose:
-            print text
-            print data
-            print text.split('\n')
+            print(text)
+            print(data)
+            print(text.split('\n'))
 
         assert text.split('\n') == data
 
@@ -247,8 +247,8 @@ class SimpleRecnoTestCase(unittest.TestCase):
         text = open(source, 'r').read()
         text = text.strip()
         if verbose:
-            print text
-            print text.split('\n')
+            print(text)
+            print(text.split('\n'))
 
         assert text.split('\n') == \
              "The quick reddish-brown fox jumped over the comatose dog".split()
@@ -269,7 +269,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
             d.append('bad' * 20)
         except db.DBInvalidArgError as val:
             assert val[0] == db.EINVAL
-            if verbose: print val
+            if verbose: print(val)
         else:
             self.fail("expected exception")
 
@@ -277,7 +277,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
         rec = c.first()
         while rec:
             if verbose:
-                print rec
+                print(rec)
             rec = c.next()
 
         c.close()
index b3d7ef94e6e668f2a8316f8c88f062fca787d4ec..eabf96a72154d237d854f46048362962539383f6 100644 (file)
@@ -93,9 +93,9 @@ class ConcurrentDataStoreBase(BaseThreadedTestCase):
 
     def test01_1WriterMultiReaders(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test01_1WriterMultiReaders..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test01_1WriterMultiReaders..." % \
+                  self.__class__.__name__)
 
         threads = []
         for x in range(self.writers):
@@ -123,17 +123,17 @@ class ConcurrentDataStoreBase(BaseThreadedTestCase):
         start = howMany * writerNum
         stop = howMany * (writerNum + 1) - 1
         if verbose:
-            print "%s: creating records %d - %d" % (name, start, stop)
+            print("%s: creating records %d - %d" % (name, start, stop))
 
         for x in range(start, stop):
             key = '%04d' % x
             dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                  max_retries=12)
             if verbose and x % 100 == 0:
-                print "%s: records %d - %d finished" % (name, start, x)
+                print("%s: records %d - %d finished" % (name, start, x))
 
         if verbose:
-            print "%s: finished creating records" % name
+            print("%s: finished creating records" % name)
 
 ##         # Each write-cursor will be exclusive, the only one that can update the DB...
 ##         if verbose: print "%s: deleting a few records" % name
@@ -147,7 +147,7 @@ class ConcurrentDataStoreBase(BaseThreadedTestCase):
 
 ##         c.close()
         if verbose:
-            print "%s: thread finished" % name
+            print("%s: thread finished" % name)
 
     def readerThread(self, d, readerNum):
         time.sleep(0.01 * readerNum)
@@ -163,12 +163,12 @@ class ConcurrentDataStoreBase(BaseThreadedTestCase):
                 self.assertEqual(self.makeData(key), data)
                 rec = c.next()
             if verbose:
-                print "%s: found %d records" % (name, count)
+                print("%s: found %d records" % (name, count))
             c.close()
             time.sleep(0.05)
 
         if verbose:
-            print "%s: thread finished" % name
+            print("%s: thread finished" % name)
 
 
 class BTreeConcurrentDataStore(ConcurrentDataStoreBase):
@@ -199,8 +199,8 @@ class SimpleThreadedBase(BaseThreadedTestCase):
 
     def test02_SimpleLocks(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test02_SimpleLocks..." % self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test02_SimpleLocks..." % self.__class__.__name__)
 
         threads = []
         for x in range(self.writers):
@@ -226,7 +226,7 @@ class SimpleThreadedBase(BaseThreadedTestCase):
         start = howMany * writerNum
         stop = howMany * (writerNum + 1) - 1
         if verbose:
-            print "%s: creating records %d - %d" % (name, start, stop)
+            print("%s: creating records %d - %d" % (name, start, stop))
 
         # create a bunch of records
         for x in xrange(start, stop):
@@ -235,7 +235,7 @@ class SimpleThreadedBase(BaseThreadedTestCase):
                                  max_retries=12)
 
             if verbose and x % 100 == 0:
-                print "%s: records %d - %d finished" % (name, start, x)
+                print("%s: records %d - %d finished" % (name, start, x))
 
             # do a bit or reading too
             if random() <= 0.05:
@@ -249,22 +249,22 @@ class SimpleThreadedBase(BaseThreadedTestCase):
             dbutils.DeadlockWrap(d.sync, max_retries=12)
         except db.DBIncompleteError as val:
             if verbose:
-                print "could not complete sync()..."
+                print("could not complete sync()...")
 
         # read them back, deleting a few
         for x in xrange(start, stop):
             key = '%04d' % x
             data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
             if verbose and x % 100 == 0:
-                print "%s: fetched record (%s, %s)" % (name, key, data)
+                print("%s: fetched record (%s, %s)" % (name, key, data))
             self.assertEqual(data, self.makeData(key))
             if random() <= 0.10:
                 dbutils.DeadlockWrap(d.delete, key, max_retries=12)
                 if verbose:
-                    print "%s: deleted record %s" % (name, key)
+                    print("%s: deleted record %s" % (name, key))
 
         if verbose:
-            print "%s: thread finished" % name
+            print("%s: thread finished" % name)
 
     def readerThread(self, d, readerNum):
         time.sleep(0.01 * readerNum)
@@ -280,12 +280,12 @@ class SimpleThreadedBase(BaseThreadedTestCase):
                 self.assertEqual(self.makeData(key), data)
                 rec = dbutils.DeadlockWrap(c.next, max_retries=10)
             if verbose:
-                print "%s: found %d records" % (name, count)
+                print("%s: found %d records" % (name, count))
             c.close()
             time.sleep(0.05)
 
         if verbose:
-            print "%s: thread finished" % name
+            print("%s: thread finished" % name)
 
 
 class BTreeSimpleThreaded(SimpleThreadedBase):
@@ -318,9 +318,9 @@ class ThreadedTransactionsBase(BaseThreadedTestCase):
 
     def test03_ThreadedTransactions(self):
         if verbose:
-            print '\n', '-=' * 30
-            print "Running %s.test03_ThreadedTransactions..." % \
-                  self.__class__.__name__
+            print('\n', '-=' * 30)
+            print("Running %s.test03_ThreadedTransactions..." % \
+                  self.__class__.__name__)
 
         threads = []
         for x in range(self.writers):
@@ -357,12 +357,12 @@ class ThreadedTransactionsBase(BaseThreadedTestCase):
                     key = '%04d' % x
                     d.put(key, self.makeData(key), txn)
                     if verbose and x % 100 == 0:
-                        print "%s: records %d - %d finished" % (name, start, x)
+                        print("%s: records %d - %d finished" % (name, start, x))
                 txn.commit()
                 finished = True
             except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val:
                 if verbose:
-                    print "%s: Aborting transaction (%s)" % (name, val[1])
+                    print("%s: Aborting transaction (%s)" % (name, val[1]))
                 txn.abort()
                 time.sleep(0.05)
 
@@ -371,16 +371,16 @@ class ThreadedTransactionsBase(BaseThreadedTestCase):
         start = howMany * writerNum
         stop = howMany * (writerNum + 1) - 1
         if verbose:
-            print "%s: creating records %d - %d" % (name, start, stop)
+            print("%s: creating records %d - %d" % (name, start, stop))
 
         step = 100
         for x in range(start, stop, step):
             self.doWrite(d, name, x, min(stop, x+step))
 
         if verbose:
-            print "%s: finished creating records" % name
+            print("%s: finished creating records" % name)
         if verbose:
-            print "%s: deleting a few records" % name
+            print("%s: deleting a few records" % name)
 
         finished = False
         while not finished:
@@ -397,15 +397,15 @@ class ThreadedTransactionsBase(BaseThreadedTestCase):
                 txn.commit()
                 finished = True
                 if verbose:
-                    print "%s: deleted records %s" % (name, recs)
+                    print("%s: deleted records %s" % (name, recs))
             except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val:
                 if verbose:
-                    print "%s: Aborting transaction (%s)" % (name, val[1])
+                    print("%s: Aborting transaction (%s)" % (name, val[1]))
                 txn.abort()
                 time.sleep(0.05)
 
         if verbose:
-            print "%s: thread finished" % name
+            print("%s: thread finished" % name)
 
     def readerThread(self, d, readerNum):
         time.sleep(0.01 * readerNum + 0.05)
@@ -424,13 +424,13 @@ class ThreadedTransactionsBase(BaseThreadedTestCase):
                         key, data = rec
                         self.assertEqual(self.makeData(key), data)
                         rec = c.next()
-                    if verbose: print "%s: found %d records" % (name, count)
+                    if verbose: print("%s: found %d records" % (name, count))
                     c.close()
                     txn.commit()
                     finished = True
                 except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val:
                     if verbose:
-                        print "%s: Aborting transaction (%s)" % (name, val[1])
+                        print("%s: Aborting transaction (%s)" % (name, val[1]))
                     c.close()
                     txn.abort()
                     time.sleep(0.05)
@@ -438,7 +438,7 @@ class ThreadedTransactionsBase(BaseThreadedTestCase):
             time.sleep(0.05)
 
         if verbose:
-            print "%s: thread finished" % name
+            print("%s: thread finished" % name)
 
     def deadlockThread(self):
         self.doLockDetect = True
@@ -448,8 +448,8 @@ class ThreadedTransactionsBase(BaseThreadedTestCase):
                 aborted = self.env.lock_detect(
                     db.DB_LOCK_RANDOM, db.DB_LOCK_CONFLICT)
                 if verbose and aborted:
-                    print "deadlock: Aborted %d deadlocked transaction(s)" \
-                          % aborted
+                    print("deadlock: Aborted %d deadlocked transaction(s)" \
+                          % aborted)
             except db.DBError:
                 pass
 
@@ -497,7 +497,7 @@ def test_suite():
         suite.addTest(unittest.makeSuite(HashThreadedNoWaitTransactions))
 
     else:
-        print "Threads not available, skipping thread tests."
+        print("Threads not available, skipping thread tests.")
 
     return suite
 
index cb26fe105eee136bc9019c1758dd176e8d7ed874..fb434bd3cddca5f3b2c2856767be6d18cec3b536 100755 (executable)
@@ -58,8 +58,8 @@ def runctx(statement, globals, locals, filename=None):
 
 # Backwards compatibility.
 def help():
-    print "Documentation for the profile/cProfile modules can be found "
-    print "in the Python Library Reference, section 'The Python Profiler'."
+    print("Documentation for the profile/cProfile modules can be found ")
+    print("in the Python Library Reference, section 'The Python Profiler'.")
 
 # ____________________________________________________________
 
index 00948efe5c084ea059158567377d6000ffc21b10..149c7adadb1961e5aff6f3a718807368bc6cffb4 100644 (file)
@@ -261,7 +261,7 @@ class TextCalendar(Calendar):
         """
         Print a single week (no newline).
         """
-        print self.week(theweek, width),
+        print(self.week(theweek, width), end=' ')
 
     def formatday(self, day, weekday, width):
         """
@@ -308,7 +308,7 @@ class TextCalendar(Calendar):
         """
         Print a month's calendar.
         """
-        print self.formatmonth(theyear, themonth, w, l),
+        print(self.formatmonth(theyear, themonth, w, l), end=' ')
 
     def formatmonth(self, theyear, themonth, w=0, l=0):
         """
@@ -365,7 +365,7 @@ class TextCalendar(Calendar):
 
     def pryear(self, theyear, w=0, l=0, c=6, m=3):
         """Print a year's calendar."""
-        print self.formatyear(theyear, w, l, c, m)
+        print(self.formatyear(theyear, w, l, c, m))
 
 
 class HTMLCalendar(Calendar):
@@ -584,7 +584,7 @@ _spacing = 6                # Number of spaces between columns
 
 def format(cols, colwidth=_colwidth, spacing=_spacing):
     """Prints multi-column formatting for year calendars"""
-    print formatstring(cols, colwidth, spacing)
+    print(formatstring(cols, colwidth, spacing))
 
 
 def formatstring(cols, colwidth=_colwidth, spacing=_spacing):
@@ -668,9 +668,9 @@ def main(args):
             encoding = sys.getdefaultencoding()
         optdict = dict(encoding=encoding, css=options.css)
         if len(args) == 1:
-            print cal.formatyearpage(datetime.date.today().year, **optdict)
+            print(cal.formatyearpage(datetime.date.today().year, **optdict))
         elif len(args) == 2:
-            print cal.formatyearpage(int(args[1]), **optdict)
+            print(cal.formatyearpage(int(args[1]), **optdict))
         else:
             parser.error("incorrect number of arguments")
             sys.exit(1)
@@ -694,7 +694,7 @@ def main(args):
             sys.exit(1)
         if options.encoding:
             result = result.encode(options.encoding)
-        print result
+        print(result)
 
 
 if __name__ == "__main__":
index 0cc5fad82aad4cdd96ccb8ced827d37a955e5753..5ddf16e8f8819dea68edb26d621ae56753fdac29 100755 (executable)
@@ -901,8 +901,8 @@ def test(environ=os.environ):
     the script in HTML form.
 
     """
-    print "Content-type: text/html"
-    print
+    print("Content-type: text/html")
+    print()
     sys.stderr = sys.stdout
     try:
         form = FieldStorage()   # Replace with other classes to test those
@@ -915,12 +915,12 @@ def test(environ=os.environ):
             exec("testing print_exception() -- <I>italics?</I>")
         def g(f=f):
             f()
-        print "<H3>What follows is a test, not an actual exception:</H3>"
+        print("<H3>What follows is a test, not an actual exception:</H3>")
         g()
     except:
         print_exception()
 
-    print "<H1>Second try with a small maxlen...</H1>"
+    print("<H1>Second try with a small maxlen...</H1>")
 
     global maxlen
     maxlen = 50
@@ -937,67 +937,67 @@ def print_exception(type=None, value=None, tb=None, limit=None):
     if type is None:
         type, value, tb = sys.exc_info()
     import traceback
-    print
-    print "<H3>Traceback (most recent call last):</H3>"
+    print()
+    print("<H3>Traceback (most recent call last):</H3>")
     list = traceback.format_tb(tb, limit) + \
            traceback.format_exception_only(type, value)
-    print "<PRE>%s<B>%s</B></PRE>" % (
+    print("<PRE>%s<B>%s</B></PRE>" % (
         escape("".join(list[:-1])),
         escape(list[-1]),
-        )
+        ))
     del tb
 
 def print_environ(environ=os.environ):
     """Dump the shell environment as HTML."""
     keys = environ.keys()
     keys.sort()
-    print
-    print "<H3>Shell Environment:</H3>"
-    print "<DL>"
+    print()
+    print("<H3>Shell Environment:</H3>")
+    print("<DL>")
     for key in keys:
-        print "<DT>", escape(key), "<DD>", escape(environ[key])
-    print "</DL>"
-    print
+        print("<DT>", escape(key), "<DD>", escape(environ[key]))
+    print("</DL>")
+    print()
 
 def print_form(form):
     """Dump the contents of a form as HTML."""
     keys = form.keys()
     keys.sort()
-    print
-    print "<H3>Form Contents:</H3>"
+    print()
+    print("<H3>Form Contents:</H3>")
     if not keys:
-        print "<P>No form fields."
-    print "<DL>"
+        print("<P>No form fields.")
+    print("<DL>")
     for key in keys:
-        print "<DT>" + escape(key) + ":",
+        print("<DT>" + escape(key) + ":", end=' ')
         value = form[key]
-        print "<i>" + escape(repr(type(value))) + "</i>"
-        print "<DD>" + escape(repr(value))
-    print "</DL>"
-    print
+        print("<i>" + escape(repr(type(value))) + "</i>")
+        print("<DD>" + escape(repr(value)))
+    print("</DL>")
+    print()
 
 def print_directory():
     """Dump the current directory as HTML."""
-    print
-    print "<H3>Current Working Directory:</H3>"
+    print()
+    print("<H3>Current Working Directory:</H3>")
     try:
         pwd = os.getcwd()
     except os.error as msg:
-        print "os.error:", escape(str(msg))
+        print("os.error:", escape(str(msg)))
     else:
-        print escape(pwd)
-    print
+        print(escape(pwd))
+    print()
 
 def print_arguments():
-    print
-    print "<H3>Command Line Arguments:</H3>"
-    print
-    print sys.argv
-    print
+    print()
+    print("<H3>Command Line Arguments:</H3>")
+    print()
+    print(sys.argv)
+    print()
 
 def print_environ_usage():
     """Dump a list of environment variables used by CGI as HTML."""
-    print """
+    print("""
 <H3>These environment variables could have been set:</H3>
 <UL>
 <LI>AUTH_TYPE
@@ -1036,7 +1036,7 @@ environment as well.  Here are some common variable names:
 <LI>HTTP_REFERER
 <LI>HTTP_USER_AGENT
 </UL>
-"""
+""")
 
 
 # Utilities
index 8d3a884263aefda95eb6b25d269e07edd14c1007..8532a2eeb9ddc1a6ab7ff72a4981812981bbd308 100644 (file)
@@ -107,7 +107,7 @@ class InteractiveInterpreter:
             self.showtraceback()
         else:
             if softspace(sys.stdout, 0):
-                print
+                print()
 
     def showsyntaxerror(self, filename=None):
         """Display the syntax error that just occurred.
index 1e5c6a6e2dbebb1efc63e70b106650b24520d749..6781908653b5dd92b4525aacadad72bb528faa2f 100644 (file)
@@ -33,11 +33,11 @@ def compile_dir(dir, maxlevels=10, ddir=None,
 
     """
     if not quiet:
-        print 'Listing', dir, '...'
+        print('Listing', dir, '...')
     try:
         names = os.listdir(dir)
     except os.error:
-        print "Can't list", dir
+        print("Can't list", dir)
         names = []
     names.sort()
     success = 1
@@ -60,18 +60,18 @@ def compile_dir(dir, maxlevels=10, ddir=None,
                 except os.error: ctime = 0
                 if (ctime > ftime) and not force: continue
                 if not quiet:
-                    print 'Compiling', fullname, '...'
+                    print('Compiling', fullname, '...')
                 try:
                     ok = py_compile.compile(fullname, None, dfile, True)
                 except KeyboardInterrupt:
                     raise KeyboardInterrupt
                 except py_compile.PyCompileError as err:
                     if quiet:
-                        print 'Compiling', fullname, '...'
-                    print err.msg
+                        print('Compiling', fullname, '...')
+                    print(err.msg)
                     success = 0
                 except IOError as e:
-                    print "Sorry", e
+                    print("Sorry", e)
                     success = 0
                 else:
                     if ok == 0:
@@ -98,7 +98,7 @@ def compile_path(skip_curdir=1, maxlevels=0, force=0, quiet=0):
     success = 1
     for dir in sys.path:
         if (not dir or dir == os.curdir) and skip_curdir:
-            print 'Skipping current directory'
+            print('Skipping current directory')
         else:
             success = success and compile_dir(dir, maxlevels, None,
                                               force, quiet=quiet)
@@ -110,16 +110,16 @@ def main():
     try:
         opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:')
     except getopt.error as msg:
-        print msg
-        print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
-              "[-x regexp] [directory ...]"
-        print "-l: don't recurse down"
-        print "-f: force rebuild even if timestamps are up-to-date"
-        print "-q: quiet operation"
-        print "-d destdir: purported directory name for error messages"
-        print "   if no directory arguments, -l sys.path is assumed"
-        print "-x regexp: skip files matching the regular expression regexp"
-        print "   the regexp is search for in the full path of the file"
+        print(msg)
+        print("usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
+              "[-x regexp] [directory ...]")
+        print("-l: don't recurse down")
+        print("-f: force rebuild even if timestamps are up-to-date")
+        print("-q: quiet operation")
+        print("-d destdir: purported directory name for error messages")
+        print("   if no directory arguments, -l sys.path is assumed")
+        print("-x regexp: skip files matching the regular expression regexp")
+        print("   the regexp is search for in the full path of the file")
         sys.exit(2)
     maxlevels = 10
     ddir = None
@@ -136,7 +136,7 @@ def main():
             rx = re.compile(a)
     if ddir:
         if len(args) != 1:
-            print "-d destdir require exactly one directory argument"
+            print("-d destdir require exactly one directory argument")
             sys.exit(2)
     success = 1
     try:
@@ -148,7 +148,7 @@ def main():
         else:
             success = compile_path()
     except KeyboardInterrupt:
-        print "\n[interrupt]"
+        print("\n[interrupt]")
         success = 0
     return success
 
index fef189e9e91dedbb27b39f7b9a66a5a020c1c339..6e724904a78df73f1d255e521ad3268b5defef68 100644 (file)
@@ -65,9 +65,9 @@ if __name__ == "__main__":
     from compiler import parseFile, walk
 
     for file in sys.argv[1:]:
-        print file
+        print(file)
         tree = parseFile(file)
         v = FutureParser()
         walk(tree, v)
-        print v.found
-        print
+        print(v.found)
+        print()
index 86e2c49443ba2ac7fa8ded91fbe9db942b1f05b1..9f45d61d992585e1c39f35f32a38892acd8c21e3 100644 (file)
@@ -19,10 +19,10 @@ class FlowGraph:
     def startBlock(self, block):
         if self._debug:
             if self.current:
-                print "end", repr(self.current)
-                print "    next", self.current.next
-                print "   ", self.current.get_children()
-            print repr(block)
+                print("end", repr(self.current))
+                print("    next", self.current.next)
+                print("   ", self.current.get_children())
+            print(repr(block))
         self.current = block
 
     def nextBlock(self, block=None):
@@ -68,7 +68,7 @@ class FlowGraph:
 
     def emit(self, *inst):
         if self._debug:
-            print "\t", inst
+            print("\t", inst)
         if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']:
             self.current.addOutEdge(self.exit)
         if len(inst) == 2 and isinstance(inst[1], Block):
@@ -400,12 +400,12 @@ class PyFlowGraph(FlowGraph):
         for t in self.insts:
             opname = t[0]
             if opname == "SET_LINENO":
-                print
+                print()
             if len(t) == 1:
-                print "\t", "%3d" % pc, opname
+                print("\t", "%3d" % pc, opname)
                 pc = pc + 1
             else:
-                print "\t", "%3d" % pc, opname, t[1]
+                print("\t", "%3d" % pc, opname, t[1])
                 pc = pc + 3
         if io:
             sys.stdout = save
@@ -601,8 +601,8 @@ class PyFlowGraph(FlowGraph):
                 try:
                     lnotab.addCode(self.opnum[opname], lo, hi)
                 except ValueError:
-                    print opname, oparg
-                    print self.opnum[opname], lo, hi
+                    print(opname, oparg)
+                    print(self.opnum[opname], lo, hi)
                     raise
         self.stage = DONE
 
@@ -744,7 +744,7 @@ class StackDepthTracker:
         for i in insts:
             opname = i[0]
             if debug:
-                print i,
+                print(i, end=' ')
             delta = self.effect.get(opname, None)
             if delta is not None:
                 depth = depth + delta
@@ -763,7 +763,7 @@ class StackDepthTracker:
             if depth > maxDepth:
                 maxDepth = depth
             if debug:
-                print depth, maxDepth
+                print(depth, maxDepth)
         return maxDepth
 
     effect = {
index a1dc9716cfbb3172b94c713cd0d19b99620e7db9..0e497817a3137ac88f75651d8119197172ca6ae9 100644 (file)
@@ -112,7 +112,7 @@ class Module(AbstractCompileMode):
         gen = ModuleCodeGenerator(tree)
         if display:
             import pprint
-            print pprint.pprint(tree)
+            print(pprint.pprint(tree))
         self.code = gen.getCode()
 
     def dump(self, f):
@@ -1018,7 +1018,7 @@ class CodeGenerator:
             self.set_lineno(node)
             self.delName(node.name)
         else:
-            print "oops", node.flags
+            print("oops", node.flags)
 
     def visitAssAttr(self, node):
         self.visit(node.expr)
@@ -1027,8 +1027,8 @@ class CodeGenerator:
         elif node.flags == 'OP_DELETE':
             self.emit('DELETE_ATTR', self.mangle(node.attrname))
         else:
-            print "warning: unexpected flags:", node.flags
-            print node
+            print("warning: unexpected flags:", node.flags)
+            print(node)
 
     def _visitAssSequence(self, node, op='UNPACK_SEQUENCE'):
         if findOp(node) != 'OP_DELETE':
@@ -1189,7 +1189,7 @@ class CodeGenerator:
         elif node.flags == 'OP_DELETE':
             self.emit('DELETE_SLICE+%d' % slice)
         else:
-            print "weird slice", node.flags
+            print("weird slice", node.flags)
             raise
 
     def visitSubscript(self, node, aug_flag=None):
index 3585efc3013aa25d1d2425b6dbe77d20528b6ce6..6c19b5ba76a7a61f5cb3dcd5fe91fb89a281a449 100644 (file)
@@ -76,12 +76,12 @@ class Scope:
         return self.children
 
     def DEBUG(self):
-        print >> sys.stderr, self.name, self.nested and "nested" or ""
-        print >> sys.stderr, "\tglobals: ", self.globals
-        print >> sys.stderr, "\tcells: ", self.cells
-        print >> sys.stderr, "\tdefs: ", self.defs
-        print >> sys.stderr, "\tuses: ", self.uses
-        print >> sys.stderr, "\tfrees:", self.frees
+        print(self.name, self.nested and "nested" or "", file=sys.stderr)
+        print("\tglobals: ", self.globals, file=sys.stderr)
+        print("\tcells: ", self.cells, file=sys.stderr)
+        print("\tdefs: ", self.defs, file=sys.stderr)
+        print("\tuses: ", self.uses, file=sys.stderr)
+        print("\tfrees:", self.frees, file=sys.stderr)
 
     def check_name(self, name):
         """Return scope of name.
@@ -429,7 +429,7 @@ if __name__ == "__main__":
                 if not (s.startswith('_[') or s.startswith('.'))]
 
     for file in sys.argv[1:]:
-        print file
+        print(file)
         f = open(file)
         buf = f.read()
         f.close()
@@ -443,10 +443,10 @@ if __name__ == "__main__":
         names2 = s.scopes[tree].get_names()
 
         if not list_eq(mod_names, names2):
-            print
-            print "oops", file
-            print sorted(mod_names)
-            print sorted(names2)
+            print()
+            print("oops", file)
+            print(sorted(mod_names))
+            print(sorted(names2))
             sys.exit(-1)
 
         d = {}
@@ -460,11 +460,11 @@ if __name__ == "__main__":
                 l = [sc for sc in scopes
                      if sc.name == s.get_name()]
                 if len(l) > 1:
-                    print "skipping", s.get_name()
+                    print("skipping", s.get_name())
                 else:
                     if not list_eq(get_names(s.get_namespace()),
                                    l[0].get_names()):
-                        print s.get_name()
-                        print sorted(get_names(s.get_namespace()))
-                        print sorted(l[0].get_names())
+                        print(s.get_name())
+                        print(sorted(get_names(s.get_namespace())))
+                        print(sorted(l[0].get_names()))
                         sys.exit(-1)
index a45d9c2cf6f3f797f5ba3fbc883cfeecc1290fb1..6187b47dbd631d46d16aec94a3b94bf5c45d30bb 100644 (file)
@@ -32,7 +32,7 @@ class SyntaxErrorChecker:
     def error(self, node, msg):
         self.errors = self.errors + 1
         if self.multi is not None:
-            print "%s:%s: %s" % (node.filename, node.lineno, msg)
+            print("%s:%s: %s" % (node.filename, node.lineno, msg))
         else:
             raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno)
 
index 0d0034001c48d2b8679a511a30666f530626da4d..3a2be135e4d66ba752d34e3e9d8f7ac13eb51093 100644 (file)
@@ -86,7 +86,7 @@ def Node(*args):
         try:
             return nodes[kind](*args[1:])
         except TypeError:
-            print nodes[kind], len(args), args
+            print(nodes[kind], len(args), args)
             raise
     else:
         raise WalkerError, "Can't find appropriate Node type: %s" % str(args)
index f10f56011a3ec629c1b8cdb695b4ffbbbfefce35..99c6716309adc9a36b982b2acefba71282cc4b5e 100644 (file)
@@ -79,20 +79,20 @@ class ExampleASTVisitor(ASTVisitor):
             meth = getattr(self.visitor, 'visit' + className, 0)
             self._cache[node.__class__] = meth
         if self.VERBOSE > 1:
-            print "dispatch", className, (meth and meth.__name__ or '')
+            print("dispatch", className, (meth and meth.__name__ or ''))
         if meth:
             meth(node, *args)
         elif self.VERBOSE > 0:
             klass = node.__class__
             if klass not in self.examples:
                 self.examples[klass] = klass
-                print
-                print self.visitor
-                print klass
+                print()
+                print(self.visitor)
+                print(klass)
                 for attr in dir(node):
                     if attr[0] != '_':
-                        print "\t", "%-12.12s" % attr, getattr(node, attr)
-                print
+                        print("\t", "%-12.12s" % attr, getattr(node, attr))
+                print()
             return self.default(node, *args)
 
 # XXX this is an API change
@@ -107,7 +107,7 @@ def walk(tree, visitor, walker=None, verbose=None):
     return walker.visitor
 
 def dumpNode(node):
-    print node.__class__
+    print(node.__class__)
     for attr in dir(node):
         if attr[0] != '_':
-            print "\t", "%-10.10s" % attr, getattr(node, attr)
+            print("\t", "%-10.10s" % attr, getattr(node, attr))
index 527759f6c4c137b37940bd31f3a8736aa0531705..37e35cf93a72504b7b639bb43c986bb352621ff2 100644 (file)
@@ -318,11 +318,11 @@ def _test():
     l = [None, 1, 2, 3.14, 'xyzzy', (1, 2), [3.14, 'abc'],
          {'abc': 'ABC'}, (), [], {}]
     l1 = copy(l)
-    print l1==l
+    print(l1==l)
     l1 = map(copy, l)
-    print l1==l
+    print(l1==l)
     l1 = deepcopy(l)
-    print l1==l
+    print(l1==l)
     class C:
         def __init__(self, arg=None):
             self.a = 1
@@ -346,26 +346,26 @@ def _test():
     c = C('argument sketch')
     l.append(c)
     l2 = copy(l)
-    print l == l2
-    print l
-    print l2
+    print(l == l2)
+    print(l)
+    print(l2)
     l2 = deepcopy(l)
-    print l == l2
-    print l
-    print l2
+    print(l == l2)
+    print(l)
+    print(l2)
     l.append({l[1]: l, 'xyz': l[2]})
     l3 = copy(l)
     import repr
-    print map(repr.repr, l)
-    print map(repr.repr, l1)
-    print map(repr.repr, l2)
-    print map(repr.repr, l3)
+    print(map(repr.repr, l))
+    print(map(repr.repr, l1))
+    print(map(repr.repr, l2))
+    print(map(repr.repr, l3))
     l3 = deepcopy(l)
     import repr
-    print map(repr.repr, l)
-    print map(repr.repr, l1)
-    print map(repr.repr, l2)
-    print map(repr.repr, l3)
+    print(map(repr.repr, l))
+    print(map(repr.repr, l1))
+    print(map(repr.repr, l2))
+    print(map(repr.repr, l3))
 
 if __name__ == '__main__':
     _test()
index 245dda65347c1fda2f30a031682c917fbdcd8f85..1101828cc979ffdb13decb9c26a8b30f3ec16558 100644 (file)
@@ -60,10 +60,10 @@ def get_tests(package, mask, verbosity):
         except ResourceDenied as detail:
             skipped.append(modname)
             if verbosity > 1:
-                print >> sys.stderr, "Skipped %s: %s" % (modname, detail)
+                print("Skipped %s: %s" % (modname, detail), file=sys.stderr)
             continue
         except Exception as detail:
-            print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail)
+            print("Warning: could not import %s: %s" % (modname, detail), file=sys.stderr)
             continue
         for name in dir(mod):
             if name.startswith("_"):
@@ -74,7 +74,7 @@ def get_tests(package, mask, verbosity):
     return skipped, tests
 
 def usage():
-    print __doc__
+    print(__doc__)
     return 1
 
 def test_with_refcounts(runner, verbosity, testcase):
@@ -106,9 +106,9 @@ def test_with_refcounts(runner, verbosity, testcase):
         cleanup()
         refcounts[i] = sys.gettotalrefcount() - rc
     if filter(None, refcounts):
-        print "%s leaks:\n\t" % testcase, refcounts
+        print("%s leaks:\n\t" % testcase, refcounts)
     elif verbosity:
-        print "%s: ok." % testcase
+        print("%s: ok." % testcase)
 
 class TestRunner(unittest.TextTestRunner):
     def run(self, test, skipped):
@@ -166,7 +166,7 @@ def main(*packages):
             try:
                 sys.gettotalrefcount
             except AttributeError:
-                print >> sys.stderr, "-r flag requires Python debug build"
+                print("-r flag requires Python debug build", file=sys.stderr)
                 return -1
             search_leaks = True
         elif flag == "-u":
index 1f6899212f25d08bddaf4d1f78950e557862fe50..4833cbc79e091a482c3202853772b1d8842cf33e 100644 (file)
@@ -15,7 +15,7 @@ def bin(s):
 
 class Test(unittest.TestCase):
     def X_test(self):
-        print >> sys.stderr,  sys.byteorder
+        print(sys.byteorder, file=sys.stderr)
         for i in range(32):
             bits = BITS()
             setattr(bits, "i%s" % i, 1)
index 810467faaceb5ab26fb0bf596dfee39f535e50a7..71cfe935265158b6656686a8f664650e3dae9d67 100644 (file)
@@ -22,12 +22,12 @@ else:
 ## print, for debugging
 if is_resource_enabled("printing"):
     if lib_gl or lib_glu or lib_glut or lib_gle:
-        print "OpenGL libraries:"
+        print("OpenGL libraries:")
         for item in (("GL", lib_gl),
                      ("GLU", lib_glu),
                      ("glut", lib_glut),
                      ("gle", lib_gle)):
-            print "\t", item
+            print("\t", item)
 
 
 # On some systems, loading the OpenGL libraries needs the RTLD_GLOBAL mode.
index 80b6ca2ae179824cca2cae98557d43a3aeb2b1d9..a0eb00fa859acaa91c4372ce284e29bd07789b6a 100644 (file)
@@ -100,13 +100,13 @@ class DeletePointerTestCase(unittest.TestCase):
         x = X()
         i = c_char_p("abc def")
         from sys import getrefcount as grc
-        print "2?", grc(i)
+        print("2?", grc(i))
         x.p = pointer(i)
-        print "3?", grc(i)
+        print("3?", grc(i))
         for i in range(320):
             c_int(99)
             x.p[0]
-        print x.p[0]
+        print(x.p[0])
 ##        del x
 ##        print "2?", grc(i)
 ##        del i
@@ -115,14 +115,14 @@ class DeletePointerTestCase(unittest.TestCase):
         for i in range(320):
             c_int(99)
             x.p[0]
-        print x.p[0]
-        print x.p.contents
+        print(x.p[0])
+        print(x.p.contents)
 ##        print x._objects
 
         x.p[0] = "spam spam"
 ##        print x.p[0]
-        print "+" * 42
-        print x._objects
+        print("+" * 42)
+        print(x._objects)
 
 class PointerToStructure(unittest.TestCase):
     def test(self):
index 28c83fd4a9deca0bc9d0df3b90cbe1de91e945ba..f265a7351bba10faeb38c740c0b51cdf3d33fc88 100644 (file)
@@ -15,7 +15,7 @@ else:
     libc_name = find_library("c")
 
 if is_resource_enabled("printing"):
-    print "libc_name is", libc_name
+    print("libc_name is", libc_name)
 
 class LoaderTest(unittest.TestCase):
 
@@ -44,8 +44,8 @@ class LoaderTest(unittest.TestCase):
     if os.name in ("nt", "ce"):
         def test_load_library(self):
             if is_resource_enabled("printing"):
-                print find_library("kernel32")
-                print find_library("user32")
+                print(find_library("kernel32"))
+                print(find_library("user32"))
 
             if os.name == "nt":
                 windll.kernel32.GetModuleHandleW
index d4f223892f3aacf73f633c57c71795e0ab07bb03..2c5a990c215eb05d54994c5c21757a2a485382f4 100644 (file)
@@ -192,7 +192,7 @@ def run_test(rep, msg, func, arg=None):
         for i in items:
             func(); func(); func(); func(); func()
         stop = clock()
-    print "%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))
+    print("%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)))
 
 def check_perf():
     # Construct 5 objects
index b5072290c8c480d1a7e4e1f71dbb90f143ea0b12..aca7282a4d5c5db6521148b21eb41140d3c77b3a 100644 (file)
@@ -189,7 +189,7 @@ def run_test(rep, msg, func, arg):
     for i in items:
         func(arg); func(arg); func(arg); func(arg); func(arg)
     stop = clock()
-    print "%20s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))
+    print("%20s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)))
 
 def check_perf():
     # Construct 5 objects
index 46f4c55305a849e7c609bace797a50702be5506d..8a9b706a7d51dd2ae79db497f9f492adaa9136f3 100644 (file)
@@ -125,15 +125,15 @@ elif os.name == "posix":
 def test():
     from ctypes import cdll
     if os.name == "nt":
-        print cdll.msvcrt
-        print cdll.load("msvcrt")
-        print find_library("msvcrt")
+        print(cdll.msvcrt)
+        print(cdll.load("msvcrt"))
+        print(find_library("msvcrt"))
 
     if os.name == "posix":
         # find and load_version
-        print find_library("m")
-        print find_library("c")
-        print find_library("bz2")
+        print(find_library("m"))
+        print(find_library("c"))
+        print(find_library("bz2"))
 
         # getattr
 ##        print cdll.m
@@ -141,14 +141,14 @@ def test():
 
         # load
         if sys.platform == "darwin":
-            print cdll.LoadLibrary("libm.dylib")
-            print cdll.LoadLibrary("libcrypto.dylib")
-            print cdll.LoadLibrary("libSystem.dylib")
-            print cdll.LoadLibrary("System.framework/System")
+            print(cdll.LoadLibrary("libm.dylib"))
+            print(cdll.LoadLibrary("libcrypto.dylib"))
+            print(cdll.LoadLibrary("libSystem.dylib"))
+            print(cdll.LoadLibrary("System.framework/System"))
         else:
-            print cdll.LoadLibrary("libm.so")
-            print cdll.LoadLibrary("libcrypt.so")
-            print find_library("crypt")
+            print(cdll.LoadLibrary("libm.so"))
+            print(cdll.LoadLibrary("libcrypt.so"))
+            print(find_library("crypt"))
 
 if __name__ == "__main__":
     test()
index 60b7be9942677c26c4cace65a1bee0b1d1c4f0b2..4e37b480f13353f5510d38d06b085de50f2ee72e 100644 (file)
@@ -189,4 +189,4 @@ if __name__ == '__main__':
                           % (_curses.keyname( key ), system, python) )
     finally:
         _curses.endwin()
-        for i in L: print i
+        for i in L: print(i)
index 120c5721ee73fcd3ee07fb9e19d3ba50eeeecbb0..24a964a1c7b8cde13c979539bd10853df3910740 100644 (file)
@@ -170,4 +170,4 @@ if __name__ == '__main__':
         return Textbox(win).edit()
 
     str = curses.wrapper(test_editbox)
-    print 'Contents of text box:', repr(str)
+    print('Contents of text box:', repr(str))
index 831840d44fbe5cea593166c26f4027e1f6dc332a..f2d13436b14310eb061962740d5817e5bed5da95 100644 (file)
@@ -76,7 +76,7 @@ class SequenceMatcher:
     sequences.  As a rule of thumb, a .ratio() value over 0.6 means the
     sequences are close matches:
 
-    >>> print round(s.ratio(), 3)
+    >>> print(round(s.ratio(), 3))
     0.866
     >>>
 
@@ -84,7 +84,7 @@ class SequenceMatcher:
     .get_matching_blocks() is handy:
 
     >>> for block in s.get_matching_blocks():
-    ...     print "a[%d] and b[%d] match for %d elements" % block
+    ...     print("a[%d] and b[%d] match for %d elements" % block)
     a[0] and b[0] match for 8 elements
     a[8] and b[17] match for 21 elements
     a[29] and b[38] match for 0 elements
@@ -97,7 +97,7 @@ class SequenceMatcher:
     use .get_opcodes():
 
     >>> for opcode in s.get_opcodes():
-    ...     print "%6s a[%d:%d] b[%d:%d]" % opcode
+    ...     print("%6s a[%d:%d] b[%d:%d]" % opcode)
      equal a[0:8] b[0:8]
     insert a[8:8] b[8:17]
      equal a[8:29] b[17:38]
@@ -545,8 +545,8 @@ class SequenceMatcher:
         >>> b = "abycdf"
         >>> s = SequenceMatcher(None, a, b)
         >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
-        ...    print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
-        ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
+        ...    print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
+        ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
          delete a[0:1] (q) b[0:0] ()
           equal a[1:3] (ab) b[0:2] (ab)
         replace a[3:4] (x) b[2:3] (y)
@@ -832,7 +832,7 @@ class Differ:
 
     As a single multi-line string it looks like this:
 
-    >>> print ''.join(result),
+    >>> print(''.join(result), end="")
         1. Beautiful is better than ugly.
     -   2. Explicit is better than implicit.
     -   3. Simple is better than complex.
@@ -889,8 +889,9 @@ class Differ:
 
         Example:
 
-        >>> print ''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
+        >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
         ...                                'ore\ntree\nemu\n'.splitlines(1))),
+        ...       end="")
         - one
         ?  ^
         + ore
@@ -950,7 +951,7 @@ class Differ:
         >>> d = Differ()
         >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
         ...                            ['abcdefGhijkl\n'], 0, 1)
-        >>> print ''.join(results),
+        >>> print(''.join(results), end="")
         - abcDefghiJkl
         ?    ^  ^  ^
         + abcdefGhijkl
@@ -1058,7 +1059,7 @@ class Differ:
         >>> d = Differ()
         >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n',
         ...                      '  ^ ^  ^      ', '+  ^ ^  ^      ')
-        >>> for line in results: print repr(line)
+        >>> for line in results: print(repr(line))
         ...
         '- \tabcDefghiJkl\n'
         '? \t ^ ^  ^\n'
@@ -1164,7 +1165,7 @@ def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
     ...             'zero one tree four'.split(), 'Original', 'Current',
     ...             'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003',
     ...             lineterm=''):
-    ...     print line
+    ...     print(line)
     --- Original Sat Jan 26 23:30:50 1991
     +++ Current Fri Jun 06 10:20:52 2003
     @@ -1,4 +1,4 @@
@@ -1223,9 +1224,10 @@ def context_diff(a, b, fromfile='', tofile='',
 
     Example:
 
-    >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
+    >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
     ...       'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current',
     ...       'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')),
+    ...       end="")
     *** Original Sat Jan 26 23:30:50 1991
     --- Current Fri Jun 06 10:22:46 2003
     ***************
@@ -1295,7 +1297,7 @@ def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
 
     >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
     ...              'ore\ntree\nemu\n'.splitlines(1))
-    >>> print ''.join(diff),
+    >>> print(''.join(diff), end="")
     - one
     ?  ^
     + ore
@@ -1992,11 +1994,11 @@ def restore(delta, which):
     >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
     ...              'ore\ntree\nemu\n'.splitlines(1))
     >>> diff = list(diff)
-    >>> print ''.join(restore(diff, 1)),
+    >>> print(''.join(restore(diff, 1)), end="")
     one
     two
     three
-    >>> print ''.join(restore(diff, 2)),
+    >>> print(''.join(restore(diff, 2)), end="")
     ore
     tree
     emu
index 7b2a0f9c9549c4a5354bcd8c780caee14e8f694e..385c19d64c936060c05d6b4c6439e96328127540 100644 (file)
@@ -30,12 +30,12 @@ def dis(x=None):
                             types.FunctionType,
                             types.CodeType,
                             types.ClassType):
-                print "Disassembly of %s:" % name
+                print("Disassembly of %s:" % name)
                 try:
                     dis(x1)
                 except TypeError as msg:
-                    print "Sorry:", msg
-                print
+                    print("Sorry:", msg)
+                print()
     elif hasattr(x, 'co_code'):
         disassemble(x)
     elif isinstance(x, str):
@@ -69,17 +69,17 @@ def disassemble(co, lasti=-1):
         op = ord(c)
         if i in linestarts:
             if i > 0:
-                print
-            print "%3d" % linestarts[i],
+                print()
+            print("%3d" % linestarts[i], end=' ')
         else:
-            print '   ',
-
-        if i == lasti: print '-->',
-        else: print '   ',
-        if i in labels: print '>>',
-        else: print '  ',
-        print repr(i).rjust(4),
-        print opname[op].ljust(20),
+            print('   ', end=' ')
+
+        if i == lasti: print('-->', end=' ')
+        else: print('   ', end=' ')
+        if i in labels: print('>>', end=' ')
+        else: print('  ', end=' ')
+        print(repr(i).rjust(4), end=' ')
+        print(opname[op].ljust(20), end=' ')
         i = i+1
         if op >= HAVE_ARGUMENT:
             oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg
@@ -87,22 +87,22 @@ def disassemble(co, lasti=-1):
             i = i+2
             if op == EXTENDED_ARG:
                 extended_arg = oparg*65536
-            print repr(oparg).rjust(5),
+            print(repr(oparg).rjust(5), end=' ')
             if op in hasconst:
-                print '(' + repr(co.co_consts[oparg]) + ')',
+                print('(' + repr(co.co_consts[oparg]) + ')', end=' ')
             elif op in hasname:
-                print '(' + co.co_names[oparg] + ')',
+                print('(' + co.co_names[oparg] + ')', end=' ')
             elif op in hasjrel:
-                print '(to ' + repr(i + oparg) + ')',
+                print('(to ' + repr(i + oparg) + ')', end=' ')
             elif op in haslocal:
-                print '(' + co.co_varnames[oparg] + ')',
+                print('(' + co.co_varnames[oparg] + ')', end=' ')
             elif op in hascompare:
-                print '(' + cmp_op[oparg] + ')',
+                print('(' + cmp_op[oparg] + ')', end=' ')
             elif op in hasfree:
                 if free is None:
                     free = co.co_cellvars + co.co_freevars
-                print '(' + free[oparg] + ')',
-        print
+                print('(' + free[oparg] + ')', end=' ')
+        print()
 
 def disassemble_string(code, lasti=-1, varnames=None, names=None,
                        constants=None):
@@ -112,37 +112,37 @@ def disassemble_string(code, lasti=-1, varnames=None, names=None,
     while i < n:
         c = code[i]
         op = ord(c)
-        if i == lasti: print '-->',
-        else: print '   ',
-        if i in labels: print '>>',
-        else: print '  ',
-        print repr(i).rjust(4),
-        print opname[op].ljust(15),
+        if i == lasti: print('-->', end=' ')
+        else: print('   ', end=' ')
+        if i in labels: print('>>', end=' ')
+        else: print('  ', end=' ')
+        print(repr(i).rjust(4), end=' ')
+        print(opname[op].ljust(15), end=' ')
         i = i+1
         if op >= HAVE_ARGUMENT:
             oparg = ord(code[i]) + ord(code[i+1])*256
             i = i+2
-            print repr(oparg).rjust(5),
+            print(repr(oparg).rjust(5), end=' ')
             if op in hasconst:
                 if constants:
-                    print '(' + repr(constants[oparg]) + ')',
+                    print('(' + repr(constants[oparg]) + ')', end=' ')
                 else:
-                    print '(%d)'%oparg,
+                    print('(%d)'%oparg, end=' ')
             elif op in hasname:
                 if names is not None:
-                    print '(' + names[oparg] + ')',
+                    print('(' + names[oparg] + ')', end=' ')
                 else:
-                    print '(%d)'%oparg,
+                    print('(%d)'%oparg, end=' ')
             elif op in hasjrel:
-                print '(to ' + repr(i + oparg) + ')',
+                print('(to ' + repr(i + oparg) + ')', end=' ')
             elif op in haslocal:
                 if varnames:
-                    print '(' + varnames[oparg] + ')',
+                    print('(' + varnames[oparg] + ')', end=' ')
                 else:
-                    print '(%d)' % oparg,
+                    print('(%d)' % oparg, end=' ')
             elif op in hascompare:
-                print '(' + cmp_op[oparg] + ')',
-        print
+                print('(' + cmp_op[oparg] + ')', end=' ')
+        print()
 
 disco = disassemble                     # XXX For backwards compatibility
 
index 6968cb8f6f63ac692e1c944017918a910a00d8de..b6a3bf62ce01eb2358dff4d402be7e84ad87587b 100644 (file)
@@ -392,7 +392,7 @@ class BCPPCompiler(CCompiler) :
             try:
                 self.spawn(pp_args)
             except DistutilsExecError as msg:
-                print msg
+                print(msg)
                 raise CompileError, msg
 
     # preprocess()
index 0ed9a40a35e29fd888846c91026abb065d882a4f..25d90c8a9a33a7eae4e26e68afa9c2e5bec9094f 100644 (file)
@@ -1026,7 +1026,7 @@ main (int argc, char **argv) {
     def debug_print (self, msg):
         from distutils.debug import DEBUG
         if DEBUG:
-            print msg
+            print(msg)
 
     def warn (self, msg):
         sys.stderr.write ("warning: %s\n" % msg)
index 3cd5858920ca6c74b355c63b4e8397975c32ab98..be0a3e23f650091dc46a93a4cedacd65fb856326 100644 (file)
@@ -163,14 +163,14 @@ class Command:
         from distutils.fancy_getopt import longopt_xlate
         if header is None:
             header = "command options for '%s':" % self.get_command_name()
-        print indent + header
+        print(indent + header)
         indent = indent + "  "
         for (option, _, _) in self.user_options:
             option = string.translate(option, longopt_xlate)
             if option[-1] == "=":
                 option = option[:-1]
             value = getattr(self, option)
-            print indent + "%s = %s" % (option, value)
+            print(indent + "%s = %s" % (option, value))
 
 
     def run (self):
@@ -199,7 +199,7 @@ class Command:
         """
         from distutils.debug import DEBUG
         if DEBUG:
-            print msg
+            print(msg)
             sys.stdout.flush()
 
 
@@ -475,4 +475,4 @@ class install_misc (Command):
 
 
 if __name__ == "__main__":
-    print "ok"
+    print("ok")
index 6f0e0d881cb3aeb93732b4ab60f750533b324019..bbcf2927dc8c7a495f48e9d3a78f51ac8fa80a4d 100644 (file)
@@ -267,11 +267,11 @@ class bdist_rpm (Command):
     def run (self):
 
         if DEBUG:
-            print "before _get_package_data():"
-            print "vendor =", self.vendor
-            print "packager =", self.packager
-            print "doc_files =", self.doc_files
-            print "changelog =", self.changelog
+            print("before _get_package_data():")
+            print("vendor =", self.vendor)
+            print("packager =", self.packager)
+            print("doc_files =", self.doc_files)
+            print("changelog =", self.changelog)
 
         # make directories
         if self.spec_only:
index 520c1b0c7632452c19efa12deaa23cef016ef942..42465693be7c0ff2383803ccdc1c30a86ea6a411 100644 (file)
@@ -359,9 +359,9 @@ class config (Command):
 
 def dump_file (filename, head=None):
     if head is None:
-        print filename + ":"
+        print(filename + ":")
     else:
-        print head
+        print(head)
 
     file = open(filename)
     sys.stdout.write(file.read())
index 453151d08b5305971364c5a930f5e893c5eadd50..fd5d6d1f39c187c0f514d34f6ab51f6e1359b233 100644 (file)
@@ -292,7 +292,7 @@ class install (Command):
 
         if DEBUG:
             from pprint import pprint
-            print "config vars:"
+            print("config vars:")
             pprint(self.config_vars)
 
         # Expand "~" and configuration variables in the installation
@@ -347,7 +347,7 @@ class install (Command):
     def dump_dirs (self, msg):
         if DEBUG:
             from distutils.fancy_getopt import longopt_xlate
-            print msg + ":"
+            print(msg + ":")
             for opt in self.user_options:
                 opt_name = opt[0]
                 if opt_name[-1] == "=":
@@ -359,7 +359,7 @@ class install (Command):
                 else:
                     opt_name = string.translate(opt_name, longopt_xlate)
                     val = getattr(self, opt_name)
-                print "  %s: %s" % (opt_name, val)
+                print("  %s: %s" % (opt_name, val))
 
 
     def finalize_unix (self):
index cb9525ab0ec787303b801bef5d3fb9552c07d573..48070ee83b13016d5a9afdc9c944eea97b38b49e 100644 (file)
@@ -86,14 +86,14 @@ class register(Command):
         ''' Fetch the list of classifiers from the server.
         '''
         response = urllib2.urlopen(self.repository+'?:action=list_classifiers')
-        print response.read()
+        print(response.read())
 
     def verify_metadata(self):
         ''' Send the metadata to the package index server to be checked.
         '''
         # send the info to the server and report the result
         (code, result) = self.post_to_server(self.build_post_data('verify'))
-        print 'Server response (%s): %s'%(code, result)
+        print('Server response (%s): %s'%(code, result))
 
     def send_metadata(self):
         ''' Send the metadata to the package index server.
@@ -128,7 +128,7 @@ class register(Command):
         if os.environ.has_key('HOME'):
             rc = os.path.join(os.environ['HOME'], '.pypirc')
             if os.path.exists(rc):
-                print 'Using PyPI login from %s'%rc
+                print('Using PyPI login from %s'%rc)
                 config = ConfigParser.ConfigParser()
                 config.read(rc)
                 username = config.get('server-login', 'username')
@@ -138,17 +138,17 @@ class register(Command):
         # get the user's login info
         choices = '1 2 3 4'.split()
         while choice not in choices:
-            print '''We need to know who you are, so please choose either:
+            print('''We need to know who you are, so please choose either:
  1. use your existing login,
  2. register as a new user,
  3. have the server generate a new password for you (and email it to you), or
  4. quit
-Your selection [default 1]: ''',
+Your selection [default 1]: ''', end=' ')
             choice = raw_input()
             if not choice:
                 choice = '1'
             elif choice not in choices:
-                print 'Please choose one of the four options!'
+                print('Please choose one of the four options!')
 
         if choice == '1':
             # get the username and password
@@ -165,13 +165,13 @@ Your selection [default 1]: ''',
             # send the info to the server and report the result
             code, result = self.post_to_server(self.build_post_data('submit'),
                 auth)
-            print 'Server response (%s): %s'%(code, result)
+            print('Server response (%s): %s'%(code, result))
 
             # possibly save the login
             if os.environ.has_key('HOME') and config is None and code == 200:
                 rc = os.path.join(os.environ['HOME'], '.pypirc')
-                print 'I can store your PyPI login so future submissions will be faster.'
-                print '(the login will be stored in %s)'%rc
+                print('I can store your PyPI login so future submissions will be faster.')
+                print('(the login will be stored in %s)'%rc)
                 choice = 'X'
                 while choice.lower() not in 'yn':
                     choice = raw_input('Save your login (y/N)?')
@@ -200,22 +200,22 @@ Your selection [default 1]: ''',
                 if data['password'] != data['confirm']:
                     data['password'] = ''
                     data['confirm'] = None
-                    print "Password and confirm don't match!"
+                    print("Password and confirm don't match!")
             while not data['email']:
                 data['email'] = raw_input('   EMail: ')
             code, result = self.post_to_server(data)
             if code != 200:
-                print 'Server response (%s): %s'%(code, result)
+                print('Server response (%s): %s'%(code, result))
             else:
-                print 'You will receive an email shortly.'
-                print 'Follow the instructions in it to complete registration.'
+                print('You will receive an email shortly.')
+                print('Follow the instructions in it to complete registration.')
         elif choice == '3':
             data = {':action': 'password_reset'}
             data['email'] = ''
             while not data['email']:
                 data['email'] = raw_input('Your email address: ')
             code, result = self.post_to_server(data)
-            print 'Server response (%s): %s'%(code, result)
+            print('Server response (%s): %s'%(code, result))
 
     def build_post_data(self, action):
         # figure the data to send - the metadata plus some additional
@@ -295,5 +295,5 @@ Your selection [default 1]: ''',
                 data = result.read()
             result = 200, 'OK'
         if self.show_response:
-            print '-'*75, data, '-'*75
+            print('-'*75, data, '-'*75)
         return result
index 7f96a475b695c2657be473fab465d513a29b8a2d..438ae99a9c7f3535cf6ee91dc0643df8cf4a83f0 100644 (file)
@@ -196,4 +196,4 @@ class upload(Command):
             self.announce('Upload failed (%s): %s' % (r.status, r.reason),
                           log.ERROR)
         if self.show_response:
-            print '-'*75, r.read(), '-'*75
+            print('-'*75, r.read(), '-'*75)
index 4dc8eb01aabe17e99840c3e693ac553e3fbf47d5..6242775c11b141481a2d09a6e7793882f66fac20 100644 (file)
@@ -125,7 +125,7 @@ def setup (**attrs):
     dist.parse_config_files()
 
     if DEBUG:
-        print "options (after parsing config files):"
+        print("options (after parsing config files):")
         dist.dump_option_dicts()
 
     if _setup_stop_after == "config":
@@ -139,7 +139,7 @@ def setup (**attrs):
         raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg
 
     if DEBUG:
-        print "options (after parsing command line):"
+        print("options (after parsing command line):")
         dist.dump_option_dicts()
 
     if _setup_stop_after == "commandline":
index d21c5e2f1b8ebf6b02c1c0c7ab1a7e0e92f16d99..ca7a2f9952fa3b7753920b899b7917bc1b8ad313 100644 (file)
@@ -290,22 +290,22 @@ Common commands: (see '--help-commands' for more)
             commands.sort()
 
         if header is not None:
-            print indent + header
+            print(indent + header)
             indent = indent + "  "
 
         if not commands:
-            print indent + "no commands known yet"
+            print(indent + "no commands known yet")
             return
 
         for cmd_name in commands:
             opt_dict = self.command_options.get(cmd_name)
             if opt_dict is None:
-                print indent + "no option dict for '%s' command" % cmd_name
+                print(indent + "no option dict for '%s' command" % cmd_name)
             else:
-                print indent + "option dict for '%s' command:" % cmd_name
+                print(indent + "option dict for '%s' command:" % cmd_name)
                 out = pformat(opt_dict)
                 for line in string.split(out, "\n"):
-                    print indent + "  " + line
+                    print(indent + "  " + line)
 
     # dump_option_dicts ()
 
@@ -365,11 +365,11 @@ Common commands: (see '--help-commands' for more)
         if filenames is None:
             filenames = self.find_config_files()
 
-        if DEBUG: print "Distribution.parse_config_files():"
+        if DEBUG: print("Distribution.parse_config_files():")
 
         parser = ConfigParser()
         for filename in filenames:
-            if DEBUG: print "  reading", filename
+            if DEBUG: print("  reading", filename)
             parser.read(filename)
             for section in parser.sections():
                 options = parser.options(section)
@@ -636,14 +636,14 @@ Common commands: (see '--help-commands' for more)
                 options = self.global_options
             parser.set_option_table(options)
             parser.print_help(self.common_usage + "\nGlobal options:")
-            print
+            print()
 
         if display_options:
             parser.set_option_table(self.display_options)
             parser.print_help(
                 "Information display options (just display " +
                 "information, ignore any commands)")
-            print
+            print()
 
         for command in self.commands:
             if type(command) is ClassType and issubclass(command, Command):
@@ -657,9 +657,9 @@ Common commands: (see '--help-commands' for more)
             else:
                 parser.set_option_table(klass.user_options)
             parser.print_help("Options for '%s' command:" % klass.__name__)
-            print
+            print()
 
-        print gen_usage(self.script_name)
+        print(gen_usage(self.script_name))
         return
 
     # _show_help ()
@@ -678,8 +678,8 @@ Common commands: (see '--help-commands' for more)
         # we ignore "foo bar").
         if self.help_commands:
             self.print_commands()
-            print
-            print gen_usage(self.script_name)
+            print()
+            print(gen_usage(self.script_name))
             return 1
 
         # If user supplied any of the "display metadata" options, then
@@ -695,12 +695,12 @@ Common commands: (see '--help-commands' for more)
                 opt = translate_longopt(opt)
                 value = getattr(self.metadata, "get_"+opt)()
                 if opt in ['keywords', 'platforms']:
-                    print string.join(value, ',')
+                    print(string.join(value, ','))
                 elif opt in ('classifiers', 'provides', 'requires',
                              'obsoletes'):
-                    print string.join(value, '\n')
+                    print(string.join(value, '\n'))
                 else:
-                    print value
+                    print(value)
                 any_display_options = 1
 
         return any_display_options
@@ -712,7 +712,7 @@ Common commands: (see '--help-commands' for more)
         'print_commands()'.
         """
 
-        print header + ":"
+        print(header + ":")
 
         for cmd in commands:
             klass = self.cmdclass.get(cmd)
@@ -723,7 +723,7 @@ Common commands: (see '--help-commands' for more)
             except AttributeError:
                 description = "(no description available)"
 
-            print "  %-*s  %s" % (max_length, cmd, description)
+            print("  %-*s  %s" % (max_length, cmd, description))
 
     # print_command_list ()
 
@@ -757,7 +757,7 @@ Common commands: (see '--help-commands' for more)
                                 "Standard commands",
                                 max_length)
         if extra_commands:
-            print
+            print()
             self.print_command_list(extra_commands,
                                     "Extra commands",
                                     max_length)
@@ -862,8 +862,8 @@ Common commands: (see '--help-commands' for more)
         cmd_obj = self.command_obj.get(command)
         if not cmd_obj and create:
             if DEBUG:
-                print "Distribution.get_command_obj(): " \
-                      "creating '%s' command object" % command
+                print("Distribution.get_command_obj(): " \
+                      "creating '%s' command object" % command)
 
             klass = self.get_command_class(command)
             cmd_obj = self.command_obj[command] = klass(self)
@@ -893,9 +893,9 @@ Common commands: (see '--help-commands' for more)
         if option_dict is None:
             option_dict = self.get_option_dict(command_name)
 
-        if DEBUG: print "  setting options for '%s' command:" % command_name
+        if DEBUG: print("  setting options for '%s' command:" % command_name)
         for (option, (source, value)) in option_dict.items():
-            if DEBUG: print "    %s = %s (from %s)" % (option, value, source)
+            if DEBUG: print("    %s = %s (from %s)" % (option, value, source))
             try:
                 bool_opts = map(translate_longopt, command_obj.boolean_options)
             except AttributeError:
@@ -1219,4 +1219,4 @@ def fix_help_options (options):
 
 if __name__ == "__main__":
     dist = Distribution()
-    print "ok"
+    print("ok")
index 62a24e8524b5d033d937dd0808436e52d8b76e26..646f8e1ee6f4d2b132e0e77595a4c74928a2f8cb 100644 (file)
@@ -497,6 +497,6 @@ How *do* you spell that odd word, anyways?
 say, "How should I know?"].)"""
 
     for w in (10, 20, 30, 40):
-        print "width: %d" % w
-        print string.join(wrap_text(text, w), "\n")
-        print
+        print("width: %d" % w)
+        print(string.join(wrap_text(text, w), "\n"))
+        print()
index 4bbdd1f00fa8812a044b52bf04e15faa31dbdf7e..e4a83d6484e05253ba7b904236b4b0b27c894fde 100644 (file)
@@ -53,7 +53,7 @@ class FileList:
         """
         from distutils.debug import DEBUG
         if DEBUG:
-            print msg
+            print(msg)
 
     # -- List-like methods ---------------------------------------------
 
index 95d4c1c5a21f0cb9041f29b7ea3caf8c8ae99278..e4959d649215a09cf52f58a753c4c601c5a8e4d5 100644 (file)
@@ -23,9 +23,9 @@ class Log:
             if not args:
                 # msg may contain a '%'. If args is empty,
                 # don't even try to string-format
-                print msg
+                print(msg)
             else:
-                print msg % args
+                print(msg % args)
             sys.stdout.flush()
 
     def log(self, level, msg, *args):
index 0de123d9e925d7368d6417fc18136729a2b8e542..9db1a39b17c9f2e2b315802191f9e869a8d203ef 100644 (file)
@@ -160,9 +160,9 @@ class MWerksCompiler (CCompiler) :
         settings['libraries'] = libraries
         settings['extrasearchdirs'] = sourcefiledirs + include_dirs + library_dirs
         if self.dry_run:
-            print 'CALLING LINKER IN', os.getcwd()
+            print('CALLING LINKER IN', os.getcwd())
             for key, value in settings.items():
-                print '%20.20s %s'%(key, value)
+                print('%20.20s %s'%(key, value))
             return
         # Build the export file
         exportfilename = os.path.join(build_temp, exportname)
index 6b07f52ebe259fd233fa1773086eadf695960725..c75931c3abfc450bba388757e24749933a1f7acf 100644 (file)
@@ -109,7 +109,7 @@ def _spawn_os2 (cmd,
                   "command '%s' failed: %s" % (cmd[0], exc[-1])
         if rc != 0:
             # and this reflects the command running but failing
-            print "command '%s' failed with exit status %d" % (cmd[0], rc)
+            print("command '%s' failed with exit status %d" % (cmd[0], rc))
             raise DistutilsExecError, \
                   "command '%s' failed with exit status %d" % (cmd[0], rc)
 
index 4d2a7cdf1a167f619ae177ce9085144948d97ed0..8d4b07037c63f683ee93758c6dd5138f7b4c95a3 100644 (file)
@@ -74,8 +74,8 @@ class DistributionTestCase(unittest.TestCase):
         sys.argv.append("build")
         f = open(TESTFN, "w")
         try:
-            print >>f, "[global]"
-            print >>f, "command_packages = foo.bar, splat"
+            print("[global]", file=f)
+            print("command_packages = foo.bar, splat", file=f)
             f.close()
             d = self.create_distribution([TESTFN])
             self.assertEqual(d.get_command_packages(),
index ff2878de1b6b59c53845fd8f3a54ba09da19cf8a..10ee1be783b63e66495360794f6a2716a38c6806 100644 (file)
@@ -342,13 +342,13 @@ line 3 \\
         result = file.readlines ()
         # result = string.join (result, '')
         if result == expected_result:
-            print "ok %d (%s)" % (count, description)
+            print("ok %d (%s)" % (count, description))
         else:
-            print "not ok %d (%s):" % (count, description)
-            print "** expected:"
-            print expected_result
-            print "** received:"
-            print result
+            print("not ok %d (%s):" % (count, description))
+            print("** expected:")
+            print(expected_result)
+            print("** received:")
+            print(result)
 
 
     filename = "test.txt"
index d120a0130615c2911c4b301df8000e9b741d1dff..f55396e21c7295787e4434bcdb93ff0b0175eac9 100644 (file)
@@ -855,7 +855,7 @@ class DocTestFinder:
         add them to `tests`.
         """
         if self._verbose:
-            print 'Finding tests in %s' % name
+            print('Finding tests in %s' % name)
 
         # If we've already processed this object, then ignore it.
         if id(obj) in seen:
@@ -1384,28 +1384,28 @@ class DocTestRunner:
                 failed.append(x)
         if verbose:
             if notests:
-                print len(notests), "items had no tests:"
+                print(len(notests), "items had no tests:")
                 notests.sort()
                 for thing in notests:
-                    print "   ", thing
+                    print("   ", thing)
             if passed:
-                print len(passed), "items passed all tests:"
+                print(len(passed), "items passed all tests:")
                 passed.sort()
                 for thing, count in passed:
-                    print " %3d tests in %s" % (count, thing)
+                    print(" %3d tests in %s" % (count, thing))
         if failed:
-            print self.DIVIDER
-            print len(failed), "items had failures:"
+            print(self.DIVIDER)
+            print(len(failed), "items had failures:")
             failed.sort()
             for thing, (f, t) in failed:
-                print " %3d of %3d in %s" % (f, t, thing)
+                print(" %3d of %3d in %s" % (f, t, thing))
         if verbose:
-            print totalt, "tests in", len(self._name2ft), "items."
-            print totalt - totalf, "passed and", totalf, "failed."
+            print(totalt, "tests in", len(self._name2ft), "items.")
+            print(totalt - totalf, "passed and", totalf, "failed.")
         if totalf:
-            print "***Test Failed***", totalf, "failures."
+            print("***Test Failed***", totalf, "failures.")
         elif verbose:
-            print "Test passed."
+            print("Test passed.")
         return totalf, totalt
 
     #/////////////////////////////////////////////////////////////////
@@ -1415,8 +1415,8 @@ class DocTestRunner:
         d = self._name2ft
         for name, (f, t) in other._name2ft.items():
             if name in d:
-                print "*** DocTestRunner.merge: '" + name + "' in both" \
-                    " testers; summing outcomes."
+                print("*** DocTestRunner.merge: '" + name + "' in both" \
+                    " testers; summing outcomes.")
                 f2, t2 = d[name]
                 f = f + f2
                 t = t + t2
@@ -1985,10 +1985,10 @@ class Tester:
     def runstring(self, s, name):
         test = DocTestParser().get_doctest(s, self.globs, name, None, None)
         if self.verbose:
-            print "Running string", name
+            print("Running string", name)
         (f,t) = self.testrunner.run(test)
         if self.verbose:
-            print f, "of", t, "examples failed in string", name
+            print(f, "of", t, "examples failed in string", name)
         return (f,t)
 
     def rundoc(self, object, name=None, module=None):
@@ -2512,7 +2512,7 @@ def debug_script(src, pm=False, globs=None):
             try:
                 execfile(srcfilename, globs, globs)
             except:
-                print sys.exc_info()[1]
+                print(sys.exc_info()[1])
                 pdb.post_mortem(sys.exc_info()[2])
         else:
             # Note that %r is vital here.  '%s' instead can, e.g., cause
index ed832a3e9a46ebb6d5bb67351c56d57c46d9dbe1..4f3fea4d011898a2bb18b436f56e33d5794a8c1d 100644 (file)
@@ -80,7 +80,7 @@ class Generator:
             ufrom = msg.get_unixfrom()
             if not ufrom:
                 ufrom = 'From nobody ' + time.ctime(time.time())
-            print >> self._fp, ufrom
+            print(ufrom, file=self._fp)
         self._write(msg)
 
     def clone(self, fp):
@@ -140,13 +140,13 @@ class Generator:
 
     def _write_headers(self, msg):
         for h, v in msg.items():
-            print >> self._fp, '%s:' % h,
+            print('%s:' % h, end=' ', file=self._fp)
             if self._maxheaderlen == 0:
                 # Explicit no-wrapping
-                print >> self._fp, v
+                print(v, file=self._fp)
             elif isinstance(v, Header):
                 # Header instances know what to do
-                print >> self._fp, v.encode()
+                print(v.encode(), file=self._fp)
             elif _is8bitstring(v):
                 # If we have raw 8bit data in a byte string, we have no idea
                 # what the encoding is.  There is no safe way to split this
@@ -154,14 +154,14 @@ class Generator:
                 # ascii split, but if it's multibyte then we could break the
                 # string.  There's no way to know so the least harm seems to
                 # be to not split the string and risk it being too long.
-                print >> self._fp, v
+                print(v, file=self._fp)
             else:
                 # Header's got lots of smarts, so use it.
-                print >> self._fp, Header(
+                print(Header(
                     v, maxlinelen=self._maxheaderlen,
-                    header_name=h, continuation_ws='\t').encode()
+                    header_name=h, continuation_ws='\t').encode(), file=self._fp)
         # A blank line always separates headers from body
-        print >> self._fp
+        print(file=self._fp)
 
     #
     # Handlers for writing types and subtypes
@@ -215,9 +215,9 @@ class Generator:
             msg.set_boundary(boundary)
         # If there's a preamble, write it out, with a trailing CRLF
         if msg.preamble is not None:
-            print >> self._fp, msg.preamble
+            print(msg.preamble, file=self._fp)
         # dash-boundary transport-padding CRLF
-        print >> self._fp, '--' + boundary
+        print('--' + boundary, file=self._fp)
         # body-part
         if msgtexts:
             self._fp.write(msgtexts.pop(0))
@@ -226,13 +226,13 @@ class Generator:
         # --> CRLF body-part
         for body_part in msgtexts:
             # delimiter transport-padding CRLF
-            print >> self._fp, '\n--' + boundary
+            print('\n--' + boundary, file=self._fp)
             # body-part
             self._fp.write(body_part)
         # close-delimiter transport-padding
         self._fp.write('\n--' + boundary + '--')
         if msg.epilogue is not None:
-            print >> self._fp
+            print(file=self._fp)
             self._fp.write(msg.epilogue)
 
     def _handle_message_delivery_status(self, msg):
@@ -308,12 +308,12 @@ class DecodedGenerator(Generator):
         for part in msg.walk():
             maintype = part.get_content_maintype()
             if maintype == 'text':
-                print >> self, part.get_payload(decode=True)
+                print(part.get_payload(decode=True), file=self)
             elif maintype == 'multipart':
                 # Just skip this
                 pass
             else:
-                print >> self, self._fmt % {
+                print(self._fmt % {
                     'type'       : part.get_content_type(),
                     'maintype'   : part.get_content_maintype(),
                     'subtype'    : part.get_content_subtype(),
@@ -322,7 +322,7 @@ class DecodedGenerator(Generator):
                                             '[no description]'),
                     'encoding'   : part.get('Content-Transfer-Encoding',
                                             '[no encoding]'),
-                    }
+                    }, file=self)
 
 
 \f
index e99f2280da3814421db67c476902cbeab96280c7..4f2c84c0994989ddeaa5953fc6727d5934204f04 100644 (file)
@@ -63,11 +63,11 @@ def _structure(msg, fp=None, level=0, include_default=False):
     if fp is None:
         fp = sys.stdout
     tab = ' ' * (level * 4)
-    print >> fp, tab + msg.get_content_type(),
+    print(tab + msg.get_content_type(), end=' ', file=fp)
     if include_default:
-        print >> fp, '[%s]' % msg.get_default_type()
+        print('[%s]' % msg.get_default_type(), file=fp)
     else:
-        print >> fp
+        print(file=fp)
     if msg.is_multipart():
         for subpart in msg.get_payload():
             _structure(subpart, fp, level+1, include_default)
index 8127ef003f41a284cd604c9739a839eaf3aab6e8..0a25a67abb30f6fff529b7088d93e4e9a1c8ef2f 100644 (file)
@@ -56,7 +56,7 @@ class TestEmailBase(unittest.TestCase):
             ssecond = str(second)
             diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
             fp = StringIO()
-            print >> fp, NL, NL.join(diff)
+            print(NL, NL.join(diff), file=fp)
             raise self.failureException, fp.getvalue()
 
     def _msgobj(self, filename):
index ce685c5f2d8e5060b3f3eedf5bf5436510bb1745..532b146a04b0d5ed66ca1797b184e4897f47e7a1 100644 (file)
@@ -57,7 +57,7 @@ class TestEmailBase(unittest.TestCase):
             ssecond = str(second)
             diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
             fp = StringIO()
-            print >> fp, NL, NL.join(diff)
+            print(NL, NL.join(diff), file=fp)
             raise self.failureException, fp.getvalue()
 
     def _msgobj(self, filename):
index 51a97a55db93d9acb92be0ae6bd9d9879a5bd881..dda227256e3a43941bfb1e9f74b1551c65fc9a68 100644 (file)
@@ -192,39 +192,39 @@ class dircmp:
 
     def report(self): # Print a report on the differences between a and b
         # Output format is purposely lousy
-        print 'diff', self.left, self.right
+        print('diff', self.left, self.right)
         if self.left_only:
             self.left_only.sort()
-            print 'Only in', self.left, ':', self.left_only
+            print('Only in', self.left, ':', self.left_only)
         if self.right_only:
             self.right_only.sort()
-            print 'Only in', self.right, ':', self.right_only
+            print('Only in', self.right, ':', self.right_only)
         if self.same_files:
             self.same_files.sort()
-            print 'Identical files :', self.same_files
+            print('Identical files :', self.same_files)
         if self.diff_files:
             self.diff_files.sort()
-            print 'Differing files :', self.diff_files
+            print('Differing files :', self.diff_files)
         if self.funny_files:
             self.funny_files.sort()
-            print 'Trouble with common files :', self.funny_files
+            print('Trouble with common files :', self.funny_files)
         if self.common_dirs:
             self.common_dirs.sort()
-            print 'Common subdirectories :', self.common_dirs
+            print('Common subdirectories :', self.common_dirs)
         if self.common_funny:
             self.common_funny.sort()
-            print 'Common funny cases :', self.common_funny
+            print('Common funny cases :', self.common_funny)
 
     def report_partial_closure(self): # Print reports on self and on subdirs
         self.report()
         for sd in self.subdirs.itervalues():
-            print
+            print()
             sd.report()
 
     def report_full_closure(self): # Report on self and subdirs recursively
         self.report()
         for sd in self.subdirs.itervalues():
-            print
+            print()
             sd.report_full_closure()
 
     methodmap = dict(subdirs=phase4,
index 19932ca8e64f1cd8da079795f1b2d950f8a7bf94..f6913eb8cbd31e675e7993ecc56e8189c8e997e2 100644 (file)
@@ -405,9 +405,9 @@ def _test():
     for line in input(args, inplace=inplace, backup=backup):
         if line[-1:] == '\n': line = line[:-1]
         if line[-1:] == '\r': line = line[:-1]
-        print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
-                                   isfirstline() and "*" or "", line)
-    print "%d: %s[%d]" % (lineno(), filename(), filelineno())
+        print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
+                                   isfirstline() and "*" or "", line))
+    print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
 
 if __name__ == '__main__':
     _test()
index fa2b38938ae6e9b228be32dad2aeb903516d920a..50a9cd813339dfa3b1c32a4292507d0913fd4ba3 100644 (file)
@@ -323,37 +323,37 @@ class AbstractWriter(NullWriter):
     """
 
     def new_alignment(self, align):
-        print "new_alignment(%r)" % (align,)
+        print("new_alignment(%r)" % (align,))
 
     def new_font(self, font):
-        print "new_font(%r)" % (font,)
+        print("new_font(%r)" % (font,))
 
     def new_margin(self, margin, level):
-        print "new_margin(%r, %d)" % (margin, level)
+        print("new_margin(%r, %d)" % (margin, level))
 
     def new_spacing(self, spacing):
-        print "new_spacing(%r)" % (spacing,)
+        print("new_spacing(%r)" % (spacing,))
 
     def new_styles(self, styles):
-        print "new_styles(%r)" % (styles,)
+        print("new_styles(%r)" % (styles,))
 
     def send_paragraph(self, blankline):
-        print "send_paragraph(%r)" % (blankline,)
+        print("send_paragraph(%r)" % (blankline,))
 
     def send_line_break(self):
-        print "send_line_break()"
+        print("send_line_break()")
 
     def send_hor_rule(self, *args, **kw):
-        print "send_hor_rule()"
+        print("send_hor_rule()")
 
     def send_label_data(self, data):
-        print "send_label_data(%r)" % (data,)
+        print("send_label_data(%r)" % (data,))
 
     def send_flowing_data(self, data):
-        print "send_flowing_data(%r)" % (data,)
+        print("send_flowing_data(%r)" % (data,))
 
     def send_literal_data(self, data):
-        print "send_literal_data(%r)" % (data,)
+        print("send_literal_data(%r)" % (data,))
 
 
 class DumbWriter(NullWriter):
index 0ae86a913fe636c247f313a0548ca1591f0605d0..485c39b292b12bd02b2571845c7792635af6b86f 100644 (file)
@@ -137,6 +137,6 @@ def test():
     try:
         while 1:
             x, digs = input('Enter (x, digs): ')
-            print x, fix(x, digs), sci(x, digs)
+            print(x, fix(x, digs), sci(x, digs))
     except (EOFError, KeyboardInterrupt):
         pass
index 16c4a0219c7fb8d758a18f525d01972620b6cff8..85e3cc915315092f071d489b93bc305620a8339f 100644 (file)
@@ -137,7 +137,7 @@ class FTP:
         '''Get the welcome message from the server.
         (this is read and squirreled away by connect())'''
         if self.debugging:
-            print '*welcome*', self.sanitize(self.welcome)
+            print('*welcome*', self.sanitize(self.welcome))
         return self.welcome
 
     def set_debuglevel(self, level):
@@ -167,12 +167,12 @@ class FTP:
     # Internal: send one line to the server, appending CRLF
     def putline(self, line):
         line = line + CRLF
-        if self.debugging > 1: print '*put*', self.sanitize(line)
+        if self.debugging > 1: print('*put*', self.sanitize(line))
         self.sock.sendall(line)
 
     # Internal: send one command to the server (through putline())
     def putcmd(self, line):
-        if self.debugging: print '*cmd*', self.sanitize(line)
+        if self.debugging: print('*cmd*', self.sanitize(line))
         self.putline(line)
 
     # Internal: return one line from the server, stripping CRLF.
@@ -180,7 +180,7 @@ class FTP:
     def getline(self):
         line = self.file.readline()
         if self.debugging > 1:
-            print '*get*', self.sanitize(line)
+            print('*get*', self.sanitize(line))
         if not line: raise EOFError
         if line[-2:] == CRLF: line = line[:-2]
         elif line[-1:] in CRLF: line = line[:-1]
@@ -206,7 +206,7 @@ class FTP:
     # Raise various errors if the response indicates an error
     def getresp(self):
         resp = self.getmultiline()
-        if self.debugging: print '*resp*', self.sanitize(resp)
+        if self.debugging: print('*resp*', self.sanitize(resp))
         self.lastresp = resp[:3]
         c = resp[:1]
         if c in ('1', '2', '3'):
@@ -230,7 +230,7 @@ class FTP:
         IP and Synch; that doesn't seem to work with the servers I've
         tried.  Instead, just send the ABOR command as OOB data.'''
         line = 'ABOR' + CRLF
-        if self.debugging > 1: print '*put urgent*', self.sanitize(line)
+        if self.debugging > 1: print('*put urgent*', self.sanitize(line))
         self.sock.sendall(line, MSG_OOB)
         resp = self.getmultiline()
         if resp[:3] not in ('426', '226'):
@@ -409,7 +409,7 @@ class FTP:
         fp = conn.makefile('rb')
         while 1:
             line = fp.readline()
-            if self.debugging > 2: print '*retr*', repr(line)
+            if self.debugging > 2: print('*retr*', repr(line))
             if not line:
                 break
             if line[-2:] == CRLF:
@@ -636,7 +636,7 @@ def parse257(resp):
 
 def print_line(line):
     '''Default retrlines callback to print a line.'''
-    print line
+    print(line)
 
 
 def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
@@ -775,7 +775,7 @@ def test():
     '''
 
     if len(sys.argv) < 2:
-        print test.__doc__
+        print(test.__doc__)
         sys.exit(0)
 
     debugging = 0
index 04e881ec73d08bfa6b29056bd75155486273c274..4882fdc25e1a3dab896145d8b5238618e2735640 100644 (file)
@@ -208,4 +208,4 @@ def short_has_arg(opt, shortopts):
 
 if __name__ == '__main__':
     import sys
-    print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
+    print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]))
index 8204a479f611d284beb12ca4a306175a8762abb9..02fe527e6b95aa7f788b50e0c710ce48db8045e7 100644 (file)
@@ -67,7 +67,7 @@ def win_getpass(prompt='Password: ', stream=None):
 
 
 def default_getpass(prompt='Password: ', stream=None):
-    print >>sys.stderr, "Warning: Problem with getpass. Passwords may be echoed."
+    print("Warning: Problem with getpass. Passwords may be echoed.", file=sys.stderr)
     return _raw_input(prompt, stream)
 
 
index d789161e60a2cc0f470aaeca8e0af288034cdd97..2fad21c9bfc6516e4af6c94dd34499eb3072de49 100644 (file)
@@ -103,7 +103,7 @@ def get_directory(f):
     while 1:
         line = f.readline()
         if not line:
-            print '(Unexpected EOF from server)'
+            print('(Unexpected EOF from server)')
             break
         if line[-2:] == CRLF:
             line = line[:-2]
@@ -112,17 +112,17 @@ def get_directory(f):
         if line == '.':
             break
         if not line:
-            print '(Empty line from server)'
+            print('(Empty line from server)')
             continue
         gtype = line[0]
         parts = line[1:].split(TAB)
         if len(parts) < 4:
-            print '(Bad line from server: %r)' % (line,)
+            print('(Bad line from server: %r)' % (line,))
             continue
         if len(parts) > 4:
             if parts[4:] != ['+']:
-                print '(Extra info from server:',
-                print parts[4:], ')'
+                print('(Extra info from server:', end=' ')
+                print(parts[4:], ')')
         else:
             parts.append('')
         parts.insert(0, gtype)
@@ -140,7 +140,7 @@ def get_alt_textfile(f, func):
     while 1:
         line = f.readline()
         if not line:
-            print '(Unexpected EOF from server)'
+            print('(Unexpected EOF from server)')
             break
         if line[-2:] == CRLF:
             line = line[:-2]
@@ -196,13 +196,13 @@ def test():
         f = send_selector(selector, host)
     if type == A_TEXT:
         lines = get_textfile(f)
-        for item in lines: print item
+        for item in lines: print(item)
     elif type in (A_MENU, A_INDEX):
         entries = get_directory(f)
-        for item in entries: print item
+        for item in entries: print(item)
     else:
         data = get_binary(f)
-        print 'binary data:', len(data), 'bytes:', repr(data[:100])[:40]
+        print('binary data:', len(data), 'bytes:', repr(data[:100])[:40])
 
 # Run the test when run as script
 if __name__ == '__main__':
index e5bb79e9dca61b904bff52a3e6e0a7f3a014e063..aac9956ea232a9e38740a1570102c1f8ac7de3fa 100644 (file)
@@ -470,7 +470,7 @@ def _test():
                 g = sys.stdout
             else:
                 if arg[-3:] != ".gz":
-                    print "filename doesn't end in .gz:", repr(arg)
+                    print("filename doesn't end in .gz:", repr(arg))
                     continue
                 f = open(arg, "rb")
                 g = __builtin__.open(arg[:-3], "wb")
index 753c3b7ec19891653baf94920130e9d7d10bf794..9ab4c99c94d2eae64cbfe9e2b6a60b5ed76b1414 100644 (file)
@@ -340,4 +340,4 @@ if __name__ == "__main__":
     sort = []
     while heap:
         sort.append(heappop(heap))
-    print sort
+    print(sort)
index df8f637547894c133e7c394aa15bf264cb1b1eac..059142eec1d8a16e617352bd651c8d3b172dccb1 100644 (file)
@@ -159,7 +159,7 @@ class LogReader:
         try:
             filename = self._filemap[fileno]
         except KeyError:
-            print "Could not identify fileId", fileno
+            print("Could not identify fileId", fileno)
             return 1
         if filename is None:
             return 1
index 7f88606329859d8ba7af026369194174102c3685..8f974b93b0ca289f1cce39d50f71b51bdcf97040 100644 (file)
@@ -10,9 +10,9 @@ def main(logfile):
     benchtime, stones = p.runcall(test.pystone.pystones)
     p.close()
 
-    print "Pystone(%s) time for %d passes = %g" % \
-          (test.pystone.__version__, test.pystone.LOOPS, benchtime)
-    print "This machine benchmarks at %g pystones/second" % stones
+    print("Pystone(%s) time for %d passes = %g" % \
+          (test.pystone.__version__, test.pystone.LOOPS, benchtime))
+    print("This machine benchmarks at %g pystones/second" % stones)
 
     stats = hotshot.stats.load(logfile)
     stats.strip_dirs()
index 652519f173163edfdc3b792187e117f571f90157..88e1df5741c06c44bb0917bc7c4085a2ceb50f3d 100644 (file)
@@ -464,7 +464,7 @@ def test(args = None):
         try:
             f = open(file, 'r')
         except IOError as msg:
-            print file, ":", msg
+            print(file, ":", msg)
             sys.exit(1)
 
     data = f.read()
index ca6e1d0b15cead993dbb31a1445df9d7f82f92c1..25075304ce945a0936d368ae623c04631d3c5dcd 100644 (file)
@@ -342,7 +342,7 @@ class HTTPResponse:
         # Initialize with Simple-Response defaults
         line = self.fp.readline()
         if self.debuglevel > 0:
-            print "reply:", repr(line)
+            print("reply:", repr(line))
         if not line:
             # Presumably, the server closed the connection before
             # sending a valid response.
@@ -391,7 +391,7 @@ class HTTPResponse:
                 if not skip:
                     break
                 if self.debuglevel > 0:
-                    print "header:", skip
+                    print("header:", skip)
 
         self.status = status
         self.reason = reason.strip()
@@ -414,7 +414,7 @@ class HTTPResponse:
         self.msg = HTTPMessage(self.fp, 0)
         if self.debuglevel > 0:
             for hdr in self.msg.headers:
-                print "header:", hdr,
+                print("header:", hdr, end=' ')
 
         # don't let the msg keep an fp
         self.msg.fp = None
@@ -665,11 +665,11 @@ class HTTPConnection:
             try:
                 self.sock = socket.socket(af, socktype, proto)
                 if self.debuglevel > 0:
-                    print "connect: (%s, %s)" % (self.host, self.port)
+                    print("connect: (%s, %s)" % (self.host, self.port))
                 self.sock.connect(sa)
             except socket.error as msg:
                 if self.debuglevel > 0:
-                    print 'connect fail:', (self.host, self.port)
+                    print('connect fail:', (self.host, self.port))
                 if self.sock:
                     self.sock.close()
                 self.sock = None
@@ -702,11 +702,11 @@ class HTTPConnection:
         # NOTE: we DO propagate the error, though, because we cannot simply
         #       ignore the error... the caller will know if they can retry.
         if self.debuglevel > 0:
-            print "send:", repr(str)
+            print("send:", repr(str))
         try:
             blocksize=8192
             if hasattr(str,'read') :
-                if self.debuglevel > 0: print "sendIng a read()able"
+                if self.debuglevel > 0: print("sendIng a read()able")
                 data=str.read(blocksize)
                 while data:
                     self.sock.sendall(data)
@@ -898,7 +898,7 @@ class HTTPConnection:
                     thelen = str(os.fstat(body.fileno()).st_size)
                 except (AttributeError, OSError):
                     # Don't send a length if this failed
-                    if self.debuglevel > 0: print "Cannot stat!!"
+                    if self.debuglevel > 0: print("Cannot stat!!")
 
             if thelen is not None:
                 self.putheader('Content-Length',thelen)
@@ -1408,13 +1408,13 @@ def test():
     h.putrequest('GET', selector)
     h.endheaders()
     status, reason, headers = h.getreply()
-    print 'status =', status
-    print 'reason =', reason
-    print "read", len(h.getfile().read())
-    print
+    print('status =', status)
+    print('reason =', reason)
+    print("read", len(h.getfile().read()))
+    print()
     if headers:
-        for header in headers.headers: print header.strip()
-    print
+        for header in headers.headers: print(header.strip())
+    print()
 
     # minimal test that code to extract host from url works
     class HTTP11(HTTP):
@@ -1431,20 +1431,20 @@ def test():
 
         for host, selector in (('sourceforge.net', '/projects/python'),
                                ):
-            print "https://%s%s" % (host, selector)
+            print("https://%s%s" % (host, selector))
             hs = HTTPS()
             hs.set_debuglevel(dl)
             hs.connect(host)
             hs.putrequest('GET', selector)
             hs.endheaders()
             status, reason, headers = hs.getreply()
-            print 'status =', status
-            print 'reason =', reason
-            print "read", len(hs.getfile().read())
-            print
+            print('status =', status)
+            print('reason =', reason)
+            print("read", len(hs.getfile().read()))
+            print()
             if headers:
-                for header in headers.headers: print header.strip()
-            print
+                for header in headers.headers: print(header.strip())
+            print()
 
 if __name__ == '__main__':
     test()
index 997eb13a0f9fb5314033aaedba57ad26b4386ef5..1ffbc162db3c398416143707cc7c60480b6b16cb 100644 (file)
@@ -201,9 +201,9 @@ if __name__=='__main__':
             arg_text = ct.fetch_tip(name)
             if arg_text != expected:
                 failed.append(t)
-                print "%s - expected %s, but got %s" % (t, expected,
-                                                        get_arg_text(entity))
-        print "%d of %d tests failed" % (len(failed), len(tests))
+                print("%s - expected %s, but got %s" % (t, expected,
+                                                        get_arg_text(entity)))
+        print("%d of %d tests failed" % (len(failed), len(tests)))
 
     tc = TC()
     tests = (t1, t2, t3, t4, t5, t6,
index 4cfcdc63534e15d55d3ed05f7b4b0392bc5ab199..5328d41196561169ef181fe6043298aae177efba 100644 (file)
@@ -72,7 +72,7 @@ class ColorDelegator(Delegator):
             "hit": idleConf.GetHighlight(theme, "hit"),
             }
 
-        if DEBUG: print 'tagdefs',self.tagdefs
+        if DEBUG: print('tagdefs',self.tagdefs)
 
     def insert(self, index, chars, tags=None):
         index = self.index(index)
@@ -91,13 +91,13 @@ class ColorDelegator(Delegator):
     def notify_range(self, index1, index2=None):
         self.tag_add("TODO", index1, index2)
         if self.after_id:
-            if DEBUG: print "colorizing already scheduled"
+            if DEBUG: print("colorizing already scheduled")
             return
         if self.colorizing:
             self.stop_colorizing = True
-            if DEBUG: print "stop colorizing"
+            if DEBUG: print("stop colorizing")
         if self.allow_colorizing:
-            if DEBUG: print "schedule colorizing"
+            if DEBUG: print("schedule colorizing")
             self.after_id = self.after(1, self.recolorize)
 
     close_when_done = None # Window to be closed when done colorizing
@@ -106,7 +106,7 @@ class ColorDelegator(Delegator):
         if self.after_id:
             after_id = self.after_id
             self.after_id = None
-            if DEBUG: print "cancel scheduled recolorizer"
+            if DEBUG: print("cancel scheduled recolorizer")
             self.after_cancel(after_id)
         self.allow_colorizing = False
         self.stop_colorizing = True
@@ -120,42 +120,42 @@ class ColorDelegator(Delegator):
         if self.after_id:
             after_id = self.after_id
             self.after_id = None
-            if DEBUG: print "cancel scheduled recolorizer"
+            if DEBUG: print("cancel scheduled recolorizer")
             self.after_cancel(after_id)
         if self.allow_colorizing and self.colorizing:
-            if DEBUG: print "stop colorizing"
+            if DEBUG: print("stop colorizing")
             self.stop_colorizing = True
         self.allow_colorizing = not self.allow_colorizing
         if self.allow_colorizing and not self.colorizing:
             self.after_id = self.after(1, self.recolorize)
         if DEBUG:
-            print "auto colorizing turned",\
-                  self.allow_colorizing and "on" or "off"
+            print("auto colorizing turned",\
+                  self.allow_colorizing and "on" or "off")
         return "break"
 
     def recolorize(self):
         self.after_id = None
         if not self.delegate:
-            if DEBUG: print "no delegate"
+            if DEBUG: print("no delegate")
             return
         if not self.allow_colorizing:
-            if DEBUG: print "auto colorizing is off"
+            if DEBUG: print("auto colorizing is off")
             return
         if self.colorizing:
-            if DEBUG: print "already colorizing"
+            if DEBUG: print("already colorizing")
             return
         try:
             self.stop_colorizing = False
             self.colorizing = True
-            if DEBUG: print "colorizing..."
+            if DEBUG: print("colorizing...")
             t0 = time.clock()
             self.recolorize_main()
             t1 = time.clock()
-            if DEBUG: print "%.3f seconds" % (t1-t0)
+            if DEBUG: print("%.3f seconds" % (t1-t0))
         finally:
             self.colorizing = False
         if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"):
-            if DEBUG: print "reschedule colorizing"
+            if DEBUG: print("reschedule colorizing")
             self.after_id = self.after(1, self.recolorize)
         if self.close_when_done:
             top = self.close_when_done
@@ -240,7 +240,7 @@ class ColorDelegator(Delegator):
                     self.tag_add("TODO", next)
                 self.update()
                 if self.stop_colorizing:
-                    if DEBUG: print "colorizing stopped"
+                    if DEBUG: print("colorizing stopped")
                     return
 
     def removecolors(self):
index 6125591fe0dd1aef5ad67dda101001c8f63b97ae..cc6266126e40f1ca22c87be2a3d5fd270ce6c3fb 100644 (file)
@@ -23,7 +23,7 @@ class Delegator:
     def cachereport(self):
         keys = self.__cache.keys()
         keys.sort()
-        print keys
+        print(keys)
 
     def setdelegate(self, delegate):
         self.resetcache()
index 396e2bdb65ad58430c430c291d9edd6757c8e64d..7cd6c1f3793324a4d4b2cb9680e9ae25c4d2ec81 100644 (file)
@@ -859,7 +859,7 @@ class EditorWindow(object):
             try:
                 self.load_extension(name)
             except:
-                print "Failed to load extension", repr(name)
+                print("Failed to load extension", repr(name))
                 import traceback
                 traceback.print_exc()
 
@@ -870,7 +870,7 @@ class EditorWindow(object):
         try:
             mod = __import__(name, globals(), locals(), [])
         except ImportError:
-            print "\nFailed to import extension: ", name
+            print("\nFailed to import extension: ", name)
             return
         cls = getattr(mod, name)
         keydefs = idleConf.GetExtensionBindings(name)
index 2ef0640c0d340ee9e48c13d9c95a6199a87cd08b..9c6fafeaa4d5f2a9e59dba39bc3573e835bcace3 100644 (file)
@@ -54,7 +54,7 @@ class FileList:
         try:
             key = self.inversedict[edit]
         except KeyError:
-            print "Don't know this EditorWindow object.  (close)"
+            print("Don't know this EditorWindow object.  (close)")
             return
         if key:
             del self.dict[key]
@@ -67,7 +67,7 @@ class FileList:
         try:
             key = self.inversedict[edit]
         except KeyError:
-            print "Don't know this EditorWindow object.  (rename)"
+            print("Don't know this EditorWindow object.  (rename)")
             return
         filename = edit.io.filename
         if not filename:
index 99d2e4dabc9b4102b372ef7d7ca89d6e05f6e12e..c96fada305fada0112128c96320945ccf4644c90 100644 (file)
@@ -77,13 +77,13 @@ class GrepDialog(SearchDialogBase):
         list.sort()
         self.close()
         pat = self.engine.getpat()
-        print "Searching %r in %s ..." % (pat, path)
+        print("Searching %r in %s ..." % (pat, path))
         hits = 0
         for fn in list:
             try:
                 f = open(fn)
             except IOError as msg:
-                print msg
+                print(msg)
                 continue
             lineno = 0
             while 1:
@@ -102,16 +102,16 @@ class GrepDialog(SearchDialogBase):
                 s = ""
             else:
                 s = "s"
-            print "Found", hits, "hit%s." % s
-            print "(Hint: right-click to open locations.)"
+            print("Found", hits, "hit%s." % s)
+            print("(Hint: right-click to open locations.)")
         else:
-            print "No hits."
+            print("No hits.")
 
     def findfiles(self, dir, base, rec):
         try:
             names = os.listdir(dir or os.curdir)
         except os.error as msg:
-            print msg
+            print(msg)
             return []
         list = []
         subdirs = []
index 40db92db738f351b63ef9a889eeaa9a063d32c90..1bb1576853684b56ce3eafda0eaf9604d2d68aee 100644 (file)
@@ -388,7 +388,7 @@ if __name__ == "__main__":
     text.pack()
     def bindseq(seq, n=[0]):
         def handler(event):
-            print seq
+            print(seq)
         text.bind("<<handler%d>>"%n[0], handler)
         text.event_add("<<handler%d>>"%n[0], seq)
         n[0] += 1
index ebbcba9e6a650728482d1ae940f94152314bf344..a0b1303792a35b428d1e30403f9d2bac2383bdcd 100644 (file)
@@ -58,10 +58,10 @@ def main():
             self.name = name
             Delegator.__init__(self, None)
         def insert(self, *args):
-            print self.name, ": insert", args
+            print(self.name, ": insert", args)
             self.delegate.insert(*args)
         def delete(self, *args):
-            print self.name, ": delete", args
+            print(self.name, ": delete", args)
             self.delegate.delete(*args)
     root = Tk()
     root.wm_protocol("WM_DELETE_WINDOW", root.quit)
index 46ef211c0529fa9a472c03a8838ffa0b7447b438..e8284d81fc71bec5e62ef326754bb24d004e8a81 100644 (file)
@@ -19,8 +19,8 @@ from code import InteractiveInterpreter
 try:
     from Tkinter import *
 except ImportError:
-    print>>sys.__stderr__, "** IDLE can't import Tkinter.  " \
-                           "Your Python may not be configured for Tk. **"
+    print("** IDLE can't import Tkinter.  " \
+                           "Your Python may not be configured for Tk. **", file=sys.__stderr__)
     sys.exit(1)
 import tkMessageBox
 
@@ -504,14 +504,14 @@ class ModifiedInterpreter(InteractiveInterpreter):
             console = self.tkconsole.console
             if how == "OK":
                 if what is not None:
-                    print >>console, repr(what)
+                    print(repr(what), file=console)
             elif how == "EXCEPTION":
                 if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
                     self.remote_stack_viewer()
             elif how == "ERROR":
                 errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n"
-                print >>sys.__stderr__, errmsg, what
-                print >>console, errmsg, what
+                print(errmsg, what, file=sys.__stderr__)
+                print(errmsg, what, file=console)
             # we received a response to the currently active seq number:
             try:
                 self.tkconsole.endexecuting()
@@ -576,8 +576,8 @@ class ModifiedInterpreter(InteractiveInterpreter):
         except (OverflowError, SyntaxError):
             self.tkconsole.resetoutput()
             tkerr = self.tkconsole.stderr
-            print>>tkerr, '*** Error in script or command!\n'
-            print>>tkerr, 'Traceback (most recent call last):'
+            print('*** Error in script or command!\n', file=tkerr)
+            print('Traceback (most recent call last):', file=tkerr)
             InteractiveInterpreter.showsyntaxerror(self, filename)
             self.tkconsole.showprompt()
         else:
@@ -730,8 +730,7 @@ class ModifiedInterpreter(InteractiveInterpreter):
                 if use_subprocess:
                     # When run w/o subprocess, both user and IDLE errors
                     # are printed here; skip message in that case.
-                    print >> self.tkconsole.stderr, \
-                             "IDLE internal error in runcode()"
+                    print("IDLE internal error in runcode()", file=self.tkconsole.stderr)
                 self.showtraceback()
                 if use_subprocess:
                     self.tkconsole.endexecuting()
@@ -1349,7 +1348,7 @@ def main():
             if os.path.isfile(script):
                 pass
             else:
-                print "No script file: ", script
+                print("No script file: ", script)
                 sys.exit()
             enable_shell = True
         if o == '-s':
index 92119365770540d8e5c57673f95f359a581892a3..350fdbd5babd529b38d3c0d7f23b65ec0bfc1585 100644 (file)
@@ -124,8 +124,8 @@ def test():
     root.protocol("WM_DELETE_WINDOW", root.destroy)
     class MyScrolledList(ScrolledList):
         def fill_menu(self): self.menu.add_command(label="pass")
-        def on_select(self, index): print "select", self.get(index)
-        def on_double(self, index): print "double", self.get(index)
+        def on_select(self, index): print("select", self.get(index))
+        def on_double(self, index): print("double", self.get(index))
     s = MyScrolledList(root)
     for i in range(30):
         s.append("item %02d" % i)
index 182a1170e83ea4861c3cd6678bfa1b7a191c95ad..0f95b3bddcc395fc0f1a73cf613a526e47303b67 100644 (file)
@@ -38,10 +38,10 @@ class UndoDelegator(Delegator):
     def dump_event(self, event):
         from pprint import pprint
         pprint(self.undolist[:self.pointer])
-        print "pointer:", self.pointer,
-        print "saved:", self.saved,
-        print "can_merge:", self.can_merge,
-        print "get_saved():", self.get_saved()
+        print("pointer:", self.pointer, end=' ')
+        print("saved:", self.saved, end=' ')
+        print("can_merge:", self.can_merge, end=' ')
+        print("get_saved():", self.get_saved())
         pprint(self.undolist[self.pointer:])
         return "break"
 
index 126a2cd67273be2160959ef2fb0a63bb824593e6..59005b8708c2009ebfaf97c465a668be4daab003 100644 (file)
@@ -83,7 +83,7 @@ def main():
     redir = WidgetRedirector(text)
     global orig_insert
     def my_insert(*args):
-        print "insert", args
+        print("insert", args)
         orig_insert(*args)
     orig_insert = redir.register("insert", my_insert)
     root.mainloop()
index 2fad998da1f1f5309674a6fdfe66ebd1592a2e44..fc463b804a08ea5b22731e0fe852a0ebf883434b 100644 (file)
@@ -46,7 +46,7 @@ class WindowList:
                 callback()
             except:
                 t, v, tb = sys.exc_info()
-                print "warning: callback failed in WindowList", t, ":", v
+                print("warning: callback failed in WindowList", t, ":", v)
 
 registry = WindowList()
 
index 826fb5dbb8141b6c952d259c6645d95c93bf29d8..469d0e4868c35c636d61995f4e93fd8b056f4c40 100644 (file)
@@ -679,18 +679,18 @@ idleConf=IdleConf()
 ### module test
 if __name__ == '__main__':
     def dumpCfg(cfg):
-        print '\n',cfg,'\n'
+        print('\n',cfg,'\n')
         for key in cfg.keys():
             sections=cfg[key].sections()
-            print key
-            print sections
+            print(key)
+            print(sections)
             for section in sections:
                 options=cfg[key].options(section)
-                print section
-                print options
+                print(section)
+                print(options)
                 for option in options:
-                    print option, '=', cfg[key].Get(section,option)
+                    print(option, '=', cfg[key].Get(section,option))
     dumpCfg(idleConf.defaultCfg)
     dumpCfg(idleConf.userCfg)
-    print idleConf.userCfg['main'].Get('Theme','name')
+    print(idleConf.userCfg['main'].Get('Theme','name'))
     #print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal')
index 661162196c7fa40bee4dc53edb9458e2fbb5a010..912a441698a3373c7641dfb56acaa277b4bb2045 100644 (file)
@@ -164,6 +164,6 @@ if __name__ == '__main__':
     def run():
         keySeq = ''
         dlg = GetHelpSourceDialog(root, 'Get Help Source')
-        print dlg.result
+        print(dlg.result)
     Button(root,text='Dialog', command=run).pack()
     root.mainloop()
index 4f1b002afcaa912797a9d80762378aa098094fb2..21dfab12ceba16efecc44adf4bdd252811e888f0 100644 (file)
@@ -92,6 +92,6 @@ if __name__ == '__main__':
         keySeq=''
         dlg=GetCfgSectionNameDialog(root,'Get Name',
                 'The information here should need to be word wrapped. Test.')
-        print dlg.result
+        print(dlg.result)
     Button(root,text='Dialog',command=run).pack()
     root.mainloop()
index aff9cac5879fa8dc69498d5568a548c59cc932a3..69900f9fbd842dc6d3ef2f65f6a40e311caef4b3 100644 (file)
@@ -263,6 +263,6 @@ if __name__ == '__main__':
     def run():
         keySeq=''
         dlg=GetKeysDialog(root,'Get Keys','find-again',[])
-        print dlg.result
+        print(dlg.result)
     Button(root,text='Dialog',command=run).pack()
     root.mainloop()
index e3a42d943a3ed0037cef73c01bf481bcebd77492..169bcebcc57a25409f6abb569dd61e6225391db5 100644 (file)
@@ -104,14 +104,14 @@ class RPCServer(SocketServer.TCPServer):
             raise
         except:
             erf = sys.__stderr__
-            print>>erf, '\n' + '-'*40
-            print>>erf, 'Unhandled server exception!'
-            print>>erf, 'Thread: %s' % threading.currentThread().getName()
-            print>>erf, 'Client Address: ', client_address
-            print>>erf, 'Request: ', repr(request)
+            print('\n' + '-'*40, file=erf)
+            print('Unhandled server exception!', file=erf)
+            print('Thread: %s' % threading.currentThread().getName(), file=erf)
+            print('Client Address: ', client_address, file=erf)
+            print('Request: ', repr(request), file=erf)
             traceback.print_exc(file=erf)
-            print>>erf, '\n*** Unrecoverable, server exiting!'
-            print>>erf, '-'*40
+            print('\n*** Unrecoverable, server exiting!', file=erf)
+            print('-'*40, file=erf)
             os._exit(0)
 
 #----------------- end class RPCServer --------------------
@@ -152,7 +152,7 @@ class SocketIO(object):
         s = self.location + " " + str(threading.currentThread().getName())
         for a in args:
             s = s + " " + str(a)
-        print>>sys.__stderr__, s
+        print(s, file=sys.__stderr__)
 
     def register(self, oid, object):
         self.objtable[oid] = object
@@ -201,7 +201,7 @@ class SocketIO(object):
         except:
             msg = "*** Internal Error: rpc.py:SocketIO.localcall()\n\n"\
                   " Object: %s \n Method: %s \n Args: %s\n"
-            print>>sys.__stderr__, msg % (oid, method, args)
+            print(msg % (oid, method, args), file=sys.__stderr__)
             traceback.print_exc(file=sys.__stderr__)
             return ("EXCEPTION", None)
 
@@ -323,7 +323,7 @@ class SocketIO(object):
         try:
             s = pickle.dumps(message)
         except pickle.PicklingError:
-            print >>sys.__stderr__, "Cannot pickle:", repr(message)
+            print("Cannot pickle:", repr(message), file=sys.__stderr__)
             raise
         s = struct.pack("<i", len(s)) + s
         while len(s) > 0:
@@ -379,10 +379,10 @@ class SocketIO(object):
         try:
             message = pickle.loads(packet)
         except pickle.UnpicklingError:
-            print >>sys.__stderr__, "-----------------------"
-            print >>sys.__stderr__, "cannot unpickle packet:", repr(packet)
+            print("-----------------------", file=sys.__stderr__)
+            print("cannot unpickle packet:", repr(packet), file=sys.__stderr__)
             traceback.print_stack(file=sys.__stderr__)
-            print >>sys.__stderr__, "-----------------------"
+            print("-----------------------", file=sys.__stderr__)
             raise
         return message
 
@@ -526,11 +526,11 @@ class RPCClient(SocketIO):
     def accept(self):
         working_sock, address = self.listening_sock.accept()
         if self.debugging:
-            print>>sys.__stderr__, "****** Connection request from ", address
+            print("****** Connection request from ", address, file=sys.__stderr__)
         if address[0] == LOCALHOST:
             SocketIO.__init__(self, working_sock)
         else:
-            print>>sys.__stderr__, "** Invalid host: ", address
+            print("** Invalid host: ", address, file=sys.__stderr__)
             raise socket.error
 
     def get_remote_proxy(self, oid):
index 6b29003f20498cb49b9b8234b34c46c68dece698..fa201a8d21c7c377f608056e91aa3b8cbac64ce1 100644 (file)
@@ -115,11 +115,11 @@ def manage_socket(address):
             server = MyRPCServer(address, MyHandler)
             break
         except socket.error as err:
-            print>>sys.__stderr__,"IDLE Subprocess: socket error: "\
-                                        + err[1] + ", retrying...."
+            print("IDLE Subprocess: socket error: "\
+                                        + err[1] + ", retrying....", file=sys.__stderr__)
     else:
-        print>>sys.__stderr__, "IDLE Subprocess: Connection to "\
-                               "IDLE GUI failed, exiting."
+        print("IDLE Subprocess: Connection to "\
+                               "IDLE GUI failed, exiting.", file=sys.__stderr__)
         show_socket_error(err, address)
         global exit_now
         exit_now = True
@@ -149,14 +149,14 @@ def print_exception():
     typ, val, tb = excinfo = sys.exc_info()
     sys.last_type, sys.last_value, sys.last_traceback = excinfo
     tbe = traceback.extract_tb(tb)
-    print>>efile, '\nTraceback (most recent call last):'
+    print('\nTraceback (most recent call last):', file=efile)
     exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
                "RemoteDebugger.py", "bdb.py")
     cleanup_traceback(tbe, exclude)
     traceback.print_list(tbe, file=efile)
     lines = traceback.format_exception_only(typ, val)
     for line in lines:
-        print>>efile, line,
+        print(line, end=' ', file=efile)
 
 def cleanup_traceback(tb, exclude):
     "Remove excluded traces from beginning/end of tb; get cached lines"
@@ -178,7 +178,7 @@ def cleanup_traceback(tb, exclude):
     if len(tb) == 0:
         # exception was in IDLE internals, don't prune!
         tb[:] = orig_tb[:]
-        print>>sys.stderr, "** IDLE Internal Exception: "
+        print("** IDLE Internal Exception: ", file=sys.stderr)
     rpchandler = rpc.objecttable['exec'].rpchandler
     for i in range(len(tb)):
         fn, ln, nm, line = tb[i]
@@ -227,14 +227,14 @@ class MyRPCServer(rpc.RPCServer):
             thread.interrupt_main()
         except:
             erf = sys.__stderr__
-            print>>erf, '\n' + '-'*40
-            print>>erf, 'Unhandled server exception!'
-            print>>erf, 'Thread: %s' % threading.currentThread().getName()
-            print>>erf, 'Client Address: ', client_address
-            print>>erf, 'Request: ', repr(request)
+            print('\n' + '-'*40, file=erf)
+            print('Unhandled server exception!', file=erf)
+            print('Thread: %s' % threading.currentThread().getName(), file=erf)
+            print('Client Address: ', client_address, file=erf)
+            print('Request: ', repr(request), file=erf)
             traceback.print_exc(file=erf)
-            print>>erf, '\n*** Unrecoverable, server exiting!'
-            print>>erf, '-'*40
+            print('\n*** Unrecoverable, server exiting!', file=erf)
+            print('-'*40, file=erf)
             quitting = True
             thread.interrupt_main()
 
index eef34742e0aa14403409e2d810f86bf7dd99e8ae..95691b6f2cacf80e8701847ba7251a31e09f387f 100644 (file)
@@ -87,9 +87,9 @@ class _Verbose:
 
     def message(self, format, *args):
         if args:
-            print format%args
+            print(format%args)
         else:
-            print format
+            print(format)
 
 
 class BasicModuleLoader(_Verbose):
index 11e262ed505b0a9c96a6172403219fefbc3b3191..fcf68ef938ee8858915888e6f47fa2cdc216de8b 100644 (file)
@@ -1485,15 +1485,15 @@ if __name__ == '__main__':
             run('uid', ('FETCH', '%s' % uid[-1],
                     '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
 
-        print '\nAll tests OK.'
+        print('\nAll tests OK.')
 
     except:
-        print '\nTests failed.'
+        print('\nTests failed.')
 
         if not Debug:
-            print '''
+            print('''
 If you would like to see debugging output,
 try: %s -d5
-''' % sys.argv[0]
+''' % sys.argv[0])
 
         raise
index 2fbc9661eb91aea93760826e325aeba2ee8e36e7..f34f234877e440276562f4acea38a554bea05d38 100644 (file)
@@ -144,18 +144,18 @@ def testall(list, recursive, toplevel):
     import os
     for filename in list:
         if os.path.isdir(filename):
-            print filename + '/:',
+            print(filename + '/:', end=' ')
             if recursive or toplevel:
-                print 'recursing down:'
+                print('recursing down:')
                 import glob
                 names = glob.glob(os.path.join(filename, '*'))
                 testall(names, recursive, 0)
             else:
-                print '*** directory (use -r) ***'
+                print('*** directory (use -r) ***')
         else:
-            print filename + ':',
+            print(filename + ':', end=' ')
             sys.stdout.flush()
             try:
-                print what(filename)
+                print(what(filename))
             except IOError:
-                print '*** not found ***'
+                print('*** not found ***')
index c3d1acd67aaebd8d7283f668613ba974ee94e445..1472d9c02be083e498e257d77e8495482172e8a3 100644 (file)
@@ -618,9 +618,9 @@ def _print_importers():
     items.sort()
     for name, module in items:
         if module:
-            print name, module.__dict__.get('__importer__', '-- no importer')
+            print(name, module.__dict__.get('__importer__', '-- no importer'))
         else:
-            print name, '-- non-existent module'
+            print(name, '-- non-existent module')
 
 def _test_revamp():
     ImportManager().install()
index b52e5b49d292c2f12f1bed3feedf52ee2df1b4a0..0ddfc735e79e10793500c6fbf4d68b83525b38c8 100644 (file)
@@ -36,7 +36,7 @@ def _test():
                       'strings': ('Save File',
                                   'Discard Changes',
                                   'Return to Editor')})
-    print d.num
+    print(d.num)
 
 
 if __name__ == '__main__':
index 06ce2b92298eacc9c6b0150f948905e4f7f0a39a..9ded88b553e0074b777c47ce4e53505fa8063e4a 100644 (file)
@@ -267,7 +267,7 @@ def test():
     loadfile = fd.go(key="test")
     fd = SaveFileDialog(root)
     savefile = fd.go(key="test")
-    print loadfile, savefile
+    print(loadfile, savefile)
 
 
 if __name__ == '__main__':
index cb08318dbdd727f79e6729295600befa99913f7b..fa2d1adc704d99486d386536cb2717e9d5fa6be0 100644 (file)
@@ -102,7 +102,7 @@ if __name__ == '__main__':
                          default=0,
                          cancel=2,
                          title="Test Dialog")
-            print d.go()
+            print(d.go())
         t = Button(root, text='Test', command=doit)
         t.pack()
         q = Button(root, text='Quit', command=t.quit)
index 157b066a0ddf9bb1bf50b482370b807fdf3fe1b3..7753f2d47350ed823a4f82756b74a28ee83bdf22 100644 (file)
@@ -86,7 +86,7 @@ def _cnfmerge(cnfs):
             try:
                 cnf.update(c)
             except (AttributeError, TypeError) as msg:
-                print "_cnfmerge: fallback due to:", msg
+                print("_cnfmerge: fallback due to:", msg)
                 for k, v in c.items():
                     cnf[k] = v
         return cnf
index a55a797dd498e9cd108470f41b22813e60c28c37..e3593ed24c835464fc467a47e1e37f8a15073da6 100644 (file)
@@ -67,4 +67,4 @@ def askcolor(color = None, **options):
 
 if __name__ == "__main__":
 
-    print "color", askcolor()
+    print("color", askcolor())
index a35feedc50e3c9151598667be60bc62dfb85cb61..0f2065d8fbfb04f1aa465a3869d925657c89c1cf 100644 (file)
@@ -204,12 +204,12 @@ if __name__ == "__main__":
         fp=open(openfilename,"r")
         fp.close()
     except:
-        print "Could not open File: "
-        print sys.exc_info()[1]
+        print("Could not open File: ")
+        print(sys.exc_info()[1])
 
-    print "open", openfilename.encode(enc)
+    print("open", openfilename.encode(enc))
 
     # dialog for saving files
 
     saveasfilename=asksaveasfilename()
-    print "saveas", saveasfilename.encode(enc)
+    print("saveas", saveasfilename.encode(enc))
index 15dea2eba3a561e7e3c4bdbc93995f4d28dfe233..ce50397bffce516e6e078ef90d73b1a7d0d9d8b4 100644 (file)
@@ -185,22 +185,22 @@ if __name__ == "__main__":
     # create a font
     f = Font(family="times", size=30, weight=NORMAL)
 
-    print f.actual()
-    print f.actual("family")
-    print f.actual("weight")
+    print(f.actual())
+    print(f.actual("family"))
+    print(f.actual("weight"))
 
-    print f.config()
-    print f.cget("family")
-    print f.cget("weight")
+    print(f.config())
+    print(f.cget("family"))
+    print(f.cget("weight"))
 
-    print names()
+    print(names())
 
-    print f.measure("hello"), f.metrics("linespace")
+    print(f.measure("hello"), f.metrics("linespace"))
 
-    print f.metrics()
+    print(f.metrics())
 
     f = Font(font=("Courier", 20, "bold"))
-    print f.measure("hello"), f.metrics("linespace")
+    print(f.measure("hello"), f.metrics("linespace"))
 
     w = Tkinter.Label(root, text="Hello, world", font=f)
     w.pack()
index d14ca86febc0bf592d5d3a9a18fc96b7efa50a5a..94ba788b15195b1c7c3c4bb69ac527fcb32fc6cb 100644 (file)
@@ -122,11 +122,11 @@ def askretrycancel(title=None, message=None, **options):
 
 if __name__ == "__main__":
 
-    print "info", showinfo("Spam", "Egg Information")
-    print "warning", showwarning("Spam", "Egg Warning")
-    print "error", showerror("Spam", "Egg Alert")
-    print "question", askquestion("Spam", "Question?")
-    print "proceed", askokcancel("Spam", "Proceed?")
-    print "yes/no", askyesno("Spam", "Got it?")
-    print "yes/no/cancel", askyesnocancel("Spam", "Want it?")
-    print "try again", askretrycancel("Spam", "Try again?")
+    print("info", showinfo("Spam", "Egg Information"))
+    print("warning", showwarning("Spam", "Egg Warning"))
+    print("error", showerror("Spam", "Egg Alert"))
+    print("question", askquestion("Spam", "Question?"))
+    print("proceed", askokcancel("Spam", "Proceed?"))
+    print("yes/no", askyesno("Spam", "Got it?"))
+    print("yes/no/cancel", askyesnocancel("Spam", "Want it?"))
+    print("try again", askretrycancel("Spam", "Try again?"))
index 8d35db277096e3e0ff38392653d78f54db186bc3..f4ed77a044a2c2c8c6d4b0e52117d42d6fdb3756 100644 (file)
@@ -315,6 +315,6 @@ if __name__ == "__main__":
     root = Tk()
     root.update()
 
-    print askinteger("Spam", "Egg count", initialvalue=12*12)
-    print askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100)
-    print askstring("Spam", "Egg label")
+    print(askinteger("Spam", "Egg count", initialvalue=12*12))
+    print(askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100))
+    print(askstring("Spam", "Egg label"))
index fd549bbde12b62e4e834ab171e8f74faddb99c70..d3294ce663681dbf21b1fc97c3a52d0e4a3b4995 100644 (file)
@@ -262,10 +262,10 @@ def _test():
     setlocale(LC_ALL, "")
     #do grouping
     s1 = format("%d", 123456789,1)
-    print s1, "is", atoi(s1)
+    print(s1, "is", atoi(s1))
     #standard formatting
     s1 = str(3.14)
-    print s1, "is", atof(s1)
+    print(s1, "is", atof(s1))
 
 ### Locale name aliasing engine
 
@@ -1499,49 +1499,49 @@ def _print_locale():
     _init_categories()
     del categories['LC_ALL']
 
-    print 'Locale defaults as determined by getdefaultlocale():'
-    print '-'*72
+    print('Locale defaults as determined by getdefaultlocale():')
+    print('-'*72)
     lang, enc = getdefaultlocale()
-    print 'Language: ', lang or '(undefined)'
-    print 'Encoding: ', enc or '(undefined)'
-    print
+    print('Language: ', lang or '(undefined)')
+    print('Encoding: ', enc or '(undefined)')
+    print()
 
-    print 'Locale settings on startup:'
-    print '-'*72
+    print('Locale settings on startup:')
+    print('-'*72)
     for name,category in categories.items():
-        print name, '...'
+        print(name, '...')
         lang, enc = getlocale(category)
-        print '   Language: ', lang or '(undefined)'
-        print '   Encoding: ', enc or '(undefined)'
-        print
+        print('   Language: ', lang or '(undefined)')
+        print('   Encoding: ', enc or '(undefined)')
+        print()
 
-    print
-    print 'Locale settings after calling resetlocale():'
-    print '-'*72
+    print()
+    print('Locale settings after calling resetlocale():')
+    print('-'*72)
     resetlocale()
     for name,category in categories.items():
-        print name, '...'
+        print(name, '...')
         lang, enc = getlocale(category)
-        print '   Language: ', lang or '(undefined)'
-        print '   Encoding: ', enc or '(undefined)'
-        print
+        print('   Language: ', lang or '(undefined)')
+        print('   Encoding: ', enc or '(undefined)')
+        print()
 
     try:
         setlocale(LC_ALL, "")
     except:
-        print 'NOTE:'
-        print 'setlocale(LC_ALL, "") does not support the default locale'
-        print 'given in the OS environment variables.'
+        print('NOTE:')
+        print('setlocale(LC_ALL, "") does not support the default locale')
+        print('given in the OS environment variables.')
     else:
-        print
-        print 'Locale settings after calling setlocale(LC_ALL, ""):'
-        print '-'*72
+        print()
+        print('Locale settings after calling setlocale(LC_ALL, ""):')
+        print('-'*72)
         for name,category in categories.items():
-            print name, '...'
+            print(name, '...')
             lang, enc = getlocale(category)
-            print '   Language: ', lang or '(undefined)'
-            print '   Encoding: ', enc or '(undefined)'
-            print
+            print('   Language: ', lang or '(undefined)')
+            print('   Encoding: ', enc or '(undefined)')
+            print()
 
 ###
 
@@ -1553,10 +1553,10 @@ else:
     __all__.append("LC_MESSAGES")
 
 if __name__=='__main__':
-    print 'Locale aliasing:'
-    print
+    print('Locale aliasing:')
+    print()
     _print_locale()
-    print
-    print 'Number formatting:'
-    print
+    print()
+    print('Number formatting:')
+    print()
     _test()
index e8c3591b07facf0f85781c984e7a06917a805cc7..687ecfe05c6a575acdd76275d6ddb672858cc0df 100644 (file)
@@ -834,8 +834,8 @@ class NTEventLogHandler(logging.Handler):
                 logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
          }
         except ImportError:
-            print "The Python Win32 extensions for NT (service, event "\
-                        "logging) appear not to be available."
+            print("The Python Win32 extensions for NT (service, event "\
+                        "logging) appear not to be available.")
             self._welu = None
 
     def getMessageID(self, record):
index 4c5ae64572e26ab59f299ce83b16ca42827b44a2..b18f2b2713b94b4d1bf9616a5d1eb3e9a10054a8 100644 (file)
@@ -82,7 +82,7 @@ def test():
                 "/foo/bar/index.html",
                 "/foo/bar/",
                 "/"]:
-        print '%r -> %r' % (url, url2pathname(url))
+        print('%r -> %r' % (url, url2pathname(url)))
     for path in ["drive:",
                  "drive:dir:",
                  "drive:dir:file",
@@ -91,7 +91,7 @@ def test():
                  ":file",
                  ":dir:",
                  ":dir:file"]:
-        print '%r -> %r' % (path, pathname2url(path))
+        print('%r -> %r' % (path, pathname2url(path)))
 
 if __name__ == '__main__':
     test()
index b2ddacd046db4555b65ebd84455dc38a70e9b486..fd17f5b2651690b353a173d41acc4614c1697996 100644 (file)
@@ -219,37 +219,37 @@ def test():
     for i in range(1, len(sys.argv), 2):
         args = sys.argv[i:i+2]
         if len(args) < 2:
-            print "usage: mailcap [MIMEtype file] ..."
+            print("usage: mailcap [MIMEtype file] ...")
             return
         MIMEtype = args[0]
         file = args[1]
         command, e = findmatch(caps, MIMEtype, 'view', file)
         if not command:
-            print "No viewer found for", type
+            print("No viewer found for", type)
         else:
-            print "Executing:", command
+            print("Executing:", command)
             sts = os.system(command)
             if sts:
-                print "Exit status:", sts
+                print("Exit status:", sts)
 
 def show(caps):
-    print "Mailcap files:"
-    for fn in listmailcapfiles(): print "\t" + fn
-    print
+    print("Mailcap files:")
+    for fn in listmailcapfiles(): print("\t" + fn)
+    print()
     if not caps: caps = getcaps()
-    print "Mailcap entries:"
-    print
+    print("Mailcap entries:")
+    print()
     ckeys = caps.keys()
     ckeys.sort()
     for type in ckeys:
-        print type
+        print(type)
         entries = caps[type]
         for e in entries:
             keys = e.keys()
             keys.sort()
             for k in keys:
-                print "  %-15s" % k, e[k]
-            print
+                print("  %-15s" % k, e[k])
+            print()
 
 if __name__ == '__main__':
     test()
index 8ae6bad1eee980bcd048313b8f30a19c1477eaba..bf9556c349613e680a4f40ed979c82f932f3b585 100644 (file)
@@ -959,7 +959,7 @@ def test():
     global mh, f
     os.system('rm -rf $HOME/Mail/@test')
     mh = MH()
-    def do(s): print s; print eval(s)
+    def do(s): print(s); print(eval(s))
     do('mh.listfolders()')
     do('mh.listallfolders()')
     testfolders = ['@test', '@test/test1', '@test/test2',
@@ -974,7 +974,7 @@ def test():
     do('f.getsequences()')
     seqs = f.getsequences()
     seqs['foo'] = IntSet('1-10 12-20', ' ').tolist()
-    print seqs
+    print(seqs)
     f.putsequences(seqs)
     do('f.getsequences()')
     for t in reversed(testfolders): do('mh.deletefolder(%r)' % (t,))
@@ -990,10 +990,10 @@ def test():
         try:
             do('f.parsesequence(%r)' % (seq,))
         except Error as msg:
-            print "Error:", msg
+            print("Error:", msg)
         stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read()
         list = map(int, stuff.split())
-        print list, "<-- pick"
+        print(list, "<-- pick")
     do('f.listmessages()')
 
 
index 83071d4b8e60ceae40ca349bedbd05c359ffc62c..8774170fe20aa23f5ae54b85d78939f76912cbf8 100644 (file)
@@ -503,8 +503,8 @@ More than one type argument may be given.
 """
 
     def usage(code, msg=''):
-        print USAGE
-        if msg: print msg
+        print(USAGE)
+        if msg: print(msg)
         sys.exit(code)
 
     try:
@@ -525,9 +525,9 @@ More than one type argument may be given.
     for gtype in args:
         if extension:
             guess = guess_extension(gtype, strict)
-            if not guess: print "I don't know anything about type", gtype
-            else: print guess
+            if not guess: print("I don't know anything about type", gtype)
+            else: print(guess)
         else:
             guess, encoding = guess_type(gtype, strict)
-            if not guess: print "I don't know anything about type", gtype
-            else: print 'type:', guess, 'encoding:', encoding
+            if not guess: print("I don't know anything about type", gtype)
+            else: print('type:', guess, 'encoding:', encoding)
index b6f61439d758d4f7d375a9649f6bf3624b886a7a..6609e80b98a428f5545c3e495c7d3659501a87cd 100755 (executable)
@@ -434,11 +434,11 @@ if __name__ == '__main__' or (len(sys.argv) > 0 and sys.argv[0] == 'mimify'):
     decode_base64 = 0
     opts, args = getopt.getopt(sys.argv[1:], 'l:edb')
     if len(args) not in (0, 1, 2):
-        print usage
+        print(usage)
         sys.exit(1)
     if (('-e', '') in opts) == (('-d', '') in opts) or \
        ((('-b', '') in opts) and (('-d', '') not in opts)):
-        print usage
+        print(usage)
         sys.exit(1)
     for o, a in opts:
         if o == '-e':
@@ -449,7 +449,7 @@ if __name__ == '__main__' or (len(sys.argv) > 0 and sys.argv[0] == 'mimify'):
             try:
                 MAXLEN = int(a)
             except (ValueError, OverflowError):
-                print usage
+                print(usage)
                 sys.exit(1)
         elif o == '-b':
             decode_base64 = 1
index 04c9abff8c312366ba09ceeac15e1b7e00888130..5145f7297f778ac5cbfc279f1caea22b75eb530c 100644 (file)
@@ -89,11 +89,11 @@ class ModuleFinder:
     def msg(self, level, str, *args):
         if level <= self.debug:
             for i in range(self.indent):
-                print "   ",
-            print str,
+                print("   ", end=' ')
+            print(str, end=' ')
             for arg in args:
-                print repr(arg),
-            print
+                print(repr(arg), end=' ')
+            print()
 
     def msgin(self, *args):
         level = args[0]
@@ -482,38 +482,38 @@ class ModuleFinder:
         """Print a report to stdout, listing the found modules with their
         paths, as well as modules that are missing, or seem to be missing.
         """
-        print
-        print "  %-25s %s" % ("Name", "File")
-        print "  %-25s %s" % ("----", "----")
+        print()
+        print("  %-25s %s" % ("Name", "File"))
+        print("  %-25s %s" % ("----", "----"))
         # Print modules found
         keys = self.modules.keys()
         keys.sort()
         for key in keys:
             m = self.modules[key]
             if m.__path__:
-                print "P",
+                print("P", end=' ')
             else:
-                print "m",
-            print "%-25s" % key, m.__file__ or ""
+                print("m", end=' ')
+            print("%-25s" % key, m.__file__ or "")
 
         # Print missing modules
         missing, maybe = self.any_missing_maybe()
         if missing:
-            print
-            print "Missing modules:"
+            print()
+            print("Missing modules:")
             for name in missing:
                 mods = self.badmodules[name].keys()
                 mods.sort()
-                print "?", name, "imported from", ', '.join(mods)
+                print("?", name, "imported from", ', '.join(mods))
         # Print modules that may be missing, but then again, maybe not...
         if maybe:
-            print
-            print "Submodules thay appear to be missing, but could also be",
-            print "global names in the parent package:"
+            print()
+            print("Submodules thay appear to be missing, but could also be", end=' ')
+            print("global names in the parent package:")
             for name in maybe:
                 mods = self.badmodules[name].keys()
                 mods.sort()
-                print "?", name, "imported from", ', '.join(mods)
+                print("?", name, "imported from", ', '.join(mods))
 
     def any_missing(self):
         """Return a list of modules that appear to be missing. Use
@@ -603,7 +603,7 @@ def test():
     try:
         opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:")
     except getopt.error as msg:
-        print msg
+        print(msg)
         return
 
     # Process options
@@ -634,9 +634,9 @@ def test():
     path[0] = os.path.dirname(script)
     path = addpath + path
     if debug > 1:
-        print "path:"
+        print("path:")
         for item in path:
-            print "   ", repr(item)
+            print("   ", repr(item))
 
     # Create the module finder and turn its crank
     mf = ModuleFinder(path, debug, exclude)
@@ -660,4 +660,4 @@ if __name__ == '__main__':
     try:
         mf = test()
     except KeyboardInterrupt:
-        print "\n[interrupt]"
+        print("\n[interrupt]")
index 269a2fa2109483b1f4eb99d9ece84834f949111f..27b03ea24abbcf27193891a7d6c04a30a82f6140 100644 (file)
@@ -40,7 +40,7 @@ class Table:
             index -= 1
             unk = type & ~knownbits
             if unk:
-                print "%s.%s unknown bits %x" % (self.name, name, unk)
+                print("%s.%s unknown bits %x" % (self.name, name, unk))
             size = type & datasizemask
             dtype = type & typemask
             if dtype == type_string:
@@ -59,7 +59,7 @@ class Table:
                 tname="OBJECT"
             else:
                 tname="unknown"
-                print "%s.%sunknown integer type %d" % (self.name, name, size)
+                print("%s.%sunknown integer type %d" % (self.name, name, size))
             if type & type_nullable:
                 flags = ""
             else:
index 5493d77d3e805da491b365dc8f1b246fe8d3eefe..754828c8aac18892bd8e5006081428aada0b200a 100644 (file)
@@ -108,4 +108,4 @@ class netrc:
         return rep
 
 if __name__ == '__main__':
-    print netrc()
+    print(netrc())
index 6e6a2b6d0d9fa8c5e021bf68c00296500cba630c..3f933f9d22663ea88e46fec5634f49389ddacaff 100644 (file)
@@ -175,7 +175,7 @@ class NNTP:
         If the response code is 200, posting is allowed;
         if it 201, posting is not allowed."""
 
-        if self.debugging: print '*welcome*', repr(self.welcome)
+        if self.debugging: print('*welcome*', repr(self.welcome))
         return self.welcome
 
     def set_debuglevel(self, level):
@@ -190,12 +190,12 @@ class NNTP:
     def putline(self, line):
         """Internal: send one line to the server, appending CRLF."""
         line = line + CRLF
-        if self.debugging > 1: print '*put*', repr(line)
+        if self.debugging > 1: print('*put*', repr(line))
         self.sock.sendall(line)
 
     def putcmd(self, line):
         """Internal: send one command to the server (through putline())."""
-        if self.debugging: print '*cmd*', repr(line)
+        if self.debugging: print('*cmd*', repr(line))
         self.putline(line)
 
     def getline(self):
@@ -203,7 +203,7 @@ class NNTP:
         Raise EOFError if the connection is closed."""
         line = self.file.readline()
         if self.debugging > 1:
-            print '*get*', repr(line)
+            print('*get*', repr(line))
         if not line: raise EOFError
         if line[-2:] == CRLF: line = line[:-2]
         elif line[-1:] in CRLF: line = line[:-1]
@@ -213,7 +213,7 @@ class NNTP:
         """Internal: get a response from the server.
         Raise various errors if the response indicates an error."""
         resp = self.getline()
-        if self.debugging: print '*resp*', repr(resp)
+        if self.debugging: print('*resp*', repr(resp))
         c = resp[:1]
         if c == '4':
             raise NNTPTemporaryError(resp)
@@ -618,11 +618,11 @@ if __name__ == '__main__':
         mode = None
     s = NNTP(newshost, readermode=mode)
     resp, count, first, last, name = s.group('comp.lang.python')
-    print resp
-    print 'Group', name, 'has', count, 'articles, range', first, 'to', last
+    print(resp)
+    print('Group', name, 'has', count, 'articles, range', first, 'to', last)
     resp, subs = s.xhdr('subject', first + '-' + last)
-    print resp
+    print(resp)
     for item in subs:
-        print "%7s %s" % item
+        print("%7s %s" % item)
     resp = s.quit()
-    print resp
+    print(resp)
index eca2818f0a79d9a1e37ade93f833de9999797b5f..5122e4974b117a012d04e9022640d1eafeb40416 100644 (file)
@@ -1578,7 +1578,7 @@ class OptionParser (OptionContainer):
         or not defined.
         """
         if self.usage:
-            print >>file, self.get_usage()
+            print(self.get_usage(), file=file)
 
     def get_version(self):
         if self.version:
@@ -1595,7 +1595,7 @@ class OptionParser (OptionContainer):
         name.  Does nothing if self.version is empty or undefined.
         """
         if self.version:
-            print >>file, self.get_version()
+            print(self.get_version(), file=file)
 
     def format_option_help(self, formatter=None):
         if formatter is None:
index 3ef03a0df2fe63d87495ecfc49485dabd059e8e1..634991383c97b613185a48e4f95638421451a4c3 100755 (executable)
@@ -135,7 +135,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         if self._wait_for_mainpyfile:
             return
         if self.stop_here(frame):
-            print >>self.stdout, '--Call--'
+            print('--Call--', file=self.stdout)
             self.interaction(frame, None)
 
     def user_line(self, frame):
@@ -171,7 +171,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
     def user_return(self, frame, return_value):
         """This function is called when a return trap is set here."""
         frame.f_locals['__return__'] = return_value
-        print >>self.stdout, '--Return--'
+        print('--Return--', file=self.stdout)
         self.interaction(frame, None)
 
     def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
@@ -181,7 +181,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         if type(exc_type) == type(''):
             exc_type_name = exc_type
         else: exc_type_name = exc_type.__name__
-        print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
+        print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
         self.interaction(frame, exc_traceback)
 
     # General interaction function
@@ -204,7 +204,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             if type(t) == type(''):
                 exc_type_name = t
             else: exc_type_name = t.__name__
-            print >>self.stdout, '***', exc_type_name + ':', v
+            print('***', exc_type_name + ':', v, file=self.stdout)
 
     def precmd(self, line):
         """Handle alias expansion and ';;' separator."""
@@ -283,7 +283,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             try:
                 bnum = int(arg)
             except:
-                print >>self.stdout, "Usage : commands [bnum]\n        ...\n        end"
+                print("Usage : commands [bnum]\n        ...\n        end", file=self.stdout)
                 return
         self.commands_bnum = bnum
         self.commands[bnum] = []
@@ -300,7 +300,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         # break [ ([filename:]lineno | function) [, "condition"] ]
         if not arg:
             if self.breaks:  # There's at least one
-                print >>self.stdout, "Num Type         Disp Enb   Where"
+                print("Num Type         Disp Enb   Where", file=self.stdout)
                 for bp in bdb.Breakpoint.bpbynumber:
                     if bp:
                         bp.bpprint(self.stdout)
@@ -322,8 +322,8 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             filename = arg[:colon].rstrip()
             f = self.lookupmodule(filename)
             if not f:
-                print >>self.stdout, '*** ', repr(filename),
-                print >>self.stdout, 'not found from sys.path'
+                print('*** ', repr(filename), end=' ', file=self.stdout)
+                print('not found from sys.path', file=self.stdout)
                 return
             else:
                 filename = f
@@ -331,7 +331,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             try:
                 lineno = int(arg)
             except ValueError as msg:
-                print >>self.stdout, '*** Bad lineno:', arg
+                print('*** Bad lineno:', arg, file=self.stdout)
                 return
         else:
             # no colon; can be lineno or function
@@ -357,10 +357,10 @@ class Pdb(bdb.Bdb, cmd.Cmd):
                     # last thing to try
                     (ok, filename, ln) = self.lineinfo(arg)
                     if not ok:
-                        print >>self.stdout, '*** The specified object',
-                        print >>self.stdout, repr(arg),
-                        print >>self.stdout, 'is not a function'
-                        print >>self.stdout, 'or was not found along sys.path.'
+                        print('*** The specified object', end=' ', file=self.stdout)
+                        print(repr(arg), end=' ', file=self.stdout)
+                        print('is not a function', file=self.stdout)
+                        print('or was not found along sys.path.', file=self.stdout)
                         return
                     funcname = ok # ok contains a function name
                     lineno = int(ln)
@@ -371,12 +371,12 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         if line:
             # now set the break point
             err = self.set_break(filename, line, temporary, cond, funcname)
-            if err: print >>self.stdout, '***', err
+            if err: print('***', err, file=self.stdout)
             else:
                 bp = self.get_breaks(filename, line)[-1]
-                print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
+                print("Breakpoint %d at %s:%d" % (bp.number,
                                                                  bp.file,
-                                                                 bp.line)
+                                                                 bp.line), file=self.stdout)
 
     # To be overridden in derived debuggers
     def defaultFile(self):
@@ -432,13 +432,13 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         """
         line = linecache.getline(filename, lineno)
         if not line:
-            print >>self.stdout, 'End of file'
+            print('End of file', file=self.stdout)
             return 0
         line = line.strip()
         # Don't allow setting breakpoint at a blank line
         if (not line or (line[0] == '#') or
              (line[:3] == '"""') or line[:3] == "'''"):
-            print >>self.stdout, '*** Blank or comment'
+            print('*** Blank or comment', file=self.stdout)
             return 0
         return lineno
 
@@ -448,11 +448,11 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             try:
                 i = int(i)
             except ValueError:
-                print >>self.stdout, 'Breakpoint index %r is not a number' % i
+                print('Breakpoint index %r is not a number' % i, file=self.stdout)
                 continue
 
             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
-                print >>self.stdout, 'No breakpoint numbered', i
+                print('No breakpoint numbered', i, file=self.stdout)
                 continue
 
             bp = bdb.Breakpoint.bpbynumber[i]
@@ -465,11 +465,11 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             try:
                 i = int(i)
             except ValueError:
-                print >>self.stdout, 'Breakpoint index %r is not a number' % i
+                print('Breakpoint index %r is not a number' % i, file=self.stdout)
                 continue
 
             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
-                print >>self.stdout, 'No breakpoint numbered', i
+                print('No breakpoint numbered', i, file=self.stdout)
                 continue
 
             bp = bdb.Breakpoint.bpbynumber[i]
@@ -483,8 +483,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             bpnum = int(args[0].strip())
         except ValueError:
             # something went wrong
-            print >>self.stdout, \
-                'Breakpoint index %r is not a number' % args[0]
+            print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
         try:
             cond = args[1]
         except:
@@ -493,8 +492,8 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         if bp:
             bp.cond = cond
             if not cond:
-                print >>self.stdout, 'Breakpoint', bpnum,
-                print >>self.stdout, 'is now unconditional.'
+                print('Breakpoint', bpnum, end=' ', file=self.stdout)
+                print('is now unconditional.', file=self.stdout)
 
     def do_ignore(self,arg):
         """arg is bp number followed by ignore count."""
@@ -503,8 +502,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             bpnum = int(args[0].strip())
         except ValueError:
             # something went wrong
-            print >>self.stdout, \
-                'Breakpoint index %r is not a number' % args[0]
+            print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
         try:
             count = int(args[1].strip())
         except:
@@ -518,10 +516,10 @@ class Pdb(bdb.Bdb, cmd.Cmd):
                     reply = reply + '%d crossings' % count
                 else:
                     reply = reply + '1 crossing'
-                print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
+                print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout)
             else:
-                print >>self.stdout, 'Will stop next time breakpoint',
-                print >>self.stdout, bpnum, 'is reached.'
+                print('Will stop next time breakpoint', end=' ', file=self.stdout)
+                print(bpnum, 'is reached.', file=self.stdout)
 
     def do_clear(self, arg):
         """Three possibilities, tried in this order:
@@ -548,24 +546,24 @@ class Pdb(bdb.Bdb, cmd.Cmd):
                 err = "Invalid line number (%s)" % arg
             else:
                 err = self.clear_break(filename, lineno)
-            if err: print >>self.stdout, '***', err
+            if err: print('***', err, file=self.stdout)
             return
         numberlist = arg.split()
         for i in numberlist:
             try:
                 i = int(i)
             except ValueError:
-                print >>self.stdout, 'Breakpoint index %r is not a number' % i
+                print('Breakpoint index %r is not a number' % i, file=self.stdout)
                 continue
 
             if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
-                print >>self.stdout, 'No breakpoint numbered', i
+                print('No breakpoint numbered', i, file=self.stdout)
                 continue
             err = self.clear_bpbynumber(i)
             if err:
-                print >>self.stdout, '***', err
+                print('***', err, file=self.stdout)
             else:
-                print >>self.stdout, 'Deleted breakpoint', i
+                print('Deleted breakpoint', i, file=self.stdout)
     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
 
     def do_where(self, arg):
@@ -575,7 +573,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
 
     def do_up(self, arg):
         if self.curindex == 0:
-            print >>self.stdout, '*** Oldest frame'
+            print('*** Oldest frame', file=self.stdout)
         else:
             self.curindex = self.curindex - 1
             self.curframe = self.stack[self.curindex][0]
@@ -585,7 +583,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
 
     def do_down(self, arg):
         if self.curindex + 1 == len(self.stack):
-            print >>self.stdout, '*** Newest frame'
+            print('*** Newest frame', file=self.stdout)
         else:
             self.curindex = self.curindex + 1
             self.curframe = self.stack[self.curindex][0]
@@ -615,12 +613,12 @@ class Pdb(bdb.Bdb, cmd.Cmd):
 
     def do_jump(self, arg):
         if self.curindex + 1 != len(self.stack):
-            print >>self.stdout, "*** You can only jump within the bottom frame"
+            print("*** You can only jump within the bottom frame", file=self.stdout)
             return
         try:
             arg = int(arg)
         except ValueError:
-            print >>self.stdout, "*** The 'jump' command requires a line number."
+            print("*** The 'jump' command requires a line number.", file=self.stdout)
         else:
             try:
                 # Do the jump, fix up our copy of the stack, and display the
@@ -629,7 +627,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
                 self.stack[self.curindex] = self.stack[self.curindex][0], arg
                 self.print_stack_entry(self.stack[self.curindex])
             except ValueError as e:
-                print >>self.stdout, '*** Jump failed:', e
+                print('*** Jump failed:', e, file=self.stdout)
     do_j = do_jump
 
     def do_debug(self, arg):
@@ -638,9 +636,9 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         locals = self.curframe.f_locals
         p = Pdb()
         p.prompt = "(%s) " % self.prompt.strip()
-        print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
+        print("ENTERING RECURSIVE DEBUGGER", file=self.stdout)
         sys.call_tracing(p.run, (arg, globals, locals))
-        print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
+        print("LEAVING RECURSIVE DEBUGGER", file=self.stdout)
         sys.settrace(self.trace_dispatch)
         self.lastcmd = p.lastcmd
 
@@ -653,7 +651,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
     do_exit = do_quit
 
     def do_EOF(self, arg):
-        print >>self.stdout
+        print(file=self.stdout)
         self._user_requested_quit = 1
         self.set_quit()
         return 1
@@ -667,16 +665,16 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         if co.co_flags & 8: n = n+1
         for i in range(n):
             name = co.co_varnames[i]
-            print >>self.stdout, name, '=',
-            if name in dict: print >>self.stdout, dict[name]
-            else: print >>self.stdout, "*** undefined ***"
+            print(name, '=', end=' ', file=self.stdout)
+            if name in dict: print(dict[name], file=self.stdout)
+            else: print("*** undefined ***", file=self.stdout)
     do_a = do_args
 
     def do_retval(self, arg):
         if '__return__' in self.curframe.f_locals:
-            print >>self.stdout, self.curframe.f_locals['__return__']
+            print(self.curframe.f_locals['__return__'], file=self.stdout)
         else:
-            print >>self.stdout, '*** Not yet returned!'
+            print('*** Not yet returned!', file=self.stdout)
     do_rv = do_retval
 
     def _getval(self, arg):
@@ -688,12 +686,12 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             if isinstance(t, str):
                 exc_type_name = t
             else: exc_type_name = t.__name__
-            print >>self.stdout, '***', exc_type_name + ':', repr(v)
+            print('***', exc_type_name + ':', repr(v), file=self.stdout)
             raise
 
     def do_p(self, arg):
         try:
-            print >>self.stdout, repr(self._getval(arg))
+            print(repr(self._getval(arg)), file=self.stdout)
         except:
             pass
 
@@ -719,7 +717,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
                 else:
                     first = max(1, int(x) - 5)
             except:
-                print >>self.stdout, '*** Error in argument:', repr(arg)
+                print('*** Error in argument:', repr(arg), file=self.stdout)
                 return
         elif self.lineno is None:
             first = max(1, self.curframe.f_lineno - 5)
@@ -733,7 +731,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             for lineno in range(first, last+1):
                 line = linecache.getline(filename, lineno)
                 if not line:
-                    print >>self.stdout, '[EOF]'
+                    print('[EOF]', file=self.stdout)
                     break
                 else:
                     s = repr(lineno).rjust(3)
@@ -742,7 +740,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
                     else: s = s + ' '
                     if lineno == self.curframe.f_lineno:
                         s = s + '->'
-                    print >>self.stdout, s + '\t' + line,
+                    print(s + '\t' + line, end=' ', file=self.stdout)
                     self.lineno = lineno
         except KeyboardInterrupt:
             pass
@@ -757,23 +755,23 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             if type(t) == type(''):
                 exc_type_name = t
             else: exc_type_name = t.__name__
-            print >>self.stdout, '***', exc_type_name + ':', repr(v)
+            print('***', exc_type_name + ':', repr(v), file=self.stdout)
             return
         code = None
         # Is it a function?
         try: code = value.func_code
         except: pass
         if code:
-            print >>self.stdout, 'Function', code.co_name
+            print('Function', code.co_name, file=self.stdout)
             return
         # Is it an instance method?
         try: code = value.im_func.func_code
         except: pass
         if code:
-            print >>self.stdout, 'Method', code.co_name
+            print('Method', code.co_name, file=self.stdout)
             return
         # None of the above...
-        print >>self.stdout, type(value)
+        print(type(value), file=self.stdout)
 
     def do_alias(self, arg):
         args = arg.split()
@@ -781,10 +779,10 @@ class Pdb(bdb.Bdb, cmd.Cmd):
             keys = self.aliases.keys()
             keys.sort()
             for alias in keys:
-                print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
+                print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout)
             return
         if args[0] in self.aliases and len(args) == 1:
-            print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
+            print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout)
         else:
             self.aliases[args[0]] = ' '.join(args[1:])
 
@@ -816,11 +814,11 @@ class Pdb(bdb.Bdb, cmd.Cmd):
     def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
         frame, lineno = frame_lineno
         if frame is self.curframe:
-            print >>self.stdout, '>',
+            print('>', end=' ', file=self.stdout)
         else:
-            print >>self.stdout, ' ',
-        print >>self.stdout, self.format_stack_entry(frame_lineno,
-                                                     prompt_prefix)
+            print(' ', end=' ', file=self.stdout)
+        print(self.format_stack_entry(frame_lineno,
+                                                     prompt_prefix), file=self.stdout)
 
 
     # Help methods (derived from pdb.doc)
@@ -829,20 +827,20 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         self.help_h()
 
     def help_h(self):
-        print >>self.stdout, """h(elp)
+        print("""h(elp)
 Without argument, print the list of available commands.
 With a command name as argument, print help about that command
 "help pdb" pipes the full documentation file to the $PAGER
-"help exec" gives help on the ! command"""
+"help exec" gives help on the ! command""", file=self.stdout)
 
     def help_where(self):
         self.help_w()
 
     def help_w(self):
-        print >>self.stdout, """w(here)
+        print("""w(here)
 Print a stack trace, with the most recent frame at the bottom.
 An arrow indicates the "current frame", which determines the
-context of most commands.  'bt' is an alias for this command."""
+context of most commands.  'bt' is an alias for this command.""", file=self.stdout)
 
     help_bt = help_w
 
@@ -850,23 +848,23 @@ context of most commands.  'bt' is an alias for this command."""
         self.help_d()
 
     def help_d(self):
-        print >>self.stdout, """d(own)
+        print("""d(own)
 Move the current frame one level down in the stack trace
-(to a newer frame)."""
+(to a newer frame).""", file=self.stdout)
 
     def help_up(self):
         self.help_u()
 
     def help_u(self):
-        print >>self.stdout, """u(p)
+        print("""u(p)
 Move the current frame one level up in the stack trace
-(to an older frame)."""
+(to an older frame).""", file=self.stdout)
 
     def help_break(self):
         self.help_b()
 
     def help_b(self):
-        print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
+        print("""b(reak) ([file:]lineno | function) [, condition]
 With a line number argument, set a break there in the current
 file.  With a function name, set a break at first executable line
 of that function.  Without argument, list all breaks.  If a second
@@ -876,14 +874,14 @@ which must evaluate to true before the breakpoint is honored.
 The line number may be prefixed with a filename and a colon,
 to specify a breakpoint in another file (probably one that
 hasn't been loaded yet).  The file is searched for on sys.path;
-the .py suffix may be omitted."""
+the .py suffix may be omitted.""", file=self.stdout)
 
     def help_clear(self):
         self.help_cl()
 
     def help_cl(self):
-        print >>self.stdout, "cl(ear) filename:lineno"
-        print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
+        print("cl(ear) filename:lineno", file=self.stdout)
+        print("""cl(ear) [bpnumber [bpnumber...]]
 With a space separated list of breakpoint numbers, clear
 those breakpoints.  Without argument, clear all breaks (but
 first ask confirmation).  With a filename:lineno argument,
@@ -892,59 +890,59 @@ clear all breaks at that line in that file.
 Note that the argument is different from previous versions of
 the debugger (in python distributions 1.5.1 and before) where
 a linenumber was used instead of either filename:lineno or
-breakpoint numbers."""
+breakpoint numbers.""", file=self.stdout)
 
     def help_tbreak(self):
-        print >>self.stdout, """tbreak  same arguments as break, but breakpoint is
-removed when first hit."""
+        print("""tbreak  same arguments as break, but breakpoint is
+removed when first hit.""", file=self.stdout)
 
     def help_enable(self):
-        print >>self.stdout, """enable bpnumber [bpnumber ...]
+        print("""enable bpnumber [bpnumber ...]
 Enables the breakpoints given as a space separated list of
-bp numbers."""
+bp numbers.""", file=self.stdout)
 
     def help_disable(self):
-        print >>self.stdout, """disable bpnumber [bpnumber ...]
+        print("""disable bpnumber [bpnumber ...]
 Disables the breakpoints given as a space separated list of
-bp numbers."""
+bp numbers.""", file=self.stdout)
 
     def help_ignore(self):
-        print >>self.stdout, """ignore bpnumber count
+        print("""ignore bpnumber count
 Sets the ignore count for the given breakpoint number.  A breakpoint
 becomes active when the ignore count is zero.  When non-zero, the
 count is decremented each time the breakpoint is reached and the
 breakpoint is not disabled and any associated condition evaluates
-to true."""
+to true.""", file=self.stdout)
 
     def help_condition(self):
-        print >>self.stdout, """condition bpnumber str_condition
+        print("""condition bpnumber str_condition
 str_condition is a string specifying an expression which
 must evaluate to true before the breakpoint is honored.
 If str_condition is absent, any existing condition is removed;
-i.e., the breakpoint is made unconditional."""
+i.e., the breakpoint is made unconditional.""", file=self.stdout)
 
     def help_step(self):
         self.help_s()
 
     def help_s(self):
-        print >>self.stdout, """s(tep)
+        print("""s(tep)
 Execute the current line, stop at the first possible occasion
-(either in a function that is called or in the current function)."""
+(either in a function that is called or in the current function).""", file=self.stdout)
 
     def help_next(self):
         self.help_n()
 
     def help_n(self):
-        print >>self.stdout, """n(ext)
+        print("""n(ext)
 Continue execution until the next line in the current function
-is reached or it returns."""
+is reached or it returns.""", file=self.stdout)
 
     def help_return(self):
         self.help_r()
 
     def help_r(self):
-        print >>self.stdout, """r(eturn)
-Continue execution until the current function returns."""
+        print("""r(eturn)
+Continue execution until the current function returns.""", file=self.stdout)
 
     def help_continue(self):
         self.help_c()
@@ -953,51 +951,51 @@ Continue execution until the current function returns."""
         self.help_c()
 
     def help_c(self):
-        print >>self.stdout, """c(ont(inue))
-Continue execution, only stop when a breakpoint is encountered."""
+        print("""c(ont(inue))
+Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout)
 
     def help_jump(self):
         self.help_j()
 
     def help_j(self):
-        print >>self.stdout, """j(ump) lineno
-Set the next line that will be executed."""
+        print("""j(ump) lineno
+Set the next line that will be executed.""", file=self.stdout)
 
     def help_debug(self):
-        print >>self.stdout, """debug code
+        print("""debug code
 Enter a recursive debugger that steps through the code argument
 (which is an arbitrary expression or statement to be executed
-in the current environment)."""
+in the current environment).""", file=self.stdout)
 
     def help_list(self):
         self.help_l()
 
     def help_l(self):
-        print >>self.stdout, """l(ist) [first [,last]]
+        print("""l(ist) [first [,last]]
 List source code for the current file.
 Without arguments, list 11 lines around the current line
 or continue the previous listing.
 With one argument, list 11 lines starting at that line.
 With two arguments, list the given range;
-if the second argument is less than the first, it is a count."""
+if the second argument is less than the first, it is a count.""", file=self.stdout)
 
     def help_args(self):
         self.help_a()
 
     def help_a(self):
-        print >>self.stdout, """a(rgs)
-Print the arguments of the current function."""
+        print("""a(rgs)
+Print the arguments of the current function.""", file=self.stdout)
 
     def help_p(self):
-        print >>self.stdout, """p expression
-Print the value of the expression."""
+        print("""p expression
+Print the value of the expression.""", file=self.stdout)
 
     def help_pp(self):
-        print >>self.stdout, """pp expression
-Pretty-print the value of the expression."""
+        print("""pp expression
+Pretty-print the value of the expression.""", file=self.stdout)
 
     def help_exec(self):
-        print >>self.stdout, """(!) statement
+        print("""(!) statement
 Execute the (one-line) statement in the context of
 the current stack frame.
 The exclamation point can be omitted unless the first word
@@ -1005,27 +1003,27 @@ of the statement resembles a debugger command.
 To assign to a global variable you must always prefix the
 command with a 'global' command, e.g.:
 (Pdb) global list_options; list_options = ['-l']
-(Pdb)"""
+(Pdb)""", file=self.stdout)
 
     def help_quit(self):
         self.help_q()
 
     def help_q(self):
-        print >>self.stdout, """q(uit) or exit - Quit from the debugger.
-The program being executed is aborted."""
+        print("""q(uit) or exit - Quit from the debugger.
+The program being executed is aborted.""", file=self.stdout)
 
     help_exit = help_q
 
     def help_whatis(self):
-        print >>self.stdout, """whatis arg
-Prints the type of the argument."""
+        print("""whatis arg
+Prints the type of the argument.""", file=self.stdout)
 
     def help_EOF(self):
-        print >>self.stdout, """EOF
-Handles the receipt of EOF as a command."""
+        print("""EOF
+Handles the receipt of EOF as a command.""", file=self.stdout)
 
     def help_alias(self):
-        print >>self.stdout, """alias [name [command [parameter parameter ...] ]]
+        print("""alias [name [command [parameter parameter ...] ]]
 Creates an alias called 'name' the executes 'command'.  The command
 must *not* be enclosed in quotes.  Replaceable parameters are
 indicated by %1, %2, and so on, while %* is replaced by all the
@@ -1046,14 +1044,14 @@ alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
 
 #Print instance variables in self
 alias ps pi self
-"""
+""", file=self.stdout)
 
     def help_unalias(self):
-        print >>self.stdout, """unalias name
-Deletes the specified alias."""
+        print("""unalias name
+Deletes the specified alias.""", file=self.stdout)
 
     def help_commands(self):
-        print >>self.stdout, """commands [bpnumber]
+        print("""commands [bpnumber]
 (com) ...
 (com) end
 (Pdb)
@@ -1085,7 +1083,7 @@ usual message about stopping at a breakpoint is not printed.  This may
 be desirable for breakpoints that are to print a specific message and
 then continue.  If none of the other commands print anything, you
 see no sign that the breakpoint was reached.
-"""
+""", file=self.stdout)
 
     def help_pdb(self):
         help()
@@ -1176,20 +1174,20 @@ def help():
         fullname = os.path.join(dirname, 'pdb.doc')
         if os.path.exists(fullname):
             sts = os.system('${PAGER-more} '+fullname)
-            if sts: print '*** Pager exit status:', sts
+            if sts: print('*** Pager exit status:', sts)
             break
     else:
-        print 'Sorry, can\'t find the help file "pdb.doc"',
-        print 'along the Python search path'
+        print('Sorry, can\'t find the help file "pdb.doc"', end=' ')
+        print('along the Python search path')
 
 def main():
     if not sys.argv[1:]:
-        print "usage: pdb.py scriptfile [arg] ..."
+        print("usage: pdb.py scriptfile [arg] ...")
         sys.exit(2)
 
     mainpyfile =  sys.argv[1]     # Get script filename
     if not os.path.exists(mainpyfile):
-        print 'Error:', mainpyfile, 'does not exist'
+        print('Error:', mainpyfile, 'does not exist')
         sys.exit(1)
 
     del sys.argv[0]         # Hide "pdb.py" from argument list
@@ -1208,20 +1206,20 @@ def main():
             pdb._runscript(mainpyfile)
             if pdb._user_requested_quit:
                 break
-            print "The program finished and will be restarted"
+            print("The program finished and will be restarted")
         except SystemExit:
             # In most cases SystemExit does not warrant a post-mortem session.
-            print "The program exited via sys.exit(). Exit status: ",
-            print sys.exc_info()[1]
+            print("The program exited via sys.exit(). Exit status: ", end=' ')
+            print(sys.exc_info()[1])
         except:
             traceback.print_exc()
-            print "Uncaught exception. Entering post mortem debugging"
-            print "Running 'cont' or 'step' will restart the program"
+            print("Uncaught exception. Entering post mortem debugging")
+            print("Running 'cont' or 'step' will restart the program")
             t = sys.exc_info()[2]
             while t.tb_next is not None:
                 t = t.tb_next
             pdb.interaction(t.tb_frame,t)
-            print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
+            print("Post mortem debugger finished. The "+mainpyfile+" will be restarted")
 
 
 # When invoked as main program, invoke the debugger on a script
index 8b255b9d34e60d7c2c4dc5caf8526dc17c48ff17..846172a8e2fcc99cb9b32ddc9ee6a50e242376f5 100644 (file)
@@ -1757,18 +1757,18 @@ def assure_pickle_consistency(verbose=False):
     for name in pickle.__all__:
         if not re.match("[A-Z][A-Z0-9_]+$", name):
             if verbose:
-                print "skipping %r: it doesn't look like an opcode name" % name
+                print("skipping %r: it doesn't look like an opcode name" % name)
             continue
         picklecode = getattr(pickle, name)
         if not isinstance(picklecode, str) or len(picklecode) != 1:
             if verbose:
-                print ("skipping %r: value %r doesn't look like a pickle "
-                       "code" % (name, picklecode))
+                print(("skipping %r: value %r doesn't look like a pickle "
+                       "code" % (name, picklecode)))
             continue
         if picklecode in copy:
             if verbose:
-                print "checking name %r w/ code %r for consistency" % (
-                      name, picklecode)
+                print("checking name %r w/ code %r for consistency" % (
+                      name, picklecode))
             d = copy[picklecode]
             if d.name != name:
                 raise ValueError("for pickle code %r, pickle.py uses name %r "
@@ -1899,7 +1899,7 @@ def dis(pickle, out=None, memo=None, indentlevel=4):
     errormsg = None
     for opcode, arg, pos in genops(pickle):
         if pos is not None:
-            print >> out, "%5d:" % pos,
+            print("%5d:" % pos, end=' ', file=out)
 
         line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
                               indentchunk * len(markstack),
@@ -1964,7 +1964,7 @@ def dis(pickle, out=None, memo=None, indentlevel=4):
                 line += ' ' + repr(arg)
             if markmsg:
                 line += ' ' + markmsg
-        print >> out, line
+        print(line, file=out)
 
         if errormsg:
             # Note that we delayed complaining until the offending opcode
@@ -1983,7 +1983,7 @@ def dis(pickle, out=None, memo=None, indentlevel=4):
 
         stack.extend(after)
 
-    print >> out, "highest protocol among opcodes =", maxproto
+    print("highest protocol among opcodes =", maxproto, file=out)
     if stack:
         raise ValueError("stack not empty after STOP: %r" % stack)
 
index 295d9c88b66ca19933c88e8a272136d83c1056bc..07ee60c275704b27fc52d7eac290006721feaeed 100644 (file)
@@ -188,7 +188,7 @@ class Template:
     def makepipeline(self, infile, outfile):
         cmd = makepipeline(infile, self.steps, outfile)
         if self.debugging:
-            print cmd
+            print(cmd)
             cmd = 'set -x; ' + cmd
         return cmd
 
@@ -286,7 +286,7 @@ def quote(file):
 # Small test program and example
 
 def test():
-    print 'Testing...'
+    print('Testing...')
     t = Template()
     t.append('togif $IN $OUT', 'ff')
     t.append('giftoppm', '--')
@@ -295,4 +295,4 @@ def test():
     t.debug(1)
     FILE = '/usr/local/images/rgb/rogues/guido.rgb'
     t.copy(FILE, '@temp')
-    print 'Done.'
+    print('Done.')
index 7b2711f0b18e4a906694decd386f95242f6ed6bb..19a9d420125792bf3f02076e3f114c9c609927c0 100755 (executable)
@@ -89,7 +89,7 @@ class Cddb:
                 break
             match = reg.match(line)
             if not match:
-                print 'syntax error in ' + file
+                print('syntax error in ' + file)
                 continue
             name1, name2, value = match.group(1, 2, 3)
             if name1 == 'album':
@@ -101,17 +101,17 @@ class Cddb:
                     if not self.toc:
                         self.toc = value
                     if self.toc != value:
-                        print 'toc\'s don\'t match'
+                        print('toc\'s don\'t match')
                 elif name2 == 'notes':
                     self.notes.append(value)
             elif name1[:5] == 'track':
                 try:
                     trackno = int(name1[5:])
                 except strings.atoi_error:
-                    print 'syntax error in ' + file
+                    print('syntax error in ' + file)
                     continue
                 if trackno > ntracks:
-                    print 'track number %r in file %r out of range' % (trackno, file)
+                    print('track number %r in file %r out of range' % (trackno, file))
                     continue
                 if name2 == 'title':
                     self.track[trackno] = value
index 1c0168f7d2ed86b357551e5ac004ac83161d2971..b3fc8a46670a482fe93d1edf949e4799efa49dca 100755 (executable)
@@ -51,7 +51,7 @@ class Cdplayer:
                 line = line[l:]
                 match = reg.match(line)
                 if not match:
-                    print 'syntax error in ~/' + cdplayerrc
+                    print('syntax error in ~/' + cdplayerrc)
                     continue
                 name, value = match.group(1, 2)
                 if name == 'title':
index 83a22b6587a91d70e41250af607120ae69f303e3..b04ecf37b8fa5ddebf34bfebeab71743feac3ea8 100755 (executable)
@@ -66,7 +66,7 @@ def checkcache(filename):
         return None
     try:
         if fp.read(4) != MAGIC:
-            print 'flp: bad magic word in cache file', cachename
+            print('flp: bad magic word in cache file', cachename)
             return None
         cache_mtime = rdlong(fp)
         file_mtime = getmtime(filename)
@@ -122,7 +122,7 @@ def writecache(filename, forms):
     try:
         fp = open(cachename, 'w')
     except IOError:
-        print 'flp: can\'t create cache file', cachename
+        print('flp: can\'t create cache file', cachename)
         return # Never mind
     fp.write('\0\0\0\0') # Seek back and write MAGIC when done
     wrlong(fp, getmtime(filename))
@@ -145,8 +145,8 @@ def writecache(filename, forms):
 def freeze(filename):
     forms = parse_forms(filename)
     altforms = _pack_cache(forms)
-    print 'import flp'
-    print 'flp._internal_cache[', repr(filename), '] =', altforms
+    print('import flp')
+    print('flp._internal_cache[', repr(filename), '] =', altforms)
 
 #
 # Internal: create the data structure to be placed in the cache
@@ -426,7 +426,7 @@ def test():
     if len(sys.argv) == 2:
         forms = parse_forms(sys.argv[1])
         t1 = time.time()
-        print 'parse time:', 0.001*(t1-t0), 'sec.'
+        print('parse time:', 0.001*(t1-t0), 'sec.')
         keys = forms.keys()
         keys.sort()
         for i in keys:
@@ -434,18 +434,18 @@ def test():
     elif len(sys.argv) == 3:
         form = parse_form(sys.argv[1], sys.argv[2])
         t1 = time.time()
-        print 'parse time:', round(t1-t0, 3), 'sec.'
+        print('parse time:', round(t1-t0, 3), 'sec.')
         _printform(form)
     else:
-        print 'Usage: test fdfile [form]'
+        print('Usage: test fdfile [form]')
 
 def _printform(form):
     f = form[0]
     objs = form[1]
-    print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects
+    print('Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects)
     for i in objs:
-        print '  Obj ', i.Name, ' type ', i.Class, i.Type
-        print '    Box ', i.Box, ' btype ', i.Boxtype
-        print '    Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment
-        print '    cols ', i.Colors
-        print '    cback ', i.Callback, i.Argument
+        print('  Obj ', i.Name, ' type ', i.Class, i.Type)
+        print('    Box ', i.Box, ' btype ', i.Boxtype)
+        print('    Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment)
+        print('    cols ', i.Colors)
+        print('    cback ', i.Callback, i.Argument)
index 1be914617cbb033471fc6cd880d4416d7ab31fa7..5a0d87ee254977727d39ced76d981deb87bc45e4 100755 (executable)
@@ -62,18 +62,18 @@ def is_endgroup(list):
 def show_actuator(prefix, a):
     for item in a:
         if not is_list(item):
-            print prefix, item
+            print(prefix, item)
         elif item and item[0] == 'al':
-            print prefix, 'Subactuator list:'
+            print(prefix, 'Subactuator list:')
             for a in item[1:]:
                 show_actuator(prefix + '    ', a)
         elif len(item) == 2:
-            print prefix, item[0], '=>', item[1]
+            print(prefix, item[0], '=>', item[1])
         elif len(item) == 3 and item[0] == 'prop':
-            print prefix, 'Prop', item[1], '=>',
-            print item[2]
+            print(prefix, 'Prop', item[1], '=>', end=' ')
+            print(item[2])
         else:
-            print prefix, '?', item
+            print(prefix, '?', item)
 
 
 # Neatly display a panel.
@@ -81,18 +81,18 @@ def show_actuator(prefix, a):
 def show_panel(prefix, p):
     for item in p:
         if not is_list(item):
-            print prefix, item
+            print(prefix, item)
         elif item and item[0] == 'al':
-            print prefix, 'Actuator list:'
+            print(prefix, 'Actuator list:')
             for a in item[1:]:
                 show_actuator(prefix + '    ', a)
         elif len(item) == 2:
-            print prefix, item[0], '=>', item[1]
+            print(prefix, item[0], '=>', item[1])
         elif len(item) == 3 and item[0] == 'prop':
-            print prefix, 'Prop', item[1], '=>',
-            print item[2]
+            print(prefix, 'Prop', item[1], '=>', end=' ')
+            print(item[2])
         else:
-            print prefix, '?', item
+            print(prefix, '?', item)
 
 
 # Exception raised by build_actuator or build_panel.
@@ -123,18 +123,18 @@ def assign_members(target, attrlist, exclist, prefix):
                 # Strange default set by Panel Editor...
                 ok = 0
             else:
-                print 'unknown value', value, 'for', name
+                print('unknown value', value, 'for', name)
                 ok = 0
             if ok:
                 lhs = 'target.' + prefix + name
                 stmt = lhs + '=' + repr(value)
-                if debug: print 'exec', stmt
+                if debug: print('exec', stmt)
                 try:
                     exec(stmt + '\n')
                 except KeyboardInterrupt: # Don't catch this!
                     raise KeyboardInterrupt
                 except:
-                    print 'assign failed:', stmt
+                    print('assign failed:', stmt)
 
 
 # Build a real actuator from an actuator description.
@@ -185,7 +185,7 @@ def build_subactuators(panel, super_act, al):
         act.addsubact(super_act)
         if name:
             stmt = 'panel.' + name + ' = act'
-            if debug: print 'exec', stmt
+            if debug: print('exec', stmt)
             exec(stmt + '\n')
         if is_endgroup(a):
             panel.endgroup()
index 45883054f817e011de3151175e3f7942f7f15b72..bfdf57da84bdf39bc2fdecafd2e3685cdf7bd91a 100644 (file)
@@ -89,7 +89,7 @@ class Cddb:
                 break
             match = reg.match(line)
             if not match:
-                print 'syntax error in ' + file
+                print('syntax error in ' + file)
                 continue
             name1, name2, value = match.group(1, 2, 3)
             if name1 == 'album':
@@ -101,17 +101,17 @@ class Cddb:
                     if not self.toc:
                         self.toc = value
                     if self.toc != value:
-                        print 'toc\'s don\'t match'
+                        print('toc\'s don\'t match')
                 elif name2 == 'notes':
                     self.notes.append(value)
             elif name1[:5] == 'track':
                 try:
                     trackno = int(name1[5:])
                 except ValueError:
-                    print 'syntax error in ' + file
+                    print('syntax error in ' + file)
                     continue
                 if trackno > ntracks:
-                    print 'track number %r in file %s out of range' % (trackno, file)
+                    print('track number %r in file %s out of range' % (trackno, file))
                     continue
                 if name2 == 'title':
                     self.track[trackno] = value
index d4bc7328ac9213ef40a840f42150480831693688..a2be8b44f187caebd5ecc23f3743d47c411973a0 100644 (file)
@@ -51,7 +51,7 @@ class Cdplayer:
                 line = line[l:]
                 match = reg.match(line)
                 if not match:
-                    print 'syntax error in ~/' + cdplayerrc
+                    print('syntax error in ~/' + cdplayerrc)
                     continue
                 name, value = match.group(1, 2)
                 if name == 'title':
index b0216226846defd0ab3b5c4b3f5c4f195dec24db..d150be09b4229c9889d41aad58a3558071b726a3 100644 (file)
@@ -65,7 +65,7 @@ def checkcache(filename):
         return None
     try:
         if fp.read(4) != MAGIC:
-            print 'flp: bad magic word in cache file', cachename
+            print('flp: bad magic word in cache file', cachename)
             return None
         cache_mtime = rdlong(fp)
         file_mtime = getmtime(filename)
@@ -121,7 +121,7 @@ def writecache(filename, forms):
     try:
         fp = open(cachename, 'w')
     except IOError:
-        print 'flp: can\'t create cache file', cachename
+        print('flp: can\'t create cache file', cachename)
         return # Never mind
     fp.write('\0\0\0\0') # Seek back and write MAGIC when done
     wrlong(fp, getmtime(filename))
@@ -144,8 +144,8 @@ def writecache(filename, forms):
 def freeze(filename):
     forms = parse_forms(filename)
     altforms = _pack_cache(forms)
-    print 'import flp'
-    print 'flp._internal_cache[', repr(filename), '] =', altforms
+    print('import flp')
+    print('flp._internal_cache[', repr(filename), '] =', altforms)
 
 #
 # Internal: create the data structure to be placed in the cache
@@ -425,7 +425,7 @@ def test():
     if len(sys.argv) == 2:
         forms = parse_forms(sys.argv[1])
         t1 = time.time()
-        print 'parse time:', 0.001*(t1-t0), 'sec.'
+        print('parse time:', 0.001*(t1-t0), 'sec.')
         keys = forms.keys()
         keys.sort()
         for i in keys:
@@ -433,18 +433,18 @@ def test():
     elif len(sys.argv) == 3:
         form = parse_form(sys.argv[1], sys.argv[2])
         t1 = time.time()
-        print 'parse time:', round(t1-t0, 3), 'sec.'
+        print('parse time:', round(t1-t0, 3), 'sec.')
         _printform(form)
     else:
-        print 'Usage: test fdfile [form]'
+        print('Usage: test fdfile [form]')
 
 def _printform(form):
     f = form[0]
     objs = form[1]
-    print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects
+    print('Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects)
     for i in objs:
-        print '  Obj ', i.Name, ' type ', i.Class, i.Type
-        print '    Box ', i.Box, ' btype ', i.Boxtype
-        print '    Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment
-        print '    cols ', i.Colors
-        print '    cback ', i.Callback, i.Argument
+        print('  Obj ', i.Name, ' type ', i.Class, i.Type)
+        print('    Box ', i.Box, ' btype ', i.Boxtype)
+        print('    Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment)
+        print('    cols ', i.Colors)
+        print('    cback ', i.Callback, i.Argument)
index 1be914617cbb033471fc6cd880d4416d7ab31fa7..5a0d87ee254977727d39ced76d981deb87bc45e4 100644 (file)
@@ -62,18 +62,18 @@ def is_endgroup(list):
 def show_actuator(prefix, a):
     for item in a:
         if not is_list(item):
-            print prefix, item
+            print(prefix, item)
         elif item and item[0] == 'al':
-            print prefix, 'Subactuator list:'
+            print(prefix, 'Subactuator list:')
             for a in item[1:]:
                 show_actuator(prefix + '    ', a)
         elif len(item) == 2:
-            print prefix, item[0], '=>', item[1]
+            print(prefix, item[0], '=>', item[1])
         elif len(item) == 3 and item[0] == 'prop':
-            print prefix, 'Prop', item[1], '=>',
-            print item[2]
+            print(prefix, 'Prop', item[1], '=>', end=' ')
+            print(item[2])
         else:
-            print prefix, '?', item
+            print(prefix, '?', item)
 
 
 # Neatly display a panel.
@@ -81,18 +81,18 @@ def show_actuator(prefix, a):
 def show_panel(prefix, p):
     for item in p:
         if not is_list(item):
-            print prefix, item
+            print(prefix, item)
         elif item and item[0] == 'al':
-            print prefix, 'Actuator list:'
+            print(prefix, 'Actuator list:')
             for a in item[1:]:
                 show_actuator(prefix + '    ', a)
         elif len(item) == 2:
-            print prefix, item[0], '=>', item[1]
+            print(prefix, item[0], '=>', item[1])
         elif len(item) == 3 and item[0] == 'prop':
-            print prefix, 'Prop', item[1], '=>',
-            print item[2]
+            print(prefix, 'Prop', item[1], '=>', end=' ')
+            print(item[2])
         else:
-            print prefix, '?', item
+            print(prefix, '?', item)
 
 
 # Exception raised by build_actuator or build_panel.
@@ -123,18 +123,18 @@ def assign_members(target, attrlist, exclist, prefix):
                 # Strange default set by Panel Editor...
                 ok = 0
             else:
-                print 'unknown value', value, 'for', name
+                print('unknown value', value, 'for', name)
                 ok = 0
             if ok:
                 lhs = 'target.' + prefix + name
                 stmt = lhs + '=' + repr(value)
-                if debug: print 'exec', stmt
+                if debug: print('exec', stmt)
                 try:
                     exec(stmt + '\n')
                 except KeyboardInterrupt: # Don't catch this!
                     raise KeyboardInterrupt
                 except:
-                    print 'assign failed:', stmt
+                    print('assign failed:', stmt)
 
 
 # Build a real actuator from an actuator description.
@@ -185,7 +185,7 @@ def build_subactuators(panel, super_act, al):
         act.addsubact(super_act)
         if name:
             stmt = 'panel.' + name + ' = act'
-            if debug: print 'exec', stmt
+            if debug: print('exec', stmt)
             exec(stmt + '\n')
         if is_endgroup(a):
             panel.endgroup()
index fd96095ad67adf3d8602f7937ef27c970850d699..67fb9598066a84d2c87acab117ad59d7846c9296 100644 (file)
@@ -104,7 +104,7 @@ def test():
     fn = EasyDialogs.AskFileForOpen(message="Select an AIFF soundfile", typeList=("AIFF",))
     if not fn: return
     af = aifc.open(fn, 'r')
-    print af.getparams()
+    print(af.getparams())
     p = Play_Audio_mac()
     p.setoutrate(af.getframerate())
     p.setsampwidth(af.getsampwidth())
@@ -114,7 +114,7 @@ def test():
         data = af.readframes(BUFSIZ)
         if not data: break
         p.writeframes(data)
-        print 'wrote', len(data), 'space', p.getfillable()
+        print('wrote', len(data), 'space', p.getfillable())
     p.wait()
 
 if __name__ == '__main__':
index 340e3edf56158c6c2fdba4c06fe12af87d8d606d..3c920119e2e37a8fa454ba543da1cf093059409f 100644 (file)
@@ -75,7 +75,7 @@ def Message(msg, id=260, ok=None):
     _interact()
     d = GetNewDialog(id, -1)
     if not d:
-        print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+        print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
         return
     h = d.GetDialogItemAsControl(2)
     SetDialogItemText(h, lf2cr(msg))
@@ -108,7 +108,7 @@ def AskString(prompt, default = "", id=261, ok=None, cancel=None):
     _interact()
     d = GetNewDialog(id, -1)
     if not d:
-        print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+        print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
         return
     h = d.GetDialogItemAsControl(3)
     SetDialogItemText(h, lf2cr(prompt))
@@ -150,7 +150,7 @@ def AskPassword(prompt,  default='', id=264, ok=None, cancel=None):
     _interact()
     d = GetNewDialog(id, -1)
     if not d:
-        print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+        print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
         return
     h = d.GetDialogItemAsControl(3)
     SetDialogItemText(h, lf2cr(prompt))
@@ -194,7 +194,7 @@ def AskYesNoCancel(question, default = 0, yes=None, no=None, cancel=None, id=262
     _interact()
     d = GetNewDialog(id, -1)
     if not d:
-        print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+        print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
         return
     # Button assignments:
     # 1 = default (invisible)
@@ -429,7 +429,7 @@ def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfo
     _interact()
     d = GetNewDialog(id, -1)
     if not d:
-        print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+        print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
         return
 #       h = d.GetDialogItemAsControl(3)
 #       SetDialogItemText(h, lf2cr(prompt))
@@ -791,7 +791,7 @@ def test():
     argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0)
     Message("Command line: %s"%' '.join(argv))
     for i in range(len(argv)):
-        print 'arg[%d] = %r' % (i, argv[i])
+        print('arg[%d] = %r' % (i, argv[i]))
     ok = AskYesNoCancel("Do you want to proceed?")
     ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No")
     if ok > 0:
index 0bd6feb7e32cc3469cbe13235762cb76e54490ef..2a07c99d89aa9b725e80af5a06c7d93e405bd28e 100644 (file)
@@ -250,7 +250,7 @@ class Application:
             if window in self._windows:
                 self._windows[window].do_itemhit(item, event)
             else:
-                print 'Dialog event for unknown dialog'
+                print('Dialog event for unknown dialog')
             return 1
         return 0
 
@@ -323,14 +323,14 @@ class Application:
 
     def do_unknownpartcode(self, partcode, window, event):
         (what, message, when, where, modifiers) = event
-        if DEBUG: print "Mouse down at global:", where
-        if DEBUG: print "\tUnknown part code:", partcode
-        if DEBUG: print "\tEvent:", self.printevent(event)
+        if DEBUG: print("Mouse down at global:", where)
+        if DEBUG: print("\tUnknown part code:", partcode)
+        if DEBUG: print("\tEvent:", self.printevent(event))
         if hasattr(MacOS, 'HandleEvent'):
             MacOS.HandleEvent(event)
 
     def do_unknownwindow(self, partcode, window, event):
-        if DEBUG: print 'Unknown window:', window
+        if DEBUG: print('Unknown window:', window)
         if hasattr(MacOS, 'HandleEvent'):
             MacOS.HandleEvent(event)
 
@@ -373,7 +373,7 @@ class Application:
             # else it wasn't for us, sigh...
 
     def do_char(self, c, event):
-        if DEBUG: print "Character", repr(c)
+        if DEBUG: print("Character", repr(c))
 
     def do_updateEvt(self, event):
         (what, message, when, where, modifiers) = event
@@ -402,7 +402,7 @@ class Application:
             self.do_suspendresume(event)
         else:
             if DEBUG:
-                print 'unknown osEvt:',
+                print('unknown osEvt:', end=' ')
                 self.printevent(event)
 
     def do_suspendresume(self, event):
@@ -415,7 +415,7 @@ class Application:
     def do_kHighLevelEvent(self, event):
         (what, message, when, where, modifiers) = event
         if DEBUG:
-            print "High Level Event:",
+            print("High Level Event:", end=' ')
             self.printevent(event)
         try:
             AEProcessAppleEvent(event)
@@ -426,7 +426,7 @@ class Application:
 
     def do_unknownevent(self, event):
         if DEBUG:
-            print "Unhandled event:",
+            print("Unhandled event:", end=' ')
             self.printevent(event)
 
     def printevent(self, event):
@@ -434,13 +434,13 @@ class Application:
         nicewhat = repr(what)
         if what in eventname:
             nicewhat = eventname[what]
-        print nicewhat,
+        print(nicewhat, end=' ')
         if what == kHighLevelEvent:
             h, v = where
-            print repr(ostypecode(message)), hex(when), repr(ostypecode(h | (v<<16))),
+            print(repr(ostypecode(message)), hex(when), repr(ostypecode(h | (v<<16))), end=' ')
         else:
-            print hex(message), hex(when), where,
-        print hex(modifiers)
+            print(hex(message), hex(when), where, end=' ')
+        print(hex(modifiers))
 
 
 class MenuBar:
@@ -477,7 +477,7 @@ class MenuBar:
     def addmenu(self, title, after = 0, id=None):
         if id == None:
             id = self.getnextid()
-        if DEBUG: print 'Newmenu', title, id # XXXX
+        if DEBUG: print('Newmenu', title, id) # XXXX
         m = NewMenu(id, title)
         m.InsertMenu(after)
         if after >= 0:
@@ -488,7 +488,7 @@ class MenuBar:
         return id, m
 
     def delmenu(self, id):
-        if DEBUG: print 'Delmenu', id # XXXX
+        if DEBUG: print('Delmenu', id) # XXXX
         DeleteMenu(id)
 
     def addpopup(self, title = ''):
@@ -531,8 +531,8 @@ class MenuBar:
         if id in self.menus:
             self.menus[id].dispatch(id, item, window, event)
         else:
-            if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \
-                (id, item, window, event)
+            if DEBUG: print("MenuBar.dispatch(%d, %d, %s, %s)" % \
+                (id, item, window, event))
 
 
 # XXX Need a way to get menus as resources and bind them to callbacks
@@ -837,10 +837,10 @@ class Window:
 
     def do_contentclick(self, local, modifiers, event):
         if DEBUG:
-            print 'Click in contents at %s, modifiers %s'%(local, modifiers)
+            print('Click in contents at %s, modifiers %s'%(local, modifiers))
 
     def do_rawupdate(self, window, event):
-        if DEBUG: print "raw update for", window
+        if DEBUG: print("raw update for", window)
         SetPort(window)
         window.BeginUpdate()
         self.do_update(window, event)
@@ -857,12 +857,12 @@ class Window:
             EraseRgn(window.GetWindowPort().visRgn)
 
     def do_activate(self, activate, event):
-        if DEBUG: print 'Activate %d for %s'%(activate, self.wid)
+        if DEBUG: print('Activate %d for %s'%(activate, self.wid))
 
 class ControlsWindow(Window):
 
     def do_rawupdate(self, window, event):
-        if DEBUG: print "raw update for", window
+        if DEBUG: print("raw update for", window)
         SetPort(window)
         window.BeginUpdate()
         self.do_update(window, event)
@@ -872,7 +872,7 @@ class ControlsWindow(Window):
         window.EndUpdate()
 
     def do_controlhit(self, window, control, pcode, event):
-        if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode
+        if DEBUG: print("control hit in", window, "on", control, "; pcode =", pcode)
 
     def do_inContent(self, partcode, window, event):
         if MyFrontWindow() != window:
@@ -885,8 +885,8 @@ class ControlsWindow(Window):
         if pcode and control:
             self.do_rawcontrolhit(window, control, pcode, local, event)
         else:
-            if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \
-                (local, window, pcode, control)
+            if DEBUG: print("FindControl(%s, %s) -> (%s, %s)" % \
+                (local, window, pcode, control))
             self.do_contentclick(local, modifiers, event)
 
     def do_rawcontrolhit(self, window, control, pcode, local, event):
@@ -975,11 +975,11 @@ class ScrolledWindow(ControlsWindow):
             pcode = control.TrackControl(local)
             if pcode == inThumb:
                 value = control.GetControlValue()
-                print 'setbars', which, value #DBG
+                print('setbars', which, value) #DBG
                 self.scrollbar_callback(which, 'set', value)
                 self.updatescrollbars()
             else:
-                print 'funny part', pcode #DBG
+                print('funny part', pcode) #DBG
         return 1
 
     def do_controltrack(self, control, pcode):
@@ -1045,7 +1045,7 @@ class ScrolledWindow(ControlsWindow):
         return 0, 0
 
     def scrollbar_callback(self, which, what, value):
-        print 'scroll', which, what, value
+        print('scroll', which, what, value)
 
 class DialogWindow(Window):
     """A modeless dialog window"""
@@ -1063,7 +1063,7 @@ class DialogWindow(Window):
         Window.do_postclose(self)
 
     def do_itemhit(self, item, event):
-        print 'Dialog %s, item %d hit'%(self.dlg, item)
+        print('Dialog %s, item %d hit'%(self.dlg, item))
 
     def do_rawupdate(self, window, event):
         pass
@@ -1096,7 +1096,7 @@ class TestApp(Application):
         self.quititem = MenuItem(m, "Quit", "Q", self.quit)
 
     def save(self, *args):
-        print "Save"
+        print("Save")
 
     def quit(self, *args):
         raise self
@@ -1106,7 +1106,7 @@ class TestApp(Application):
         self.nohelpitem = MenuItem(hm, "There isn't any", None, self.nohelp)
 
     def nohelp(self, *args):
-        print "I told you there isn't any!"
+        print("I told you there isn't any!")
 
     def debug(self, *args):
         import pdb
index 1d990af1c592cdf6fe325fea37f1fc3e7163f5d8..7ae3351042eb913f7a22e060564d5ad4bbe6c65a 100644 (file)
@@ -71,8 +71,8 @@ class MiniApplication:
             try:
                 AE.AEProcessAppleEvent(event)
             except AE.Error as err:
-                print 'AE error: ', err
-                print 'in', msg
+                print('AE error: ', err)
+                print('in', msg)
                 traceback.print_exc()
             return
         elif what == keyDown:
@@ -107,7 +107,7 @@ class MiniApplication:
         if hasattr(MacOS, 'HandleEvent'):
             MacOS.HandleEvent(event)
         else:
-            print "Unhandled event:", event
+            print("Unhandled event:", event)
 
     def getabouttext(self):
         return self.__class__.__name__
@@ -191,7 +191,7 @@ class _Test(AEServer, MiniApplication):
         pass
 
     def other(self, _object=None, _class=None, _type=None, **args):
-        print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args
+        print('AppleEvent', (_class, _type), 'for', _object, 'Other args:', args)
 
 
 if __name__ == '__main__':
index 7a52eb9a8e4d542fcfeff5fe64722089166639c1..d1812341a815d1a12339a6c22f90269d04b3e9f5 100644 (file)
@@ -349,15 +349,15 @@ def test():
 
     target = AE.AECreateDesc('sign', 'quil')
     ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0)
-    print unpackevent(ae)
+    print(unpackevent(ae))
     raw_input(":")
     ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0)
     obj = Character(2, Word(1, Document(1)))
-    print obj
-    print repr(obj)
+    print(obj)
+    print(repr(obj))
     packevent(ae, {'----': obj})
     params, attrs = unpackevent(ae)
-    print params['----']
+    print(params['----'])
     raw_input(":")
 
 if __name__ == '__main__':
index fdd163d4f7ae0f882bb0812eda026c019ead0310..2e0e96708a14fc194e1ceb0b9f5879c600fd847e 100644 (file)
@@ -51,9 +51,9 @@ class AppleSingle(object):
         except ValueError as arg:
             raise Error, "Unpack header error: %s" % (arg,)
         if verbose:
-            print 'Magic:   0x%8.8x' % (magic,)
-            print 'Version: 0x%8.8x' % (version,)
-            print 'Entries: %d' % (nentry,)
+            print('Magic:   0x%8.8x' % (magic,))
+            print('Version: 0x%8.8x' % (version,))
+            print('Entries: %d' % (nentry,))
         if magic != AS_MAGIC:
             raise Error, "Unknown AppleSingle magic number 0x%8.8x" % (magic,)
         if version != AS_VERSION:
@@ -68,7 +68,7 @@ class AppleSingle(object):
             except ValueError as arg:
                 raise Error, "Unpack entry error: %s" % (arg,)
             if verbose:
-                print "Fork %d, offset %d, length %d" % (restype, offset, length)
+                print("Fork %d, offset %d, length %d" % (restype, offset, length))
             fileobj.seek(offset)
             data = fileobj.read(length)
             if len(data) != length:
@@ -124,7 +124,7 @@ def decode(infile, outpath, resonly=False, verbose=False):
 
 def _test():
     if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4:
-        print 'Usage: applesingle.py [-r] applesinglefile decodedfile'
+        print('Usage: applesingle.py [-r] applesinglefile decodedfile')
         sys.exit(1)
     if sys.argv[1] == '-r':
         resonly = True
index fe9e8f8fcd6118ebc6116215df37389ed31a176b..676e80ac5c140b3ae1e99e6cbe2ec2ed11ab0165 100644 (file)
@@ -37,7 +37,7 @@ class ArgvCollector:
             self._dooneevent(mask, timeout)
 
         if not self.quitting:
-            print "argvemulator: timeout waiting for arguments"
+            print("argvemulator: timeout waiting for arguments")
 
         self.close()
 
@@ -54,12 +54,12 @@ class ArgvCollector:
                 AE.AEProcessAppleEvent(event)
             except AE.Error as err:
                 msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16)))
-                print 'AE error: ', err
-                print 'in', msg
+                print('AE error: ', err)
+                print('in', msg)
                 traceback.print_exc()
             return
         else:
-            print "Unhandled event:", event
+            print("Unhandled event:", event)
 
 
     def _quit(self):
@@ -78,7 +78,7 @@ class ArgvCollector:
                 pathname = fsref.as_pathname()
                 sys.argv.append(pathname)
         except  Exception as e:
-            print "argvemulator.py warning: can't unpack an open document event"
+            print("argvemulator.py warning: can't unpack an open document event")
             import traceback
             traceback.print_exc()
 
@@ -86,4 +86,4 @@ class ArgvCollector:
 
 if __name__ == '__main__':
     ArgvCollector().mainloop()
-    print "sys.argv=", sys.argv
+    print("sys.argv=", sys.argv)
index d58adf25f53b66c95fd7afeda908eb2e2756ce28..bf11ed9fd5786651b25aac286b4b53ca21a09ff4 100755 (executable)
@@ -831,8 +831,8 @@ Options:
 
 def usage(msg=None):
     if msg:
-        print msg
-    print cmdline_doc
+        print(msg)
+    print(cmdline_doc)
     sys.exit(1)
 
 def main(builder=None):
index f013c856456951709f7f82a09b285f0ca688e5f6..282cc27975fbe9698d04dbd56d4002ca2e22307c 100644 (file)
@@ -695,76 +695,76 @@ def emptytrash():
 
 def _test():
     import EasyDialogs
-    print 'Original findertools functionality test...'
-    print 'Testing launch...'
+    print('Original findertools functionality test...')
+    print('Testing launch...')
     pathname = EasyDialogs.AskFileForOpen('File to launch:')
     if pathname:
         result = launch(pathname)
         if result:
-            print 'Result: ', result
-        print 'Press return-',
+            print('Result: ', result)
+        print('Press return-', end=' ')
         sys.stdin.readline()
-    print 'Testing print...'
+    print('Testing print...')
     pathname = EasyDialogs.AskFileForOpen('File to print:')
     if pathname:
         result = Print(pathname)
         if result:
-            print 'Result: ', result
-        print 'Press return-',
+            print('Result: ', result)
+        print('Press return-', end=' ')
         sys.stdin.readline()
-    print 'Testing copy...'
+    print('Testing copy...')
     pathname = EasyDialogs.AskFileForOpen('File to copy:')
     if pathname:
         destdir = EasyDialogs.AskFolder('Destination:')
         if destdir:
             result = copy(pathname, destdir)
             if result:
-                print 'Result:', result
-            print 'Press return-',
+                print('Result:', result)
+            print('Press return-', end=' ')
             sys.stdin.readline()
-    print 'Testing move...'
+    print('Testing move...')
     pathname = EasyDialogs.AskFileForOpen('File to move:')
     if pathname:
         destdir = EasyDialogs.AskFolder('Destination:')
         if destdir:
             result = move(pathname, destdir)
             if result:
-                print 'Result:', result
-            print 'Press return-',
+                print('Result:', result)
+            print('Press return-', end=' ')
             sys.stdin.readline()
-    print 'Testing sleep...'
+    print('Testing sleep...')
     if EasyDialogs.AskYesNoCancel('Sleep?') > 0:
         result = sleep()
         if result:
-            print 'Result:', result
-        print 'Press return-',
+            print('Result:', result)
+        print('Press return-', end=' ')
         sys.stdin.readline()
-    print 'Testing shutdown...'
+    print('Testing shutdown...')
     if EasyDialogs.AskYesNoCancel('Shut down?') > 0:
         result = shutdown()
         if result:
-            print 'Result:', result
-        print 'Press return-',
+            print('Result:', result)
+        print('Press return-', end=' ')
         sys.stdin.readline()
-    print 'Testing restart...'
+    print('Testing restart...')
     if EasyDialogs.AskYesNoCancel('Restart?') > 0:
         result = restart()
         if result:
-            print 'Result:', result
-        print 'Press return-',
+            print('Result:', result)
+        print('Press return-', end=' ')
         sys.stdin.readline()
 
 def _test2():
-    print '\nmorefindertools version %s\nTests coming up...' %__version__
+    print('\nmorefindertools version %s\nTests coming up...' %__version__)
     import os
     import random
 
     # miscellaneous
-    print '\tfilesharing on?',  filesharing()       # is file sharing on, off, starting up?
-    print '\tOS version',       OSversion()     # the version of the system software
+    print('\tfilesharing on?',  filesharing())       # is file sharing on, off, starting up?
+    print('\tOS version',       OSversion())     # the version of the system software
 
     # set the soundvolume in a simple way
-    print '\tSystem beep volume'
+    print('\tSystem beep volume')
     for i in range(0, 7):
         volumelevel(i)
         MacOS.SysBeep()
@@ -781,10 +781,10 @@ def _test2():
     windowview(base, 1) # set the view by list
 
     label(f, 2)             # set the label of this file to something orange
-    print '\tlabel', label(f)   # get the label of this file
+    print('\tlabel', label(f))   # get the label of this file
 
     # the file location only works in a window with icon view!
-    print 'Random locations for an icon'
+    print('Random locations for an icon')
     windowview(base, 0)     # set the view by icon
     windowsize(base, (600, 600))
     for i in range(50):
@@ -794,36 +794,36 @@ def _test2():
     windowview(base, 1)     # set the view by icon
 
     orgpos = windowposition(base)
-    print 'Animated window location'
+    print('Animated window location')
     for i in range(10):
         pos = (100+i*10, 100+i*10)
         windowposition(base, pos)
-        print '\twindow position', pos
+        print('\twindow position', pos)
     windowposition(base, orgpos)    # park it where it was before
 
-    print 'Put a comment in file', f, ':'
-    print '\t', comment(f)      # print the Finder comment this file has
+    print('Put a comment in file', f, ':')
+    print('\t', comment(f))      # print the Finder comment this file has
     s = 'This is a comment no one reads!'
     comment(f, s)           # set the Finder comment
 
 def _test3():
-    print 'MacOS9 or better specific functions'
+    print('MacOS9 or better specific functions')
     # processes
     pr = processes()        # return a list of tuples with (active_processname, creatorcode)
-    print 'Return a list of current active processes:'
+    print('Return a list of current active processes:')
     for p in pr:
-        print '\t', p
+        print('\t', p)
 
     # get attributes of the first process in the list
-    print 'Attributes of the first process in the list:'
+    print('Attributes of the first process in the list:')
     pinfo = processinfo(pr[0][0])
-    print '\t', pr[0][0]
-    print '\t\tmemory partition', pinfo.partition       # the memory allocated to this process
-    print '\t\tmemory used', pinfo.used         # the memory actuall used by this process
-    print '\t\tis visible', pinfo.visible           # is the process visible to the user
-    print '\t\tis frontmost', pinfo.frontmost       # is the process the front most one?
-    print '\t\thas scripting', pinfo.hasscripting       # is the process scriptable?
-    print '\t\taccepts high level events',  pinfo.accepthighlevel   # does the process accept high level appleevents?
+    print('\t', pr[0][0])
+    print('\t\tmemory partition', pinfo.partition)       # the memory allocated to this process
+    print('\t\tmemory used', pinfo.used)         # the memory actuall used by this process
+    print('\t\tis visible', pinfo.visible)           # is the process visible to the user
+    print('\t\tis frontmost', pinfo.frontmost)       # is the process the front most one?
+    print('\t\thas scripting', pinfo.hasscripting)       # is the process scriptable?
+    print('\t\taccepts high level events',  pinfo.accepthighlevel)   # does the process accept high level appleevents?
 
 if __name__ == '__main__':
     _test()
index 7d03d8f6e7d3a488c631ceaf16ef7ee06aa74c82..fd706a0cdab23c41d925b6b886781991b615d642 100644 (file)
@@ -115,8 +115,8 @@ def main_interactive(interact=0, basepkgname='StdSuites'):
         processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname,
         verbose=sys.stderr)
     except MacOS.Error as arg:
-        print "Error getting terminology:", arg
-        print "Retry, manually parsing resources"
+        print("Error getting terminology:", arg)
+        print("Retry, manually parsing resources")
         processfile_fromresource(filename, edit_modnames=edit_modnames,
             basepkgname=basepkgname, verbose=sys.stderr)
 
@@ -145,10 +145,10 @@ def processfile_fromresource(fullname, output=None, basepkgname=None,
         edit_modnames=None, creatorsignature=None, dump=None, verbose=None):
     """Process all resources in a single file"""
     if not is_scriptable(fullname) and verbose:
-        print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
+        print("Warning: app does not seem scriptable: %s" % fullname, file=verbose)
     cur = CurResFile()
     if verbose:
-        print >>verbose, "Processing", fullname
+        print("Processing", fullname, file=verbose)
     rf = macresource.open_pathname(fullname)
     try:
         UseResFile(rf)
@@ -160,11 +160,11 @@ def processfile_fromresource(fullname, output=None, basepkgname=None,
             res = Get1IndResource('aeut', 1+i)
             resources.append(res)
         if verbose:
-            print >>verbose, "\nLISTING aete+aeut RESOURCES IN", repr(fullname)
+            print("\nLISTING aete+aeut RESOURCES IN", repr(fullname), file=verbose)
         aetelist = []
         for res in resources:
             if verbose:
-                print >>verbose, "decoding", res.GetResInfo(), "..."
+                print("decoding", res.GetResInfo(), "...", file=verbose)
             data = res.data
             aete = decode(data, verbose)
             aetelist.append((aete, res.GetResInfo()))
@@ -185,15 +185,15 @@ def processfile(fullname, output=None, basepkgname=None,
         verbose=None):
     """Ask an application for its terminology and process that"""
     if not is_scriptable(fullname) and verbose:
-        print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
+        print("Warning: app does not seem scriptable: %s" % fullname, file=verbose)
     if verbose:
-        print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname)
+        print("\nASKING FOR aete DICTIONARY IN", repr(fullname), file=verbose)
     try:
         aedescobj, launched = OSATerminology.GetAppTerminology(fullname)
     except MacOS.Error as arg:
         if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound
             if verbose:
-                print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually"
+                print("GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually", file=verbose)
             aedata, sig = getappterminology(fullname, verbose=verbose)
             if not creatorsignature:
                 creatorsignature = sig
@@ -202,15 +202,15 @@ def processfile(fullname, output=None, basepkgname=None,
     else:
         if launched:
             if verbose:
-                print >>verbose, "Launched", fullname
+                print("Launched", fullname, file=verbose)
         raw = aetools.unpack(aedescobj)
         if not raw:
             if verbose:
-                print >>verbose, 'Unpack returned empty value:', raw
+                print('Unpack returned empty value:', raw, file=verbose)
             return
         if not raw[0].data:
             if verbose:
-                print >>verbose, 'Unpack returned value without data:', raw
+                print('Unpack returned value without data:', raw, file=verbose)
             return
         aedata = raw[0]
     aete = decode(aedata.data, verbose)
@@ -246,7 +246,7 @@ def getappterminology(fullname, verbose=None):
         talker._start()
     except (MacOS.Error, aetools.Error) as arg:
         if verbose:
-            print >>verbose, 'Warning: start() failed, continuing anyway:', arg
+            print('Warning: start() failed, continuing anyway:', arg, file=verbose)
     reply = talker.send("ascr", "gdte")
     #reply2 = talker.send("ascr", "gdut")
     # Now pick the bits out of the return that we need.
@@ -344,9 +344,9 @@ def getlist(f, description, getitem):
     return list
 
 def alt_generic(what, f, *args):
-    print "generic", repr(what), args
+    print("generic", repr(what), args)
     res = vageneric(what, f, args)
-    print '->', repr(res)
+    print('->', repr(res))
     return res
 
 def generic(what, f, *args):
@@ -940,14 +940,14 @@ class ObjectCompiler:
         for mapper in self.othernamemappers:
             if mapper.hasname(name) and mapper.modulename != self.modulename:
                 if self.verbose:
-                    print >>self.verbose, "Duplicate Python identifier:", name, self.modulename, mapper.modulename
+                    print("Duplicate Python identifier:", name, self.modulename, mapper.modulename, file=self.verbose)
                 return True
         return False
 
     def askdefinitionmodule(self, type, code):
         if not self.can_interact:
             if self.verbose:
-                print >>self.verbose, "** No definition for %s '%s' found" % (type, code)
+                print("** No definition for %s '%s' found" % (type, code), file=self.verbose)
             return None
         path = EasyDialogs.AskFileForSave(message='Where is %s %s declared?'%(type, code))
         if not path: return
@@ -1018,7 +1018,7 @@ class ObjectCompiler:
             if self.fp and (elements or len(properties) > 1 or (len(properties) == 1 and
                 properties[0][1] != 'c@#!')):
                 if self.verbose:
-                    print >>self.verbose, '** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code)
+                    print('** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code), file=self.verbose)
                 raise RuntimeError, "About to skip non-empty class"
             return
         plist = []
index 490cbf72e975826cf3ead10ed65de3468cf28531..5c109d6cf1136aa8f0a6ecd983c1c9dd9c1b1a31 100644 (file)
@@ -94,7 +94,7 @@ def _code_fontrecord(data, key):
         chr(0) + _code_default(name)
 
 def _code_boolean(data, key):
-    print 'XXXX boolean:', repr(data)
+    print('XXXX boolean:', repr(data))
     return chr(data)
 
 def _code_text(data, key):
@@ -258,7 +258,7 @@ def _test():
             v = ic[k]
         except error:
             v = '????'
-        print k, '\t', v
+        print(k, '\t', v)
     sys.exit(1)
 
 if __name__ == '__main__':
index 91dfffa1c6a4dc707a5611558b2294d0522321f7..fa14c045db095722829dc891222a5a12399f5f91 100644 (file)
@@ -140,7 +140,7 @@ def _decode(pathname, verbose=0):
         import tempfile
         fd, newpathname = tempfile.mkstemp(".rsrc")
     if verbose:
-        print 'Decoding', pathname, 'to', newpathname
+        print('Decoding', pathname, 'to', newpathname)
     import applesingle
     applesingle.decode(pathname, newpathname, resonly=1)
     return newpathname
index 3b1a6861f18b7e48a4cd25ff9c4425f0eb7aab6b..09f63db2fa1554cfd2fc84a6f354fba629896038 100644 (file)
@@ -229,7 +229,7 @@ class PimpTarUnpacker(PimpUnpacker):
                             #print 'SKIP', member.name
                         else:
                             member.name = newprefix + member.name[len(oldprefix):]
-                            print '    ', member.name
+                            print('    ', member.name)
                         break
                     elif oldprefix2 and member.name[:len(oldprefix2)] == oldprefix2:
                         if newprefix is None:
@@ -1020,8 +1020,8 @@ def _run(mode, verbose, force, args, prefargs, watcher):
     elif mode =='list':
         if not args:
             args = db.listnames()
-        print "%-20.20s\t%s" % ("Package", "Description")
-        print
+        print("%-20.20s\t%s" % ("Package", "Description"))
+        print()
         for pkgname in args:
             pkg = db.find(pkgname)
             if pkg:
@@ -1029,21 +1029,21 @@ def _run(mode, verbose, force, args, prefargs, watcher):
                 pkgname = pkg.fullname()
             else:
                 description = 'Error: no such package'
-            print "%-20.20s\t%s" % (pkgname, description)
+            print("%-20.20s\t%s" % (pkgname, description))
             if verbose:
-                print "\tHome page:\t", pkg.homepage()
+                print("\tHome page:\t", pkg.homepage())
                 try:
-                    print "\tDownload URL:\t", pkg.downloadURL()
+                    print("\tDownload URL:\t", pkg.downloadURL())
                 except KeyError:
                     pass
                 description = pkg.description()
                 description = '\n\t\t\t\t\t'.join(description.splitlines())
-                print "\tDescription:\t%s" % description
+                print("\tDescription:\t%s" % description)
     elif mode =='status':
         if not args:
             args = db.listnames()
-            print "%-20.20s\t%s\t%s" % ("Package", "Installed", "Message")
-            print
+            print("%-20.20s\t%s\t%s" % ("Package", "Installed", "Message"))
+            print()
         for pkgname in args:
             pkg = db.find(pkgname)
             if pkg:
@@ -1052,7 +1052,7 @@ def _run(mode, verbose, force, args, prefargs, watcher):
             else:
                 status = 'error'
                 msg = 'No such package'
-            print "%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg)
+            print("%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg))
             if verbose and status == "no":
                 prereq = pkg.prerequisites()
                 for pkg, msg in prereq:
@@ -1060,22 +1060,22 @@ def _run(mode, verbose, force, args, prefargs, watcher):
                         pkg = ''
                     else:
                         pkg = pkg.fullname()
-                    print "%-20.20s\tRequirement: %s %s" % ("", pkg, msg)
+                    print("%-20.20s\tRequirement: %s %s" % ("", pkg, msg))
     elif mode == 'install':
         if not args:
-            print 'Please specify packages to install'
+            print('Please specify packages to install')
             sys.exit(1)
         inst = PimpInstaller(db)
         for pkgname in args:
             pkg = db.find(pkgname)
             if not pkg:
-                print '%s: No such package' % pkgname
+                print('%s: No such package' % pkgname)
                 continue
             list, messages = inst.prepareInstall(pkg, force)
             if messages and not force:
-                print "%s: Not installed:" % pkgname
+                print("%s: Not installed:" % pkgname)
                 for m in messages:
-                    print "\t", m
+                    print("\t", m)
             else:
                 if verbose:
                     output = sys.stdout
@@ -1083,26 +1083,26 @@ def _run(mode, verbose, force, args, prefargs, watcher):
                     output = None
                 messages = inst.install(list, output)
                 if messages:
-                    print "%s: Not installed:" % pkgname
+                    print("%s: Not installed:" % pkgname)
                     for m in messages:
-                        print "\t", m
+                        print("\t", m)
 
 def main():
     """Minimal commandline tool to drive pimp."""
 
     import getopt
     def _help():
-        print "Usage: pimp [options] -s [package ...]  List installed status"
-        print "       pimp [options] -l [package ...]  Show package information"
-        print "       pimp [options] -i package ...    Install packages"
-        print "       pimp -d                          Dump database to stdout"
-        print "       pimp -V                          Print version number"
-        print "Options:"
-        print "       -v     Verbose"
-        print "       -f     Force installation"
-        print "       -D dir Set destination directory"
-        print "              (default: %s)" % DEFAULT_INSTALLDIR
-        print "       -u url URL for database"
+        print("Usage: pimp [options] -s [package ...]  List installed status")
+        print("       pimp [options] -l [package ...]  Show package information")
+        print("       pimp [options] -i package ...    Install packages")
+        print("       pimp -d                          Dump database to stdout")
+        print("       pimp -V                          Print version number")
+        print("Options:")
+        print("       -v     Verbose")
+        print("       -f     Force installation")
+        print("       -D dir Set destination directory")
+        print("              (default: %s)" % DEFAULT_INSTALLDIR)
+        print("       -u url URL for database")
         sys.exit(1)
 
     class _Watcher:
@@ -1152,7 +1152,7 @@ def main():
     if not mode:
         _help()
     if mode == 'version':
-        print 'Pimp version %s; module name is %s' % (PIMP_VERSION, __name__)
+        print('Pimp version %s; module name is %s' % (PIMP_VERSION, __name__))
     else:
         _run(mode, verbose, force, args, prefargs, watcher)
 
index f16228b82876730e37da5baa775e84b73d032c24..42954b7028cfc985647d3d8205ecdbf80f7dd2ac 100644 (file)
@@ -272,8 +272,8 @@ def _test():
         fname = 'frame%04.4d.jpg'%num
         num = num+1
         pname = os.path.join(dstdir, fname)
-        if not img: print 'Not',
-        print 'Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data))
+        if not img: print('Not', end=' ')
+        print('Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data)))
         if img:
             wrt = img.writer(imgfmt, pname)
             wrt.width = imgw
@@ -282,9 +282,9 @@ def _test():
             timestamp, data = rdr.ReadVideo()
             MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG')
             if num > 20:
-                print 'stopping at 20 frames so your disk does not fill up:-)'
+                print('stopping at 20 frames so your disk does not fill up:-)')
                 break
-    print 'Total frames:', num
+    print('Total frames:', num)
 
 if __name__ == '__main__':
     _test()
index 422c2bbf6f0ad182564b34c4a7160f48f8840b5e..e8298680b12454b68cf4a2239f62f367301051b5 100644 (file)
@@ -74,6 +74,6 @@ if __name__ == '__main__':
     try:
         link(sys.argv[1], sys.argv[2])
     except IndexError:
-        print 'Usage: emx_link <source> <target>'
+        print('Usage: emx_link <source> <target>')
     except OSError:
-        print 'emx_link: %s' % str(sys.exc_info()[1])
+        print('emx_link: %s' % str(sys.exc_info()[1]))
index 981cebab6929bd14ab2cabe23860433d94045a99..a5aee3490e7484b813b21f38c9710f3546b11c0f 100644 (file)
@@ -60,12 +60,12 @@ def test():
                 "/foo/bar/index.html",
                 "/foo/bar/",
                 "/"]:
-        print '%r -> %r' % (url, url2pathname(url))
-    print "*******************************************************"
+        print('%r -> %r' % (url, url2pathname(url)))
+    print("*******************************************************")
     for path in ["SCSI::SCSI4.$.Anwendung",
                  "PythonApp:Lib",
                  "PythonApp:Lib.rourl2path/py"]:
-        print '%r -> %r' % (path, pathname2url(path))
+        print('%r -> %r' % (path, pathname2url(path)))
 
 if __name__ == '__main__':
     test()
index 7d3c34f1da10a5a483fe6eb65c95b0298253a6df..720da0400675e226b9aacdb6f64a5eb56f0ebca8 100755 (executable)
@@ -283,7 +283,7 @@ def _test_parse_release_file():
         ):
         parsed = _parse_release_file(input)
         if parsed != output:
-            print (input, parsed)
+            print((input, parsed))
 
 def linux_distribution(distname='', version='', id='',
 
@@ -1308,7 +1308,7 @@ def _test_sys_version():
         ):
         parsed = _sys_version(input)
         if parsed != output:
-            print (input, parsed)
+            print((input, parsed))
 
 def python_implementation():
 
@@ -1480,5 +1480,5 @@ if __name__ == '__main__':
     # Default is to print the aliased verbose platform string
     terse = ('terse' in sys.argv or '--terse' in sys.argv)
     aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
-    print platform(aliased,terse)
+    print(platform(aliased,terse))
     sys.exit(0)
index 694979e6d632a16cb598bf267cd8ada1e2bef41d..3618487c45627e125791fade06637f75f9b5e233 100644 (file)
@@ -213,14 +213,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...")
     r, w = 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:
         r, w, e = popen3([cmd])
     except:
@@ -238,7 +238,7 @@ def _test():
     _cleanup()
     if _active:
         raise ValueError("_active not empty")
-    print "All OK"
+    print("All OK")
 
 if __name__ == '__main__':
     _test()
index b7a7a8af75f28282e60e9686ce7bb418ea49034f..adf784f6dd845e05c2f2de4bdfa812bb21d47d27 100644 (file)
@@ -100,14 +100,14 @@ class POP3:
 
 
     def _putline(self, line):
-        if self._debugging > 1: print '*put*', repr(line)
+        if self._debugging > 1: print('*put*', repr(line))
         self.sock.sendall('%s%s' % (line, CRLF))
 
 
     # Internal: send one command to the server (through _putline())
 
     def _putcmd(self, line):
-        if self._debugging: print '*cmd*', repr(line)
+        if self._debugging: print('*cmd*', repr(line))
         self._putline(line)
 
 
@@ -117,7 +117,7 @@ class POP3:
 
     def _getline(self):
         line = self.file.readline()
-        if self._debugging > 1: print '*get*', repr(line)
+        if self._debugging > 1: print('*get*', repr(line))
         if not line: raise error_proto('-ERR EOF')
         octets = len(line)
         # server can send any combination of CR & LF
@@ -135,7 +135,7 @@ class POP3:
 
     def _getresp(self):
         resp, o = self._getline()
-        if self._debugging > 1: print '*resp*', repr(resp)
+        if self._debugging > 1: print('*resp*', repr(resp))
         c = resp[:1]
         if c != '+':
             raise error_proto(resp)
@@ -209,7 +209,7 @@ class POP3:
         """
         retval = self._shortcmd('STAT')
         rets = retval.split()
-        if self._debugging: print '*stat*', repr(rets)
+        if self._debugging: print('*stat*', repr(rets))
         numMessages = int(rets[1])
         sizeMessages = int(rets[2])
         return (numMessages, sizeMessages)
@@ -375,7 +375,7 @@ class POP3_SSL(POP3):
             match = renewline.match(self.buffer)
         line = match.group(0)
         self.buffer = renewline.sub('' ,self.buffer, 1)
-        if self._debugging > 1: print '*get*', repr(line)
+        if self._debugging > 1: print('*get*', repr(line))
 
         octets = len(line)
         if line[-2:] == CRLF:
@@ -385,7 +385,7 @@ class POP3_SSL(POP3):
         return line[:-1], octets
 
     def _putline(self, line):
-        if self._debugging > 1: print '*put*', repr(line)
+        if self._debugging > 1: print('*put*', repr(line))
         line += CRLF
         bytes = len(line)
         while bytes > 0:
@@ -409,15 +409,15 @@ class POP3_SSL(POP3):
 if __name__ == "__main__":
     import sys
     a = POP3(sys.argv[1])
-    print a.getwelcome()
+    print(a.getwelcome())
     a.user(sys.argv[2])
     a.pass_(sys.argv[3])
     a.list()
     (numMsgs, totalSize) = a.stat()
     for i in range(1, numMsgs + 1):
         (header, msg, octets) = a.retr(i)
-        print "Message %d:" % i
+        print("Message %d:" % i)
         for line in msg:
-            print '   ' + line
-        print '-----------------------'
+            print('   ' + line)
+        print('-----------------------')
     a.quit()
index 97135ebfe54e81c39d2fc7026b495285fe62506a..e54edbe19cb25736977506fff963d5ef4d22a6a5 100644 (file)
@@ -313,8 +313,8 @@ def _perfcheck(object=None):
     t2 = time.time()
     p.pformat(object)
     t3 = time.time()
-    print "_safe_repr:", t2 - t1
-    print "pformat:", t3 - t2
+    print("_safe_repr:", t2 - t1)
+    print("pformat:", t3 - t2)
 
 if __name__ == "__main__":
     _perfcheck()
index dc278dd5ee6492e4b490ef081b11623758a57273..83480cf4919a0e9864cc30ed60d80e91589dda25 100755 (executable)
@@ -94,8 +94,8 @@ def runctx(statement, globals, locals, filename=None):
 
 # Backwards compatibility.
 def help():
-    print "Documentation for the profile module can be found "
-    print "in the Python Library Reference, section 'The Python Profiler'."
+    print("Documentation for the profile module can be found ")
+    print("in the Python Library Reference, section 'The Python Profiler'.")
 
 if os.name == "mac":
     import MacOS
@@ -550,7 +550,7 @@ class Profile:
         t1 = get_time()
         elapsed_noprofile = t1 - t0
         if verbose:
-            print "elapsed time without profiling =", elapsed_noprofile
+            print("elapsed time without profiling =", elapsed_noprofile)
 
         # elapsed_profile <- time f(m) takes with profiling.  The difference
         # is profiling overhead, only some of which the profiler subtracts
@@ -561,7 +561,7 @@ class Profile:
         t1 = get_time()
         elapsed_profile = t1 - t0
         if verbose:
-            print "elapsed time with profiling =", elapsed_profile
+            print("elapsed time with profiling =", elapsed_profile)
 
         # reported_time <- "CPU seconds" the profiler charged to f and f1.
         total_calls = 0.0
@@ -573,8 +573,8 @@ class Profile:
                 reported_time += tt
 
         if verbose:
-            print "'CPU seconds' profiler reported =", reported_time
-            print "total # calls =", total_calls
+            print("'CPU seconds' profiler reported =", reported_time)
+            print("total # calls =", total_calls)
         if total_calls != m + 1:
             raise ValueError("internal error: total calls = %d" % total_calls)
 
@@ -584,12 +584,12 @@ class Profile:
         # overhead per event.
         mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls
         if verbose:
-            print "mean stopwatch overhead per profile event =", mean
+            print("mean stopwatch overhead per profile event =", mean)
         return mean
 
 #****************************************************************************
 def Stats(*args):
-    print 'Report generating functions are in the "pstats" module\a'
+    print('Report generating functions are in the "pstats" module\a')
 
 def main():
     usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
index 2b152c312718d1621936ac53bfc0a7ddc52dc5ef..439ac84dd06d896b9ad0460d88c4ef51bf2a43c4 100644 (file)
@@ -110,9 +110,9 @@ class Stats:
             trouble = 0
         finally:
             if trouble:
-                print >> self.stream, "Invalid timing data",
-                if self.files: print >> self.stream, self.files[-1],
-                print >> self.stream
+                print("Invalid timing data", end=' ', file=self.stream)
+                if self.files: print(self.files[-1], end=' ', file=self.stream)
+                print(file=self.stream)
 
     def load_stats(self, arg):
         if not arg:  self.stats = {}
@@ -334,7 +334,7 @@ class Stats:
 
         if not list:
             return 0, list
-        print >> self.stream, msg
+        print(msg, file=self.stream)
         if count < len(self.stats):
             width = 0
             for func in list:
@@ -344,24 +344,24 @@ class Stats:
 
     def print_stats(self, *amount):
         for filename in self.files:
-            print >> self.stream, filename
-        if self.files: print >> self.stream
+            print(filename, file=self.stream)
+        if self.files: print(file=self.stream)
         indent = ' ' * 8
         for func in self.top_level:
-            print >> self.stream, indent, func_get_function_name(func)
+            print(indent, func_get_function_name(func), file=self.stream)
 
-        print >> self.stream, indent, self.total_calls, "function calls",
+        print(indent, self.total_calls, "function calls", end=' ', file=self.stream)
         if self.total_calls != self.prim_calls:
-            print >> self.stream, "(%d primitive calls)" % self.prim_calls,
-        print >> self.stream, "in %.3f CPU seconds" % self.total_tt
-        print >> self.stream
+            print("(%d primitive calls)" % self.prim_calls, end=' ', file=self.stream)
+        print("in %.3f CPU seconds" % self.total_tt, file=self.stream)
+        print(file=self.stream)
         width, list = self.get_print_list(amount)
         if list:
             self.print_title()
             for func in list:
                 self.print_line(func)
-            print >> self.stream
-            print >> self.stream
+            print(file=self.stream)
+            print(file=self.stream)
         return self
 
     def print_callees(self, *amount):
@@ -375,8 +375,8 @@ class Stats:
                     self.print_call_line(width, func, self.all_callees[func])
                 else:
                     self.print_call_line(width, func, {})
-            print >> self.stream
-            print >> self.stream
+            print(file=self.stream)
+            print(file=self.stream)
         return self
 
     def print_callers(self, *amount):
@@ -386,12 +386,12 @@ class Stats:
             for func in list:
                 cc, nc, tt, ct, callers = self.stats[func]
                 self.print_call_line(width, func, callers, "<-")
-            print >> self.stream
-            print >> self.stream
+            print(file=self.stream)
+            print(file=self.stream)
         return self
 
     def print_call_heading(self, name_size, column_title):
-        print >> self.stream, "Function ".ljust(name_size) + column_title
+        print("Function ".ljust(name_size) + column_title, file=self.stream)
         # print sub-header only if we have new-style callers
         subheader = False
         for cc, nc, tt, ct, callers in self.stats.itervalues():
@@ -400,12 +400,12 @@ class Stats:
                 subheader = isinstance(value, tuple)
                 break
         if subheader:
-            print >> self.stream, " "*name_size + "    ncalls  tottime  cumtime"
+            print(" "*name_size + "    ncalls  tottime  cumtime", file=self.stream)
 
     def print_call_line(self, name_size, source, call_dict, arrow="->"):
-        print >> self.stream, func_std_string(source).ljust(name_size) + arrow,
+        print(func_std_string(source).ljust(name_size) + arrow, end=' ', file=self.stream)
         if not call_dict:
-            print >> self.stream
+            print(file=self.stream)
             return
         clist = call_dict.keys()
         clist.sort()
@@ -425,30 +425,30 @@ class Stats:
             else:
                 substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3]))
                 left_width = name_size + 3
-            print >> self.stream, indent*left_width + substats
+            print(indent*left_width + substats, file=self.stream)
             indent = " "
 
     def print_title(self):
-        print >> self.stream, '   ncalls  tottime  percall  cumtime  percall',
-        print >> self.stream, 'filename:lineno(function)'
+        print('   ncalls  tottime  percall  cumtime  percall', end=' ', file=self.stream)
+        print('filename:lineno(function)', file=self.stream)
 
     def print_line(self, func):  # hack : should print percentages
         cc, nc, tt, ct, callers = self.stats[func]
         c = str(nc)
         if nc != cc:
             c = c + '/' + str(cc)
-        print >> self.stream, c.rjust(9),
-        print >> self.stream, f8(tt),
+        print(c.rjust(9), end=' ', file=self.stream)
+        print(f8(tt), end=' ', file=self.stream)
         if nc == 0:
-            print >> self.stream, ' '*8,
+            print(' '*8, end=' ', file=self.stream)
         else:
-            print >> self.stream, f8(tt/nc),
-        print >> self.stream, f8(ct),
+            print(f8(tt/nc), end=' ', file=self.stream)
+        print(f8(ct), end=' ', file=self.stream)
         if cc == 0:
-            print >> self.stream, ' '*8,
+            print(' '*8, end=' ', file=self.stream)
         else:
-            print >> self.stream, f8(ct/cc),
-        print >> self.stream, func_std_string(func)
+            print(f8(ct/cc), end=' ', file=self.stream)
+        print(func_std_string(func), file=self.stream)
 
 class TupleComp:
     """This class provides a generic function for comparing any two tuples.
@@ -565,7 +565,7 @@ if __name__ == '__main__':
                 try:
                     frac = float(term)
                     if frac > 1 or frac < 0:
-                        print >> self.stream, "Fraction argument must be in [0, 1]"
+                        print("Fraction argument must be in [0, 1]", file=self.stream)
                         continue
                     processed.append(frac)
                     continue
@@ -575,93 +575,93 @@ if __name__ == '__main__':
             if self.stats:
                 getattr(self.stats, fn)(*processed)
             else:
-                print >> self.stream, "No statistics object is loaded."
+                print("No statistics object is loaded.", file=self.stream)
             return 0
         def generic_help(self):
-            print >> self.stream, "Arguments may be:"
-            print >> self.stream, "* An integer maximum number of entries to print."
-            print >> self.stream, "* A decimal fractional number between 0 and 1, controlling"
-            print >> self.stream, "  what fraction of selected entries to print."
-            print >> self.stream, "* A regular expression; only entries with function names"
-            print >> self.stream, "  that match it are printed."
+            print("Arguments may be:", file=self.stream)
+            print("* An integer maximum number of entries to print.", file=self.stream)
+            print("* A decimal fractional number between 0 and 1, controlling", file=self.stream)
+            print("  what fraction of selected entries to print.", file=self.stream)
+            print("* A regular expression; only entries with function names", file=self.stream)
+            print("  that match it are printed.", file=self.stream)
 
         def do_add(self, line):
             self.stats.add(line)
             return 0
         def help_add(self):
-            print >> self.stream, "Add profile info from given file to current statistics object."
+            print("Add profile info from given file to current statistics object.", file=self.stream)
 
         def do_callees(self, line):
             return self.generic('print_callees', line)
         def help_callees(self):
-            print >> self.stream, "Print callees statistics from the current stat object."
+            print("Print callees statistics from the current stat object.", file=self.stream)
             self.generic_help()
 
         def do_callers(self, line):
             return self.generic('print_callers', line)
         def help_callers(self):
-            print >> self.stream, "Print callers statistics from the current stat object."
+            print("Print callers statistics from the current stat object.", file=self.stream)
             self.generic_help()
 
         def do_EOF(self, line):
-            print >> self.stream, ""
+            print("", file=self.stream)
             return 1
         def help_EOF(self):
-            print >> self.stream, "Leave the profile brower."
+            print("Leave the profile brower.", file=self.stream)
 
         def do_quit(self, line):
             return 1
         def help_quit(self):
-            print >> self.stream, "Leave the profile brower."
+            print("Leave the profile brower.", file=self.stream)
 
         def do_read(self, line):
             if line:
                 try:
                     self.stats = Stats(line)
                 except IOError as args:
-                    print >> self.stream, args[1]
+                    print(args[1], file=self.stream)
                     return
                 self.prompt = line + "% "
             elif len(self.prompt) > 2:
                 line = self.prompt[-2:]
             else:
-                print >> self.stream, "No statistics object is current -- cannot reload."
+                print("No statistics object is current -- cannot reload.", file=self.stream)
             return 0
         def help_read(self):
-            print >> self.stream, "Read in profile data from a specified file."
+            print("Read in profile data from a specified file.", file=self.stream)
 
         def do_reverse(self, line):
             self.stats.reverse_order()
             return 0
         def help_reverse(self):
-            print >> self.stream, "Reverse the sort order of the profiling report."
+            print("Reverse the sort order of the profiling report.", file=self.stream)
 
         def do_sort(self, line):
             abbrevs = self.stats.get_sort_arg_defs()
             if line and not filter(lambda x,a=abbrevs: x not in a,line.split()):
                 self.stats.sort_stats(*line.split())
             else:
-                print >> self.stream, "Valid sort keys (unique prefixes are accepted):"
+                print("Valid sort keys (unique prefixes are accepted):", file=self.stream)
                 for (key, value) in Stats.sort_arg_dict_default.iteritems():
-                    print >> self.stream, "%s -- %s" % (key, value[1])
+                    print("%s -- %s" % (key, value[1]), file=self.stream)
             return 0
         def help_sort(self):
-            print >> self.stream, "Sort profile data according to specified keys."
-            print >> self.stream, "(Typing `sort' without arguments lists valid keys.)"
+            print("Sort profile data according to specified keys.", file=self.stream)
+            print("(Typing `sort' without arguments lists valid keys.)", file=self.stream)
         def complete_sort(self, text, *args):
             return [a for a in Stats.sort_arg_dict_default if a.startswith(text)]
 
         def do_stats(self, line):
             return self.generic('print_stats', line)
         def help_stats(self):
-            print >> self.stream, "Print statistics from the current stat object."
+            print("Print statistics from the current stat object.", file=self.stream)
             self.generic_help()
 
         def do_strip(self, line):
             self.stats.strip_dirs()
             return 0
         def help_strip(self):
-            print >> self.stream, "Strip leading path information from filenames in the report."
+            print("Strip leading path information from filenames in the report.", file=self.stream)
 
         def postcmd(self, stop, line):
             if stop:
@@ -675,9 +675,9 @@ if __name__ == '__main__':
         initprofile = None
     try:
         browser = ProfileBrowser(initprofile)
-        print >> browser.stream, "Welcome to the profile statistics browser."
+        print("Welcome to the profile statistics browser.", file=browser.stream)
         browser.cmdloop()
-        print >> browser.stream, "Goodbye."
+        print("Goodbye.", file=browser.stream)
     except KeyboardInterrupt:
         pass
 
index 079b38c411518d451177587461acb609df5b7276..a4ec3692f1d4db8f6d75fe31802f43af2bdc7037 100644 (file)
@@ -328,13 +328,13 @@ def _main():
                                getattr(b, 'lineno', 0)))
     for obj in objs:
         if isinstance(obj, Class):
-            print "class", obj.name, obj.super, obj.lineno
+            print("class", obj.name, obj.super, obj.lineno)
             methods = sorted(obj.methods.iteritems(), key=itemgetter(1))
             for name, lineno in methods:
                 if name != "__path__":
-                    print "  def", name, lineno
+                    print("  def", name, lineno)
         elif isinstance(obj, Function):
-            print "def", obj.name, obj.lineno
+            print("def", obj.name, obj.lineno)
 
 if __name__ == "__main__":
     _main()
index c496d1dd6ff6b47b5d915ed5e581d9f6747a537a..63bd2f7c38907b3fd00eb858fb7356779470ef2e 100755 (executable)
@@ -1480,7 +1480,7 @@ def doc(thing, title='Python Library Documentation: %s', forceload=0):
             desc += ' object'
         pager(title % desc + '\n\n' + text.document(object, name))
     except (ImportError, ErrorDuringImport) as value:
-        print value
+        print(value)
 
 def writedoc(thing, forceload=0):
     """Write HTML documentation to a file in the current directory."""
@@ -1490,9 +1490,9 @@ def writedoc(thing, forceload=0):
         file = open(name + '.html', 'w')
         file.write(page)
         file.close()
-        print 'wrote', name + '.html'
+        print('wrote', name + '.html')
     except (ImportError, ErrorDuringImport) as value:
-        print value
+        print(value)
 
 def writedocs(dir, pkgpath='', done=None):
     """Write out HTML documentation for all modules in a directory tree."""
@@ -1883,7 +1883,7 @@ def apropos(key):
     def callback(path, modname, desc):
         if modname[-9:] == '.__init__':
             modname = modname[:-9] + ' (package)'
-        print modname, desc and '- ' + desc
+        print(modname, desc and '- ' + desc)
     try: import warnings
     except ImportError: pass
     else: warnings.filterwarnings('ignore') # ignore problems during import
@@ -2200,9 +2200,9 @@ def cli():
                 except ValueError:
                     raise BadUsage
                 def ready(server):
-                    print 'pydoc server ready at %s' % server.url
+                    print('pydoc server ready at %s' % server.url)
                 def stopped():
-                    print 'pydoc server stopped'
+                    print('pydoc server stopped')
                 serve(port, ready, stopped)
                 return
             if opt == '-w':
@@ -2211,7 +2211,7 @@ def cli():
         if not args: raise BadUsage
         for arg in args:
             if ispath(arg) and not os.path.exists(arg):
-                print 'file %r does not exist' % arg
+                print('file %r does not exist' % arg)
                 break
             try:
                 if ispath(arg) and os.path.isfile(arg):
@@ -2224,11 +2224,11 @@ def cli():
                 else:
                     help.help(arg)
             except ErrorDuringImport as value:
-                print value
+                print(value)
 
     except (getopt.error, BadUsage):
         cmd = os.path.basename(sys.argv[0])
-        print """pydoc - the Python documentation tool
+        print("""pydoc - the Python documentation tool
 
 %s <name> ...
     Show text documentation on something.  <name> may be the name of a
@@ -2251,6 +2251,6 @@ def cli():
     Write out the HTML documentation for a module to a file in the current
     directory.  If <name> contains a '%s', it is treated as a filename; if
     it names a directory, documentation is written for all the contents.
-""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
+""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep))
 
 if __name__ == '__main__': cli()
index 171a59e0ae5bc816aa64d32f00b7d8840d075921..fccfe85b9f07888b1e596bcee018121b161b98d2 100755 (executable)
@@ -196,10 +196,10 @@ def main():
         opts, args = getopt.getopt(sys.argv[1:], 'td')
     except getopt.error as msg:
         sys.stdout = sys.stderr
-        print msg
-        print "usage: quopri [-t | -d] [file] ..."
-        print "-t: quote tabs"
-        print "-d: decode; default encode"
+        print(msg)
+        print("usage: quopri [-t | -d] [file] ...")
+        print("-t: quote tabs")
+        print("-d: decode; default encode")
         sys.exit(2)
     deco = 0
     tabs = 0
@@ -208,7 +208,7 @@ def main():
         if o == '-d': deco = 1
     if tabs and deco:
         sys.stdout = sys.stderr
-        print "-t and -d are mutually exclusive"
+        print("-t and -d are mutually exclusive")
         sys.exit(2)
     if not args: args = ['-']
     sts = 0
index 79ffb551e65534eac54ca5af3add3428dd7288d3..8adcff5f6dd508ca63226d65b150e250b5e9a03a 100644 (file)
@@ -792,7 +792,7 @@ class SystemRandom(Random):
 
 def _test_generator(n, func, args):
     import time
-    print n, 'times', func.__name__
+    print(n, 'times', func.__name__)
     total = 0.0
     sqsum = 0.0
     smallest = 1e10
@@ -805,11 +805,11 @@ def _test_generator(n, func, args):
         smallest = min(x, smallest)
         largest = max(x, largest)
     t1 = time.time()
-    print round(t1-t0, 3), 'sec,',
+    print(round(t1-t0, 3), 'sec,', end=' ')
     avg = total/n
     stddev = _sqrt(sqsum/n - avg*avg)
-    print 'avg %g, stddev %g, min %g, max %g' % \
-              (avg, stddev, smallest, largest)
+    print('avg %g, stddev %g, min %g, max %g' % \
+              (avg, stddev, smallest, largest))
 
 
 def _test(N=2000):
index 665f294dd40f0d7c3994810ac8bdae3dcf2736bb..e5ceb728dcb40b776d542c55961f0f892fdd01d3 100644 (file)
@@ -552,7 +552,7 @@ def test():
         try:
             fp = open(args[0])
         except IOError as msg:
-            print "%s: can't open file %r" % (sys.argv[0], args[0])
+            print("%s: can't open file %r" % (sys.argv[0], args[0]))
             return 1
     if fp.isatty():
         try:
index a9109cdfd2db99af6dbfda0cd345465fd7628290..8c636c1bd85881850d2cb8c98a40d89ee13d3522 100644 (file)
@@ -972,32 +972,32 @@ if __name__ == '__main__':
     if sys.argv[1:]: file = sys.argv[1]
     f = open(file, 'r')
     m = Message(f)
-    print 'From:', m.getaddr('from')
-    print 'To:', m.getaddrlist('to')
-    print 'Subject:', m.getheader('subject')
-    print 'Date:', m.getheader('date')
+    print('From:', m.getaddr('from'))
+    print('To:', m.getaddrlist('to'))
+    print('Subject:', m.getheader('subject'))
+    print('Date:', m.getheader('date'))
     date = m.getdate_tz('date')
     tz = date[-1]
     date = time.localtime(mktime_tz(date))
     if date:
-        print 'ParsedDate:', time.asctime(date),
+        print('ParsedDate:', time.asctime(date), end=' ')
         hhmmss = tz
         hhmm, ss = divmod(hhmmss, 60)
         hh, mm = divmod(hhmm, 60)
-        print "%+03d%02d" % (hh, mm),
-        if ss: print ".%02d" % ss,
-        print
+        print("%+03d%02d" % (hh, mm), end=' ')
+        if ss: print(".%02d" % ss, end=' ')
+        print()
     else:
-        print 'ParsedDate:', None
+        print('ParsedDate:', None)
     m.rewindbody()
     n = 0
     while f.readline():
         n += 1
-    print 'Lines:', n
-    print '-'*70
-    print 'len =', len(m)
-    if 'Date' in m: print 'Date =', m['Date']
+    print('Lines:', n)
+    print('-'*70)
+    print('len =', len(m))
+    if 'Date' in m: print('Date =', m['Date'])
     if 'X-Nonsense' in m: pass
-    print 'keys =', m.keys()
-    print 'values =', m.values()
-    print 'items =', m.items()
+    print('keys =', m.keys())
+    print('values =', m.values())
+    print('items =', m.items())
index 48ea066682e1878d3402c4275cbcf45276ff5fae..0edb55fd218e8800496504b323b327a9b3615f86 100644 (file)
@@ -16,7 +16,7 @@ __all__ = ["RobotFileParser"]
 debug = 0
 
 def _debug(msg):
-    if debug: print msg
+    if debug: print(msg)
 
 
 class RobotFileParser:
@@ -244,10 +244,10 @@ def _check(a,b):
     else:
         ac = "access allowed"
     if a!=b:
-        print "failed"
+        print("failed")
     else:
-        print "ok (%s)" % ac
-    print
+        print("ok (%s)" % ac)
+    print()
 
 def _test():
     global debug
index dc350cf94a25441c9d44e40533b0d1edd9ec5ec5..b0129c9a4729e33dd80dddce32492cea557d2679 100755 (executable)
@@ -98,7 +98,7 @@ def run_module(mod_name, init_globals=None,
 if __name__ == "__main__":
     # Run the module specified as the next command line argument
     if len(sys.argv) < 2:
-        print >> sys.stderr, "No module specified for execution"
+        print("No module specified for execution", file=sys.stderr)
     else:
         del sys.argv[0] # Make the requested module sys.argv[0]
         run_module(sys.argv[0], run_name="__main__", alter_sys=True)
index 1574f44a9d8bd4b8ff1362465dc5872c2e5f533f..987b65edff313ee6f5f556a89ff64a8e9e29a619 100644 (file)
@@ -382,8 +382,8 @@ class SGMLParser(markupbase.ParserBase):
     # Example -- report an unbalanced </...> tag.
     def report_unbalanced(self, tag):
         if self.verbose:
-            print '*** Unbalanced </' + tag + '>'
-            print '*** Stack:', self.stack
+            print('*** Unbalanced </' + tag + '>')
+            print('*** Stack:', self.stack)
 
     def convert_charref(self, name):
         """Convert character reference, may be overridden."""
@@ -468,40 +468,40 @@ class TestSGMLParser(SGMLParser):
         data = self.testdata
         if data:
             self.testdata = ""
-            print 'data:', repr(data)
+            print('data:', repr(data))
 
     def handle_comment(self, data):
         self.flush()
         r = repr(data)
         if len(r) > 68:
             r = r[:32] + '...' + r[-32:]
-        print 'comment:', r
+        print('comment:', r)
 
     def unknown_starttag(self, tag, attrs):
         self.flush()
         if not attrs:
-            print 'start tag: <' + tag + '>'
+            print('start tag: <' + tag + '>')
         else:
-            print 'start tag: <' + tag,
+            print('start tag: <' + tag, end=' ')
             for name, value in attrs:
-                print name + '=' + '"' + value + '"',
-            print '>'
+                print(name + '=' + '"' + value + '"', end=' ')
+            print('>')
 
     def unknown_endtag(self, tag):
         self.flush()
-        print 'end tag: </' + tag + '>'
+        print('end tag: </' + tag + '>')
 
     def unknown_entityref(self, ref):
         self.flush()
-        print '*** unknown entity ref: &' + ref + ';'
+        print('*** unknown entity ref: &' + ref + ';')
 
     def unknown_charref(self, ref):
         self.flush()
-        print '*** unknown char ref: &#' + ref + ';'
+        print('*** unknown char ref: &#' + ref + ';')
 
     def unknown_decl(self, data):
         self.flush()
-        print '*** unknown decl: [' + data + ']'
+        print('*** unknown decl: [' + data + ']')
 
     def close(self):
         SGMLParser.close(self)
@@ -531,7 +531,7 @@ def test(args = None):
         try:
             f = open(file, 'r')
         except IOError as msg:
-            print file, ":", msg
+            print(file, ":", msg)
             sys.exit(1)
 
     data = f.read()
index 6632b87596047c55d75d1b2d739c355f17807c9f..d81e99ec84d2587c1a41d48e7bd1a2587a04505a 100644 (file)
@@ -53,13 +53,13 @@ class shlex:
         self.filestack = deque()
         self.source = None
         if self.debug:
-            print 'shlex: reading from %s, line %d' \
-                  % (self.instream, self.lineno)
+            print('shlex: reading from %s, line %d' \
+                  % (self.instream, self.lineno))
 
     def push_token(self, tok):
         "Push a token onto the stack popped by the get_token method"
         if self.debug >= 1:
-            print "shlex: pushing token " + repr(tok)
+            print("shlex: pushing token " + repr(tok))
         self.pushback.appendleft(tok)
 
     def push_source(self, newstream, newfile=None):
@@ -72,17 +72,17 @@ class shlex:
         self.lineno = 1
         if self.debug:
             if newfile is not None:
-                print 'shlex: pushing to file %s' % (self.infile,)
+                print('shlex: pushing to file %s' % (self.infile,))
             else:
-                print 'shlex: pushing to stream %s' % (self.instream,)
+                print('shlex: pushing to stream %s' % (self.instream,))
 
     def pop_source(self):
         "Pop the input source stack."
         self.instream.close()
         (self.infile, self.instream, self.lineno) = self.filestack.popleft()
         if self.debug:
-            print 'shlex: popping to %s, line %d' \
-                  % (self.instream, self.lineno)
+            print('shlex: popping to %s, line %d' \
+                  % (self.instream, self.lineno))
         self.state = ' '
 
     def get_token(self):
@@ -90,7 +90,7 @@ class shlex:
         if self.pushback:
             tok = self.pushback.popleft()
             if self.debug >= 1:
-                print "shlex: popping token " + repr(tok)
+                print("shlex: popping token " + repr(tok))
             return tok
         # No pushback.  Get a token.
         raw = self.read_token()
@@ -112,9 +112,9 @@ class shlex:
         # Neither inclusion nor EOF
         if self.debug >= 1:
             if raw != self.eof:
-                print "shlex: token=" + repr(raw)
+                print("shlex: token=" + repr(raw))
             else:
-                print "shlex: token=EOF"
+                print("shlex: token=EOF")
         return raw
 
     def read_token(self):
@@ -125,8 +125,8 @@ class shlex:
             if nextchar == '\n':
                 self.lineno = self.lineno + 1
             if self.debug >= 3:
-                print "shlex: in state", repr(self.state), \
-                      "I see character:", repr(nextchar)
+                print("shlex: in state", repr(self.state), \
+                      "I see character:", repr(nextchar))
             if self.state is None:
                 self.token = ''        # past end of file
                 break
@@ -136,7 +136,7 @@ class shlex:
                     break
                 elif nextchar in self.whitespace:
                     if self.debug >= 2:
-                        print "shlex: I see whitespace in whitespace state"
+                        print("shlex: I see whitespace in whitespace state")
                     if self.token or (self.posix and quoted):
                         break   # emit current token
                     else:
@@ -167,7 +167,7 @@ class shlex:
                 quoted = True
                 if not nextchar:      # end of file
                     if self.debug >= 2:
-                        print "shlex: I see EOF in quotes state"
+                        print("shlex: I see EOF in quotes state")
                     # XXX what error should be raised here?
                     raise ValueError, "No closing quotation"
                 if nextchar == self.state:
@@ -186,7 +186,7 @@ class shlex:
             elif self.state in self.escape:
                 if not nextchar:      # end of file
                     if self.debug >= 2:
-                        print "shlex: I see EOF in escape state"
+                        print("shlex: I see EOF in escape state")
                     # XXX what error should be raised here?
                     raise ValueError, "No escaped character"
                 # In posix shells, only the quote itself or the escape
@@ -202,7 +202,7 @@ class shlex:
                     break
                 elif nextchar in self.whitespace:
                     if self.debug >= 2:
-                        print "shlex: I see whitespace in word state"
+                        print("shlex: I see whitespace in word state")
                     self.state = ' '
                     if self.token or (self.posix and quoted):
                         break   # emit current token
@@ -228,7 +228,7 @@ class shlex:
                 else:
                     self.pushback.appendleft(nextchar)
                     if self.debug >= 2:
-                        print "shlex: I see punctuation in word state"
+                        print("shlex: I see punctuation in word state")
                     self.state = ' '
                     if self.token:
                         break   # emit current token
@@ -240,9 +240,9 @@ class shlex:
             result = None
         if self.debug > 1:
             if result:
-                print "shlex: raw token=" + repr(result)
+                print("shlex: raw token=" + repr(result))
             else:
-                print "shlex: raw token=EOF"
+                print("shlex: raw token=EOF")
         return result
 
     def sourcehook(self, newfile):
@@ -287,6 +287,6 @@ if __name__ == '__main__':
     while 1:
         tt = lexer.get_token()
         if tt:
-            print "Token: " + repr(tt)
+            print("Token: " + repr(tt))
         else:
             break
index 5b03b5e802fe52efc3578f5ee71fc23e7bec1d61..95001ba314477ff2f4c4cd63217f6301838774e1 100644 (file)
@@ -301,7 +301,7 @@ class _Printer(object):
         while 1:
             try:
                 for i in range(lineno, lineno + self.MAXLINES):
-                    print self.__lines[i]
+                    print(self.__lines[i])
             except IndexError:
                 break
             else:
@@ -424,10 +424,10 @@ def main():
 main()
 
 def _test():
-    print "sys.path = ["
+    print("sys.path = [")
     for dir in sys.path:
-        print "    %r," % (dir,)
-    print "]"
+        print("    %r," % (dir,))
+    print("]")
 
 if __name__ == '__main__':
     _test()
index 3b818564c0d9c483b23e210557c7aabffa94755f..73e7777fa001b98407ebb40bbfb140223fb365d8 100755 (executable)
@@ -98,9 +98,9 @@ COMMASPACE = ', '
 
 \f
 def usage(code, msg=''):
-    print >> sys.stderr, __doc__ % globals()
+    print(__doc__ % globals(), file=sys.stderr)
     if msg:
-        print >> sys.stderr, msg
+        print(msg, file=sys.stderr)
     sys.exit(code)
 
 
@@ -122,7 +122,7 @@ class SMTPChannel(asynchat.async_chat):
         self.__data = ''
         self.__fqdn = socket.getfqdn()
         self.__peer = conn.getpeername()
-        print >> DEBUGSTREAM, 'Peer:', repr(self.__peer)
+        print('Peer:', repr(self.__peer), file=DEBUGSTREAM)
         self.push('220 %s %s' % (self.__fqdn, __version__))
         self.set_terminator('\r\n')
 
@@ -137,7 +137,7 @@ class SMTPChannel(asynchat.async_chat):
     # Implementation of base class abstract method
     def found_terminator(self):
         line = EMPTYSTRING.join(self.__line)
-        print >> DEBUGSTREAM, 'Data:', repr(line)
+        print('Data:', repr(line), file=DEBUGSTREAM)
         self.__line = []
         if self.__state == self.COMMAND:
             if not line:
@@ -220,7 +220,7 @@ class SMTPChannel(asynchat.async_chat):
         return address
 
     def smtp_MAIL(self, arg):
-        print >> DEBUGSTREAM, '===> MAIL', arg
+        print('===> MAIL', arg, file=DEBUGSTREAM)
         address = self.__getaddr('FROM:', arg)
         if not address:
             self.push('501 Syntax: MAIL FROM:<address>')
@@ -229,11 +229,11 @@ class SMTPChannel(asynchat.async_chat):
             self.push('503 Error: nested MAIL command')
             return
         self.__mailfrom = address
-        print >> DEBUGSTREAM, 'sender:', self.__mailfrom
+        print('sender:', self.__mailfrom, file=DEBUGSTREAM)
         self.push('250 Ok')
 
     def smtp_RCPT(self, arg):
-        print >> DEBUGSTREAM, '===> RCPT', arg
+        print('===> RCPT', arg, file=DEBUGSTREAM)
         if not self.__mailfrom:
             self.push('503 Error: need MAIL command')
             return
@@ -242,7 +242,7 @@ class SMTPChannel(asynchat.async_chat):
             self.push('501 Syntax: RCPT TO: <address>')
             return
         self.__rcpttos.append(address)
-        print >> DEBUGSTREAM, 'recips:', self.__rcpttos
+        print('recips:', self.__rcpttos, file=DEBUGSTREAM)
         self.push('250 Ok')
 
     def smtp_RSET(self, arg):
@@ -279,14 +279,13 @@ class SMTPServer(asyncore.dispatcher):
         self.set_reuse_addr()
         self.bind(localaddr)
         self.listen(5)
-        print >> DEBUGSTREAM, \
-              '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
+        print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
             self.__class__.__name__, time.ctime(time.time()),
-            localaddr, remoteaddr)
+            localaddr, remoteaddr), file=DEBUGSTREAM)
 
     def handle_accept(self):
         conn, addr = self.accept()
-        print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr)
+        print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM)
         channel = SMTPChannel(self, conn, addr)
 
     # API for "doing something useful with the message"
@@ -321,14 +320,14 @@ class DebuggingServer(SMTPServer):
     def process_message(self, peer, mailfrom, rcpttos, data):
         inheaders = 1
         lines = data.split('\n')
-        print '---------- MESSAGE FOLLOWS ----------'
+        print('---------- MESSAGE FOLLOWS ----------')
         for line in lines:
             # headers first
             if inheaders and not line:
-                print 'X-Peer:', peer[0]
+                print('X-Peer:', peer[0])
                 inheaders = 0
-            print line
-        print '------------ END MESSAGE ------------'
+            print(line)
+        print('------------ END MESSAGE ------------')
 
 
 \f
@@ -345,7 +344,7 @@ class PureProxy(SMTPServer):
         data = NEWLINE.join(lines)
         refused = self._deliver(mailfrom, rcpttos, data)
         # TBD: what to do with refused addresses?
-        print >> DEBUGSTREAM, 'we got some refusals:', refused
+        print('we got some refusals:', refused, file=DEBUGSTREAM)
 
     def _deliver(self, mailfrom, rcpttos, data):
         import smtplib
@@ -358,10 +357,10 @@ class PureProxy(SMTPServer):
             finally:
                 s.quit()
         except smtplib.SMTPRecipientsRefused as e:
-            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
+            print('got SMTPRecipientsRefused', file=DEBUGSTREAM)
             refused = e.recipients
         except (socket.error, smtplib.SMTPException) as e:
-            print >> DEBUGSTREAM, 'got', e.__class__
+            print('got', e.__class__, file=DEBUGSTREAM)
             # All recipients were refused.  If the exception had an associated
             # error code, use it.  Otherwise,fake it with a non-triggering
             # exception code.
@@ -410,11 +409,11 @@ class MailmanProxy(PureProxy):
         for rcpt, listname, command in listnames:
             rcpttos.remove(rcpt)
         # If there's any non-list destined recipients left,
-        print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos)
+        print('forwarding recips:', ' '.join(rcpttos), file=DEBUGSTREAM)
         if rcpttos:
             refused = self._deliver(mailfrom, rcpttos, data)
             # TBD: what to do with refused addresses?
-            print >> DEBUGSTREAM, 'we got refusals:', refused
+            print('we got refusals:', refused, file=DEBUGSTREAM)
         # Now deliver directly to the list commands
         mlists = {}
         s = StringIO(data)
@@ -427,7 +426,7 @@ class MailmanProxy(PureProxy):
         if not msg.getheader('date'):
             msg['Date'] = time.ctime(time.time())
         for rcpt, listname, command in listnames:
-            print >> DEBUGSTREAM, 'sending message to', rcpt
+            print('sending message to', rcpt, file=DEBUGSTREAM)
             mlist = mlists.get(listname)
             if not mlist:
                 mlist = MailList.MailList(listname, lock=0)
@@ -472,7 +471,7 @@ def parseargs():
         if opt in ('-h', '--help'):
             usage(0)
         elif opt in ('-V', '--version'):
-            print >> sys.stderr, __version__
+            print(__version__, file=sys.stderr)
             sys.exit(0)
         elif opt in ('-n', '--nosetuid'):
             options.setuid = 0
@@ -522,16 +521,14 @@ if __name__ == '__main__':
         try:
             import pwd
         except ImportError:
-            print >> sys.stderr, \
-                  'Cannot import module "pwd"; try running with -n option.'
+            print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr)
             sys.exit(1)
         nobody = pwd.getpwnam('nobody')[2]
         try:
             os.setuid(nobody)
         except OSError as e:
             if e.errno != errno.EPERM: raise
-            print >> sys.stderr, \
-                  'Cannot setuid "nobody"; try running with -n option.'
+            print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr)
             sys.exit(1)
     classname = options.classname
     if "." in classname:
index 701306d66c3435610db6f85a4281838dbd2d2330..aedcac43bc4b3331f0372d38be7fdcb7135c43a5 100755 (executable)
@@ -277,7 +277,7 @@ class SMTP:
         # This makes it simpler for SMTP_SSL to use the SMTP connect code
         # and just alter the socket connection bit.
         self.sock = socket.socket(af, socktype, proto)
-        if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
+        if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
         self.sock.connect(sa)
 
     def connect(self, host='localhost', port = 0):
@@ -299,7 +299,7 @@ class SMTP:
                 except ValueError:
                     raise socket.error, "nonnumeric port"
         if not port: port = self.default_port
-        if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
+        if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
         msg = "getaddrinfo returns an empty list"
         self.sock = None
         for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
@@ -307,7 +307,7 @@ class SMTP:
             try:
                 self._get_socket(af,socktype,proto,sa)
             except socket.error as msg:
-                if self.debuglevel > 0: print>>stderr, 'connect fail:', msg
+                if self.debuglevel > 0: print('connect fail:', msg, file=stderr)
                 if self.sock:
                     self.sock.close()
                 self.sock = None
@@ -316,12 +316,12 @@ class SMTP:
         if not self.sock:
             raise socket.error, msg
         (code, msg) = self.getreply()
-        if self.debuglevel > 0: print>>stderr, "connect:", msg
+        if self.debuglevel > 0: print("connect:", msg, file=stderr)
         return (code, msg)
 
     def send(self, str):
         """Send `str' to the server."""
-        if self.debuglevel > 0: print>>stderr, 'send:', repr(str)
+        if self.debuglevel > 0: print('send:', repr(str), file=stderr)
         if self.sock:
             try:
                 self.sock.sendall(str)
@@ -360,7 +360,7 @@ class SMTP:
             if line == '':
                 self.close()
                 raise SMTPServerDisconnected("Connection unexpectedly closed")
-            if self.debuglevel > 0: print>>stderr, 'reply:', repr(line)
+            if self.debuglevel > 0: print('reply:', repr(line), file=stderr)
             resp.append(line[4:].strip())
             code=line[:3]
             # Check that the error code is syntactically correct.
@@ -376,7 +376,7 @@ class SMTP:
 
         errmsg = "\n".join(resp)
         if self.debuglevel > 0:
-            print>>stderr, 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
+            print('reply: retcode (%s); Msg: %s' % (errcode,errmsg), file=stderr)
         return errcode, errmsg
 
     def docmd(self, cmd, args=""):
@@ -489,7 +489,7 @@ class SMTP:
         """
         self.putcmd("data")
         (code,repl)=self.getreply()
-        if self.debuglevel >0 : print>>stderr, "data:", (code,repl)
+        if self.debuglevel >0 : print("data:", (code,repl), file=stderr)
         if code != 354:
             raise SMTPDataError(code,repl)
         else:
@@ -499,7 +499,7 @@ class SMTP:
             q = q + "." + CRLF
             self.send(q)
             (code,msg)=self.getreply()
-            if self.debuglevel >0 : print>>stderr, "data:", (code,msg)
+            if self.debuglevel >0 : print("data:", (code,msg), file=stderr)
             return (code,msg)
 
     def verify(self, address):
@@ -740,7 +740,7 @@ class SMTP_SSL(SMTP):
 
     def _get_socket(self,af, socktype, proto,sa):
         self.sock = socket.socket(af, socktype, proto)
-        if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
+        if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
         self.sock.connect(sa)
         sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
         self.sock = SSLFakeSocket(self.sock, sslobj)
@@ -757,14 +757,14 @@ if __name__ == '__main__':
 
     fromaddr = prompt("From")
     toaddrs  = prompt("To").split(',')
-    print "Enter message, end with ^D:"
+    print("Enter message, end with ^D:")
     msg = ''
     while 1:
         line = sys.stdin.readline()
         if not line:
             break
         msg = msg + line
-    print "Message length is %d" % len(msg)
+    print("Message length is %d" % len(msg))
 
     server = SMTP('localhost')
     server.set_debuglevel(1)
index df2ccf17ba4b99510329549bf147ac68f65e4fd4..f505804c69aa2e2d35b6ac0726bea568aaa50b05 100644 (file)
@@ -208,21 +208,21 @@ def testall(list, recursive, toplevel):
     import os
     for filename in list:
         if os.path.isdir(filename):
-            print filename + '/:',
+            print(filename + '/:', end=' ')
             if recursive or toplevel:
-                print 'recursing down:'
+                print('recursing down:')
                 import glob
                 names = glob.glob(os.path.join(filename, '*'))
                 testall(names, recursive, 0)
             else:
-                print '*** directory (use -r) ***'
+                print('*** directory (use -r) ***')
         else:
-            print filename + ':',
+            print(filename + ':', end=' ')
             sys.stdout.flush()
             try:
-                print what(filename)
+                print(what(filename))
             except IOError:
-                print '*** not found ***'
+                print('*** not found ***')
 
 if __name__ == '__main__':
     test()
index 6fe93abe6ce6885e72faebb396078ff2c7b22e73..287848a438e70d17a9cc0031cb23a1829dd446a1 100644 (file)
@@ -327,7 +327,7 @@ class CursorTests(unittest.TestCase):
         except TypeError:
             return
         except Exception as e:
-            print "raised", e.__class__
+            print("raised", e.__class__)
             self.fail("raised wrong exception.")
 
     def CheckFetchIter(self):
index 1863f48bb16fcea1963be0f4bba092006865b7dd..94962cbc39b1fe6dedf34dcd08dec5c6b5d6998c 100644 (file)
@@ -258,4 +258,4 @@ if __name__ == "__main__":
     f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET)
 
     f.close()
-    print "done"
+    print("done")
index 2b3064b0ef87ba003d5be0b8d400d0589c462db0..49dc080ed40c80bb5773586e134140a3253c10e1 100644 (file)
@@ -103,30 +103,30 @@ class SubPattern:
         nl = 1
         seqtypes = type(()), type([])
         for op, av in self.data:
-            print level*"  " + op,; nl = 0
+            print(level*"  " + op, end=' '); nl = 0
             if op == "in":
                 # member sublanguage
-                print; nl = 1
+                print(); nl = 1
                 for op, a in av:
-                    print (level+1)*"  " + op, a
+                    print((level+1)*"  " + op, a)
             elif op == "branch":
-                print; nl = 1
+                print(); nl = 1
                 i = 0
                 for a in av[1]:
                     if i > 0:
-                        print level*"  " + "or"
+                        print(level*"  " + "or")
                     a.dump(level+1); nl = 1
                     i = i + 1
             elif type(av) in seqtypes:
                 for a in av:
                     if isinstance(a, SubPattern):
-                        if not nl: print
+                        if not nl: print()
                         a.dump(level+1); nl = 1
                     else:
-                        print a, ; nl = 0
+                        print(a, end=' ') ; nl = 0
             else:
-                print av, ; nl = 0
-            if not nl: print
+                print(av, end=' ') ; nl = 0
+            if not nl: print()
     def __repr__(self):
         return repr(self.data)
     def __len__(self):
index 1b4ef89c155832012565d132bd6893ce8cb3c5ba..759b59f13baa1b617e29e2e191795fb2b8194eb0 100644 (file)
@@ -1165,8 +1165,8 @@ def _demo_posix():
     # Example 1: Simple redirection: Get process list
     #
     plist = Popen(["ps"], stdout=PIPE).communicate()[0]
-    print "Process list:"
-    print plist
+    print("Process list:")
+    print(plist)
 
     #
     # Example 2: Change uid before executing child
@@ -1178,42 +1178,42 @@ def _demo_posix():
     #
     # Example 3: Connecting several subprocesses
     #
-    print "Looking for 'hda'..."
+    print("Looking for 'hda'...")
     p1 = Popen(["dmesg"], stdout=PIPE)
     p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
-    print repr(p2.communicate()[0])
+    print(repr(p2.communicate()[0]))
 
     #
     # Example 4: Catch execution error
     #
-    print
-    print "Trying a weird file..."
+    print()
+    print("Trying a weird file...")
     try:
-        print Popen(["/this/path/does/not/exist"]).communicate()
+        print(Popen(["/this/path/does/not/exist"]).communicate())
     except OSError as e:
         if e.errno == errno.ENOENT:
-            print "The file didn't exist.  I thought so..."
-            print "Child traceback:"
-            print e.child_traceback
+            print("The file didn't exist.  I thought so...")
+            print("Child traceback:")
+            print(e.child_traceback)
         else:
-            print "Error", e.errno
+            print("Error", e.errno)
     else:
-        print >>sys.stderr, "Gosh.  No error."
+        print("Gosh.  No error.", file=sys.stderr)
 
 
 def _demo_windows():
     #
     # Example 1: Connecting several subprocesses
     #
-    print "Looking for 'PROMPT' in set output..."
+    print("Looking for 'PROMPT' in set output...")
     p1 = Popen("set", stdout=PIPE, shell=True)
     p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
-    print repr(p2.communicate()[0])
+    print(repr(p2.communicate()[0]))
 
     #
     # Example 2: Simple execution of program
     #
-    print "Executing calc..."
+    print("Executing calc...")
     p = Popen("calc")
     p.wait()
 
index 3b0ee2793c126b1008a0cd960f9e459937166d0a..05bd867281c2fe0ee8c3214e91ddd00aabc7938b 100644 (file)
@@ -36,9 +36,9 @@ def printhdr(file):
     data_size, encoding, sample_rate, channels, info = hdr
     while info[-1:] == '\0':
         info = info[:-1]
-    print 'File name:  ', file
-    print 'Data size:  ', data_size
-    print 'Encoding:   ', encoding
-    print 'Sample rate:', sample_rate
-    print 'Channels:   ', channels
-    print 'Info:       ', repr(info)
+    print('File name:  ', file)
+    print('Data size:  ', data_size)
+    print('Encoding:   ', encoding)
+    print('Sample rate:', sample_rate)
+    print('Channels:   ', channels)
+    print('Info:       ', repr(info))
index 399faa12086f7a904684cfd2631c631643babf27..d18d30b816ff9665c15000fe4c04d7c04cb3e8c0 100644 (file)
@@ -249,4 +249,4 @@ if __name__ == "__main__":
     mod = symtable(src, os.path.split(sys.argv[0])[1], "exec")
     for ident in mod.get_identifiers():
         info = mod.lookup(ident)
-        print info, info.is_local(), info.is_namespace()
+        print(info, info.is_local(), info.is_namespace())
index 1d2c6db2bc93c479b4b9056fb24474d3d96ef754..0ae5e9f0df2f8966eb4f7620656cf95258822c76 100755 (executable)
@@ -83,7 +83,7 @@ def check(file):
 
     if os.path.isdir(file) and not os.path.islink(file):
         if verbose:
-            print "%r: listing directory" % (file,)
+            print("%r: listing directory" % (file,))
         names = os.listdir(file)
         for name in names:
             fullname = os.path.join(file, name)
@@ -100,7 +100,7 @@ def check(file):
         return
 
     if verbose > 1:
-        print "checking %r ..." % file
+        print("checking %r ..." % file)
 
     try:
         process_tokens(tokenize.generate_tokens(f.readline))
@@ -117,17 +117,17 @@ def check(file):
         badline = nag.get_lineno()
         line = nag.get_line()
         if verbose:
-            print "%r: *** Line %d: trouble in tab city! ***" % (file, badline)
-            print "offending line: %r" % (line,)
-            print nag.get_msg()
+            print("%r: *** Line %d: trouble in tab city! ***" % (file, badline))
+            print("offending line: %r" % (line,))
+            print(nag.get_msg())
         else:
             if ' ' in file: file = '"' + file + '"'
-            if filename_only: print file
-            else: print file, badline, repr(line)
+            if filename_only: print(file)
+            else: print(file, badline, repr(line))
         return
 
     if verbose:
-        print "%r: Clean bill of health." % (file,)
+        print("%r: Clean bill of health." % (file,))
 
 class Whitespace:
     # the characters used for space and tab
index 1685426fbfc8c793a5ad9af68e8bc9df43688155..feea433703f5f9df4b7ca13e426004525398751c 100644 (file)
@@ -1408,25 +1408,25 @@ class TarFile(object):
 
         for tarinfo in self:
             if verbose:
-                print filemode(tarinfo.mode),
-                print "%s/%s" % (tarinfo.uname or tarinfo.uid,
-                                 tarinfo.gname or tarinfo.gid),
+                print(filemode(tarinfo.mode), end=' ')
+                print("%s/%s" % (tarinfo.uname or tarinfo.uid,
+                                 tarinfo.gname or tarinfo.gid), end=' ')
                 if tarinfo.ischr() or tarinfo.isblk():
-                    print "%10s" % ("%d,%d" \
-                                    % (tarinfo.devmajor, tarinfo.devminor)),
+                    print("%10s" % ("%d,%d" \
+                                    % (tarinfo.devmajor, tarinfo.devminor)), end=' ')
                 else:
-                    print "%10d" % tarinfo.size,
-                print "%d-%02d-%02d %02d:%02d:%02d" \
-                      % time.localtime(tarinfo.mtime)[:6],
+                    print("%10d" % tarinfo.size, end=' ')
+                print("%d-%02d-%02d %02d:%02d:%02d" \
+                      % time.localtime(tarinfo.mtime)[:6], end=' ')
 
-            print tarinfo.name,
+            print(tarinfo.name, end=' ')
 
             if verbose:
                 if tarinfo.issym():
-                    print "->", tarinfo.linkname,
+                    print("->", tarinfo.linkname, end=' ')
                 if tarinfo.islnk():
-                    print "link to", tarinfo.linkname,
-            print
+                    print("link to", tarinfo.linkname, end=' ')
+            print()
 
     def add(self, name, arcname=None, recursive=True):
         """Add the file `name' to the archive. `name' may be any type of file
@@ -2022,7 +2022,7 @@ class TarFile(object):
         """Write debugging output to sys.stderr.
         """
         if level <= self.debug:
-            print >> sys.stderr, msg
+            print(msg, file=sys.stderr)
 # class TarFile
 
 class TarIter:
index 4964d590939c2cb8ecd42d5162bae8ed7b210642..f482abf37c2601029650df387db180bf261e49c9 100644 (file)
@@ -248,11 +248,11 @@ class Telnet:
 
         """
         if self.debuglevel > 0:
-            print 'Telnet(%s,%d):' % (self.host, self.port),
+            print('Telnet(%s,%d):' % (self.host, self.port), end=' ')
             if args:
-                print msg % args
+                print(msg % args)
             else:
-                print msg
+                print(msg)
 
     def set_debuglevel(self, debuglevel):
         """Set the debug level.
@@ -545,7 +545,7 @@ class Telnet:
                 try:
                     text = self.read_eager()
                 except EOFError:
-                    print '*** Connection closed by remote host ***'
+                    print('*** Connection closed by remote host ***')
                     break
                 if text:
                     sys.stdout.write(text)
@@ -572,7 +572,7 @@ class Telnet:
             try:
                 data = self.read_eager()
             except EOFError:
-                print '*** Connection closed by remote host ***'
+                print('*** Connection closed by remote host ***')
                 return
             if data:
                 sys.stdout.write(data)
index c167b0933df751a8d34e65639ee9f7092b9b831e..ca45289e2e5a4fd5c0a23bc3b4f9da23c95bff86 100644 (file)
@@ -7,4 +7,4 @@ def f(x):
         return x + y
     return g
 
-print f(2)(4)
+print(f(2)(4))
index cdce32a4ebbd54a858b486c61e69f7fc701662fa..916de06ab71e975edbd99cd90a98765a0cedaa05 100644 (file)
@@ -7,4 +7,4 @@ def f(x):
         return x + y
     return g
 
-print f(2)(4)
+print(f(2)(4))
index 4bfc7300d53c113983505cf344258b69beb6d6c6..7f006d9edeb368e4fa555782d76e77a4f61aa890 100644 (file)
@@ -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:
index d16ede2e461c2251418b73262509a90daabf16fd..b82f4644bf960a82849235d2e8931ff1fa839f0d 100644 (file)
@@ -8,7 +8,7 @@ class A(object):
 
 class B(object):
     def __del__(self):
-        print 'hi'
+        print('hi')
         del D.__missing__
 
 class D(dict):
index 1a7b3ff7504dd3d1c816825e3bdb2f033024226c..f3ca35016da08a1b47d4df2571b322af4f12414f 100644 (file)
@@ -10,7 +10,7 @@ class A(object):
 
 class B(object):
     def __del__(self):
-        print "hi"
+        print("hi")
         del C.d
 
 class D(object):
index 10caa797825728036c72b1ff203a683a9f6d7607..ae85f97a74adc93979c592f2ef940d438dc059d6 100644 (file)
@@ -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())
index f0b8047d8d1972f0514fad39bbab75fbe2eda4eb..5ecde638208b4efd7bd71a4718a755030d80b690 100644 (file)
@@ -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.
index dfce467c8e1556c485607e483f3f3dab0fd05d72..2a8fce04b5dc177650698a8cfb92208624bf61e1 100644 (file)
@@ -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
index 3f3083da89dc211f19608a3ddf45897f9aafd716..85f7cafa238e1ba54529f9bfb3eade5490f49e7a 100644 (file)
@@ -44,4 +44,4 @@ dict = {y: "OK!"}
 
 z = Yuck()
 y.make_dangerous()
-print dict[z]
+print(dict[z])
index 3d978cffe3d38c088e6c4d194909a2001700cee1..ef70c090409d117c0e0ba1948d29bb766b483344 100644 (file)
@@ -7,7 +7,7 @@ def wrap(foo=None):
 # line 7
 def replace(func):
     def insteadfunc():
-        print 'hello'
+        print('hello')
     return insteadfunc
 
 # line 13
index 3867be5ff4dd4ba18be583f5e229b1ef9fadd580..507506ec0daf8d2c623e55bd1451e528ead36932 100644 (file)
@@ -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))
index becdf2250e8aabe37aabc0c195b8dfe5fe68b872..0ae013b119a482a698c9bda9b145bc9ea19d911a 100644 (file)
@@ -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')
index 0a25981eb68cbd6d8d3be1cce126175f835234c4..3ddb9465afa3328795e0d037e7f16237483837c3 100755 (executable)
@@ -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:
index 4517c59e1aa2d4bc43da36cd64a97fd43788368e..2efd3916220b8c3e109165a6e657ea17d4e8d10a 100755 (executable)
@@ -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()
index 68ac40f13281631e45e95f68dbd16d155b2a02cd..7c6823471ea2c5c57213b9a031c23e37eae490c2 100644 (file)
@@ -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()
index 3c95b891825ec7ab73d019ca74de27e9807cc1b0..205ff87098057b6e35e609ad256a453709ef860a 100644 (file)
@@ -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.
index 02876f0b38c2a1d16d0d1460e6d82733ddb3842c..e97ca65492d623d683bbc7b5a3a7dedd94de253d 100755 (executable)
@@ -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()
index 02215e5ab96e95e8b621ece2a2b04377f5f0b776..6abfb90d73875166a8ed0f067be41a7386b78018 100755 (executable)
@@ -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)
index 289b533f1a6e01fa0fbb73a997c4808effc2626d..24394ed925f424629cd892260a86a39d1dda83cc 100644 (file)
@@ -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):
index 684d6079c103927fd55ecf2ac1a0207ab9eafbd7..9d1e003bcd0e72b71565962810cedd3359fbdf89 100644 (file)
@@ -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
index f585733eacc9438ef6232e6873cd42ce4287feca..926a3cda848ad575f015a1ef839d5b2bd93b9e0b 100644 (file)
@@ -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()]
index 772e80836228686b74e3e7e557744e5e1dcb2ac4..1d62352f171ee7d788f6112644595a1b06a900ac 100644 (file)
@@ -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)
index 954423f1e9bf397f4ddbfb970266c4d38a48657a..1d9a60b61c8c070d330e303b260b64dbc968e4fb 100644 (file)
@@ -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')
index 91c1cca7a029bce11fbac9f268719370c7d5d76a..3b33c48b9cb20910999931a60469cfa6c98df8ad 100755 (executable)
@@ -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)
index 166ad03ab2a71620a126be5b3c00fab5d9d041bf..69e99c034c4ae49d82cc81573dfbef9609d340a9 100644 (file)
@@ -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')
index 56417a341d10001987ee08f0c9e1828f37ee4e7b..ab9dfc8cf050cb116fec524e69d57e0da79c5fd1 100644 (file)
@@ -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__":
index cdd84bb222e24fb3477fba28b891a3429395ba36..074f5815a89a013b427a09993a235566e3dde155 100644 (file)
@@ -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 = []
 
index d85621178a7a9bc490ddafde0a24311521b32581..217b38b5edee7cb0ae87ea861e491b582d1d0a09 100755 (executable)
@@ -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()
index abfe3c19f5785ed5845a083991dd4944649866b5..0df7f6f8e286d8252b0e0024d6d0d21f08688cbb 100755 (executable)
@@ -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()
index c450c808d3e91b18db1d51216afccbe18fe99e7a..221fd48dcfb63b5c6d3827b25a19e3ed600ea658 100644 (file)
@@ -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
index 6e392928c3c989b355a79509900f2548c0755a09..fd3a6bfcd71d881891241c3cd810372ed7f68a05 100755 (executable)
@@ -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))
index 6e0a1819c9c09d861d579f0e241ff3d521801aae..13ec254885e4575c652b88286544b23dd32fc982 100644 (file)
@@ -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
index 071192371464af4a3c2d5b777c0ae6a84a48b33e..44ce8eb79a79f28f5c70b1e3a54bdc70c3ba4b69 100644 (file)
@@ -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):
index 732036888dc5820f83dd510a78160fc63a4984d7..ab9a66045aff926048fada4f77c91be7d3999772 100644 (file)
@@ -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:
index afc7caee23970dc141d57c7d76d7aacd34babf3c..91f074b8cabe8f8630e23845c6e38481d472a574 100644 (file)
@@ -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))
index dfbcbdf2283dd886c155358a6e966f80c77af25a..7336711e5f77b3c6ae0060ae86ec755a8c135b38 100755 (executable)
@@ -8,4 +8,4 @@ import crypt
 
 c = crypt.crypt('mypassword', 'ab')
 if verbose:
-    print 'Test encryption: ', c
+    print('Test encryption: ', c)
index feb6ddf61398dca62be5360a0a458a232f0da892..46361c8254bf0e87308b881dfaa9d627dab8e209 100644 (file)
@@ -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):
index 4022149310f9a3048768022c1ad196134dfbca69..fd8e6edb39390fe02270cac61d2d4d9c4645072e 100644 (file)
@@ -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):
index b32017e52734dcbcf6f1538c56ab9e8eb94a8989..70b00a401da0f50b1626b18b557c053afa42d692 100644 (file)
@@ -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__":
index 0a9db4e244d79d4f7c8ed92b32818445e19ec6c5..a3b7716e23180c87b9cc78bc6ae6a1684b0d1786 100755 (executable)
@@ -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()
 
index 4a531224525ceb7a80d48326df29d0587c31b49b..c39a8e31b712ab5456e5dc33e55b8618a458548a 100644 (file)
@@ -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()
index 602e0d929f901f9574781df41d5583b00a04c386..03900de558c43d1cf4935625deb2ffc30b7b9caa 100644 (file)
@@ -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")
index a98339b78fcdbfffc20530d701a448acc461d0b3..9f7caec4e20fbd1cb486330c1ee9bfa4cdb49436 100644 (file)
@@ -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
index bcfadf77151547045e873b0258aa8b47cc9d0319..aab33314a436369babbc5cd1f1b1ea38cde1568b 100644 (file)
@@ -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()
index f9a6a07081c3df477c5e230692b554b8f9b20bcd..3916c32f9d91287947fd7a7dc585c11fa2f5e949 100644 (file)
@@ -8,7 +8,7 @@ import StringIO
 import unittest
 
 def _f(a):
-    print a
+    print(a)
     return 1
 
 dis_f = """\
index 9c704270704da6903ca6cf97562e72dd6fc8f451..ba5d8bd3d3411a2bde9a1be35d3fbdb114fb4ac4 100755 (executable)
@@ -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'
index 56c244988d51ae3a2e1f177ab51130f89f5dc048..ac9d00d6ae80e87fd6fe9ac59b995ff35e7e1174 100644 (file)
@@ -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)
 
index f274e0a0d0f6c8eea4f103be916acb4e6ec38804..288b6218c281404ce5a3ed1fedd59883f78a5e67 100644 (file)
@@ -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__':
index 3724f1e5a4ee27a761c32065dd6e016353cea192..90bf6e0ee91f1bae1d91b66502f3cf7b65b00ae9 100644 (file)
@@ -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')
 
 
 
index 4ee8680e8d42bc899358cc9552a8d038c29519a1..62900704606af8ebd60bcdba1cba500f9c44e695 100644 (file)
@@ -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)
index 6b02e25cf397bd3ce9355748ca58634c488a062f..25937dc6128bf46a3be9dfe1cb0ff2ee8bf54cdb 100755 (executable)
@@ -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))
index 11cf43afb9732b8aeb39a6a36a2fb087762a7709..e67b3f8f41b456d355e445e773e11b61dc59405d 100644 (file)
@@ -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)
index 2d800b2a5c9e5aa9b64f2413c8b1d7c1a8c30ad8..f544f1ff9888e84c8d035789b1158b957f2c7308 100755 (executable)
@@ -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)
index 52c4a02fd6a891a9a00d32462d617c52996da2cb..91f6e76c312431680b5a3661f910ee49962ef4f6 100644 (file)
@@ -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):
index 301769e4f568e4e7a37f4037e3ff43c8da3c3d59..2b7b255dae9a447f5eb6668535785adc03590ab2 100644 (file)
@@ -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)
index df78a320eebc46a171e0c1196f263b654ca8fa1e..658a3022069360e345544feb98b470d5a94e0b15 100644 (file)
@@ -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
index 930c85147e6bef73e7e950a9b46ff1febc729374..2f4b67abe027306be6c5e92091c3c85223544118 100644 (file)
@@ -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)
index 828331e649cc542d392ae0adf07da10e01665d11..2d5e33c54bded61810faf66bc6d0593ce4e9a052 100644 (file)
@@ -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)
index 675b988db9ea1fa4768b859dbf866e007e4098a7..8068b35c21d7fdacaca40548c45b5d50be30a012 100644 (file)
@@ -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())
index a68957633ae483d005632e18c8b752630ffdcb6d..ae76e39178fab51ddd611eb01c009201b1628487 100755 (executable)
@@ -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()
index a40d8ea9be3b87970af0d2991deeed9fac28671e..39d016c2cd6ab6b393c826e86284f0b53e11660b 100644 (file)
@@ -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 = """
 
index 2598a7913ad4e1a4a38e492b3f7b54cd46ade8d0..5fd9c7b949488f72778d0c2fff9cfc18e694fc88 100644 (file)
@@ -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)
index f565d2328a402bfb198b7b8c6c8ce7340437c1ae..10bd256494d431bdab226de7ee72e98804b801d2 100644 (file)
@@ -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.")
index c9cce7760769a466d32ef7c8604a6b0e31715062..adae10eb09b072de73936eebe189365690cc2c5b 100755 (executable)
@@ -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()
index 33bfd3269dfab3bde3a9ee77401722041e40208b..4a480aa14a5dc763d255cbe82f71eea5a0660d14 100644 (file)
@@ -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])
index b652d41fab83f4eb9b3c3ab9da0ef5129f34e3b4..934f7b66b143f8e890a130c23f1493b1f6160e72 100644 (file)
@@ -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)
index b01e83fa284d847833f9613f73600caf2c1c020f..d0794735fa15a396a6a5d416a847149ca3125e56 100755 (executable)
@@ -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])
index bdfd796b1e028904dce9266e7e54515a67090b4c..4e31cb1a98b32e355aaf4931bf8b5c2aa90df526 100755 (executable)
@@ -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)
index f3d1d49cf3a798af2d7a07d86fb2cbcc237f3fa1..a8f912fc8d9836c13110ae663453f05678b0ceab 100644 (file)
@@ -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)
index 0b9f165ea10dc007e7918b811dab2e6596a6b7d4..5a1d4a16318e3d6d345d23e5094482026c58105a 100644 (file)
@@ -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)
index d7ed1b3bcb9a85ec540aaba9a4f7331ca731e774..f4b51ffa7bd6b9493e5990553ec1e2f4a2ab3f05 100644 (file)
@@ -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)
index 05e404166246c1dc103cf7462f1f740fdfc37a02..eac204f71156321fbf8317c31217119192a57b39 100644 (file)
@@ -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'))
index 711ac4b75c91968b5391d9dcfee1acb8fb63159d..5d9983f454320bf8ae16ef532d6746f7deddcbcb 100644 (file)
@@ -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__":
index 9e264b9c4ee4389bc4c7dd08311d99c9c19167b9..ba7d653a4689406f7bdbaf0ec827d73d94917f44 100644 (file)
@@ -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':
index 3f137d6a12d69752c693e826405aed2ce43e297a..fc0100119e3020d4e425bf23bf7e3a08bc17c1ea 100644 (file)
@@ -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)
index a6d309f7d9abc98852344abd42a9a0a98a83b8b7..d0a99a7fb9f11a52f9cfab5b2d2f359eb94f7dfa 100644 (file)
@@ -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)
index 2b35a531afd5e7baae7d95fcec05f9824b69876a..7911a0eb981234bdef20c7f3cd4c3df846defa63 100644 (file)
@@ -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")
index fb7f82d18e41ef88f8cc3de933a5cfb85e56c2fa..2ac7061f697e8e3e5803e9417656eef834499e80 100644 (file)
@@ -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)
index 621522617ac9c5256312e484b6b812db0e715b9a..a710248ac8ecb9a3f9dc844ac7e646bf7f18f3ec 100644 (file)
@@ -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:
index 81bdfbd96c8646a059e9b9625ad614071e554664..d890067ea24cb2fa9e32d8aac7b6aeb92c8e2bf4 100644 (file)
@@ -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)
index 6bc2a054de5d2cb172976e9404ab1d009d3e0c4d..939886d159dade36c35fc373b54895bb1681d472 100644 (file)
@@ -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.")
index 8baef4cd8acb007263c7af01dc2f9319facaabdd..e8b1ae80f933cc234dcebcbcce3fd79dc91c7846 100644 (file)
@@ -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.')
index c71a4e62aa3b6e81990d491ffaaaf26c66528a1d..2183508bba8df07869b9cca7ef7ddba64493851c 100644 (file)
@@ -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)
index 0377e9c4ea21ab69bb650cedb2877adb18195040..e97e788d7b287766345a38e9d6ae19495fb9f838 100644 (file)
@@ -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'))
index 779a20a51250c27c678a0623e97e3c74b0aa5a4d..213edd2ccb0da40e6cefbe71abac274383a08073 100644 (file)
@@ -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)
index 88f246131b14fde306321d2d1e034e7102bc5511..cbd071bf691cd30ff4e3972efe6444f5d26e66b7 100644 (file)
@@ -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__':
index ff71bf2fbb269f7b5edc0cd8d6f3d98b58d52643..8efa50a7c391355a77c7bc3936beba24f883c703 100644 (file)
@@ -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)
index c3657428895ffe12eb9da786c2b06036340798aa..79c909882af3f4b2b3eb658b0b88d7a599338f74 100644 (file)
@@ -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
index 2d54eb008d00d7c8e8653aa891b8c353f473500c..008a67af8ff909dc272585a08e717e797911bc1e 100644 (file)
@@ -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()
index 02290be71b98ddfbdad4beea28b7c04be753d8ce..123c3f8173c80165ab27ea77c117899fd9d59ed8 100644 (file)
@@ -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
index a03daa9b4cd06957a0564cbde8128e848db84304..478083eb6c1d138ae78ff529cae2d2ae483649f2 100644 (file)
@@ -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.
index 73092c1ce2c53764cf6fa8b2b998e781aedb4a41..fed1a9cf9b5c8e972f99839a9407425190555524 100644 (file)
@@ -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:
index 66977e64f8312fade4c090ebdcc41df9bbafc807..ac382c14cfb33439cfe7ce8238aa122351f396ce 100644 (file)
@@ -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()
index 5a76b1e2cb0428cc5944ea637bfed8c805b61652..e4a279256aaf25052e880aa3181a8274df99080c 100644 (file)
@@ -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)
index dafd82e98a92a9d634512b39e242cf9f114f0508..bb97433f4012032d3dcdeff333d27755ac4d2f18 100644 (file)
@@ -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)
index d59e743e94bfd0e0ef4438528d02d627e953c3ef..91e694a279f99217c893a47d49a40cc0ff219510 100644 (file)
@@ -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:
index 650c02aa0f9a6adc32080ee88b3448a5908c6524..65a0f422fa41bcb4d0d8db7e23dddb4ac3fdfa17 100644 (file)
@@ -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:
index a37ee7b7cd8c095842010fc9ba4d9c4fb2b29218..e0fdabc913e5f452eac64fa338d3f2d7f8b4df3a 100644 (file)
@@ -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)
 
 
index d3939c06cf0e48f2671f160ddd761aec0331fb3d..5715d67d5493d4ee033631be746273dbb8d3a4c2 100644 (file)
@@ -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)))
index 777e85a18c432e3e960201c72e4579da440b7086..31e57e5209509edc56c588587e7f48b765e651f7 100644 (file)
@@ -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
 
index d341324094be15b0951ed1dbc45a46d17b3f5e65..fd766746f7baf3334028cba8318c58d25ddfd822 100644 (file)
@@ -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()
 
index 13d02bbc2654cffbb8d75d3ed9829c755ec0a31b..9093965b5688578eea15e1248ecbb71a52f5f5fc 100644 (file)
@@ -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.
index d379ab5c215f85401247e026bb48865b1c221fd7..6f32fcaa0bac668426a6049dd64186cc6932c216 100644 (file)
@@ -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)
index 5d308c5848f9710bf5cfa1f4813f2edc5e532ca8..b04effea28744cc07a610fdbc32de4fad66e4ae3 100644 (file)
@@ -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
index 202f2da2e745fef2dabfcf8d277bf83ccf7a5a5f..062be650f87962696b27e9973398a1094a6f41d5 100644 (file)
@@ -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',):
index 5405ba3fe9f7061f950c1ea9e16961162d8777b6..c0b4e8f3c3ebeb19157811723093c69ee675f536 100644 (file)
@@ -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')
index 031780adb8985da73031b9ed84a5bf628c79899e..ad3a817ec1c936350972cdf388a8737a55cdccf1 100644 (file)
@@ -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)
index 26bae1bb79c2643a866e0f2f95ff1dd9fe029a4d..c6db3dd00c45b7ec398c4b223ba03065ae6b8cf1 100755 (executable)
@@ -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] == ' ':
index e0f0971eac49971ce14b4286e13cddc35451011f..21cba890c23193084baf634aab19d90a02d9cab1 100644 (file)
@@ -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:
index f19467c7672ccfa16f23a7b3f2f3c822497a5d55..dcc21ac2b600a9797141ff5803176222d8e329e8 100644 (file)
@@ -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!).
index 0b37306a6236dcab88955b7896a5b4d61a5569b0..6cc52ea05b6e450b131995790cba81ad25bf0455 100644 (file)
@@ -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
 
 #=======================================================================
index c4c21fed00f312e3149dde069dafda62e15ad1a4..57057986c9a9b0776b1dd656bd8d23d6c6c798c5 100644 (file)
@@ -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)
index 602ad2af90146ce76fbb7ce38abd357999e4cac4..41a2b9099fef042aaecfa63215a0e8c2c1d542a5 100644 (file)
@@ -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()
index 974333b486109d3f1487d61cae1c3e5e799a5c4b..75d719dd068d9ea3886d6a540d71cf611bbc0833 100644 (file)
@@ -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)
 
index 8614ecb49c97f75fd9bd9f5736a10cba3ae3e7cd..95557c0ce16eca3aee8aea4522bb19da6a06385f 100644 (file)
@@ -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
index de6e888ca2b913694f783a702418529c93a17b5f..7d6a81813b5705a3443aec9ddd3cf261c8887b71 100644 (file)
@@ -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():
     """
index 42d1a4a197b805b31df2ed4a16822209f63f7232..7b5ac7d1b2ad87a4feb90878d03c34c539fef42d 100644 (file)
@@ -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
index 5c8a4e48583a62d1ad738307af962ade665afadc..1ccb2b29c61033c83205ad336fca8a78e045ac24 100644 (file)
@@ -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()
index 5c70df15f7769f3d181e3db91eecbff685e1174a..bb3338b450ea0d6795ac70adc2c98c4c5ed4cf34 100644 (file)
@@ -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:
index 25aa307abe84f6cca8a95c3072023d3a6ea217aa..a7fc60aa5d1c9c5eb05a131a03a18f217d69fb6a 100644 (file)
@@ -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()
index f1d1d1c7faa5057b2955ca3dbf99e355d18adb34..3e5f77d4c9b8625d7498712eca0fc132c0de0bb3 100644 (file)
@@ -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()
index 81bd7601f6aae322fcb349cd8b0b60d107bd8e14..08de67c490430352c762bb6c2be531e4d199980d 100644 (file)
@@ -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()
index 78adb42e19142e128342326ad8ce031ec0fb59a8..6df19c411cdbffcf2cfa9529bd5c73402c6cdfe7 100644 (file)
@@ -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
index 250f7910738e0587cef38e98efb70a00ded4efc9..75b5a82226de649f4c9249d9e8d3978c5cf55b26 100644 (file)
@@ -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
index 449cf39d7560b90f2d431929d4d4ef9fa9c741d5..445e23d52d2ef4e7e2b39f143b75652b1c2e110c 100644 (file)
@@ -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()
 
index de25cfd3919f0ab61a5d75159f5e9c25db052209..c210bd22aa10e306bf4a8207f404fadf4c1abc9f 100644 (file)
@@ -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()
index ccff2aba1287b61ca96918c8be631f6f0305ddbf..0917d759b706598143e67b19d8fc0de3e97c574d 100644 (file)
@@ -371,4 +371,4 @@ def dedent(text):
 if __name__ == "__main__":
     #print dedent("\tfoo\n\tbar")
     #print dedent("  \thello there\n  \t  how are you?")
-    print dedent("Hello there.\n  This is indented.")
+    print(dedent("Hello there.\n  This is indented."))
index 37754b785ab17820732e8ce0b0f0c543ef075b12..e68dd3ff39b04ff857420b98889bee590b344024 100644 (file)
@@ -25,4 +25,4 @@ for c in (65, 97):
     for i in range(26):
         d[chr(i+c)] = chr((i+13) % 26 + c)
 
-print "".join([d.get(c, c) for c in s])
+print("".join([d.get(c, c) for c in s]))
index fecd3cc3041a2c0c405f09dfea9acac30b66b190..e23007e92fde05ca4cbe4c46673cc0e6f07f7410 100644 (file)
@@ -477,19 +477,19 @@ class Thread(_Verbose):
                     # Lib/traceback.py)
                     exc_type, exc_value, exc_tb = self.__exc_info()
                     try:
-                        print>>self.__stderr, (
+                        print((
                             "Exception in thread " + self.getName() +
-                            " (most likely raised during interpreter shutdown):")
-                        print>>self.__stderr, (
-                            "Traceback (most recent call last):")
+                            " (most likely raised during interpreter shutdown):"), file=self.__stderr)
+                        print((
+                            "Traceback (most recent call last):"), file=self.__stderr)
                         while exc_tb:
-                            print>>self.__stderr, (
+                            print((
                                 '  File "%s", line %s, in %s' %
                                 (exc_tb.tb_frame.f_code.co_filename,
                                     exc_tb.tb_lineno,
-                                    exc_tb.tb_frame.f_code.co_name))
+                                    exc_tb.tb_frame.f_code.co_name)), file=self.__stderr)
                             exc_tb = exc_tb.tb_next
-                        print>>self.__stderr, ("%s: %s" % (exc_type, exc_value))
+                        print(("%s: %s" % (exc_type, exc_value)), file=self.__stderr)
                     # Make sure that exc_tb gets deleted since it is a memory
                     # hog; deleting everything else is just for thoroughness
                     finally:
@@ -790,7 +790,7 @@ def _test():
         def run(self):
             while self.count > 0:
                 item = self.queue.get()
-                print item
+                print(item)
                 self.count = self.count - 1
 
     NP = 3
index 5dd3ca9249b52fcdd5acbf4c7885d8fe8378c864..e760c6235337e47986ce5b1028d202c725188af3 100644 (file)
@@ -210,8 +210,8 @@ def main(args=None):
                                    ["number=", "setup=", "repeat=",
                                     "time", "clock", "verbose", "help"])
     except getopt.error as err:
-        print err
-        print "use -h/--help for command line help"
+        print(err)
+        print("use -h/--help for command line help")
         return 2
     timer = default_timer
     stmt = "\n".join(args) or "pass"
@@ -238,7 +238,7 @@ def main(args=None):
                 precision += 1
             verbose += 1
         if o in ("-h", "--help"):
-            print __doc__,
+            print(__doc__, end=' ')
             return 0
     setup = "\n".join(setup) or "pass"
     # Include the current directory, so that local imports work (sys.path
@@ -257,7 +257,7 @@ def main(args=None):
                 t.print_exc()
                 return 1
             if verbose:
-                print "%d loops -> %.*g secs" % (number, precision, x)
+                print("%d loops -> %.*g secs" % (number, precision, x))
             if x >= 0.2:
                 break
     try:
@@ -267,18 +267,18 @@ def main(args=None):
         return 1
     best = min(r)
     if verbose:
-        print "raw times:", " ".join(["%.*g" % (precision, x) for x in r])
-    print "%d loops," % number,
+        print("raw times:", " ".join(["%.*g" % (precision, x) for x in r]))
+    print("%d loops," % number, end=' ')
     usec = best * 1e6 / number
     if usec < 1000:
-        print "best of %d: %.*g usec per loop" % (repeat, precision, usec)
+        print("best of %d: %.*g usec per loop" % (repeat, precision, usec))
     else:
         msec = usec / 1000
         if msec < 1000:
-            print "best of %d: %.*g msec per loop" % (repeat, precision, msec)
+            print("best of %d: %.*g msec per loop" % (repeat, precision, msec))
         else:
             sec = msec / 1000
-            print "best of %d: %.*g sec per loop" % (repeat, precision, sec)
+            print("best of %d: %.*g sec per loop" % (repeat, precision, sec))
     return None
 
 if __name__ == "__main__":
index 152bfdb85bfcc4db73c7667c964d654f56d7bac5..e502da96bc831c99a308a83a32fa944f0ad0f3b3 100644 (file)
@@ -133,8 +133,8 @@ class TokenError(Exception): pass
 class StopTokenizing(Exception): pass
 
 def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing
-    print "%d,%d-%d,%d:\t%s\t%s" % \
-        (srow, scol, erow, ecol, tok_name[type], repr(token))
+    print("%d,%d-%d,%d:\t%s\t%s" % \
+        (srow, scol, erow, ecol, tok_name[type], repr(token)))
 
 def tokenize(readline, tokeneater=printtoken):
     """
index ca44eae9272c241a7b26b9a5f39d3737b30db2ea..b2ec557461121bc74bb78d3873abd80253c3c3a4 100644 (file)
@@ -221,8 +221,8 @@ class CoverageResults:
                         pickle.load(open(self.infile, 'rb'))
                 self.update(self.__class__(counts, calledfuncs, callers))
             except (IOError, EOFError, ValueError) as err:
-                print >> sys.stderr, ("Skipping counts file %r: %s"
-                                      % (self.infile, err))
+                print(("Skipping counts file %r: %s"
+                                      % (self.infile, err)), file=sys.stderr)
 
     def update(self, other):
         """Merge in the data from another CoverageResults"""
@@ -247,30 +247,30 @@ class CoverageResults:
         @param coverdir
         """
         if self.calledfuncs:
-            print
-            print "functions called:"
+            print()
+            print("functions called:")
             calls = self.calledfuncs.keys()
             calls.sort()
             for filename, modulename, funcname in calls:
-                print ("filename: %s, modulename: %s, funcname: %s"
-                       % (filename, modulename, funcname))
+                print(("filename: %s, modulename: %s, funcname: %s"
+                       % (filename, modulename, funcname)))
 
         if self.callers:
-            print
-            print "calling relationships:"
+            print()
+            print("calling relationships:")
             calls = self.callers.keys()
             calls.sort()
             lastfile = lastcfile = ""
             for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls:
                 if pfile != lastfile:
-                    print
-                    print "***", pfile, "***"
+                    print()
+                    print("***", pfile, "***")
                     lastfile = pfile
                     lastcfile = ""
                 if cfile != pfile and lastcfile != cfile:
-                    print "  -->", cfile
+                    print("  -->", cfile)
                     lastcfile = cfile
-                print "    %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)
+                print("    %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc))
 
         # turn the counts data ("(filename, lineno) = count") into something
         # accessible on a per-file basis
@@ -318,10 +318,10 @@ class CoverageResults:
         if summary and sums:
             mods = sums.keys()
             mods.sort()
-            print "lines   cov%   module   (path)"
+            print("lines   cov%   module   (path)")
             for m in mods:
                 n_lines, percent, modulename, filename = sums[m]
-                print "%5d   %3d%%   %s   (%s)" % sums[m]
+                print("%5d   %3d%%   %s   (%s)" % sums[m])
 
         if self.outfile:
             # try and store counts and module info into self.outfile
@@ -329,7 +329,7 @@ class CoverageResults:
                 pickle.dump((self.counts, self.calledfuncs, self.callers),
                             open(self.outfile, 'wb'), 1)
             except IOError as err:
-                print >> sys.stderr, "Can't save counts files because %s" % err
+                print("Can't save counts files because %s" % err, file=sys.stderr)
 
     def write_results_file(self, path, lines, lnotab, lines_hit):
         """Return a coverage results file in path."""
@@ -337,8 +337,8 @@ class CoverageResults:
         try:
             outfile = open(path, "w")
         except IOError as err:
-            print >> sys.stderr, ("trace: Could not open %r for writing: %s"
-                                  "- skipping" % (path, err))
+            print(("trace: Could not open %r for writing: %s"
+                                  "- skipping" % (path, err)), file=sys.stderr)
             return 0, 0
 
         n_lines = 0
@@ -423,8 +423,8 @@ def find_executable_linenos(filename):
     try:
         prog = open(filename, "rU").read()
     except IOError as err:
-        print >> sys.stderr, ("Not printing coverage data for %r: %s"
-                              % (filename, err))
+        print(("Not printing coverage data for %r: %s"
+                              % (filename, err)), file=sys.stderr)
         return {}
     code = compile(prog, filename, "exec")
     strs = find_strings(filename)
@@ -596,8 +596,8 @@ class Trace:
                     ignore_it = self.ignore.names(filename, modulename)
                     if not ignore_it:
                         if self.trace:
-                            print (" --- modulename: %s, funcname: %s"
-                                   % (modulename, code.co_name))
+                            print((" --- modulename: %s, funcname: %s"
+                                   % (modulename, code.co_name)))
                         return self.localtrace
             else:
                 return None
@@ -611,8 +611,8 @@ class Trace:
             self.counts[key] = self.counts.get(key, 0) + 1
 
             bname = os.path.basename(filename)
-            print "%s(%d): %s" % (bname, lineno,
-                                  linecache.getline(filename, lineno)),
+            print("%s(%d): %s" % (bname, lineno,
+                                  linecache.getline(filename, lineno)), end=' ')
         return self.localtrace
 
     def localtrace_trace(self, frame, why, arg):
@@ -622,8 +622,8 @@ class Trace:
             lineno = frame.f_lineno
 
             bname = os.path.basename(filename)
-            print "%s(%d): %s" % (bname, lineno,
-                                  linecache.getline(filename, lineno)),
+            print("%s(%d): %s" % (bname, lineno,
+                                  linecache.getline(filename, lineno)), end=' ')
         return self.localtrace
 
     def localtrace_count(self, frame, why, arg):
index 9163e84cd56d2101fd4e19ebed192ed0a6ebadb7..cde310f8a782fde15bb656a1ff61793bfb3bbc43 100644 (file)
@@ -759,8 +759,8 @@ Examples:
         self.runTests()
 
     def usageExit(self, msg=None):
-        if msg: print msg
-        print self.USAGE % self.__dict__
+        if msg: print(msg)
+        print(self.USAGE % self.__dict__)
         sys.exit(2)
 
     def parseArgs(self, argv):
index bb9472bbe0b4642e94bf1554cd68976fb9024d71..d2ae1becf0c2e3210056186be2cd16df5fa75fbb 100644 (file)
@@ -777,7 +777,7 @@ class FancyURLopener(URLopener):
                 (user, realm, host))
             return user, passwd
         except KeyboardInterrupt:
-            print
+            print()
             return None, None
 
 
@@ -1453,17 +1453,17 @@ def test1():
     uqs = unquote(qs)
     t1 = time.time()
     if uqs != s:
-        print 'Wrong!'
-    print repr(s)
-    print repr(qs)
-    print repr(uqs)
-    print round(t1 - t0, 3), 'sec'
+        print('Wrong!')
+    print(repr(s))
+    print(repr(qs))
+    print(repr(uqs))
+    print(round(t1 - t0, 3), 'sec')
 
 
 def reporthook(blocknum, blocksize, totalsize):
     # Report during remote transfers
-    print "Block number: %d, Block size: %d, Total size: %d" % (
-        blocknum, blocksize, totalsize)
+    print("Block number: %d, Block size: %d, Total size: %d" % (
+        blocknum, blocksize, totalsize))
 
 # Test program
 def test(args=[]):
@@ -1480,22 +1480,22 @@ def test(args=[]):
             args.append('https://synergy.as.cmu.edu/~geek/')
     try:
         for url in args:
-            print '-'*10, url, '-'*10
+            print('-'*10, url, '-'*10)
             fn, h = urlretrieve(url, None, reporthook)
-            print fn
+            print(fn)
             if h:
-                print '======'
-                for k in h.keys(): print k + ':', h[k]
-                print '======'
+                print('======')
+                for k in h.keys(): print(k + ':', h[k])
+                print('======')
             fp = open(fn, 'rb')
             data = fp.read()
             del fp
             if '\r' in data:
                 table = string.maketrans("", "")
                 data = data.translate(table, "\r")
-            print data
+            print(data)
             fn, h = None, None
-        print '-'*40
+        print('-'*40)
     finally:
         urlcleanup()
 
@@ -1504,17 +1504,17 @@ def main():
     try:
         opts, args = getopt.getopt(sys.argv[1:], "th")
     except getopt.error as msg:
-        print msg
-        print "Use -h for help"
+        print(msg)
+        print("Use -h for help")
         return
     t = 0
     for o, a in opts:
         if o == '-t':
             t = t + 1
         if o == '-h':
-            print "Usage: python urllib.py [-t] [url ...]"
-            print "-t runs self-test;",
-            print "otherwise, contents of urls are printed"
+            print("Usage: python urllib.py [-t] [url ...]")
+            print("-t runs self-test;", end=' ')
+            print("otherwise, contents of urls are printed")
             return
     if t:
         if t > 1:
@@ -1522,9 +1522,9 @@ def main():
         test(args)
     else:
         if not args:
-            print "Use -h for help"
+            print("Use -h for help")
         for url in args:
-            print urlopen(url).read(),
+            print(urlopen(url).read(), end=' ')
 
 # Run test program when run as a script
 if __name__ == '__main__':
index eade040ff62c31fd0e5bb017d9246f2f790c6780..9c9af451e141224886b4eb18e8ef4b97d0824777 100644 (file)
@@ -361,15 +361,15 @@ def test():
             continue
         url = words[0]
         parts = urlparse(url)
-        print '%-10s : %s' % (url, parts)
+        print('%-10s : %s' % (url, parts))
         abs = urljoin(base, url)
         if not base:
             base = abs
         wrapped = '<URL:%s>' % abs
-        print '%-10s = %s' % (url, wrapped)
+        print('%-10s = %s' % (url, wrapped))
         if len(words) == 3 and words[1] == '=':
             if wrapped != words[2]:
-                print 'EXPECTED', words[2], '!!!!!!!!!!'
+                print('EXPECTED', words[2], '!!!!!!!!!!')
 
 if __name__ == '__main__':
     test()
index 887d99a35e0f9492cf5267c157d6a61e6900281a..4d3cbd603f80c02b3e3bb8869f9271a528a9d35f 100755 (executable)
--- a/Lib/uu.py
+++ b/Lib/uu.py
@@ -170,7 +170,7 @@ def test():
             if isinstance(output, basestring):
                 output = open(output, 'w')
             else:
-                print sys.argv[0], ': cannot do -t to stdout'
+                print(sys.argv[0], ': cannot do -t to stdout')
                 sys.exit(1)
         decode(input, output)
     else:
@@ -178,7 +178,7 @@ def test():
             if isinstance(input, basestring):
                 input = open(input, 'r')
             else:
-                print sys.argv[0], ': cannot do -t from stdin'
+                print(sys.argv[0], ': cannot do -t from stdin')
                 sys.exit(1)
         encode(input, output)
 
index c0a96d6de49d742df5c9001bf433ac9e2e9197a5..87ae8494a2f9066d765865715e9be48732f1109a 100644 (file)
@@ -193,7 +193,7 @@ def _processoptions(args):
         try:
             _setoption(arg)
         except _OptionError as msg:
-            print >>sys.stderr, "Invalid -W option ignored:", msg
+            print("Invalid -W option ignored:", msg, file=sys.stderr)
 
 # Helper for _processoptions()
 def _setoption(arg):
index 28e6bdebbea4389e1a454cc0d931f482068df7a0..55aa04c8638fc93d1a2a0f7cbadebc2b6ced20b5 100644 (file)
@@ -626,21 +626,21 @@ def main():
     try:
         opts, args = getopt.getopt(sys.argv[1:], 'ntd')
     except getopt.error as msg:
-        print >>sys.stderr, msg
-        print >>sys.stderr, usage
+        print(msg, file=sys.stderr)
+        print(usage, file=sys.stderr)
         sys.exit(1)
     new_win = 0
     for o, a in opts:
         if o == '-n': new_win = 1
         elif o == '-t': new_win = 2
     if len(args) != 1:
-        print >>sys.stderr, usage
+        print(usage, file=sys.stderr)
         sys.exit(1)
 
     url = args[0]
     open(url, new_win)
 
-    print "\a"
+    print("\a")
 
 if __name__ == "__main__":
     main()
index f077f875310eeeacb0ff844c186db21baf36874c..4d7a5602b48daede2f0fe48e0ff42abc12a901f3 100644 (file)
@@ -114,4 +114,4 @@ def whichdb(filename):
 
 if __name__ == "__main__":
     for filename in sys.argv[1:]:
-        print whichdb(filename) or "UNKNOWN", filename
+        print(whichdb(filename) or "UNKNOWN", filename)
index e6c9f38baeef51494f4f83371fc9b40af28fa9d1..abb3620510adcf1df4713f11919562a8517c6b7f 100644 (file)
@@ -165,11 +165,11 @@ class WSGIRequestHandler(BaseHTTPRequestHandler):
 def demo_app(environ,start_response):
     from StringIO import StringIO
     stdout = StringIO()
-    print >>stdout, "Hello world!"
-    print >>stdout
+    print("Hello world!", file=stdout)
+    print(file=stdout)
     h = environ.items(); h.sort()
     for k,v in h:
-        print >>stdout, k,'=',repr(v)
+        print(k,'=',repr(v), file=stdout)
     start_response("200 OK", [('Content-Type','text/plain')])
     return [stdout.getvalue()]
 
@@ -186,7 +186,7 @@ def make_server(
 if __name__ == '__main__':
     httpd = make_server('', 8000, demo_app)
     sa = httpd.socket.getsockname()
-    print "Serving HTTP on", sa[0], "port", sa[1], "..."
+    print("Serving HTTP on", sa[0], "port", sa[1], "...")
     import webbrowser
     webbrowser.open('http://localhost:8000/xyz?abc')
     httpd.handle_request()  # serve one request, then exit
index 18f49b501969dbf253042f12eabcfe2d9c0285db..f0245c49c39acb2aacdb8e65a42b76d72cad50ed 100644 (file)
@@ -201,7 +201,7 @@ class PullDOM(xml.sax.ContentHandler):
 
 class ErrorHandler:
     def warning(self, exception):
-        print exception
+        print(exception)
     def error(self, exception):
         raise exception
     def fatalError(self, exception):
index f9e91b6d470423d643f4745fb9e19c41e794b4e3..481733d2cbe6e5a6dce7979884ec3e986483d1ad 100644 (file)
@@ -39,7 +39,7 @@ class ErrorHandler:
 
     def warning(self, exception):
         "Handle a warning."
-        print exception
+        print(exception)
 
 
 # ===== CONTENTHANDLER =====
index 59fbcd189b8f0c09c610e3f10c330bdd1def3778..6663a23b80180c30211c825e081472b61bf51bcb 100644 (file)
@@ -809,11 +809,11 @@ class TestXMLParser(XMLParser):
 
     def handle_xml(self, encoding, standalone):
         self.flush()
-        print 'xml: encoding =',encoding,'standalone =',standalone
+        print('xml: encoding =',encoding,'standalone =',standalone)
 
     def handle_doctype(self, tag, pubid, syslit, data):
         self.flush()
-        print 'DOCTYPE:',tag, repr(data)
+        print('DOCTYPE:',tag, repr(data))
 
     def handle_data(self, data):
         self.testdata = self.testdata + data
@@ -824,47 +824,47 @@ class TestXMLParser(XMLParser):
         data = self.testdata
         if data:
             self.testdata = ""
-            print 'data:', repr(data)
+            print('data:', repr(data))
 
     def handle_cdata(self, data):
         self.flush()
-        print 'cdata:', repr(data)
+        print('cdata:', repr(data))
 
     def handle_proc(self, name, data):
         self.flush()
-        print 'processing:',name,repr(data)
+        print('processing:',name,repr(data))
 
     def handle_comment(self, data):
         self.flush()
         r = repr(data)
         if len(r) > 68:
             r = r[:32] + '...' + r[-32:]
-        print 'comment:', r
+        print('comment:', r)
 
     def syntax_error(self, message):
-        print 'error at line %d:' % self.lineno, message
+        print('error at line %d:' % self.lineno, message)
 
     def unknown_starttag(self, tag, attrs):
         self.flush()
         if not attrs:
-            print 'start tag: <' + tag + '>'
+            print('start tag: <' + tag + '>')
         else:
-            print 'start tag: <' + tag,
+            print('start tag: <' + tag, end=' ')
             for name, value in attrs.items():
-                print name + '=' + '"' + value + '"',
-            print '>'
+                print(name + '=' + '"' + value + '"', end=' ')
+            print('>')
 
     def unknown_endtag(self, tag):
         self.flush()
-        print 'end tag: </' + tag + '>'
+        print('end tag: </' + tag + '>')
 
     def unknown_entityref(self, ref):
         self.flush()
-        print '*** unknown entity ref: &' + ref + ';'
+        print('*** unknown entity ref: &' + ref + ';')
 
     def unknown_charref(self, ref):
         self.flush()
-        print '*** unknown char ref: &#' + ref + ';'
+        print('*** unknown char ref: &#' + ref + ';')
 
     def close(self):
         XMLParser.close(self)
@@ -897,7 +897,7 @@ def test(args = None):
         try:
             f = open(file, 'r')
         except IOError as msg:
-            print file, ":", msg
+            print(file, ":", msg)
             sys.exit(1)
 
     data = f.read()
@@ -916,13 +916,13 @@ def test(args = None):
             x.close()
     except Error as msg:
         t1 = time()
-        print msg
+        print(msg)
         if do_time:
-            print 'total time: %g' % (t1-t0)
+            print('total time: %g' % (t1-t0))
         sys.exit(1)
     t1 = time()
     if do_time:
-        print 'total time: %g' % (t1-t0)
+        print('total time: %g' % (t1-t0))
 
 
 if __name__ == '__main__':
index 16e2b3b27611c5a55fe7dece5e0b3d2f5eb85e47..494100124c94eca8695f965500fe9c85a22a3882 100644 (file)
@@ -1310,7 +1310,7 @@ class Transport:
             if not response:
                 break
             if self.verbose:
-                print "body:", repr(response)
+                print("body:", repr(response))
             p.feed(response)
 
         file.close()
@@ -1450,18 +1450,18 @@ if __name__ == "__main__":
     # server = ServerProxy("http://localhost:8000") # local server
     server = ServerProxy("http://time.xmlrpc.com/RPC2")
 
-    print server
+    print(server)
 
     try:
-        print server.currentTime.getCurrentTime()
+        print(server.currentTime.getCurrentTime())
     except Error as v:
-        print "ERROR", v
+        print("ERROR", v)
 
     multi = MultiCall(server)
     multi.currentTime.getCurrentTime()
     multi.currentTime.getCurrentTime()
     try:
         for response in multi():
-            print response
+            print(response)
     except Error as v:
-        print "ERROR", v
+        print("ERROR", v)
index cae04f486991bb075dd7972f20482584d0eabc59..c6162ff37c26e8f050d43927b99a3908b2d01685 100644 (file)
@@ -377,7 +377,7 @@ class ZipFile:
         if not endrec:
             raise BadZipfile, "File is not a zip file"
         if self.debug > 1:
-            print endrec
+            print(endrec)
         size_cd = endrec[5]             # bytes in central directory
         offset_cd = endrec[6]   # offset of central directory
         self.comment = endrec[8]        # archive comment
@@ -389,7 +389,7 @@ class ZipFile:
         # "concat" is zero, unless zip was concatenated to another file
         concat = x - offset_cd
         if self.debug > 2:
-            print "given, inferred, offset", offset_cd, x, concat
+            print("given, inferred, offset", offset_cd, x, concat)
         # self.start_dir:  Position of start of central directory
         self.start_dir = offset_cd + concat
         fp.seek(self.start_dir, 0)
@@ -403,7 +403,7 @@ class ZipFile:
                 raise BadZipfile, "Bad magic number for central directory"
             centdir = struct.unpack(structCentralDir, centdir)
             if self.debug > 2:
-                print centdir
+                print(centdir)
             filename = fp.read(centdir[_CD_FILENAME_LENGTH])
             # Create ZipInfo instance to store file information
             x = ZipInfo(filename)
@@ -426,7 +426,7 @@ class ZipFile:
             self.filelist.append(x)
             self.NameToInfo[x.filename] = x
             if self.debug > 2:
-                print "total", total
+                print("total", total)
 
 
     def namelist(self):
@@ -443,10 +443,10 @@ class ZipFile:
 
     def printdir(self):
         """Print a table of contents for the zip file."""
-        print "%-46s %19s %12s" % ("File Name", "Modified    ", "Size")
+        print("%-46s %19s %12s" % ("File Name", "Modified    ", "Size"))
         for zinfo in self.filelist:
             date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time
-            print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)
+            print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size))
 
     def testzip(self):
         """Read all the files and check the CRC."""
@@ -516,7 +516,7 @@ class ZipFile:
         """Check for errors before writing a file to the archive."""
         if zinfo.filename in self.NameToInfo:
             if self.debug:      # Warning for duplicate names
-                print "Duplicate name:", zinfo.filename
+                print("Duplicate name:", zinfo.filename)
         if self.mode not in ("w", "a"):
             raise RuntimeError, 'write() requires mode "w" or "a"'
         if not self.fp:
@@ -749,10 +749,10 @@ class PyZipFile(ZipFile):
                 else:
                     basename = name
                 if self.debug:
-                    print "Adding package in", pathname, "as", basename
+                    print("Adding package in", pathname, "as", basename)
                 fname, arcname = self._get_codename(initname[0:-3], basename)
                 if self.debug:
-                    print "Adding", arcname
+                    print("Adding", arcname)
                 self.write(fname, arcname)
                 dirlist = os.listdir(pathname)
                 dirlist.remove("__init__.py")
@@ -768,12 +768,12 @@ class PyZipFile(ZipFile):
                         fname, arcname = self._get_codename(path[0:-3],
                                          basename)
                         if self.debug:
-                            print "Adding", arcname
+                            print("Adding", arcname)
                         self.write(fname, arcname)
             else:
                 # This is NOT a package directory, add its files at top level
                 if self.debug:
-                    print "Adding files from directory", pathname
+                    print("Adding files from directory", pathname)
                 for filename in os.listdir(pathname):
                     path = os.path.join(pathname, filename)
                     root, ext = os.path.splitext(filename)
@@ -781,7 +781,7 @@ class PyZipFile(ZipFile):
                         fname, arcname = self._get_codename(path[0:-3],
                                          basename)
                         if self.debug:
-                            print "Adding", arcname
+                            print("Adding", arcname)
                         self.write(fname, arcname)
         else:
             if pathname[-3:] != ".py":
@@ -789,7 +789,7 @@ class PyZipFile(ZipFile):
                       'Files added with writepy() must end with ".py"'
             fname, arcname = self._get_codename(pathname[0:-3], basename)
             if self.debug:
-                print "Adding file", arcname
+                print("Adding file", arcname)
             self.write(fname, arcname)
 
     def _get_codename(self, pathname, basename):
@@ -809,11 +809,11 @@ class PyZipFile(ZipFile):
              os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime:
             import py_compile
             if self.debug:
-                print "Compiling", file_py
+                print("Compiling", file_py)
             try:
                 py_compile.compile(file_py, file_pyc, None, True)
             except py_compile.PyCompileError as err:
-                print err.msg
+                print(err.msg)
             fname = file_pyc
         else:
             fname = file_pyc
@@ -836,12 +836,12 @@ def main(args = None):
         args = sys.argv[1:]
 
     if not args or args[0] not in ('-l', '-c', '-e', '-t'):
-        print USAGE
+        print(USAGE)
         sys.exit(1)
 
     if args[0] == '-l':
         if len(args) != 2:
-            print USAGE
+            print(USAGE)
             sys.exit(1)
         zf = ZipFile(args[1], 'r')
         zf.printdir()
@@ -849,15 +849,15 @@ def main(args = None):
 
     elif args[0] == '-t':
         if len(args) != 2:
-            print USAGE
+            print(USAGE)
             sys.exit(1)
         zf = ZipFile(args[1], 'r')
         zf.testzip()
-        print "Done testing"
+        print("Done testing")
 
     elif args[0] == '-e':
         if len(args) != 3:
-            print USAGE
+            print(USAGE)
             sys.exit(1)
 
         zf = ZipFile(args[1], 'r')
@@ -878,7 +878,7 @@ def main(args = None):
 
     elif args[0] == '-c':
         if len(args) < 3:
-            print USAGE
+            print(USAGE)
             sys.exit(1)
 
         def addToZip(zf, path, zippath):