summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Lib/BaseHTTPServer.py2
-rw-r--r--Lib/Bastion.py2
-rw-r--r--Lib/Cookie.py10
-rw-r--r--Lib/DocXMLRPCServer.py6
-rw-r--r--Lib/SimpleXMLRPCServer.py16
-rw-r--r--Lib/SocketServer.py8
-rw-r--r--Lib/StringIO.py14
-rw-r--r--Lib/aifc.py30
-rw-r--r--Lib/asyncore.py2
-rw-r--r--Lib/atexit.py8
-rw-r--r--Lib/audiodev.py4
-rwxr-xr-xLib/base64.py8
-rw-r--r--Lib/bdb.py28
-rw-r--r--Lib/bsddb/dbtables.py4
-rw-r--r--Lib/bsddb/test/test_all.py18
-rw-r--r--Lib/bsddb/test/test_associate.py36
-rw-r--r--Lib/bsddb/test/test_basics.py148
-rw-r--r--Lib/bsddb/test/test_compat.py30
-rw-r--r--Lib/bsddb/test/test_dbshelve.py20
-rw-r--r--Lib/bsddb/test/test_dbtables.py8
-rw-r--r--Lib/bsddb/test/test_join.py6
-rw-r--r--Lib/bsddb/test/test_lock.py20
-rw-r--r--Lib/bsddb/test/test_queue.py34
-rw-r--r--Lib/bsddb/test/test_recno.py42
-rw-r--r--Lib/bsddb/test/test_thread.py72
-rwxr-xr-xLib/cProfile.py4
-rw-r--r--Lib/calendar.py14
-rwxr-xr-xLib/cgi.py70
-rw-r--r--Lib/code.py2
-rw-r--r--Lib/compileall.py38
-rw-r--r--Lib/compiler/future.py6
-rw-r--r--Lib/compiler/pyassem.py24
-rw-r--r--Lib/compiler/pycodegen.py10
-rw-r--r--Lib/compiler/symbols.py30
-rw-r--r--Lib/compiler/syntax.py2
-rw-r--r--Lib/compiler/transformer.py2
-rw-r--r--Lib/compiler/visitor.py16
-rw-r--r--Lib/copy.py34
-rw-r--r--Lib/ctypes/test/__init__.py12
-rw-r--r--Lib/ctypes/test/test_byteswap.py2
-rw-r--r--Lib/ctypes/test/test_find.py4
-rw-r--r--Lib/ctypes/test/test_keeprefs.py14
-rw-r--r--Lib/ctypes/test/test_loading.py6
-rw-r--r--Lib/ctypes/test/test_numbers.py2
-rw-r--r--Lib/ctypes/test/test_strings.py2
-rw-r--r--Lib/ctypes/util.py26
-rw-r--r--Lib/curses/has_key.py2
-rw-r--r--Lib/curses/textpad.py2
-rw-r--r--Lib/difflib.py30
-rw-r--r--Lib/dis.py74
-rw-r--r--Lib/distutils/bcppcompiler.py2
-rw-r--r--Lib/distutils/ccompiler.py2
-rw-r--r--Lib/distutils/cmd.py8
-rw-r--r--Lib/distutils/command/bdist_rpm.py10
-rw-r--r--Lib/distutils/command/config.py4
-rw-r--r--Lib/distutils/command/install.py6
-rw-r--r--Lib/distutils/command/register.py30
-rw-r--r--Lib/distutils/command/upload.py2
-rw-r--r--Lib/distutils/core.py4
-rw-r--r--Lib/distutils/dist.py48
-rw-r--r--Lib/distutils/fancy_getopt.py6
-rw-r--r--Lib/distutils/filelist.py2
-rw-r--r--Lib/distutils/log.py4
-rw-r--r--Lib/distutils/mwerkscompiler.py4
-rw-r--r--Lib/distutils/spawn.py2
-rw-r--r--Lib/distutils/tests/test_dist.py4
-rw-r--r--Lib/distutils/text_file.py12
-rw-r--r--Lib/doctest.py34
-rw-r--r--Lib/email/generator.py30
-rw-r--r--Lib/email/iterators.py6
-rw-r--r--Lib/email/test/test_email.py2
-rw-r--r--Lib/email/test/test_email_renamed.py2
-rw-r--r--Lib/filecmp.py20
-rw-r--r--Lib/fileinput.py6
-rw-r--r--Lib/formatter.py22
-rw-r--r--Lib/fpformat.py2
-rw-r--r--Lib/ftplib.py18
-rw-r--r--Lib/getopt.py2
-rw-r--r--Lib/getpass.py2
-rw-r--r--Lib/gopherlib.py18
-rw-r--r--Lib/gzip.py2
-rw-r--r--Lib/heapq.py2
-rw-r--r--Lib/hotshot/log.py2
-rw-r--r--Lib/hotshot/stones.py6
-rw-r--r--Lib/htmllib.py2
-rw-r--r--Lib/httplib.py42
-rw-r--r--Lib/idlelib/CallTips.py6
-rw-r--r--Lib/idlelib/ColorDelegator.py32
-rw-r--r--Lib/idlelib/Delegator.py2
-rw-r--r--Lib/idlelib/EditorWindow.py4
-rw-r--r--Lib/idlelib/FileList.py4
-rw-r--r--Lib/idlelib/GrepDialog.py12
-rw-r--r--Lib/idlelib/MultiCall.py2
-rw-r--r--Lib/idlelib/Percolator.py4
-rw-r--r--Lib/idlelib/PyShell.py19
-rw-r--r--Lib/idlelib/ScrolledList.py4
-rw-r--r--Lib/idlelib/UndoDelegator.py8
-rw-r--r--Lib/idlelib/WidgetRedirector.py2
-rw-r--r--Lib/idlelib/WindowList.py2
-rw-r--r--Lib/idlelib/configHandler.py14
-rw-r--r--Lib/idlelib/configHelpSourceEdit.py2
-rw-r--r--Lib/idlelib/configSectionNameDialog.py2
-rw-r--r--Lib/idlelib/keybindingDialog.py2
-rw-r--r--Lib/idlelib/rpc.py30
-rw-r--r--Lib/idlelib/run.py28
-rw-r--r--Lib/ihooks.py4
-rw-r--r--Lib/imaplib.py8
-rw-r--r--Lib/imghdr.py12
-rw-r--r--Lib/imputil.py4
-rw-r--r--Lib/lib-tk/Dialog.py2
-rw-r--r--Lib/lib-tk/FileDialog.py2
-rw-r--r--Lib/lib-tk/SimpleDialog.py2
-rw-r--r--Lib/lib-tk/Tkinter.py2
-rw-r--r--Lib/lib-tk/tkColorChooser.py2
-rw-r--r--Lib/lib-tk/tkFileDialog.py8
-rw-r--r--Lib/lib-tk/tkFont.py20
-rw-r--r--Lib/lib-tk/tkMessageBox.py16
-rw-r--r--Lib/lib-tk/tkSimpleDialog.py6
-rw-r--r--Lib/locale.py70
-rw-r--r--Lib/logging/handlers.py4
-rw-r--r--Lib/macurl2path.py4
-rw-r--r--Lib/mailcap.py24
-rw-r--r--Lib/mhlib.py8
-rw-r--r--Lib/mimetypes.py12
-rwxr-xr-xLib/mimify.py6
-rw-r--r--Lib/modulefinder.py42
-rw-r--r--Lib/msilib/__init__.py4
-rw-r--r--Lib/netrc.py2
-rw-r--r--Lib/nntplib.py20
-rw-r--r--Lib/optparse.py4
-rwxr-xr-xLib/pdb.py262
-rw-r--r--Lib/pickletools.py16
-rw-r--r--Lib/pipes.py6
-rwxr-xr-xLib/plat-irix5/cddb.py8
-rwxr-xr-xLib/plat-irix5/cdplayer.py2
-rwxr-xr-xLib/plat-irix5/flp.py26
-rwxr-xr-xLib/plat-irix5/panel.py32
-rw-r--r--Lib/plat-irix6/cddb.py8
-rw-r--r--Lib/plat-irix6/cdplayer.py2
-rw-r--r--Lib/plat-irix6/flp.py26
-rw-r--r--Lib/plat-irix6/panel.py32
-rw-r--r--Lib/plat-mac/Audio_mac.py4
-rw-r--r--Lib/plat-mac/EasyDialogs.py12
-rw-r--r--Lib/plat-mac/FrameWork.py60
-rw-r--r--Lib/plat-mac/MiniAEFrame.py8
-rw-r--r--Lib/plat-mac/aetools.py8
-rw-r--r--Lib/plat-mac/applesingle.py10
-rw-r--r--Lib/plat-mac/argvemulator.py12
-rwxr-xr-xLib/plat-mac/bundlebuilder.py4
-rw-r--r--Lib/plat-mac/findertools.py86
-rw-r--r--Lib/plat-mac/gensuitemodule.py36
-rw-r--r--Lib/plat-mac/ic.py4
-rw-r--r--Lib/plat-mac/macresource.py2
-rw-r--r--Lib/plat-mac/pimp.py58
-rw-r--r--Lib/plat-mac/videoreader.py8
-rw-r--r--Lib/plat-os2emx/_emx_link.py4
-rw-r--r--Lib/plat-riscos/rourl2path.py6
-rwxr-xr-xLib/platform.py6
-rw-r--r--Lib/popen2.py6
-rw-r--r--Lib/poplib.py22
-rw-r--r--Lib/pprint.py4
-rwxr-xr-xLib/profile.py16
-rw-r--r--Lib/pstats.py116
-rw-r--r--Lib/pyclbr.py6
-rwxr-xr-xLib/pydoc.py20
-rwxr-xr-xLib/quopri.py10
-rw-r--r--Lib/random.py8
-rw-r--r--Lib/rexec.py2
-rw-r--r--Lib/rfc822.py32
-rw-r--r--Lib/robotparser.py8
-rwxr-xr-xLib/runpy.py2
-rw-r--r--Lib/sgmllib.py26
-rw-r--r--Lib/shlex.py40
-rw-r--r--Lib/site.py8
-rwxr-xr-xLib/smtpd.py51
-rwxr-xr-xLib/smtplib.py24
-rw-r--r--Lib/sndhdr.py12
-rw-r--r--Lib/sqlite3/test/dbapi.py2
-rw-r--r--Lib/sre_constants.py2
-rw-r--r--Lib/sre_parse.py18
-rw-r--r--Lib/subprocess.py30
-rw-r--r--Lib/sunaudio.py12
-rw-r--r--Lib/symtable.py2
-rwxr-xr-xLib/tabnanny.py16
-rw-r--r--Lib/tarfile.py26
-rw-r--r--Lib/telnetlib.py10
-rw-r--r--Lib/test/badsyntax_future8.py2
-rw-r--r--Lib/test/badsyntax_future9.py2
-rw-r--r--Lib/test/crashers/bogus_sre_bytecode.py2
-rw-r--r--Lib/test/crashers/borrowed_ref_1.py2
-rw-r--r--Lib/test/crashers/borrowed_ref_2.py2
-rw-r--r--Lib/test/crashers/gc_inspection.py4
-rw-r--r--Lib/test/crashers/loosing_mro_ref.py2
-rw-r--r--Lib/test/crashers/modify_dict_attr.py2
-rw-r--r--Lib/test/crashers/nasty_eq_vs_dict.py2
-rw-r--r--Lib/test/inspect_fodder2.py2
-rw-r--r--Lib/test/list_tests.py2
-rw-r--r--Lib/test/pydocfodder.py6
-rwxr-xr-xLib/test/pystone.py10
-rwxr-xr-xLib/test/regrtest.py104
-rw-r--r--Lib/test/reperf.py4
-rw-r--r--Lib/test/sortperf.py10
-rwxr-xr-xLib/test/test_al.py4
-rwxr-xr-xLib/test/test_array.py2
-rw-r--r--Lib/test/test_ast.py8
-rw-r--r--Lib/test/test_atexit.py8
-rw-r--r--Lib/test/test_audioop.py56
-rw-r--r--Lib/test/test_bisect.py2
-rw-r--r--Lib/test/test_bool.py2
-rwxr-xr-xLib/test/test_bsddb.py24
-rw-r--r--Lib/test/test_bsddb3.py14
-rw-r--r--Lib/test/test_builtin.py12
-rw-r--r--Lib/test/test_capi.py4
-rwxr-xr-xLib/test/test_cd.py4
-rwxr-xr-xLib/test/test_cl.py4
-rw-r--r--Lib/test/test_class.py48
-rwxr-xr-xLib/test/test_cmath.py6
-rw-r--r--Lib/test/test_code.py4
-rw-r--r--Lib/test/test_codecs.py2
-rw-r--r--Lib/test/test_compiler.py9
-rw-r--r--Lib/test/test_complex.py2
-rwxr-xr-xLib/test/test_crypt.py2
-rw-r--r--Lib/test/test_csv.py2
-rw-r--r--Lib/test/test_curses.py2
-rw-r--r--Lib/test/test_datetime.py6
-rwxr-xr-xLib/test/test_dbm.py2
-rw-r--r--Lib/test/test_decimal.py6
-rw-r--r--Lib/test/test_defaultdict.py4
-rw-r--r--Lib/test/test_deque.py4
-rw-r--r--Lib/test/test_descr.py222
-rw-r--r--Lib/test/test_dis.py2
-rwxr-xr-xLib/test/test_dl.py8
-rw-r--r--Lib/test/test_doctest.py4
-rw-r--r--Lib/test/test_dummy_thread.py20
-rw-r--r--Lib/test/test_dummy_threading.py12
-rw-r--r--Lib/test/test_enumerate.py2
-rwxr-xr-xLib/test/test_errno.py4
-rw-r--r--Lib/test/test_extcall.py94
-rwxr-xr-xLib/test/test_fcntl.py6
-rw-r--r--Lib/test/test_file.py4
-rw-r--r--Lib/test/test_fileinput.py26
-rw-r--r--Lib/test/test_format.py28
-rw-r--r--Lib/test/test_funcattrs.py12
-rw-r--r--Lib/test/test_functools.py2
-rw-r--r--Lib/test/test_gc.py8
-rwxr-xr-xLib/test/test_gdbm.py2
-rw-r--r--Lib/test/test_generators.py12
-rw-r--r--Lib/test/test_genexps.py2
-rw-r--r--Lib/test/test_getopt.py14
-rwxr-xr-xLib/test/test_gl.py36
-rw-r--r--Lib/test/test_grammar.py74
-rw-r--r--Lib/test/test_heapq.py2
-rwxr-xr-xLib/test/test_imageop.py34
-rwxr-xr-xLib/test/test_imgfile.py20
-rw-r--r--Lib/test/test_import.py16
-rw-r--r--Lib/test/test_itertools.py2
-rw-r--r--Lib/test/test_largefile.py18
-rw-r--r--Lib/test/test_linuxaudiodev.py14
-rw-r--r--Lib/test/test_list.py2
-rw-r--r--Lib/test/test_locale.py24
-rw-r--r--Lib/test/test_long_future.py2
-rw-r--r--Lib/test/test_minidom.py40
-rw-r--r--Lib/test/test_module.py2
-rw-r--r--Lib/test/test_multibytecodec.py2
-rw-r--r--Lib/test/test_mutants.py14
-rw-r--r--Lib/test/test_normalization.py2
-rw-r--r--Lib/test/test_ntpath.py12
-rw-r--r--Lib/test/test_operations.py14
-rw-r--r--Lib/test/test_operator.py2
-rw-r--r--Lib/test/test_ossaudiodev.py8
-rw-r--r--Lib/test/test_peepholer.py2
-rw-r--r--Lib/test/test_pep247.py2
-rw-r--r--Lib/test/test_pep277.py4
-rw-r--r--Lib/test/test_pkg.py12
-rw-r--r--Lib/test/test_popen2.py10
-rw-r--r--Lib/test/test_pty.py2
-rw-r--r--Lib/test/test_pyclbr.py10
-rw-r--r--Lib/test/test_pyexpat.py86
-rw-r--r--Lib/test/test_queue.py4
-rw-r--r--Lib/test/test_random.py2
-rw-r--r--Lib/test/test_re.py28
-rw-r--r--Lib/test/test_rfc822.py4
-rw-r--r--Lib/test/test_rgbimg.py6
-rw-r--r--Lib/test/test_runpy.py32
-rw-r--r--Lib/test/test_sax.py4
-rw-r--r--Lib/test/test_scope.py8
-rw-r--r--Lib/test/test_select.py18
-rw-r--r--Lib/test/test_signal.py24
-rw-r--r--Lib/test/test_site.py10
-rw-r--r--Lib/test/test_socket_ssl.py12
-rw-r--r--Lib/test/test_socketserver.py23
-rw-r--r--Lib/test/test_softspace.py6
-rw-r--r--Lib/test/test_sort.py32
-rwxr-xr-xLib/test/test_strftime.py30
-rw-r--r--Lib/test/test_struct.py20
-rw-r--r--Lib/test/test_sundry.py2
-rw-r--r--Lib/test/test_support.py16
-rw-r--r--Lib/test/test_thread.py34
-rw-r--r--Lib/test/test_threaded_import.py8
-rw-r--r--Lib/test/test_threadedtempfile.py10
-rw-r--r--Lib/test/test_threading.py38
-rw-r--r--Lib/test/test_tokenize.py10
-rw-r--r--Lib/test/test_trace.py2
-rw-r--r--Lib/test/test_traceback.py8
-rw-r--r--Lib/test/test_unicode.py18
-rw-r--r--Lib/test/test_userdict.py2
-rw-r--r--Lib/test/test_uuid.py15
-rw-r--r--Lib/test/test_winreg.py10
-rw-r--r--Lib/test/test_xml_etree.py2
-rw-r--r--Lib/test/test_xml_etree_c.py2
-rw-r--r--Lib/test/test_zipfile64.py8
-rw-r--r--Lib/test/time_hashlib.py32
-rw-r--r--Lib/textwrap.py2
-rw-r--r--Lib/this.py2
-rw-r--r--Lib/threading.py16
-rw-r--r--Lib/timeit.py18
-rw-r--r--Lib/tokenize.py4
-rw-r--r--Lib/trace.py50
-rw-r--r--Lib/unittest.py4
-rw-r--r--Lib/urllib.py44
-rw-r--r--Lib/urlparse.py6
-rwxr-xr-xLib/uu.py4
-rw-r--r--Lib/warnings.py2
-rw-r--r--Lib/webbrowser.py8
-rw-r--r--Lib/whichdb.py2
-rw-r--r--Lib/wsgiref/simple_server.py8
-rw-r--r--Lib/xml/dom/pulldom.py2
-rw-r--r--Lib/xml/sax/handler.py2
-rw-r--r--Lib/xmllib.py36
-rw-r--r--Lib/xmlrpclib.py12
-rw-r--r--Lib/zipfile.py42
331 files changed, 2568 insertions, 2649 deletions
diff --git a/Lib/BaseHTTPServer.py b/Lib/BaseHTTPServer.py
index ae916b6c96..982c9d2c0f 100644
--- a/Lib/BaseHTTPServer.py
+++ b/Lib/BaseHTTPServer.py
@@ -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()
diff --git a/Lib/Bastion.py b/Lib/Bastion.py
index 2127f46dba..6a5cb5c605 100644
--- a/Lib/Bastion.py
+++ b/Lib/Bastion.py
@@ -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__')
diff --git a/Lib/Cookie.py b/Lib/Cookie.py
index 46ef3ea61c..fb06840de9 100644
--- a/Lib/Cookie.py
+++ b/Lib/Cookie.py
@@ -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
diff --git a/Lib/DocXMLRPCServer.py b/Lib/DocXMLRPCServer.py
index ddd56047d4..fd3b2c9d18 100644
--- a/Lib/DocXMLRPCServer.py
+++ b/Lib/DocXMLRPCServer.py
@@ -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):
diff --git a/Lib/SimpleXMLRPCServer.py b/Lib/SimpleXMLRPCServer.py
index 0a62b47fe5..814ede1025 100644
--- a/Lib/SimpleXMLRPCServer.py
+++ b/Lib/SimpleXMLRPCServer.py
@@ -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')
diff --git a/Lib/SocketServer.py b/Lib/SocketServer.py
index 3a74c444ba..eedb25149a 100644
--- a/Lib/SocketServer.py
+++ b/Lib/SocketServer.py
@@ -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):
diff --git a/Lib/StringIO.py b/Lib/StringIO.py
index 9394360fa7..a6b0ea4061 100644
--- a/Lib/StringIO.py
+++ b/Lib/StringIO.py
@@ -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()
diff --git a/Lib/aifc.py b/Lib/aifc.py
index e28c5c0b9f..bc82f48dc8 100644
--- a/Lib/aifc.py
+++ b/Lib/aifc.py
@@ -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.")
diff --git a/Lib/asyncore.py b/Lib/asyncore.py
index 9eb6d7f2e2..fc110c9ef2 100644
--- a/Lib/asyncore.py
+++ b/Lib/asyncore.py
@@ -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:
diff --git a/Lib/atexit.py b/Lib/atexit.py
index 93fddf7f99..51a153e7e9 100644
--- a/Lib/atexit.py
+++ b/Lib/atexit.py
@@ -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)
diff --git a/Lib/audiodev.py b/Lib/audiodev.py
index 8945c983c2..0585bcfb59 100644
--- a/Lib/audiodev.py
+++ b/Lib/audiodev.py
@@ -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()
diff --git a/Lib/base64.py b/Lib/base64.py
index dbcccd849a..19de5143b0 100755
--- a/Lib/base64.py
+++ b/Lib/base64.py
@@ -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__':
diff --git a/Lib/bdb.py b/Lib/bdb.py
index 11cce42397..d49e7e385d 100644
--- a/Lib/bdb.py
+++ b/Lib/bdb.py
@@ -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():
diff --git a/Lib/bsddb/dbtables.py b/Lib/bsddb/dbtables.py
index 704c4d2057..5359de8a66 100644
--- a/Lib/bsddb/dbtables.py
+++ b/Lib/bsddb/dbtables.py
@@ -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
diff --git a/Lib/bsddb/test/test_all.py b/Lib/bsddb/test/test_all.py
index 0b132f49cc..b3ef5b9299 100644
--- a/Lib/bsddb/test/test_all.py
+++ b/Lib/bsddb/test/test_all.py
@@ -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):
diff --git a/Lib/bsddb/test/test_associate.py b/Lib/bsddb/test/test_associate.py
index 7ae7c53ff8..857cd3d0ae 100644
--- a/Lib/bsddb/test/test_associate.py
+++ b/Lib/bsddb/test/test_associate.py
@@ -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
diff --git a/Lib/bsddb/test/test_basics.py b/Lib/bsddb/test/test_basics.py
index 281e9428a9..a9d7be0c4c 100644
--- a/Lib/bsddb/test/test_basics.py
+++ b/Lib/bsddb/test/test_basics.py
@@ -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
diff --git a/Lib/bsddb/test/test_compat.py b/Lib/bsddb/test/test_compat.py
index af9e128904..7561f9f01d 100644
--- a/Lib/bsddb/test/test_compat.py
+++ b/Lib/bsddb/test/test_compat.py
@@ -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']
diff --git a/Lib/bsddb/test/test_dbshelve.py b/Lib/bsddb/test/test_dbshelve.py
index 1da6546a55..e75e9c8caf 100644
--- a/Lib/bsddb/test/test_dbshelve.py
+++ b/Lib/bsddb/test/test_dbshelve.py
@@ -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()
diff --git a/Lib/bsddb/test/test_dbtables.py b/Lib/bsddb/test/test_dbtables.py
index a31fcec910..c476e5561a 100644
--- a/Lib/bsddb/test/test_dbtables.py
+++ b/Lib/bsddb/test/test_dbtables.py
@@ -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'])
diff --git a/Lib/bsddb/test/test_join.py b/Lib/bsddb/test/test_join.py
index 5e307aead7..67507eabeb 100644
--- a/Lib/bsddb/test/test_join.py
+++ b/Lib/bsddb/test/test_join.py
@@ -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)
diff --git a/Lib/bsddb/test/test_lock.py b/Lib/bsddb/test/test_lock.py
index 61bdae8b76..e44bf214a6 100644
--- a/Lib/bsddb/test/test_lock.py
+++ b/Lib/bsddb/test/test_lock.py
@@ -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))
#----------------------------------------------------------------------
diff --git a/Lib/bsddb/test/test_queue.py b/Lib/bsddb/test/test_queue.py
index 4226c9e1e8..9f80b4362f 100644
--- a/Lib/bsddb/test/test_queue.py
+++ b/Lib/bsddb/test/test_queue.py
@@ -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()
diff --git a/Lib/bsddb/test/test_recno.py b/Lib/bsddb/test/test_recno.py
index 7bf3695dfa..8baf8438ee 100644
--- a/Lib/bsddb/test/test_recno.py
+++ b/Lib/bsddb/test/test_recno.py
@@ -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()
diff --git a/Lib/bsddb/test/test_thread.py b/Lib/bsddb/test/test_thread.py
index b3d7ef94e6..eabf96a721 100644
--- a/Lib/bsddb/test/test_thread.py
+++ b/Lib/bsddb/test/test_thread.py
@@ -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
diff --git a/Lib/cProfile.py b/Lib/cProfile.py
index cb26fe105e..fb434bd3cd 100755
--- a/Lib/cProfile.py
+++ b/Lib/cProfile.py
@@ -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'.")
# ____________________________________________________________
diff --git a/Lib/calendar.py b/Lib/calendar.py
index 00948efe5c..149c7adadb 100644
--- a/Lib/calendar.py
+++ b/Lib/calendar.py
@@ -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__":
diff --git a/Lib/cgi.py b/Lib/cgi.py
index 0cc5fad82a..5ddf16e8f8 100755
--- a/Lib/cgi.py
+++ b/Lib/cgi.py
@@ -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
diff --git a/Lib/code.py b/Lib/code.py
index 8d3a884263..8532a2eeb9 100644
--- a/Lib/code.py
+++ b/Lib/code.py
@@ -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.
diff --git a/Lib/compileall.py b/Lib/compileall.py
index 1e5c6a6e2d..6781908653 100644
--- a/Lib/compileall.py
+++ b/Lib/compileall.py
@@ -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
diff --git a/Lib/compiler/future.py b/Lib/compiler/future.py
index fef189e9e9..6e724904a7 100644
--- a/Lib/compiler/future.py
+++ b/Lib/compiler/future.py
@@ -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()
diff --git a/Lib/compiler/pyassem.py b/Lib/compiler/pyassem.py
index 86e2c49443..9f45d61d99 100644
--- a/Lib/compiler/pyassem.py
+++ b/Lib/compiler/pyassem.py
@@ -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 = {
diff --git a/Lib/compiler/pycodegen.py b/Lib/compiler/pycodegen.py
index a1dc9716cf..0e497817a3 100644
--- a/Lib/compiler/pycodegen.py
+++ b/Lib/compiler/pycodegen.py
@@ -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):
diff --git a/Lib/compiler/symbols.py b/Lib/compiler/symbols.py
index 3585efc301..6c19b5ba76 100644
--- a/Lib/compiler/symbols.py
+++ b/Lib/compiler/symbols.py
@@ -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)
diff --git a/Lib/compiler/syntax.py b/Lib/compiler/syntax.py
index a45d9c2cf6..6187b47dbd 100644
--- a/Lib/compiler/syntax.py
+++ b/Lib/compiler/syntax.py
@@ -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)
diff --git a/Lib/compiler/transformer.py b/Lib/compiler/transformer.py
index 0d0034001c..3a2be135e4 100644
--- a/Lib/compiler/transformer.py
+++ b/Lib/compiler/transformer.py
@@ -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)
diff --git a/Lib/compiler/visitor.py b/Lib/compiler/visitor.py
index f10f56011a..99c6716309 100644
--- a/Lib/compiler/visitor.py
+++ b/Lib/compiler/visitor.py
@@ -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))
diff --git a/Lib/copy.py b/Lib/copy.py
index 527759f6c4..37e35cf93a 100644
--- a/Lib/copy.py
+++ b/Lib/copy.py
@@ -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()
diff --git a/Lib/ctypes/test/__init__.py b/Lib/ctypes/test/__init__.py
index 245dda6534..1101828cc9 100644
--- a/Lib/ctypes/test/__init__.py
+++ b/Lib/ctypes/test/__init__.py
@@ -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":
diff --git a/Lib/ctypes/test/test_byteswap.py b/Lib/ctypes/test/test_byteswap.py
index 1f6899212f..4833cbc79e 100644
--- a/Lib/ctypes/test/test_byteswap.py
+++ b/Lib/ctypes/test/test_byteswap.py
@@ -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)
diff --git a/Lib/ctypes/test/test_find.py b/Lib/ctypes/test/test_find.py
index 810467faac..71cfe93526 100644
--- a/Lib/ctypes/test/test_find.py
+++ b/Lib/ctypes/test/test_find.py
@@ -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.
diff --git a/Lib/ctypes/test/test_keeprefs.py b/Lib/ctypes/test/test_keeprefs.py
index 80b6ca2ae1..a0eb00fa85 100644
--- a/Lib/ctypes/test/test_keeprefs.py
+++ b/Lib/ctypes/test/test_keeprefs.py
@@ -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):
diff --git a/Lib/ctypes/test/test_loading.py b/Lib/ctypes/test/test_loading.py
index 28c83fd4a9..f265a7351b 100644
--- a/Lib/ctypes/test/test_loading.py
+++ b/Lib/ctypes/test/test_loading.py
@@ -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
diff --git a/Lib/ctypes/test/test_numbers.py b/Lib/ctypes/test/test_numbers.py
index d4f223892f..2c5a990c21 100644
--- a/Lib/ctypes/test/test_numbers.py
+++ b/Lib/ctypes/test/test_numbers.py
@@ -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
diff --git a/Lib/ctypes/test/test_strings.py b/Lib/ctypes/test/test_strings.py
index b5072290c8..aca7282a4d 100644
--- a/Lib/ctypes/test/test_strings.py
+++ b/Lib/ctypes/test/test_strings.py
@@ -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
diff --git a/Lib/ctypes/util.py b/Lib/ctypes/util.py
index 46f4c55305..8a9b706a7d 100644
--- a/Lib/ctypes/util.py
+++ b/Lib/ctypes/util.py
@@ -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()
diff --git a/Lib/curses/has_key.py b/Lib/curses/has_key.py
index 60b7be9942..4e37b480f1 100644
--- a/Lib/curses/has_key.py
+++ b/Lib/curses/has_key.py
@@ -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)
diff --git a/Lib/curses/textpad.py b/Lib/curses/textpad.py
index 120c5721ee..24a964a1c7 100644
--- a/Lib/curses/textpad.py
+++ b/Lib/curses/textpad.py
@@ -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))
diff --git a/Lib/difflib.py b/Lib/difflib.py
index 831840d44f..f2d13436b1 100644
--- a/Lib/difflib.py
+++ b/Lib/difflib.py
@@ -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
diff --git a/Lib/dis.py b/Lib/dis.py
index 7b2a0f9c95..385c19d64c 100644
--- a/Lib/dis.py
+++ b/Lib/dis.py
@@ -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
diff --git a/Lib/distutils/bcppcompiler.py b/Lib/distutils/bcppcompiler.py
index 6968cb8f6f..b6a3bf62ce 100644
--- a/Lib/distutils/bcppcompiler.py
+++ b/Lib/distutils/bcppcompiler.py
@@ -392,7 +392,7 @@ class BCPPCompiler(CCompiler) :
try:
self.spawn(pp_args)
except DistutilsExecError as msg:
- print msg
+ print(msg)
raise CompileError, msg
# preprocess()
diff --git a/Lib/distutils/ccompiler.py b/Lib/distutils/ccompiler.py
index 0ed9a40a35..25d90c8a9a 100644
--- a/Lib/distutils/ccompiler.py
+++ b/Lib/distutils/ccompiler.py
@@ -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)
diff --git a/Lib/distutils/cmd.py b/Lib/distutils/cmd.py
index 3cd5858920..be0a3e23f6 100644
--- a/Lib/distutils/cmd.py
+++ b/Lib/distutils/cmd.py
@@ -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")
diff --git a/Lib/distutils/command/bdist_rpm.py b/Lib/distutils/command/bdist_rpm.py
index 6f0e0d881c..bbcf2927dc 100644
--- a/Lib/distutils/command/bdist_rpm.py
+++ b/Lib/distutils/command/bdist_rpm.py
@@ -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:
diff --git a/Lib/distutils/command/config.py b/Lib/distutils/command/config.py
index 520c1b0c76..42465693be 100644
--- a/Lib/distutils/command/config.py
+++ b/Lib/distutils/command/config.py
@@ -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())
diff --git a/Lib/distutils/command/install.py b/Lib/distutils/command/install.py
index 453151d08b..fd5d6d1f39 100644
--- a/Lib/distutils/command/install.py
+++ b/Lib/distutils/command/install.py
@@ -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):
diff --git a/Lib/distutils/command/register.py b/Lib/distutils/command/register.py
index cb9525ab0e..48070ee83b 100644
--- a/Lib/distutils/command/register.py
+++ b/Lib/distutils/command/register.py
@@ -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
diff --git a/Lib/distutils/command/upload.py b/Lib/distutils/command/upload.py
index 7f96a475b6..438ae99a9c 100644
--- a/Lib/distutils/command/upload.py
+++ b/Lib/distutils/command/upload.py
@@ -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)
diff --git a/Lib/distutils/core.py b/Lib/distutils/core.py
index 4dc8eb01aa..6242775c11 100644
--- a/Lib/distutils/core.py
+++ b/Lib/distutils/core.py
@@ -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":
diff --git a/Lib/distutils/dist.py b/Lib/distutils/dist.py
index d21c5e2f1b..ca7a2f9952 100644
--- a/Lib/distutils/dist.py
+++ b/Lib/distutils/dist.py
@@ -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")
diff --git a/Lib/distutils/fancy_getopt.py b/Lib/distutils/fancy_getopt.py
index 62a24e8524..646f8e1ee6 100644
--- a/Lib/distutils/fancy_getopt.py
+++ b/Lib/distutils/fancy_getopt.py
@@ -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()
diff --git a/Lib/distutils/filelist.py b/Lib/distutils/filelist.py
index 4bbdd1f00f..e4a83d6484 100644
--- a/Lib/distutils/filelist.py
+++ b/Lib/distutils/filelist.py
@@ -53,7 +53,7 @@ class FileList:
"""
from distutils.debug import DEBUG
if DEBUG:
- print msg
+ print(msg)
# -- List-like methods ---------------------------------------------
diff --git a/Lib/distutils/log.py b/Lib/distutils/log.py
index 95d4c1c5a2..e4959d6492 100644
--- a/Lib/distutils/log.py
+++ b/Lib/distutils/log.py
@@ -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):
diff --git a/Lib/distutils/mwerkscompiler.py b/Lib/distutils/mwerkscompiler.py
index 0de123d9e9..9db1a39b17 100644
--- a/Lib/distutils/mwerkscompiler.py
+++ b/Lib/distutils/mwerkscompiler.py
@@ -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)
diff --git a/Lib/distutils/spawn.py b/Lib/distutils/spawn.py
index 6b07f52ebe..c75931c3ab 100644
--- a/Lib/distutils/spawn.py
+++ b/Lib/distutils/spawn.py
@@ -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)
diff --git a/Lib/distutils/tests/test_dist.py b/Lib/distutils/tests/test_dist.py
index 4d2a7cdf1a..8d4b07037c 100644
--- a/Lib/distutils/tests/test_dist.py
+++ b/Lib/distutils/tests/test_dist.py
@@ -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(),
diff --git a/Lib/distutils/text_file.py b/Lib/distutils/text_file.py
index ff2878de1b..10ee1be783 100644
--- a/Lib/distutils/text_file.py
+++ b/Lib/distutils/text_file.py
@@ -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"
diff --git a/Lib/doctest.py b/Lib/doctest.py
index d120a01306..f55396e21c 100644
--- a/Lib/doctest.py
+++ b/Lib/doctest.py
@@ -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
diff --git a/Lib/email/generator.py b/Lib/email/generator.py
index ed832a3e9a..4f3fea4d01 100644
--- a/Lib/email/generator.py
+++ b/Lib/email/generator.py
@@ -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)
diff --git a/Lib/email/iterators.py b/Lib/email/iterators.py
index e99f2280da..4f2c84c099 100644
--- a/Lib/email/iterators.py
+++ b/Lib/email/iterators.py
@@ -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)
diff --git a/Lib/email/test/test_email.py b/Lib/email/test/test_email.py
index 8127ef003f..0a25a67abb 100644
--- a/Lib/email/test/test_email.py
+++ b/Lib/email/test/test_email.py
@@ -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):
diff --git a/Lib/email/test/test_email_renamed.py b/Lib/email/test/test_email_renamed.py
index ce685c5f2d..532b146a04 100644
--- a/Lib/email/test/test_email_renamed.py
+++ b/Lib/email/test/test_email_renamed.py
@@ -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):
diff --git a/Lib/filecmp.py b/Lib/filecmp.py
index 51a97a55db..dda227256e 100644
--- a/Lib/filecmp.py
+++ b/Lib/filecmp.py
@@ -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,
diff --git a/Lib/fileinput.py b/Lib/fileinput.py
index 19932ca8e6..f6913eb8cb 100644
--- a/Lib/fileinput.py
+++ b/Lib/fileinput.py
@@ -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()
diff --git a/Lib/formatter.py b/Lib/formatter.py
index fa2b38938a..50a9cd8133 100644
--- a/Lib/formatter.py
+++ b/Lib/formatter.py
@@ -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):
diff --git a/Lib/fpformat.py b/Lib/fpformat.py
index 0ae86a913f..485c39b292 100644
--- a/Lib/fpformat.py
+++ b/Lib/fpformat.py
@@ -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
diff --git a/Lib/ftplib.py b/Lib/ftplib.py
index 16c4a0219c..85e3cc9153 100644
--- a/Lib/ftplib.py
+++ b/Lib/ftplib.py
@@ -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
diff --git a/Lib/getopt.py b/Lib/getopt.py
index 04e881ec73..4882fdc25e 100644
--- a/Lib/getopt.py
+++ b/Lib/getopt.py
@@ -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"]))
diff --git a/Lib/getpass.py b/Lib/getpass.py
index 8204a479f6..02fe527e6b 100644
--- a/Lib/getpass.py
+++ b/Lib/getpass.py
@@ -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)
diff --git a/Lib/gopherlib.py b/Lib/gopherlib.py
index d789161e60..2fad21c9bf 100644
--- a/Lib/gopherlib.py
+++ b/Lib/gopherlib.py
@@ -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__':
diff --git a/Lib/gzip.py b/Lib/gzip.py
index e5bb79e9dc..aac9956ea2 100644
--- a/Lib/gzip.py
+++ b/Lib/gzip.py
@@ -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")
diff --git a/Lib/heapq.py b/Lib/heapq.py
index 753c3b7ec1..9ab4c99c94 100644
--- a/Lib/heapq.py
+++ b/Lib/heapq.py
@@ -340,4 +340,4 @@ if __name__ == "__main__":
sort = []
while heap:
sort.append(heappop(heap))
- print sort
+ print(sort)
diff --git a/Lib/hotshot/log.py b/Lib/hotshot/log.py
index df8f637547..059142eec1 100644
--- a/Lib/hotshot/log.py
+++ b/Lib/hotshot/log.py
@@ -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
diff --git a/Lib/hotshot/stones.py b/Lib/hotshot/stones.py
index 7f88606329..8f974b93b0 100644
--- a/Lib/hotshot/stones.py
+++ b/Lib/hotshot/stones.py
@@ -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()
diff --git a/Lib/htmllib.py b/Lib/htmllib.py
index 652519f173..88e1df5741 100644
--- a/Lib/htmllib.py
+++ b/Lib/htmllib.py
@@ -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()
diff --git a/Lib/httplib.py b/Lib/httplib.py
index ca6e1d0b15..25075304ce 100644
--- a/Lib/httplib.py
+++ b/Lib/httplib.py
@@ -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()
diff --git a/Lib/idlelib/CallTips.py b/Lib/idlelib/CallTips.py
index 997eb13a0f..1ffbc162db 100644
--- a/Lib/idlelib/CallTips.py
+++ b/Lib/idlelib/CallTips.py
@@ -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,
diff --git a/Lib/idlelib/ColorDelegator.py b/Lib/idlelib/ColorDelegator.py
index 4cfcdc6353..5328d41196 100644
--- a/Lib/idlelib/ColorDelegator.py
+++ b/Lib/idlelib/ColorDelegator.py
@@ -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):
diff --git a/Lib/idlelib/Delegator.py b/Lib/idlelib/Delegator.py
index 6125591fe0..cc6266126e 100644
--- a/Lib/idlelib/Delegator.py
+++ b/Lib/idlelib/Delegator.py
@@ -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()
diff --git a/Lib/idlelib/EditorWindow.py b/Lib/idlelib/EditorWindow.py
index 396e2bdb65..7cd6c1f379 100644
--- a/Lib/idlelib/EditorWindow.py
+++ b/Lib/idlelib/EditorWindow.py
@@ -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)
diff --git a/Lib/idlelib/FileList.py b/Lib/idlelib/FileList.py
index 2ef0640c0d..9c6fafeaa4 100644
--- a/Lib/idlelib/FileList.py
+++ b/Lib/idlelib/FileList.py
@@ -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:
diff --git a/Lib/idlelib/GrepDialog.py b/Lib/idlelib/GrepDialog.py
index 99d2e4dabc..c96fada305 100644
--- a/Lib/idlelib/GrepDialog.py
+++ b/Lib/idlelib/GrepDialog.py
@@ -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 = []
diff --git a/Lib/idlelib/MultiCall.py b/Lib/idlelib/MultiCall.py
index 40db92db73..1bb1576853 100644
--- a/Lib/idlelib/MultiCall.py
+++ b/Lib/idlelib/MultiCall.py
@@ -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
diff --git a/Lib/idlelib/Percolator.py b/Lib/idlelib/Percolator.py
index ebbcba9e6a..a0b1303792 100644
--- a/Lib/idlelib/Percolator.py
+++ b/Lib/idlelib/Percolator.py
@@ -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)
diff --git a/Lib/idlelib/PyShell.py b/Lib/idlelib/PyShell.py
index 46ef211c05..e8284d81fc 100644
--- a/Lib/idlelib/PyShell.py
+++ b/Lib/idlelib/PyShell.py
@@ -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':
diff --git a/Lib/idlelib/ScrolledList.py b/Lib/idlelib/ScrolledList.py
index 9211936577..350fdbd5ba 100644
--- a/Lib/idlelib/ScrolledList.py
+++ b/Lib/idlelib/ScrolledList.py
@@ -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)
diff --git a/Lib/idlelib/UndoDelegator.py b/Lib/idlelib/UndoDelegator.py
index 182a1170e8..0f95b3bddc 100644
--- a/Lib/idlelib/UndoDelegator.py
+++ b/Lib/idlelib/UndoDelegator.py
@@ -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"
diff --git a/Lib/idlelib/WidgetRedirector.py b/Lib/idlelib/WidgetRedirector.py
index 126a2cd672..59005b8708 100644
--- a/Lib/idlelib/WidgetRedirector.py
+++ b/Lib/idlelib/WidgetRedirector.py
@@ -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()
diff --git a/Lib/idlelib/WindowList.py b/Lib/idlelib/WindowList.py
index 2fad998da1..fc463b804a 100644
--- a/Lib/idlelib/WindowList.py
+++ b/Lib/idlelib/WindowList.py
@@ -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()
diff --git a/Lib/idlelib/configHandler.py b/Lib/idlelib/configHandler.py
index 826fb5dbb8..469d0e4868 100644
--- a/Lib/idlelib/configHandler.py
+++ b/Lib/idlelib/configHandler.py
@@ -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')
diff --git a/Lib/idlelib/configHelpSourceEdit.py b/Lib/idlelib/configHelpSourceEdit.py
index 661162196c..912a441698 100644
--- a/Lib/idlelib/configHelpSourceEdit.py
+++ b/Lib/idlelib/configHelpSourceEdit.py
@@ -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()
diff --git a/Lib/idlelib/configSectionNameDialog.py b/Lib/idlelib/configSectionNameDialog.py
index 4f1b002afc..21dfab12ce 100644
--- a/Lib/idlelib/configSectionNameDialog.py
+++ b/Lib/idlelib/configSectionNameDialog.py
@@ -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()
diff --git a/Lib/idlelib/keybindingDialog.py b/Lib/idlelib/keybindingDialog.py
index aff9cac587..69900f9fbd 100644
--- a/Lib/idlelib/keybindingDialog.py
+++ b/Lib/idlelib/keybindingDialog.py
@@ -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()
diff --git a/Lib/idlelib/rpc.py b/Lib/idlelib/rpc.py
index e3a42d943a..169bcebcc5 100644
--- a/Lib/idlelib/rpc.py
+++ b/Lib/idlelib/rpc.py
@@ -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):
diff --git a/Lib/idlelib/run.py b/Lib/idlelib/run.py
index 6b29003f20..fa201a8d21 100644
--- a/Lib/idlelib/run.py
+++ b/Lib/idlelib/run.py
@@ -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()
diff --git a/Lib/ihooks.py b/Lib/ihooks.py
index eef34742e0..95691b6f2c 100644
--- a/Lib/ihooks.py
+++ b/Lib/ihooks.py
@@ -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):
diff --git a/Lib/imaplib.py b/Lib/imaplib.py
index 11e262ed50..fcf68ef938 100644
--- a/Lib/imaplib.py
+++ b/Lib/imaplib.py
@@ -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
diff --git a/Lib/imghdr.py b/Lib/imghdr.py
index 2fbc9661eb..f34f234877 100644
--- a/Lib/imghdr.py
+++ b/Lib/imghdr.py
@@ -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 ***')
diff --git a/Lib/imputil.py b/Lib/imputil.py
index c3d1acd67a..1472d9c02b 100644
--- a/Lib/imputil.py
+++ b/Lib/imputil.py
@@ -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()
diff --git a/Lib/lib-tk/Dialog.py b/Lib/lib-tk/Dialog.py
index b52e5b49d2..0ddfc735e7 100644
--- a/Lib/lib-tk/Dialog.py
+++ b/Lib/lib-tk/Dialog.py
@@ -36,7 +36,7 @@ def _test():
'strings': ('Save File',
'Discard Changes',
'Return to Editor')})
- print d.num
+ print(d.num)
if __name__ == '__main__':
diff --git a/Lib/lib-tk/FileDialog.py b/Lib/lib-tk/FileDialog.py
index 06ce2b9229..9ded88b553 100644
--- a/Lib/lib-tk/FileDialog.py
+++ b/Lib/lib-tk/FileDialog.py
@@ -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__':
diff --git a/Lib/lib-tk/SimpleDialog.py b/Lib/lib-tk/SimpleDialog.py
index cb08318dbd..fa2d1adc70 100644
--- a/Lib/lib-tk/SimpleDialog.py
+++ b/Lib/lib-tk/SimpleDialog.py
@@ -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)
diff --git a/Lib/lib-tk/Tkinter.py b/Lib/lib-tk/Tkinter.py
index 157b066a0d..7753f2d473 100644
--- a/Lib/lib-tk/Tkinter.py
+++ b/Lib/lib-tk/Tkinter.py
@@ -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
diff --git a/Lib/lib-tk/tkColorChooser.py b/Lib/lib-tk/tkColorChooser.py
index a55a797dd4..e3593ed24c 100644
--- a/Lib/lib-tk/tkColorChooser.py
+++ b/Lib/lib-tk/tkColorChooser.py
@@ -67,4 +67,4 @@ def askcolor(color = None, **options):
if __name__ == "__main__":
- print "color", askcolor()
+ print("color", askcolor())
diff --git a/Lib/lib-tk/tkFileDialog.py b/Lib/lib-tk/tkFileDialog.py
index a35feedc50..0f2065d8fb 100644
--- a/Lib/lib-tk/tkFileDialog.py
+++ b/Lib/lib-tk/tkFileDialog.py
@@ -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))
diff --git a/Lib/lib-tk/tkFont.py b/Lib/lib-tk/tkFont.py
index 15dea2eba3..ce50397bff 100644
--- a/Lib/lib-tk/tkFont.py
+++ b/Lib/lib-tk/tkFont.py
@@ -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()
diff --git a/Lib/lib-tk/tkMessageBox.py b/Lib/lib-tk/tkMessageBox.py
index d14ca86feb..94ba788b15 100644
--- a/Lib/lib-tk/tkMessageBox.py
+++ b/Lib/lib-tk/tkMessageBox.py
@@ -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?"))
diff --git a/Lib/lib-tk/tkSimpleDialog.py b/Lib/lib-tk/tkSimpleDialog.py
index 8d35db2770..f4ed77a044 100644
--- a/Lib/lib-tk/tkSimpleDialog.py
+++ b/Lib/lib-tk/tkSimpleDialog.py
@@ -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"))
diff --git a/Lib/locale.py b/Lib/locale.py
index fd549bbde1..d3294ce663 100644
--- a/Lib/locale.py
+++ b/Lib/locale.py
@@ -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()
diff --git a/Lib/logging/handlers.py b/Lib/logging/handlers.py
index e8c3591b07..687ecfe05c 100644
--- a/Lib/logging/handlers.py
+++ b/Lib/logging/handlers.py
@@ -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):
diff --git a/Lib/macurl2path.py b/Lib/macurl2path.py
index 4c5ae64572..b18f2b2713 100644
--- a/Lib/macurl2path.py
+++ b/Lib/macurl2path.py
@@ -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()
diff --git a/Lib/mailcap.py b/Lib/mailcap.py
index b2ddacd046..fd17f5b265 100644
--- a/Lib/mailcap.py
+++ b/Lib/mailcap.py
@@ -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()
diff --git a/Lib/mhlib.py b/Lib/mhlib.py
index 8ae6bad1ee..bf9556c349 100644
--- a/Lib/mhlib.py
+++ b/Lib/mhlib.py
@@ -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()')
diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py
index 83071d4b8e..8774170fe2 100644
--- a/Lib/mimetypes.py
+++ b/Lib/mimetypes.py
@@ -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)
diff --git a/Lib/mimify.py b/Lib/mimify.py
index b6f61439d7..6609e80b98 100755
--- a/Lib/mimify.py
+++ b/Lib/mimify.py
@@ -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
diff --git a/Lib/modulefinder.py b/Lib/modulefinder.py
index 04c9abff8c..5145f7297f 100644
--- a/Lib/modulefinder.py
+++ b/Lib/modulefinder.py
@@ -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]")
diff --git a/Lib/msilib/__init__.py b/Lib/msilib/__init__.py
index 269a2fa210..27b03ea24a 100644
--- a/Lib/msilib/__init__.py
+++ b/Lib/msilib/__init__.py
@@ -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:
diff --git a/Lib/netrc.py b/Lib/netrc.py
index 5493d77d3e..754828c8aa 100644
--- a/Lib/netrc.py
+++ b/Lib/netrc.py
@@ -108,4 +108,4 @@ class netrc:
return rep
if __name__ == '__main__':
- print netrc()
+ print(netrc())
diff --git a/Lib/nntplib.py b/Lib/nntplib.py
index 6e6a2b6d0d..3f933f9d22 100644
--- a/Lib/nntplib.py
+++ b/Lib/nntplib.py
@@ -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)
diff --git a/Lib/optparse.py b/Lib/optparse.py
index eca2818f0a..5122e4974b 100644
--- a/Lib/optparse.py
+++ b/Lib/optparse.py
@@ -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:
diff --git a/Lib/pdb.py b/Lib/pdb.py
index 3ef03a0df2..634991383c 100755
--- a/Lib/pdb.py
+++ b/Lib/pdb.py
@@ -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
diff --git a/Lib/pickletools.py b/Lib/pickletools.py
index 8b255b9d34..846172a8e2 100644
--- a/Lib/pickletools.py
+++ b/Lib/pickletools.py
@@ -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)
diff --git a/Lib/pipes.py b/Lib/pipes.py
index 295d9c88b6..07ee60c275 100644
--- a/Lib/pipes.py
+++ b/Lib/pipes.py
@@ -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.')
diff --git a/Lib/plat-irix5/cddb.py b/Lib/plat-irix5/cddb.py
index 7b2711f0b1..19a9d42012 100755
--- a/Lib/plat-irix5/cddb.py
+++ b/Lib/plat-irix5/cddb.py
@@ -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
diff --git a/Lib/plat-irix5/cdplayer.py b/Lib/plat-irix5/cdplayer.py
index 1c0168f7d2..b3fc8a4667 100755
--- a/Lib/plat-irix5/cdplayer.py
+++ b/Lib/plat-irix5/cdplayer.py
@@ -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':
diff --git a/Lib/plat-irix5/flp.py b/Lib/plat-irix5/flp.py
index 83a22b6587..b04ecf37b8 100755
--- a/Lib/plat-irix5/flp.py
+++ b/Lib/plat-irix5/flp.py
@@ -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)
diff --git a/Lib/plat-irix5/panel.py b/Lib/plat-irix5/panel.py
index 1be914617c..5a0d87ee25 100755
--- a/Lib/plat-irix5/panel.py
+++ b/Lib/plat-irix5/panel.py
@@ -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()
diff --git a/Lib/plat-irix6/cddb.py b/Lib/plat-irix6/cddb.py
index 45883054f8..bfdf57da84 100644
--- a/Lib/plat-irix6/cddb.py
+++ b/Lib/plat-irix6/cddb.py
@@ -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
diff --git a/Lib/plat-irix6/cdplayer.py b/Lib/plat-irix6/cdplayer.py
index d4bc7328ac..a2be8b44f1 100644
--- a/Lib/plat-irix6/cdplayer.py
+++ b/Lib/plat-irix6/cdplayer.py
@@ -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':
diff --git a/Lib/plat-irix6/flp.py b/Lib/plat-irix6/flp.py
index b021622684..d150be09b4 100644
--- a/Lib/plat-irix6/flp.py
+++ b/Lib/plat-irix6/flp.py
@@ -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)
diff --git a/Lib/plat-irix6/panel.py b/Lib/plat-irix6/panel.py
index 1be914617c..5a0d87ee25 100644
--- a/Lib/plat-irix6/panel.py
+++ b/Lib/plat-irix6/panel.py
@@ -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()
diff --git a/Lib/plat-mac/Audio_mac.py b/Lib/plat-mac/Audio_mac.py
index fd96095ad6..67fb959806 100644
--- a/Lib/plat-mac/Audio_mac.py
+++ b/Lib/plat-mac/Audio_mac.py
@@ -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__':
diff --git a/Lib/plat-mac/EasyDialogs.py b/Lib/plat-mac/EasyDialogs.py
index 340e3edf56..3c920119e2 100644
--- a/Lib/plat-mac/EasyDialogs.py
+++ b/Lib/plat-mac/EasyDialogs.py
@@ -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:
diff --git a/Lib/plat-mac/FrameWork.py b/Lib/plat-mac/FrameWork.py
index 0bd6feb7e3..2a07c99d89 100644
--- a/Lib/plat-mac/FrameWork.py
+++ b/Lib/plat-mac/FrameWork.py
@@ -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
diff --git a/Lib/plat-mac/MiniAEFrame.py b/Lib/plat-mac/MiniAEFrame.py
index 1d990af1c5..7ae3351042 100644
--- a/Lib/plat-mac/MiniAEFrame.py
+++ b/Lib/plat-mac/MiniAEFrame.py
@@ -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__':
diff --git a/Lib/plat-mac/aetools.py b/Lib/plat-mac/aetools.py
index 7a52eb9a8e..d1812341a8 100644
--- a/Lib/plat-mac/aetools.py
+++ b/Lib/plat-mac/aetools.py
@@ -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__':
diff --git a/Lib/plat-mac/applesingle.py b/Lib/plat-mac/applesingle.py
index fdd163d4f7..2e0e96708a 100644
--- a/Lib/plat-mac/applesingle.py
+++ b/Lib/plat-mac/applesingle.py
@@ -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
diff --git a/Lib/plat-mac/argvemulator.py b/Lib/plat-mac/argvemulator.py
index fe9e8f8fcd..676e80ac5c 100644
--- a/Lib/plat-mac/argvemulator.py
+++ b/Lib/plat-mac/argvemulator.py
@@ -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)
diff --git a/Lib/plat-mac/bundlebuilder.py b/Lib/plat-mac/bundlebuilder.py
index d58adf25f5..bf11ed9fd5 100755
--- a/Lib/plat-mac/bundlebuilder.py
+++ b/Lib/plat-mac/bundlebuilder.py
@@ -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):
diff --git a/Lib/plat-mac/findertools.py b/Lib/plat-mac/findertools.py
index f013c85645..282cc27975 100644
--- a/Lib/plat-mac/findertools.py
+++ b/Lib/plat-mac/findertools.py
@@ -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()
diff --git a/Lib/plat-mac/gensuitemodule.py b/Lib/plat-mac/gensuitemodule.py
index 7d03d8f6e7..fd706a0cda 100644
--- a/Lib/plat-mac/gensuitemodule.py
+++ b/Lib/plat-mac/gensuitemodule.py
@@ -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 = []
diff --git a/Lib/plat-mac/ic.py b/Lib/plat-mac/ic.py
index 490cbf72e9..5c109d6cf1 100644
--- a/Lib/plat-mac/ic.py
+++ b/Lib/plat-mac/ic.py
@@ -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__':
diff --git a/Lib/plat-mac/macresource.py b/Lib/plat-mac/macresource.py
index 91dfffa1c6..fa14c045db 100644
--- a/Lib/plat-mac/macresource.py
+++ b/Lib/plat-mac/macresource.py
@@ -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
diff --git a/Lib/plat-mac/pimp.py b/Lib/plat-mac/pimp.py
index 3b1a6861f1..09f63db2fa 100644
--- a/Lib/plat-mac/pimp.py
+++ b/Lib/plat-mac/pimp.py
@@ -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)
diff --git a/Lib/plat-mac/videoreader.py b/Lib/plat-mac/videoreader.py
index f16228b828..42954b7028 100644
--- a/Lib/plat-mac/videoreader.py
+++ b/Lib/plat-mac/videoreader.py
@@ -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()
diff --git a/Lib/plat-os2emx/_emx_link.py b/Lib/plat-os2emx/_emx_link.py
index 422c2bbf6f..e8298680b1 100644
--- a/Lib/plat-os2emx/_emx_link.py
+++ b/Lib/plat-os2emx/_emx_link.py
@@ -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]))
diff --git a/Lib/plat-riscos/rourl2path.py b/Lib/plat-riscos/rourl2path.py
index 981cebab69..a5aee3490e 100644
--- a/Lib/plat-riscos/rourl2path.py
+++ b/Lib/plat-riscos/rourl2path.py
@@ -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()
diff --git a/Lib/platform.py b/Lib/platform.py
index 7d3c34f1da..720da04006 100755
--- a/Lib/platform.py
+++ b/Lib/platform.py
@@ -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)
diff --git a/Lib/popen2.py b/Lib/popen2.py
index 694979e6d6..3618487c45 100644
--- a/Lib/popen2.py
+++ b/Lib/popen2.py
@@ -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()
diff --git a/Lib/poplib.py b/Lib/poplib.py
index b7a7a8af75..adf784f6dd 100644
--- a/Lib/poplib.py
+++ b/Lib/poplib.py
@@ -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()
diff --git a/Lib/pprint.py b/Lib/pprint.py
index 97135ebfe5..e54edbe19c 100644
--- a/Lib/pprint.py
+++ b/Lib/pprint.py
@@ -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()
diff --git a/Lib/profile.py b/Lib/profile.py
index dc278dd5ee..83480cf491 100755
--- a/Lib/profile.py
+++ b/Lib/profile.py
@@ -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] ..."
diff --git a/Lib/pstats.py b/Lib/pstats.py
index 2b152c3127..439ac84dd0 100644
--- a/Lib/pstats.py
+++ b/Lib/pstats.py
@@ -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
diff --git a/Lib/pyclbr.py b/Lib/pyclbr.py
index 079b38c411..a4ec3692f1 100644
--- a/Lib/pyclbr.py
+++ b/Lib/pyclbr.py
@@ -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()
diff --git a/Lib/pydoc.py b/Lib/pydoc.py
index c496d1dd6f..63bd2f7c38 100755
--- a/Lib/pydoc.py
+++ b/Lib/pydoc.py
@@ -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()
diff --git a/Lib/quopri.py b/Lib/quopri.py
index 171a59e0ae..fccfe85b9f 100755
--- a/Lib/quopri.py
+++ b/Lib/quopri.py
@@ -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
diff --git a/Lib/random.py b/Lib/random.py
index 79ffb551e6..8adcff5f6d 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -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):
diff --git a/Lib/rexec.py b/Lib/rexec.py
index 665f294dd4..e5ceb728dc 100644
--- a/Lib/rexec.py
+++ b/Lib/rexec.py
@@ -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:
diff --git a/Lib/rfc822.py b/Lib/rfc822.py
index a9109cdfd2..8c636c1bd8 100644
--- a/Lib/rfc822.py
+++ b/Lib/rfc822.py
@@ -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())
diff --git a/Lib/robotparser.py b/Lib/robotparser.py
index 48ea066682..0edb55fd21 100644
--- a/Lib/robotparser.py
+++ b/Lib/robotparser.py
@@ -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
diff --git a/Lib/runpy.py b/Lib/runpy.py
index dc350cf94a..b0129c9a47 100755
--- a/Lib/runpy.py
+++ b/Lib/runpy.py
@@ -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)
diff --git a/Lib/sgmllib.py b/Lib/sgmllib.py
index 1574f44a9d..987b65edff 100644
--- a/Lib/sgmllib.py
+++ b/Lib/sgmllib.py
@@ -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()
diff --git a/Lib/shlex.py b/Lib/shlex.py
index 6632b87596..d81e99ec84 100644
--- a/Lib/shlex.py
+++ b/Lib/shlex.py
@@ -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
diff --git a/Lib/site.py b/Lib/site.py
index 5b03b5e802..95001ba314 100644
--- a/Lib/site.py
+++ b/Lib/site.py
@@ -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()
diff --git a/Lib/smtpd.py b/Lib/smtpd.py
index 3b818564c0..73e7777fa0 100755
--- a/Lib/smtpd.py
+++ b/Lib/smtpd.py
@@ -98,9 +98,9 @@ COMMASPACE = ', '
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 ------------')
@@ -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:
diff --git a/Lib/smtplib.py b/Lib/smtplib.py
index 701306d66c..aedcac43bc 100755
--- a/Lib/smtplib.py
+++ b/Lib/smtplib.py
@@ -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)
diff --git a/Lib/sndhdr.py b/Lib/sndhdr.py
index df2ccf17ba..f505804c69 100644
--- a/Lib/sndhdr.py
+++ b/Lib/sndhdr.py
@@ -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()
diff --git a/Lib/sqlite3/test/dbapi.py b/Lib/sqlite3/test/dbapi.py
index 6fe93abe6c..287848a438 100644
--- a/Lib/sqlite3/test/dbapi.py
+++ b/Lib/sqlite3/test/dbapi.py
@@ -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):
diff --git a/Lib/sre_constants.py b/Lib/sre_constants.py
index 1863f48bb1..94962cbc39 100644
--- a/Lib/sre_constants.py
+++ b/Lib/sre_constants.py
@@ -258,4 +258,4 @@ if __name__ == "__main__":
f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET)
f.close()
- print "done"
+ print("done")
diff --git a/Lib/sre_parse.py b/Lib/sre_parse.py
index 2b3064b0ef..49dc080ed4 100644
--- a/Lib/sre_parse.py
+++ b/Lib/sre_parse.py
@@ -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):
diff --git a/Lib/subprocess.py b/Lib/subprocess.py
index 1b4ef89c15..759b59f13b 100644
--- a/Lib/subprocess.py
+++ b/Lib/subprocess.py
@@ -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()
diff --git a/Lib/sunaudio.py b/Lib/sunaudio.py
index 3b0ee2793c..05bd867281 100644
--- a/Lib/sunaudio.py
+++ b/Lib/sunaudio.py
@@ -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))
diff --git a/Lib/symtable.py b/Lib/symtable.py
index 399faa1208..d18d30b816 100644
--- a/Lib/symtable.py
+++ b/Lib/symtable.py
@@ -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())
diff --git a/Lib/tabnanny.py b/Lib/tabnanny.py
index 1d2c6db2bc..0ae5e9f0df 100755
--- a/Lib/tabnanny.py
+++ b/Lib/tabnanny.py
@@ -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
diff --git a/Lib/tarfile.py b/Lib/tarfile.py
index 1685426fbf..feea433703 100644
--- a/Lib/tarfile.py
+++ b/Lib/tarfile.py
@@ -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:
diff --git a/Lib/telnetlib.py b/Lib/telnetlib.py
index 4964d59093..f482abf37c 100644
--- a/Lib/telnetlib.py
+++ b/Lib/telnetlib.py
@@ -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)
diff --git a/Lib/test/badsyntax_future8.py b/Lib/test/badsyntax_future8.py
index c167b0933d..ca45289e2e 100644
--- a/Lib/test/badsyntax_future8.py
+++ b/Lib/test/badsyntax_future8.py
@@ -7,4 +7,4 @@ def f(x):
return x + y
return g
-print f(2)(4)
+print(f(2)(4))
diff --git a/Lib/test/badsyntax_future9.py b/Lib/test/badsyntax_future9.py
index cdce32a4eb..916de06ab7 100644
--- a/Lib/test/badsyntax_future9.py
+++ b/Lib/test/badsyntax_future9.py
@@ -7,4 +7,4 @@ def f(x):
return x + y
return g
-print f(2)(4)
+print(f(2)(4))
diff --git a/Lib/test/crashers/bogus_sre_bytecode.py b/Lib/test/crashers/bogus_sre_bytecode.py
index 4bfc7300d5..7f006d9ede 100644
--- a/Lib/test/crashers/bogus_sre_bytecode.py
+++ b/Lib/test/crashers/bogus_sre_bytecode.py
@@ -38,7 +38,7 @@ ss = ["", "world", "x" * 500]
while 1:
code = [pick() for i in range(random.randrange(5, 25))]
- print code
+ print(code)
pat = _sre.compile(None, 0, code)
for s in ss:
try:
diff --git a/Lib/test/crashers/borrowed_ref_1.py b/Lib/test/crashers/borrowed_ref_1.py
index d16ede2e46..b82f4644bf 100644
--- a/Lib/test/crashers/borrowed_ref_1.py
+++ b/Lib/test/crashers/borrowed_ref_1.py
@@ -8,7 +8,7 @@ class A(object):
class B(object):
def __del__(self):
- print 'hi'
+ print('hi')
del D.__missing__
class D(dict):
diff --git a/Lib/test/crashers/borrowed_ref_2.py b/Lib/test/crashers/borrowed_ref_2.py
index 1a7b3ff750..f3ca35016d 100644
--- a/Lib/test/crashers/borrowed_ref_2.py
+++ b/Lib/test/crashers/borrowed_ref_2.py
@@ -10,7 +10,7 @@ class A(object):
class B(object):
def __del__(self):
- print "hi"
+ print("hi")
del C.d
class D(object):
diff --git a/Lib/test/crashers/gc_inspection.py b/Lib/test/crashers/gc_inspection.py
index 10caa79782..ae85f97a74 100644
--- a/Lib/test/crashers/gc_inspection.py
+++ b/Lib/test/crashers/gc_inspection.py
@@ -25,8 +25,8 @@ def g():
yield marker
# now the marker is in the tuple being constructed
[tup] = [x for x in gc.get_referrers(marker) if type(x) is tuple]
- print tup
- print tup[1]
+ print(tup)
+ print(tup[1])
tuple(g())
diff --git a/Lib/test/crashers/loosing_mro_ref.py b/Lib/test/crashers/loosing_mro_ref.py
index f0b8047d8d..5ecde63820 100644
--- a/Lib/test/crashers/loosing_mro_ref.py
+++ b/Lib/test/crashers/loosing_mro_ref.py
@@ -32,5 +32,5 @@ class X(Base):
# there from the beginning :-)
locals()[MyKey()] = 5
-print X.mykey
+print(X.mykey)
# I get a segfault, or a slightly wrong assertion error in a debug build.
diff --git a/Lib/test/crashers/modify_dict_attr.py b/Lib/test/crashers/modify_dict_attr.py
index dfce467c8e..2a8fce04b5 100644
--- a/Lib/test/crashers/modify_dict_attr.py
+++ b/Lib/test/crashers/modify_dict_attr.py
@@ -16,4 +16,4 @@ class MyClass(object):
if __name__ == '__main__':
del MyClass.__dict__ # if we set tp_dict to NULL,
- print MyClass # doing anything with MyClass segfaults
+ print(MyClass) # doing anything with MyClass segfaults
diff --git a/Lib/test/crashers/nasty_eq_vs_dict.py b/Lib/test/crashers/nasty_eq_vs_dict.py
index 3f3083da89..85f7cafa23 100644
--- a/Lib/test/crashers/nasty_eq_vs_dict.py
+++ b/Lib/test/crashers/nasty_eq_vs_dict.py
@@ -44,4 +44,4 @@ dict = {y: "OK!"}
z = Yuck()
y.make_dangerous()
-print dict[z]
+print(dict[z])
diff --git a/Lib/test/inspect_fodder2.py b/Lib/test/inspect_fodder2.py
index 3d978cffe3..ef70c09040 100644
--- a/Lib/test/inspect_fodder2.py
+++ b/Lib/test/inspect_fodder2.py
@@ -7,7 +7,7 @@ def wrap(foo=None):
# line 7
def replace(func):
def insteadfunc():
- print 'hello'
+ print('hello')
return insteadfunc
# line 13
diff --git a/Lib/test/list_tests.py b/Lib/test/list_tests.py
index 3867be5ff4..507506ec0d 100644
--- a/Lib/test/list_tests.py
+++ b/Lib/test/list_tests.py
@@ -54,7 +54,7 @@ class CommonTest(seq_tests.CommonTest):
d.append(400)
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, d,
+ print(d, end=' ', file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), repr(d))
diff --git a/Lib/test/pydocfodder.py b/Lib/test/pydocfodder.py
index becdf2250e..0ae013b119 100644
--- a/Lib/test/pydocfodder.py
+++ b/Lib/test/pydocfodder.py
@@ -192,19 +192,19 @@ class FunkyProperties(object):
def __init__(self, attr):
self.attr = attr
def __call__(self, inst):
- print 'Get called', self, inst
+ print('Get called', self, inst)
return inst.desc[self.attr]
class set_desc:
def __init__(self, attr):
self.attr = attr
def __call__(self, inst, val):
- print 'Set called', self, inst, val
+ print('Set called', self, inst, val)
inst.desc[self.attr] = val
class del_desc:
def __init__(self, attr):
self.attr = attr
def __call__(self, inst):
- print 'Del called', self, inst
+ print('Del called', self, inst)
del inst.desc[self.attr]
x = property(get_desc('x'), set_desc('x'), del_desc('x'), 'prop x')
diff --git a/Lib/test/pystone.py b/Lib/test/pystone.py
index 0a25981eb6..3ddb9465af 100755
--- a/Lib/test/pystone.py
+++ b/Lib/test/pystone.py
@@ -59,9 +59,9 @@ FALSE = 0
def main(loops=LOOPS):
benchtime, stones = pystones(loops)
- print "Pystone(%s) time for %d passes = %g" % \
- (__version__, loops, benchtime)
- print "This machine benchmarks at %g pystones/second" % stones
+ print("Pystone(%s) time for %d passes = %g" % \
+ (__version__, loops, benchtime))
+ print("This machine benchmarks at %g pystones/second" % stones)
def pystones(loops=LOOPS):
@@ -251,8 +251,8 @@ def Func3(EnumParIn):
if __name__ == '__main__':
import sys
def error(msg):
- print >>sys.stderr, msg,
- print >>sys.stderr, "usage: %s [number_of_loops]" % sys.argv[0]
+ print(msg, end=' ', file=sys.stderr)
+ print("usage: %s [number_of_loops]" % sys.argv[0], file=sys.stderr)
sys.exit(100)
nargs = len(sys.argv) - 1
if nargs > 1:
diff --git a/Lib/test/regrtest.py b/Lib/test/regrtest.py
index 4517c59e1a..2efd391622 100755
--- a/Lib/test/regrtest.py
+++ b/Lib/test/regrtest.py
@@ -171,8 +171,8 @@ RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb',
def usage(code, msg=''):
- print __doc__
- if msg: print msg
+ print(__doc__)
+ if msg: print(msg)
sys.exit(code)
@@ -253,7 +253,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
elif o in ('-R', '--huntrleaks'):
huntrleaks = a.split(':')
if len(huntrleaks) != 3:
- print a, huntrleaks
+ print(a, huntrleaks)
usage(2, '-R takes three colon-separated arguments')
if len(huntrleaks[0]) == 0:
huntrleaks[0] = 5
@@ -298,7 +298,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
try:
import gc
except ImportError:
- print 'No GC available, disabling findleaks.'
+ print('No GC available, disabling findleaks.')
findleaks = False
else:
# Uncomment the line below to report garbage that is not
@@ -355,7 +355,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
save_modules = sys.modules.keys()
for test in tests:
if not quiet:
- print test
+ print(test)
sys.stdout.flush()
if trace:
# If we're tracing code coverage, then we don't exit with status
@@ -368,7 +368,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
huntrleaks)
except KeyboardInterrupt:
# print a newline separate from the ^C
- print
+ print()
break
except:
raise
@@ -383,8 +383,8 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
if findleaks:
gc.collect()
if gc.garbage:
- print "Warning: test created", len(gc.garbage),
- print "uncollectable object(s)."
+ print("Warning: test created", len(gc.garbage), end=' ')
+ print("uncollectable object(s).")
# move the uncollectable objects somewhere so we don't see
# them again
found_garbage.extend(gc.garbage)
@@ -401,16 +401,16 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
if good and not quiet:
if not bad and not skipped and len(good) > 1:
- print "All",
- print count(len(good), "test"), "OK."
+ print("All", end=' ')
+ print(count(len(good), "test"), "OK.")
if verbose:
- print "CAUTION: stdout isn't compared in verbose mode:"
- print "a test that passes in verbose mode may fail without it."
+ print("CAUTION: stdout isn't compared in verbose mode:")
+ print("a test that passes in verbose mode may fail without it.")
if bad:
- print count(len(bad), "test"), "failed:"
+ print(count(len(bad), "test"), "failed:")
printlist(bad)
if skipped and not quiet:
- print count(len(skipped), "test"), "skipped:"
+ print(count(len(skipped), "test"), "skipped:")
printlist(skipped)
e = _ExpectedSkips()
@@ -418,19 +418,19 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
if e.isvalid():
surprise = set(skipped) - e.getexpected() - set(resource_denieds)
if surprise:
- print count(len(surprise), "skip"), \
- "unexpected on", plat + ":"
+ print(count(len(surprise), "skip"), \
+ "unexpected on", plat + ":")
printlist(surprise)
else:
- print "Those skips are all expected on", plat + "."
+ print("Those skips are all expected on", plat + ".")
else:
- print "Ask someone to teach regrtest.py about which tests are"
- print "expected to get skipped on", plat + "."
+ print("Ask someone to teach regrtest.py about which tests are")
+ print("expected to get skipped on", plat + ".")
if verbose2 and bad:
- print "Re-running failed tests in verbose mode"
+ print("Re-running failed tests in verbose mode")
for test in bad:
- print "Re-running test %r in verbose mode" % test
+ print("Re-running test %r in verbose mode" % test)
sys.stdout.flush()
try:
test_support.verbose = 1
@@ -438,7 +438,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
huntrleaks)
except KeyboardInterrupt:
# print a newline separate from the ^C
- print
+ print()
break
except:
raise
@@ -537,7 +537,7 @@ def runtest_inner(test, generate, verbose, quiet,
try:
if cfp:
sys.stdout = cfp
- print test # Output file starts with test name
+ print(test) # Output file starts with test name
if test.startswith('test.'):
abstest = test
else:
@@ -558,23 +558,23 @@ def runtest_inner(test, generate, verbose, quiet,
sys.stdout = save_stdout
except test_support.ResourceDenied as msg:
if not quiet:
- print test, "skipped --", msg
+ print(test, "skipped --", msg)
sys.stdout.flush()
return -2
except (ImportError, test_support.TestSkipped) as msg:
if not quiet:
- print test, "skipped --", msg
+ print(test, "skipped --", msg)
sys.stdout.flush()
return -1
except KeyboardInterrupt:
raise
except test_support.TestFailed as msg:
- print "test", test, "failed --", msg
+ print("test", test, "failed --", msg)
sys.stdout.flush()
return 0
except:
type, value = sys.exc_info()[:2]
- print "test", test, "crashed --", str(type) + ":", value
+ print("test", test, "crashed --", str(type) + ":", value)
sys.stdout.flush()
if verbose:
traceback.print_exc(file=sys.stdout)
@@ -590,8 +590,8 @@ def runtest_inner(test, generate, verbose, quiet,
# Write it since it already exists (and the contents
# may have changed), but let the user know it isn't
# needed:
- print "output file", outputfile, \
- "is no longer needed; consider removing it"
+ print("output file", outputfile, \
+ "is no longer needed; consider removing it")
else:
# We don't need it, so don't create it.
return 1
@@ -607,7 +607,7 @@ def runtest_inner(test, generate, verbose, quiet,
expected = test + "\n"
if output == expected or huntrleaks:
return 1
- print "test", test, "produced unexpected output:"
+ print("test", test, "produced unexpected output:")
sys.stdout.flush()
reportdiff(expected, output)
sys.stdout.flush()
@@ -637,12 +637,12 @@ def cleanup_test_droppings(testname, verbose):
"directory nor file" % name)
if verbose:
- print "%r left behind %s %r" % (testname, kind, name)
+ print("%r left behind %s %r" % (testname, kind, name))
try:
nuker(name)
except Exception as msg:
- print >> sys.stderr, ("%r left behind %s %r and it couldn't be "
- "removed: %s" % (testname, kind, name, msg))
+ print(("%r left behind %s %r and it couldn't be "
+ "removed: %s" % (testname, kind, name, msg)), file=sys.stderr)
def dash_R(the_module, test, indirect_test, huntrleaks):
# This code is hackish and inelegant, but it seems to do the job.
@@ -667,8 +667,8 @@ def dash_R(the_module, test, indirect_test, huntrleaks):
deltas = []
nwarmup, ntracked, fname = huntrleaks
repcount = nwarmup + ntracked
- print >> sys.stderr, "beginning", repcount, "repetitions"
- print >> sys.stderr, ("1234567890"*(repcount//10 + 1))[:repcount]
+ print("beginning", repcount, "repetitions", file=sys.stderr)
+ print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr)
dash_R_cleanup(fs, ps, pic)
for i in range(repcount):
rc = sys.gettotalrefcount()
@@ -677,11 +677,11 @@ def dash_R(the_module, test, indirect_test, huntrleaks):
dash_R_cleanup(fs, ps, pic)
if i >= nwarmup:
deltas.append(sys.gettotalrefcount() - rc - 2)
- print >> sys.stderr
+ print(file=sys.stderr)
if any(deltas):
- print >> sys.stderr, test, 'leaked', deltas, 'references'
+ print(test, 'leaked', deltas, 'references', file=sys.stderr)
refrep = open(fname, "a")
- print >> refrep, test, 'leaked', deltas, 'references'
+ print(test, 'leaked', deltas, 'references', file=refrep)
refrep.close()
def dash_R_cleanup(fs, ps, pic):
@@ -717,7 +717,7 @@ def dash_R_cleanup(fs, ps, pic):
def reportdiff(expected, output):
import difflib
- print "*" * 70
+ print("*" * 70)
a = expected.splitlines(1)
b = output.splitlines(1)
sm = difflib.SequenceMatcher(a=a, b=b)
@@ -736,26 +736,26 @@ def reportdiff(expected, output):
pass
elif op == 'delete':
- print "***", pair(a0, a1), "of expected output missing:"
+ print("***", pair(a0, a1), "of expected output missing:")
for line in a[a0:a1]:
- print "-", line,
+ print("-", line, end=' ')
elif op == 'replace':
- print "*** mismatch between", pair(a0, a1), "of expected", \
- "output and", pair(b0, b1), "of actual output:"
+ print("*** mismatch between", pair(a0, a1), "of expected", \
+ "output and", pair(b0, b1), "of actual output:")
for line in difflib.ndiff(a[a0:a1], b[b0:b1]):
- print line,
+ print(line, end=' ')
elif op == 'insert':
- print "***", pair(b0, b1), "of actual output doesn't appear", \
- "in expected output after line", str(a1)+":"
+ print("***", pair(b0, b1), "of actual output doesn't appear", \
+ "in expected output after line", str(a1)+":")
for line in b[b0:b1]:
- print "+", line,
+ print("+", line, end=' ')
else:
- print "get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1)
+ print("get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1))
- print "*" * 70
+ print("*" * 70)
def findtestdir():
if __name__ == '__main__':
@@ -786,8 +786,8 @@ def printlist(x, width=70, indent=4):
from textwrap import fill
blanks = ' ' * indent
- print fill(' '.join(map(str, x)), width,
- initial_indent=blanks, subsequent_indent=blanks)
+ print(fill(' '.join(map(str, x)), width,
+ initial_indent=blanks, subsequent_indent=blanks))
# Map sys.platform to a string containing the basenames of tests
# expected to be skipped on that platform.
@@ -1369,5 +1369,5 @@ if __name__ == '__main__':
if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
del sys.path[i]
if len(sys.path) == pathlen:
- print 'Could not find %r in sys.path to remove it' % mydir
+ print('Could not find %r in sys.path to remove it' % mydir)
main()
diff --git a/Lib/test/reperf.py b/Lib/test/reperf.py
index 68ac40f132..7c6823471e 100644
--- a/Lib/test/reperf.py
+++ b/Lib/test/reperf.py
@@ -17,7 +17,7 @@ def timefunc(n, func, *args, **kw):
finally:
t1 = time.clock()
if n > 1:
- print n, "times",
- print func.__name__, "%.3f" % (t1-t0), "CPU seconds"
+ print(n, "times", end=' ')
+ print(func.__name__, "%.3f" % (t1-t0), "CPU seconds")
main()
diff --git a/Lib/test/sortperf.py b/Lib/test/sortperf.py
index 3c95b89182..205ff87098 100644
--- a/Lib/test/sortperf.py
+++ b/Lib/test/sortperf.py
@@ -38,7 +38,7 @@ def randfloats(n):
except os.error:
pass
except IOError as msg:
- print "can't write", fn, ":", msg
+ print("can't write", fn, ":", msg)
else:
result = marshal.load(fp)
fp.close()
@@ -60,7 +60,7 @@ def doit(L):
t0 = time.clock()
L.sort()
t1 = time.clock()
- print "%6.2f" % (t1-t0),
+ print("%6.2f" % (t1-t0), end=' ')
flush()
def tabulate(r):
@@ -84,11 +84,11 @@ def tabulate(r):
"""
cases = tuple([ch + "sort" for ch in r"*\/3+%~=!"])
fmt = ("%2s %7s" + " %6s"*len(cases))
- print fmt % (("i", "2**i") + cases)
+ print(fmt % (("i", "2**i") + cases))
for i in r:
n = 1 << i
L = randfloats(n)
- print "%2d %7d" % (i, n),
+ print("%2d %7d" % (i, n), end=' ')
flush()
doit(L) # *sort
L.reverse()
@@ -137,7 +137,7 @@ def tabulate(r):
# significantly faster if we leave tham as ints.
L = map(float, L)
doit(L) # !sort
- print
+ print()
def main():
"""Main program when invoked as a script.
diff --git a/Lib/test/test_al.py b/Lib/test/test_al.py
index 02876f0b38..e97ca65492 100755
--- a/Lib/test/test_al.py
+++ b/Lib/test/test_al.py
@@ -14,10 +14,10 @@ alattrs = ['__doc__', '__name__', 'getdefault', 'getminmax', 'getname', 'getpara
def main():
# touch all the attributes of al without doing anything
if verbose:
- print 'Touching al module attributes...'
+ print('Touching al module attributes...')
for attr in alattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(al, attr)
main()
diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py
index 02215e5ab9..6abfb90d73 100755
--- a/Lib/test/test_array.py
+++ b/Lib/test/test_array.py
@@ -975,7 +975,7 @@ def test_main(verbose=None):
test_support.run_unittest(*tests)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index 289b533f1a..24394ed925 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -117,11 +117,11 @@ eval_tests = [
if __name__=='__main__' and sys.argv[1:] == ['-g']:
for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
(eval_tests, "eval")):
- print kind+"_results = ["
+ print(kind+"_results = [")
for s in statements:
- print repr(to_tuple(compile(s, "?", kind, 0x400)))+","
- print "]"
- print "run_tests()"
+ print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
+ print("]")
+ print("run_tests()")
raise SystemExit
def test_order(ast_node, parent_pos):
diff --git a/Lib/test/test_atexit.py b/Lib/test/test_atexit.py
index 684d6079c1..9d1e003bcd 100644
--- a/Lib/test/test_atexit.py
+++ b/Lib/test/test_atexit.py
@@ -75,16 +75,16 @@ class TestCase(unittest.TestCase):
### helpers
def h1(self):
- print "h1"
+ print("h1")
def h2(self):
- print "h2"
+ print("h2")
def h3(self):
- print "h3"
+ print("h3")
def h4(self, *args, **kwargs):
- print "h4", args, kwargs
+ print("h4", args, kwargs)
def raise1(self):
raise TypeError
diff --git a/Lib/test/test_audioop.py b/Lib/test/test_audioop.py
index f585733eac..926a3cda84 100644
--- a/Lib/test/test_audioop.py
+++ b/Lib/test/test_audioop.py
@@ -7,7 +7,7 @@ def gendata1():
def gendata2():
if verbose:
- print 'getsample'
+ print('getsample')
if audioop.getsample('\0\1', 2, 0) == 1:
return '\0\0\0\1\0\2'
else:
@@ -15,7 +15,7 @@ def gendata2():
def gendata4():
if verbose:
- print 'getsample'
+ print('getsample')
if audioop.getsample('\0\0\0\1', 4, 0) == 1:
return '\0\0\0\0\0\0\0\1\0\0\0\2'
else:
@@ -23,7 +23,7 @@ def gendata4():
def testmax(data):
if verbose:
- print 'max'
+ print('max')
if audioop.max(data[0], 1) != 2 or \
audioop.max(data[1], 2) != 2 or \
audioop.max(data[2], 4) != 2:
@@ -32,7 +32,7 @@ def testmax(data):
def testminmax(data):
if verbose:
- print 'minmax'
+ print('minmax')
if audioop.minmax(data[0], 1) != (0, 2) or \
audioop.minmax(data[1], 2) != (0, 2) or \
audioop.minmax(data[2], 4) != (0, 2):
@@ -41,7 +41,7 @@ def testminmax(data):
def testmaxpp(data):
if verbose:
- print 'maxpp'
+ print('maxpp')
if audioop.maxpp(data[0], 1) != 0 or \
audioop.maxpp(data[1], 2) != 0 or \
audioop.maxpp(data[2], 4) != 0:
@@ -50,7 +50,7 @@ def testmaxpp(data):
def testavg(data):
if verbose:
- print 'avg'
+ print('avg')
if audioop.avg(data[0], 1) != 1 or \
audioop.avg(data[1], 2) != 1 or \
audioop.avg(data[2], 4) != 1:
@@ -59,7 +59,7 @@ def testavg(data):
def testavgpp(data):
if verbose:
- print 'avgpp'
+ print('avgpp')
if audioop.avgpp(data[0], 1) != 0 or \
audioop.avgpp(data[1], 2) != 0 or \
audioop.avgpp(data[2], 4) != 0:
@@ -75,7 +75,7 @@ def testrms(data):
def testcross(data):
if verbose:
- print 'cross'
+ print('cross')
if audioop.cross(data[0], 1) != 0 or \
audioop.cross(data[1], 2) != 0 or \
audioop.cross(data[2], 4) != 0:
@@ -84,7 +84,7 @@ def testcross(data):
def testadd(data):
if verbose:
- print 'add'
+ print('add')
data2 = []
for d in data:
str = ''
@@ -99,7 +99,7 @@ def testadd(data):
def testbias(data):
if verbose:
- print 'bias'
+ print('bias')
# Note: this test assumes that avg() works
d1 = audioop.bias(data[0], 1, 100)
d2 = audioop.bias(data[1], 2, 100)
@@ -112,7 +112,7 @@ def testbias(data):
def testlin2lin(data):
if verbose:
- print 'lin2lin'
+ print('lin2lin')
# too simple: we test only the size
for d1 in data:
for d2 in data:
@@ -130,7 +130,7 @@ def testadpcm2lin(data):
def testlin2adpcm(data):
if verbose:
- print 'lin2adpcm'
+ print('lin2adpcm')
# Very cursory test
if audioop.lin2adpcm('\0\0\0\0', 1, None) != ('\0\0', (0,0)):
return 0
@@ -138,7 +138,7 @@ def testlin2adpcm(data):
def testlin2alaw(data):
if verbose:
- print 'lin2alaw'
+ print('lin2alaw')
if audioop.lin2alaw(data[0], 1) != '\xd5\xc5\xf5' or \
audioop.lin2alaw(data[1], 2) != '\xd5\xd5\xd5' or \
audioop.lin2alaw(data[2], 4) != '\xd5\xd5\xd5':
@@ -147,7 +147,7 @@ def testlin2alaw(data):
def testalaw2lin(data):
if verbose:
- print 'alaw2lin'
+ print('alaw2lin')
# Cursory
d = audioop.lin2alaw(data[0], 1)
if audioop.alaw2lin(d, 1) != data[0]:
@@ -156,7 +156,7 @@ def testalaw2lin(data):
def testlin2ulaw(data):
if verbose:
- print 'lin2ulaw'
+ print('lin2ulaw')
if audioop.lin2ulaw(data[0], 1) != '\xff\xe7\xdb' or \
audioop.lin2ulaw(data[1], 2) != '\xff\xff\xff' or \
audioop.lin2ulaw(data[2], 4) != '\xff\xff\xff':
@@ -165,7 +165,7 @@ def testlin2ulaw(data):
def testulaw2lin(data):
if verbose:
- print 'ulaw2lin'
+ print('ulaw2lin')
# Cursory
d = audioop.lin2ulaw(data[0], 1)
if audioop.ulaw2lin(d, 1) != data[0]:
@@ -174,7 +174,7 @@ def testulaw2lin(data):
def testmul(data):
if verbose:
- print 'mul'
+ print('mul')
data2 = []
for d in data:
str = ''
@@ -189,7 +189,7 @@ def testmul(data):
def testratecv(data):
if verbose:
- print 'ratecv'
+ print('ratecv')
state = None
d1, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state)
d2, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state)
@@ -199,14 +199,14 @@ def testratecv(data):
def testreverse(data):
if verbose:
- print 'reverse'
+ print('reverse')
if audioop.reverse(data[0], 1) != '\2\1\0':
return 0
return 1
def testtomono(data):
if verbose:
- print 'tomono'
+ print('tomono')
data2 = ''
for d in data[0]:
data2 = data2 + d + d
@@ -216,7 +216,7 @@ def testtomono(data):
def testtostereo(data):
if verbose:
- print 'tostereo'
+ print('tostereo')
data2 = ''
for d in data[0]:
data2 = data2 + d + d
@@ -226,28 +226,28 @@ def testtostereo(data):
def testfindfactor(data):
if verbose:
- print 'findfactor'
+ print('findfactor')
if audioop.findfactor(data[1], data[1]) != 1.0:
return 0
return 1
def testfindfit(data):
if verbose:
- print 'findfit'
+ print('findfit')
if audioop.findfit(data[1], data[1]) != (0, 1.0):
return 0
return 1
def testfindmax(data):
if verbose:
- print 'findmax'
+ print('findmax')
if audioop.findmax(data[1], 1) != 2:
return 0
return 1
def testgetsample(data):
if verbose:
- print 'getsample'
+ print('getsample')
for i in range(3):
if audioop.getsample(data[0], 1, i) != i or \
audioop.getsample(data[1], 2, i) != i or \
@@ -259,15 +259,15 @@ def testone(name, data):
try:
func = eval('test'+name)
except NameError:
- print 'No test found for audioop.'+name+'()'
+ print('No test found for audioop.'+name+'()')
return
try:
rv = func(data)
except 'xx':
- print 'Test FAILED for audioop.'+name+'() (with an exception)'
+ print('Test FAILED for audioop.'+name+'() (with an exception)')
return
if not rv:
- print 'Test FAILED for audioop.'+name+'()'
+ print('Test FAILED for audioop.'+name+'()')
def testall():
data = [gendata1(), gendata2(), gendata4()]
diff --git a/Lib/test/test_bisect.py b/Lib/test/test_bisect.py
index 772e808362..1d62352f17 100644
--- a/Lib/test/test_bisect.py
+++ b/Lib/test/test_bisect.py
@@ -252,7 +252,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_bool.py b/Lib/test/test_bool.py
index 954423f1e9..1d9a60b61c 100644
--- a/Lib/test/test_bool.py
+++ b/Lib/test/test_bool.py
@@ -27,7 +27,7 @@ class BoolTest(unittest.TestCase):
def test_print(self):
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, False, True
+ print(False, True, file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), 'False True\n')
diff --git a/Lib/test/test_bsddb.py b/Lib/test/test_bsddb.py
index 91c1cca7a0..3b33c48b9c 100755
--- a/Lib/test/test_bsddb.py
+++ b/Lib/test/test_bsddb.py
@@ -147,42 +147,42 @@ class TestBSDDB(unittest.TestCase):
# in pybsddb's _DBWithCursor this causes an internal DBCursor
# object is created. Other test_ methods in this class could
# inadvertently cause the deadlock but an explicit test is needed.
- if debug: print "A"
+ if debug: print("A")
k,v = self.f.first()
- if debug: print "B", k
+ if debug: print("B", k)
self.f[k] = "deadlock. do not pass go. do not collect $200."
- if debug: print "C"
+ if debug: print("C")
# if the bsddb implementation leaves the DBCursor open during
# the database write and locking+threading support is enabled
# the cursor's read lock will deadlock the write lock request..
# test the iterator interface (if present)
if hasattr(self.f, 'iteritems'):
- if debug: print "D"
+ if debug: print("D")
i = self.f.iteritems()
k,v = i.next()
- if debug: print "E"
+ if debug: print("E")
self.f[k] = "please don't deadlock"
- if debug: print "F"
+ if debug: print("F")
while 1:
try:
k,v = i.next()
except StopIteration:
break
- if debug: print "F2"
+ if debug: print("F2")
i = iter(self.f)
- if debug: print "G"
+ if debug: print("G")
while i:
try:
- if debug: print "H"
+ if debug: print("H")
k = i.next()
- if debug: print "I"
+ if debug: print("I")
self.f[k] = "deadlocks-r-us"
- if debug: print "J"
+ if debug: print("J")
except StopIteration:
i = None
- if debug: print "K"
+ if debug: print("K")
# test the legacy cursor interface mixed with writes
self.assert_(self.f.first()[0] in self.d)
diff --git a/Lib/test/test_bsddb3.py b/Lib/test/test_bsddb3.py
index 166ad03ab2..69e99c034c 100644
--- a/Lib/test/test_bsddb3.py
+++ b/Lib/test/test_bsddb3.py
@@ -65,12 +65,12 @@ def test_main():
# For invocation as a script
if __name__ == '__main__':
from bsddb import db
- print '-=' * 38
- print db.DB_VERSION_STRING
- print 'bsddb.db.version(): %s' % (db.version(),)
- print 'bsddb.db.__version__: %s' % db.__version__
- print 'bsddb.db.cvsid: %s' % db.cvsid
- print 'python version: %s' % sys.version
- print '-=' * 38
+ print('-=' * 38)
+ print(db.DB_VERSION_STRING)
+ print('bsddb.db.version(): %s' % (db.version(),))
+ print('bsddb.db.__version__: %s' % db.__version__)
+ print('bsddb.db.cvsid: %s' % db.cvsid)
+ print('python version: %s' % sys.version)
+ print('-=' * 38)
unittest.main(defaultTest='suite')
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index 56417a341d..ab9dfc8cf0 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -204,15 +204,15 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(TypeError, cmp)
def test_compile(self):
- compile('print 1\n', '', 'exec')
+ compile('print(1)\n', '', 'exec')
bom = '\xef\xbb\xbf'
- compile(bom + 'print 1\n', '', 'exec')
+ compile(bom + 'print(1)\n', '', 'exec')
self.assertRaises(TypeError, compile)
- self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode')
- self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff)
+ self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
+ self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
if have_unicode:
- compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
+ compile(unicode('print(u"\xc3\xa5")\n', 'utf8'), '', 'exec')
self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
@@ -1659,7 +1659,7 @@ def test_main(verbose=None):
run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
diff --git a/Lib/test/test_capi.py b/Lib/test/test_capi.py
index cdd84bb222..074f5815a8 100644
--- a/Lib/test/test_capi.py
+++ b/Lib/test/test_capi.py
@@ -11,7 +11,7 @@ def test_main():
if name.startswith('test_'):
test = getattr(_testcapi, name)
if test_support.verbose:
- print "internal", name
+ print("internal", name)
try:
test()
except _testcapi.error:
@@ -23,7 +23,7 @@ def test_main():
import time
if test_support.verbose:
- print "auto-thread-state"
+ print("auto-thread-state")
idents = []
diff --git a/Lib/test/test_cd.py b/Lib/test/test_cd.py
index d85621178a..217b38b5ed 100755
--- a/Lib/test/test_cd.py
+++ b/Lib/test/test_cd.py
@@ -17,10 +17,10 @@ cdattrs = ['BLOCKSIZE', 'CDROM', 'DATASIZE', 'ERROR', 'NODISC', 'PAUSED', 'PLAYI
def main():
# touch all the attributes of cd without doing anything
if verbose:
- print 'Touching cd module attributes...'
+ print('Touching cd module attributes...')
for attr in cdattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(cd, attr)
main()
diff --git a/Lib/test/test_cl.py b/Lib/test/test_cl.py
index abfe3c19f5..0df7f6f8e2 100755
--- a/Lib/test/test_cl.py
+++ b/Lib/test/test_cl.py
@@ -69,10 +69,10 @@ clattrs = ['ADDED_ALGORITHM_ERROR', 'ALAW', 'ALGORITHM_ID',
def main():
# touch all the attributes of al without doing anything
if verbose:
- print 'Touching cl module attributes...'
+ print('Touching cl module attributes...')
for attr in clattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(cl, attr)
main()
diff --git a/Lib/test/test_class.py b/Lib/test/test_class.py
index c450c808d3..221fd48dcf 100644
--- a/Lib/test/test_class.py
+++ b/Lib/test/test_class.py
@@ -65,63 +65,63 @@ testmeths = [
class AllTests:
def __hash__(self, *args):
- print "__hash__:", args
+ print("__hash__:", args)
return hash(id(self))
def __str__(self, *args):
- print "__str__:", args
+ print("__str__:", args)
return "AllTests"
def __repr__(self, *args):
- print "__repr__:", args
+ print("__repr__:", args)
return "AllTests"
def __int__(self, *args):
- print "__int__:", args
+ print("__int__:", args)
return 1
def __float__(self, *args):
- print "__float__:", args
+ print("__float__:", args)
return 1.0
def __oct__(self, *args):
- print "__oct__:", args
+ print("__oct__:", args)
return '01'
def __hex__(self, *args):
- print "__hex__:", args
+ print("__hex__:", args)
return '0x1'
def __cmp__(self, *args):
- print "__cmp__:", args
+ print("__cmp__:", args)
return 0
def __eq__(self, *args):
- print "__eq__:", args
+ print("__eq__:", args)
return True
def __ne__(self, *args):
- print "__ne__:", args
+ print("__ne__:", args)
return False
def __lt__(self, *args):
- print "__lt__:", args
+ print("__lt__:", args)
return False
def __le__(self, *args):
- print "__le__:", args
+ print("__le__:", args)
return True
def __gt__(self, *args):
- print "__gt__:", args
+ print("__gt__:", args)
return False
def __ge__(self, *args):
- print "__ge__:", args
+ print("__ge__:", args)
return True
def __del__(self, *args):
- print "__del__:", args
+ print("__del__:", args)
# Synthesize AllTests methods from the names in testmeths.
@@ -186,7 +186,7 @@ class Empty: pass
try:
1 in Empty()
- print 'failed, should have raised TypeError'
+ print('failed, should have raised TypeError')
except TypeError:
pass
@@ -224,9 +224,9 @@ if sys.platform[:4] != 'java':
else:
# This works under Jython, but the actual slice values are
# different.
- print "__getitem__: (slice(0, 42, None),)"
- print "__setitem__: (slice(0, 42, None), 'The Answer')"
- print "__delitem__: (slice(0, 42, None),)"
+ print("__getitem__: (slice(0, 42, None),)")
+ print("__setitem__: (slice(0, 42, None), 'The Answer')")
+ print("__delitem__: (slice(0, 42, None),)")
# Unary operations
@@ -265,14 +265,14 @@ if sys.platform[:4] == 'java':
class ExtraTests:
def __getattr__(self, *args):
- print "__getattr__:", args
+ print("__getattr__:", args)
return "SomeVal"
def __setattr__(self, *args):
- print "__setattr__:", args
+ print("__setattr__:", args)
def __delattr__(self, *args):
- print "__delattr__:", args
+ print("__delattr__:", args)
testme = ExtraTests()
testme.spam
@@ -349,7 +349,7 @@ try:
A().a # Raised AttributeError: A instance has no attribute 'a'
except AttributeError as x:
if str(x) != "booh":
- print "attribute error for A().a got masked:", str(x)
+ print("attribute error for A().a got masked:", str(x))
class E:
__eq__ = property(booh)
@@ -362,7 +362,7 @@ try:
except AttributeError as x:
pass
else:
- print "attribute error for I.__init__ got masked"
+ print("attribute error for I.__init__ got masked")
# Test comparison and hash of methods
diff --git a/Lib/test/test_cmath.py b/Lib/test/test_cmath.py
index 6e392928c3..fd3a6bfcd7 100755
--- a/Lib/test/test_cmath.py
+++ b/Lib/test/test_cmath.py
@@ -43,10 +43,10 @@ for func in testdict.keys():
f = getattr(cmath, func)
r = f(testdict[func])
if verbose:
- print 'Calling %s(%f) = %f' % (func, testdict[func], abs(r))
+ print('Calling %s(%f) = %f' % (func, testdict[func], abs(r)))
p = cmath.pi
e = cmath.e
if verbose:
- print 'PI = ', abs(p)
- print 'E = ', abs(e)
+ print('PI = ', abs(p))
+ print('E = ', abs(e))
diff --git a/Lib/test/test_code.py b/Lib/test/test_code.py
index 6e0a1819c9..13ec254885 100644
--- a/Lib/test/test_code.py
+++ b/Lib/test/test_code.py
@@ -115,8 +115,8 @@ def dump(co):
"""Print out a text representation of a code object."""
for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames",
"cellvars", "freevars", "nlocals", "flags"]:
- print "%s: %s" % (attr, getattr(co, "co_" + attr))
- print "consts:", tuple(consts(co.co_consts))
+ print("%s: %s" % (attr, getattr(co, "co_" + attr)))
+ print("consts:", tuple(consts(co.co_consts)))
def test_main(verbose=None):
from test.test_support import run_doctest
diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py
index 0711923714..44ce8eb79a 100644
--- a/Lib/test/test_codecs.py
+++ b/Lib/test/test_codecs.py
@@ -548,7 +548,7 @@ punycode_testcases = [
for i in punycode_testcases:
if len(i)!=2:
- print repr(i)
+ print(repr(i))
class PunycodeTest(unittest.TestCase):
def test_encode(self):
diff --git a/Lib/test/test_compiler.py b/Lib/test/test_compiler.py
index 732036888d..ab9a66045a 100644
--- a/Lib/test/test_compiler.py
+++ b/Lib/test/test_compiler.py
@@ -30,8 +30,7 @@ class CompilerTest(unittest.TestCase):
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, \
- ' testCompileLibrary still working, be patient...'
+ print(' testCompileLibrary still working, be patient...', file=sys.__stdout__)
sys.__stdout__.flush()
if not basename.endswith(".py"):
@@ -40,7 +39,7 @@ class CompilerTest(unittest.TestCase):
continue
path = os.path.join(dir, basename)
if test.test_support.verbose:
- print "compiling", path
+ print("compiling", path)
f = open(path, "U")
buf = f.read()
f.close()
@@ -94,7 +93,7 @@ class CompilerTest(unittest.TestCase):
try:
self._check_lineno(node)
except AssertionError:
- print node.__class__, node.lineno
+ print(node.__class__, node.lineno)
raise
def _check_lineno(self, node):
@@ -217,7 +216,7 @@ else:
a, b = b, a
try:
- print yo
+ print(yo)
except:
yo = 3
else:
diff --git a/Lib/test/test_complex.py b/Lib/test/test_complex.py
index afc7caee23..91f074b8ca 100644
--- a/Lib/test/test_complex.py
+++ b/Lib/test/test_complex.py
@@ -315,7 +315,7 @@ class ComplexTest(unittest.TestCase):
fo = None
try:
fo = open(test_support.TESTFN, "wb")
- print >>fo, a, b
+ print(a, b, file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), "%s %s\n" % (a, b))
diff --git a/Lib/test/test_crypt.py b/Lib/test/test_crypt.py
index dfbcbdf228..7336711e5f 100755
--- a/Lib/test/test_crypt.py
+++ b/Lib/test/test_crypt.py
@@ -8,4 +8,4 @@ import crypt
c = crypt.crypt('mypassword', 'ab')
if verbose:
- print 'Test encryption: ', c
+ print('Test encryption: ', c)
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index feb6ddf613..46361c8254 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -894,7 +894,7 @@ Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back
self.assertEqual(dialect.quotechar, "'")
if not hasattr(sys, "gettotalrefcount"):
- if test_support.verbose: print "*** skipping leakage tests ***"
+ if test_support.verbose: print("*** skipping leakage tests ***")
else:
class NUL:
def write(s, *args):
diff --git a/Lib/test/test_curses.py b/Lib/test/test_curses.py
index 4022149310..fd8e6edb39 100644
--- a/Lib/test/test_curses.py
+++ b/Lib/test/test_curses.py
@@ -228,7 +228,7 @@ def unit_tests():
('\x8a', '!^J'), ('\xc1', '!A'),
]:
if ascii.unctrl(ch) != expected:
- print 'curses.unctrl fails on character', repr(ch)
+ print('curses.unctrl fails on character', repr(ch))
def test_userptr_without_set(stdscr):
diff --git a/Lib/test/test_datetime.py b/Lib/test/test_datetime.py
index b32017e527..70b00a401d 100644
--- a/Lib/test/test_datetime.py
+++ b/Lib/test/test_datetime.py
@@ -3287,11 +3287,11 @@ def test_main():
gc.garbage)
if hasattr(sys, 'gettotalrefcount'):
thisrc = sys.gettotalrefcount()
- print >> sys.stderr, '*' * 10, 'total refs:', thisrc,
+ print('*' * 10, 'total refs:', thisrc, end=' ', file=sys.stderr)
if lastrc:
- print >> sys.stderr, 'delta:', thisrc - lastrc
+ print('delta:', thisrc - lastrc, file=sys.stderr)
else:
- print >> sys.stderr
+ print(file=sys.stderr)
lastrc = thisrc
if __name__ == "__main__":
diff --git a/Lib/test/test_dbm.py b/Lib/test/test_dbm.py
index 0a9db4e244..a3b7716e23 100755
--- a/Lib/test/test_dbm.py
+++ b/Lib/test/test_dbm.py
@@ -31,7 +31,7 @@ def test_keys():
d.keys()
if 'a' in d:
if verbose:
- print 'Test dbm keys: ', d.keys()
+ print('Test dbm keys: ', d.keys())
d.close()
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
index 4a53122452..c39a8e31b7 100644
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -143,8 +143,8 @@ class DecimalTest(unittest.TestCase):
try:
t = self.eval_line(line)
except InvalidOperation:
- print 'Error in test cases:'
- print line
+ print('Error in test cases:')
+ print(line)
continue
except DecimalException as exception:
#Exception raised where there shoudn't have been one.
@@ -271,7 +271,7 @@ class DecimalTest(unittest.TestCase):
except Signals as error:
self.fail("Raised %s in %s" % (error, s))
except: #Catch any error long enough to state the test case.
- print "ERROR:", s
+ print("ERROR:", s)
raise
myexceptions = self.getexceptions()
diff --git a/Lib/test/test_defaultdict.py b/Lib/test/test_defaultdict.py
index 602e0d929f..03900de558 100644
--- a/Lib/test/test_defaultdict.py
+++ b/Lib/test/test_defaultdict.py
@@ -81,8 +81,8 @@ class TestDefaultDict(unittest.TestCase):
try:
f = open(tfn, "w+")
try:
- print >>f, d1
- print >>f, d2
+ print(d1, file=f)
+ print(d2, file=f)
f.seek(0)
self.assertEqual(f.readline(), repr(d1) + "\n")
self.assertEqual(f.readline(), repr(d2) + "\n")
diff --git a/Lib/test/test_deque.py b/Lib/test/test_deque.py
index a98339b78f..9f7caec4e2 100644
--- a/Lib/test/test_deque.py
+++ b/Lib/test/test_deque.py
@@ -245,7 +245,7 @@ class TestBasic(unittest.TestCase):
d.append(d)
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, d,
+ print(d, end=' ', file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), repr(d))
@@ -622,7 +622,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
# doctests
from test import test_deque
diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py
index bcfadf7715..aab33314a4 100644
--- a/Lib/test/test_descr.py
+++ b/Lib/test/test_descr.py
@@ -13,7 +13,7 @@ def veris(a, b):
raise TestFailed, "%r is %r" % (a, b)
def testunop(a, res, expr="len(a)", meth="__len__"):
- if verbose: print "checking", expr
+ if verbose: print("checking", expr)
dict = {'a': a}
vereq(eval(expr, dict), res)
t = type(a)
@@ -26,7 +26,7 @@ def testunop(a, res, expr="len(a)", meth="__len__"):
vereq(bm(), res)
def testbinop(a, b, res, expr="a+b", meth="__add__"):
- if verbose: print "checking", expr
+ if verbose: print("checking", expr)
dict = {'a': a, 'b': b}
vereq(eval(expr, dict), res)
@@ -40,7 +40,7 @@ def testbinop(a, b, res, expr="a+b", meth="__add__"):
vereq(bm(b), res)
def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
- if verbose: print "checking", expr
+ if verbose: print("checking", expr)
dict = {'a': a, 'b': b, 'c': c}
vereq(eval(expr, dict), res)
t = type(a)
@@ -53,7 +53,7 @@ def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
vereq(bm(b, c), res)
def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
- if verbose: print "checking", stmt
+ if verbose: print("checking", stmt)
dict = {'a': deepcopy(a), 'b': b}
exec(stmt, dict)
vereq(dict['a'], res)
@@ -71,7 +71,7 @@ def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
vereq(dict['a'], res)
def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
- if verbose: print "checking", stmt
+ if verbose: print("checking", stmt)
dict = {'a': deepcopy(a), 'b': b, 'c': c}
exec(stmt, dict)
vereq(dict['a'], res)
@@ -89,7 +89,7 @@ def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
vereq(dict['a'], res)
def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
- if verbose: print "checking", stmt
+ if verbose: print("checking", stmt)
dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
exec(stmt, dict)
vereq(dict['a'], res)
@@ -135,7 +135,7 @@ def class_docstrings():
verify(NewDynamic2.__doc__ is None)
def lists():
- if verbose: print "Testing list operations..."
+ if verbose: print("Testing list operations...")
testbinop([1], [2], [1,2], "a+b", "__add__")
testbinop([1,2,3], 2, 1, "b in a", "__contains__")
testbinop([1,2,3], 4, 0, "b in a", "__contains__")
@@ -150,7 +150,7 @@ def lists():
testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
def dicts():
- if verbose: print "Testing dict operations..."
+ if verbose: print("Testing dict operations...")
##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
@@ -175,7 +175,7 @@ def dicts():
def dict_constructor():
if verbose:
- print "Testing dict constructor ..."
+ print("Testing dict constructor ...")
d = dict()
vereq(d, {})
d = dict({})
@@ -258,7 +258,7 @@ def dict_constructor():
def test_dir():
if verbose:
- print "Testing dir() ..."
+ print("Testing dir() ...")
junk = 12
vereq(dir(), ['junk'])
del junk
@@ -413,7 +413,7 @@ def numops(a, b, skip=[]):
testunop(a, res, expr, name)
def ints():
- if verbose: print "Testing int operations..."
+ if verbose: print("Testing int operations...")
numops(100, 3)
# The following crashes in Python 2.2
vereq((1).__bool__(), True)
@@ -431,15 +431,15 @@ def ints():
raise TestFailed, "NotImplemented should have caused TypeError"
def longs():
- if verbose: print "Testing long operations..."
+ if verbose: print("Testing long operations...")
numops(100, 3)
def floats():
- if verbose: print "Testing float operations..."
+ if verbose: print("Testing float operations...")
numops(100.0, 3.0)
def complexes():
- if verbose: print "Testing complex operations..."
+ if verbose: print("Testing complex operations...")
numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
class Number(complex):
__slots__ = ['prec']
@@ -469,7 +469,7 @@ def complexes():
vereq(a.prec, 12)
def spamlists():
- if verbose: print "Testing spamlist operations..."
+ if verbose: print("Testing spamlist operations...")
import copy, xxsubtype as spam
def spamlist(l, memo=None):
import xxsubtype as spam
@@ -505,7 +505,7 @@ def spamlists():
vereq(a.getstate(), 42)
def spamdicts():
- if verbose: print "Testing spamdict operations..."
+ if verbose: print("Testing spamdict operations...")
import copy, xxsubtype as spam
def spamdict(d, memo=None):
import xxsubtype as spam
@@ -550,7 +550,7 @@ def spamdicts():
vereq(a.getstate(), 100)
def pydicts():
- if verbose: print "Testing Python subclass of dict..."
+ if verbose: print("Testing Python subclass of dict...")
verify(issubclass(dict, dict))
verify(isinstance({}, dict))
d = dict()
@@ -591,7 +591,7 @@ def pydicts():
vereq(a[42], 0)
a[42] = 24
vereq(a[42], 24)
- if verbose: print "pydict stress test ..."
+ if verbose: print("pydict stress test ...")
N = 50
for i in range(N):
a[i] = C()
@@ -602,7 +602,7 @@ def pydicts():
vereq(a[i][j], i*j)
def pylists():
- if verbose: print "Testing Python subclass of list..."
+ if verbose: print("Testing Python subclass of list...")
class C(list):
def __getitem__(self, i):
return list.__getitem__(self, i) + 100
@@ -616,7 +616,7 @@ def pylists():
vereq(a[100:200], (100,200))
def metaclass():
- if verbose: print "Testing __metaclass__..."
+ if verbose: print("Testing __metaclass__...")
class C:
__metaclass__ = type
def __init__(self):
@@ -778,7 +778,7 @@ def metaclass():
else: raise TestFailed, "calling object w/o call method should raise TypeError"
def pymods():
- if verbose: print "Testing Python subclass of module..."
+ if verbose: print("Testing Python subclass of module...")
log = []
import sys
MT = type(sys)
@@ -803,7 +803,7 @@ def pymods():
("delattr", "foo")])
def multi():
- if verbose: print "Testing multiple inheritance..."
+ if verbose: print("Testing multiple inheritance...")
class C(object):
def __init__(self):
self.__state = 0
@@ -844,7 +844,7 @@ def multi():
vereq(int(Frag()), 42)
def diamond():
- if verbose: print "Testing multiple inheritance special cases..."
+ if verbose: print("Testing multiple inheritance special cases...")
class A(object):
def spam(self): return "A"
vereq(A().spam(), "A")
@@ -882,7 +882,7 @@ def diamond():
# see thread python-dev/2002-October/029035.html
def ex5():
- if verbose: print "Testing ex5 from C3 switch discussion..."
+ if verbose: print("Testing ex5 from C3 switch discussion...")
class A(object): pass
class B(object): pass
class C(object): pass
@@ -894,7 +894,7 @@ def ex5():
# see "A Monotonic Superclass Linearization for Dylan",
# by Kim Barrett et al. (OOPSLA 1996)
def monotonicity():
- if verbose: print "Testing MRO monotonicity..."
+ if verbose: print("Testing MRO monotonicity...")
class Boat(object): pass
class DayBoat(Boat): pass
class WheelBoat(Boat): pass
@@ -917,7 +917,7 @@ def monotonicity():
# see "A Monotonic Superclass Linearization for Dylan",
# by Kim Barrett et al. (OOPSLA 1996)
def consistency_with_epg():
- if verbose: print "Testing consistentcy with EPG..."
+ if verbose: print("Testing consistentcy with EPG...")
class Pane(object): pass
class ScrollingMixin(object): pass
class EditingMixin(object): pass
@@ -933,7 +933,7 @@ mro_err_msg = """Cannot create a consistent method resolution
order (MRO) for bases """
def mro_disagreement():
- if verbose: print "Testing error messages for MRO disagreement..."
+ if verbose: print("Testing error messages for MRO disagreement...")
def raises(exc, expected, callable, *args):
try:
callable(*args)
@@ -963,7 +963,7 @@ def mro_disagreement():
type, "ConfusedGrid", (HVGrid, VHGrid), {})
def objects():
- if verbose: print "Testing object class..."
+ if verbose: print("Testing object class...")
a = object()
vereq(a.__class__, object)
vereq(type(a), object)
@@ -987,7 +987,7 @@ def objects():
vereq(x.__dict__, {'foo': 1})
def slots():
- if verbose: print "Testing __slots__..."
+ if verbose: print("Testing __slots__...")
class C0(object):
__slots__ = []
x = C0()
@@ -1152,7 +1152,7 @@ def slots():
sys.stderr = save_stderr
def slotspecials():
- if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
+ if verbose: print("Testing __dict__ and __weakref__ in __slots__...")
class D(object):
__slots__ = ["__dict__"]
@@ -1199,7 +1199,7 @@ def slotspecials():
# __slots__ = []
def dynamics():
- if verbose: print "Testing class attribute propagation..."
+ if verbose: print("Testing class attribute propagation...")
class D(object):
pass
class E(D):
@@ -1278,7 +1278,7 @@ def dynamics():
verify(someclass != object)
def errors():
- if verbose: print "Testing errors..."
+ if verbose: print("Testing errors...")
try:
class C(list, dict):
@@ -1323,7 +1323,7 @@ def errors():
verify(0, "__slots__ = [1] should be illegal")
def classmethods():
- if verbose: print "Testing class methods..."
+ if verbose: print("Testing class methods...")
class C(object):
def foo(*a): return a
goo = classmethod(foo)
@@ -1369,7 +1369,7 @@ def classmethods():
raise TestFailed, "classmethod shouldn't accept keyword args"
def classmethods_in_c():
- if verbose: print "Testing C-based class methods..."
+ if verbose: print("Testing C-based class methods...")
import xxsubtype as spam
a = (1, 2, 3)
d = {'abc': 123}
@@ -1383,7 +1383,7 @@ def classmethods_in_c():
vereq(d, d1)
def staticmethods():
- if verbose: print "Testing static methods..."
+ if verbose: print("Testing static methods...")
class C(object):
def foo(*a): return a
goo = staticmethod(foo)
@@ -1400,7 +1400,7 @@ def staticmethods():
vereq(D.foo(d, 1), (d, 1))
def staticmethods_in_c():
- if verbose: print "Testing C-based static methods..."
+ if verbose: print("Testing C-based static methods...")
import xxsubtype as spam
a = (1, 2, 3)
d = {"abc": 123}
@@ -1414,7 +1414,7 @@ def staticmethods_in_c():
vereq(d, d1)
def classic():
- if verbose: print "Testing classic classes..."
+ if verbose: print("Testing classic classes...")
class C:
def foo(*a): return a
goo = classmethod(foo)
@@ -1435,7 +1435,7 @@ def classic():
verify(repr(C.foo.__get__(C())).startswith("<bound method "))
def compattr():
- if verbose: print "Testing computed attributes..."
+ if verbose: print("Testing computed attributes...")
class C(object):
class computed_attribute(object):
def __init__(self, get, set=None, delete=None):
@@ -1469,7 +1469,7 @@ def compattr():
vereq(hasattr(a, 'x'), 0)
def newslot():
- if verbose: print "Testing __new__ slot override..."
+ if verbose: print("Testing __new__ slot override...")
class C(list):
def __new__(cls):
self = list.__new__(cls)
@@ -1487,7 +1487,7 @@ def newslot():
verify(b.__class__ is D)
def altmro():
- if verbose: print "Testing mro() and overriding it..."
+ if verbose: print("Testing mro() and overriding it...")
class A(object):
def f(self): return "A"
class B(A):
@@ -1542,7 +1542,7 @@ def altmro():
def overloading():
- if verbose: print "Testing operator overloading..."
+ if verbose: print("Testing operator overloading...")
class B(object):
"Intermediate class because object doesn't have a __setattr__"
@@ -1599,7 +1599,7 @@ def overloading():
vereq(a.delslice, (0, 10))
def methods():
- if verbose: print "Testing methods..."
+ if verbose: print("Testing methods...")
class C(object):
def __init__(self, x):
self.x = x
@@ -1621,7 +1621,7 @@ def methods():
def specials():
# Test operators like __hash__ for which a built-in default exists
- if verbose: print "Testing special operators..."
+ if verbose: print("Testing special operators...")
# Test the default behavior for static classes
class C(object):
def __getitem__(self, i):
@@ -1782,7 +1782,7 @@ def specials():
sys.stdout = get_original_stdout()
try:
# nothing should actually be printed, this should raise an exception
- print Letter('w')
+ print(Letter('w'))
except RuntimeError:
pass
else:
@@ -1790,7 +1790,7 @@ def specials():
sys.stdout = test_stdout
def weakrefs():
- if verbose: print "Testing weak references..."
+ if verbose: print("Testing weak references...")
import weakref
class C(object):
pass
@@ -1819,7 +1819,7 @@ def weakrefs():
del r
def properties():
- if verbose: print "Testing property..."
+ if verbose: print("Testing property...")
class C(object):
def getx(self):
return self.__x
@@ -1902,7 +1902,7 @@ def properties():
def supers():
- if verbose: print "Testing super..."
+ if verbose: print("Testing super...")
class A(object):
def meth(self, a):
@@ -2018,7 +2018,7 @@ def supers():
raise TestFailed, "super shouldn't accept keyword args"
def inherits():
- if verbose: print "Testing inheritance from basic types..."
+ if verbose: print("Testing inheritance from basic types...")
class hexint(int):
def __repr__(self):
@@ -2362,7 +2362,7 @@ def inherits():
def keywords():
if verbose:
- print "Testing keyword args to basic type constructors ..."
+ print("Testing keyword args to basic type constructors ...")
vereq(int(x=1), 1)
vereq(float(x=2), 2.0)
vereq(int(x=3), 3)
@@ -2388,7 +2388,7 @@ def restricted():
return
import rexec
if verbose:
- print "Testing interaction with restricted execution ..."
+ print("Testing interaction with restricted execution ...")
sandbox = rexec.RExec()
@@ -2428,7 +2428,7 @@ f = t(%r, 'w') # rexec can't catch this by itself
def str_subclass_as_dict_key():
if verbose:
- print "Testing a str subclass used as dict key .."
+ print("Testing a str subclass used as dict key ..")
class cistr(str):
"""Sublcass of str that computes __eq__ case-insensitively.
@@ -2460,11 +2460,11 @@ def str_subclass_as_dict_key():
vereq(d.get(cistr('thrEE')), 3)
def classic_comparisons():
- if verbose: print "Testing classic comparisons..."
+ if verbose: print("Testing classic comparisons...")
class classic:
pass
for base in (classic, int, object):
- if verbose: print " (base = %s)" % base
+ if verbose: print(" (base = %s)" % base)
class C(base):
def __init__(self, value):
self.value = int(value)
@@ -2521,7 +2521,7 @@ def classic_comparisons():
def rich_comparisons():
if verbose:
- print "Testing rich comparisons..."
+ print("Testing rich comparisons...")
class Z(complex):
pass
z = Z(1)
@@ -2540,7 +2540,7 @@ def rich_comparisons():
class classic:
pass
for base in (classic, int, object, list):
- if verbose: print " (base = %s)" % base
+ if verbose: print(" (base = %s)" % base)
class C(base):
def __init__(self, value):
self.value = int(value)
@@ -2598,14 +2598,14 @@ def rich_comparisons():
"x=%d, y=%d" % (x, y))
def descrdoc():
- if verbose: print "Testing descriptor doc strings..."
+ if verbose: print("Testing descriptor doc strings...")
def check(descr, what):
vereq(descr.__doc__, what)
check(file.closed, "True if the file is closed") # getset descriptor
check(file.name, "file name") # member descriptor
def setclass():
- if verbose: print "Testing __class__ assignment..."
+ if verbose: print("Testing __class__ assignment...")
class C(object): pass
class D(object): pass
class E(object): pass
@@ -2647,7 +2647,7 @@ def setclass():
del o
def setdict():
- if verbose: print "Testing __dict__ assignment..."
+ if verbose: print("Testing __dict__ assignment...")
class C(object): pass
a = C()
a.__dict__ = {'b': 1}
@@ -2668,7 +2668,7 @@ def setdict():
def pickles():
if verbose:
- print "Testing pickling and copying new-style classes and objects..."
+ print("Testing pickling and copying new-style classes and objects...")
import pickle
try:
import cPickle
@@ -2733,7 +2733,7 @@ def pickles():
continue # cPickle not found -- skip it
for bin in 0, 1:
if verbose:
- print p.__name__, ["text", "binary"][bin]
+ print(p.__name__, ["text", "binary"][bin])
for cls in C, C1, C2:
s = p.dumps(cls, bin)
@@ -2751,8 +2751,8 @@ def pickles():
vereq(repr(x), repr(a))
vereq(repr(y), repr(b))
if verbose:
- print "a = x =", a
- print "b = y =", b
+ print("a = x =", a)
+ print("b = y =", b)
# Test for __getstate__ and __setstate__ on new style class
u = C3(42)
s = p.dumps(u, bin)
@@ -2769,7 +2769,7 @@ def pickles():
# Testing copy.deepcopy()
if verbose:
- print "deepcopy"
+ print("deepcopy")
import copy
for cls in C, C1, C2:
cls2 = copy.deepcopy(cls)
@@ -2785,11 +2785,11 @@ def pickles():
vereq(repr(x), repr(a))
vereq(repr(y), repr(b))
if verbose:
- print "a = x =", a
- print "b = y =", b
+ print("a = x =", a)
+ print("b = y =", b)
def pickleslots():
- if verbose: print "Testing pickling of classes with __slots__ ..."
+ if verbose: print("Testing pickling of classes with __slots__ ...")
import pickle, pickle as cPickle
# Pickling of classes with __slots__ but without __getstate__ should fail
global B, C, D, E
@@ -2876,7 +2876,7 @@ def pickleslots():
vereq(y.b, x.b)
def copies():
- if verbose: print "Testing copy.copy() and copy.deepcopy()..."
+ if verbose: print("Testing copy.copy() and copy.deepcopy()...")
import copy
class C(object):
pass
@@ -2897,7 +2897,7 @@ def copies():
vereq(d.bar, [1,2,3])
def binopoverride():
- if verbose: print "Testing overrides of binary operations..."
+ if verbose: print("Testing overrides of binary operations...")
class I(int):
def __repr__(self):
return "I(%r)" % int(self)
@@ -2927,7 +2927,7 @@ def binopoverride():
return self.lower() == other.lower()
def subclasspropagation():
- if verbose: print "Testing propagation of slot functions to subclasses..."
+ if verbose: print("Testing propagation of slot functions to subclasses...")
class A(object):
pass
class B(A):
@@ -3000,7 +3000,7 @@ def buffer_inherit():
import binascii
# SF bug [#470040] ParseTuple t# vs subclasses.
if verbose:
- print "Testing that buffer interface is inherited ..."
+ print("Testing that buffer interface is inherited ...")
class MyStr(str):
pass
@@ -3032,7 +3032,7 @@ def str_of_str_subclass():
import cStringIO
if verbose:
- print "Testing __str__ defined in subclass of str ..."
+ print("Testing __str__ defined in subclass of str ...")
class octetstring(str):
def __str__(self):
@@ -3052,13 +3052,13 @@ def str_of_str_subclass():
capture = cStringIO.StringIO()
# Calling str() or not exercises different internal paths.
- print >> capture, o
- print >> capture, str(o)
+ print(o, file=capture)
+ print(str(o), file=capture)
vereq(capture.getvalue(), '41\n41\n')
capture.close()
def kwdargs():
- if verbose: print "Testing keyword arguments to __init__, __call__..."
+ if verbose: print("Testing keyword arguments to __init__, __call__...")
def f(a): return a
vereq(f.__call__(a=42), 42)
a = []
@@ -3066,8 +3066,8 @@ def kwdargs():
vereq(a, [0, 1, 2])
def recursive__call__():
- if verbose: print ("Testing recursive __call__() by setting to instance of "
- "class ...")
+ if verbose: print(("Testing recursive __call__() by setting to instance of "
+ "class ..."))
class A(object):
pass
@@ -3081,7 +3081,7 @@ def recursive__call__():
"__call__()")
def delhook():
- if verbose: print "Testing __del__ hook..."
+ if verbose: print("Testing __del__ hook...")
log = []
class C(object):
def __del__(self):
@@ -3098,7 +3098,7 @@ def delhook():
else: raise TestFailed, "invalid del() didn't raise TypeError"
def hashinherit():
- if verbose: print "Testing hash of mutable subclasses..."
+ if verbose: print("Testing hash of mutable subclasses...")
class mydict(dict):
pass
@@ -3167,7 +3167,7 @@ def strops():
vereq('%c' % '5', '5')
def deepcopyrecursive():
- if verbose: print "Testing deepcopy of recursive objects..."
+ if verbose: print("Testing deepcopy of recursive objects...")
class Node:
pass
a = Node()
@@ -3177,7 +3177,7 @@ def deepcopyrecursive():
z = deepcopy(a) # This blew up before
def modules():
- if verbose: print "Testing uninitialized module objects..."
+ if verbose: print("Testing uninitialized module objects...")
from types import ModuleType as M
m = M.__new__(M)
str(m)
@@ -3192,7 +3192,7 @@ def dictproxyiterkeys():
class C(object):
def meth(self):
pass
- if verbose: print "Testing dict-proxy iterkeys..."
+ if verbose: print("Testing dict-proxy iterkeys...")
keys = [ key for key in C.__dict__.iterkeys() ]
keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
@@ -3201,7 +3201,7 @@ def dictproxyitervalues():
class C(object):
def meth(self):
pass
- if verbose: print "Testing dict-proxy itervalues..."
+ if verbose: print("Testing dict-proxy itervalues...")
values = [ values for values in C.__dict__.itervalues() ]
vereq(len(values), 5)
@@ -3209,13 +3209,13 @@ def dictproxyiteritems():
class C(object):
def meth(self):
pass
- if verbose: print "Testing dict-proxy iteritems..."
+ if verbose: print("Testing dict-proxy iteritems...")
keys = [ key for (key, value) in C.__dict__.iteritems() ]
keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
def funnynew():
- if verbose: print "Testing __new__ returning something unexpected..."
+ if verbose: print("Testing __new__ returning something unexpected...")
class C(object):
def __new__(cls, arg):
if isinstance(arg, str): return [1, 2, 3]
@@ -3237,7 +3237,7 @@ def funnynew():
def imulbug():
# SF bug 544647
- if verbose: print "Testing for __imul__ problems..."
+ if verbose: print("Testing for __imul__ problems...")
class C(object):
def __imul__(self, other):
return (self, other)
@@ -3263,7 +3263,7 @@ def imulbug():
def docdescriptor():
# SF bug 542984
- if verbose: print "Testing __doc__ descriptor..."
+ if verbose: print("Testing __doc__ descriptor...")
class DocDescr(object):
def __get__(self, object, otype):
if object:
@@ -3282,7 +3282,7 @@ def docdescriptor():
def copy_setstate():
if verbose:
- print "Testing that copy.*copy() correctly uses __setstate__..."
+ print("Testing that copy.*copy() correctly uses __setstate__...")
import copy
class C(object):
def __init__(self, foo=None):
@@ -3310,7 +3310,7 @@ def copy_setstate():
def slices():
if verbose:
- print "Testing cases with slices and overridden __getitem__ ..."
+ print("Testing cases with slices and overridden __getitem__ ...")
# Strings
vereq("hello"[:4], "hell")
vereq("hello"[slice(4)], "hell")
@@ -3354,7 +3354,7 @@ def slices():
def subtype_resurrection():
if verbose:
- print "Testing resurrection of new-style instance..."
+ print("Testing resurrection of new-style instance...")
class C(object):
container = []
@@ -3384,7 +3384,7 @@ def subtype_resurrection():
def slottrash():
# Deallocating deeply nested slotted trash caused stack overflows
if verbose:
- print "Testing slot trash..."
+ print("Testing slot trash...")
class trash(object):
__slots__ = ['x']
def __init__(self, x):
@@ -3410,7 +3410,7 @@ def slotmultipleinheritance():
def testrmul():
# SF patch 592646
if verbose:
- print "Testing correct invocation of __rmul__..."
+ print("Testing correct invocation of __rmul__...")
class C(object):
def __mul__(self, other):
return "mul"
@@ -3425,7 +3425,7 @@ def testrmul():
def testipow():
# [SF bug 620179]
if verbose:
- print "Testing correct invocation of __ipow__..."
+ print("Testing correct invocation of __ipow__...")
class C(object):
def __ipow__(self, other):
pass
@@ -3434,7 +3434,7 @@ def testipow():
def do_this_first():
if verbose:
- print "Testing SF bug 551412 ..."
+ print("Testing SF bug 551412 ...")
# This dumps core when SF bug 551412 isn't fixed --
# but only when test_descr.py is run separately.
# (That can't be helped -- as soon as PyType_Ready()
@@ -3448,14 +3448,14 @@ def do_this_first():
pass
if verbose:
- print "Testing SF bug 570483..."
+ print("Testing SF bug 570483...")
# Another segfault only when run early
# (before PyType_Ready(tuple) is called)
type.mro(tuple)
def test_mutable_bases():
if verbose:
- print "Testing mutable bases..."
+ print("Testing mutable bases...")
# stuff that should work:
class C(object):
pass
@@ -3545,7 +3545,7 @@ def test_mutable_bases():
def test_mutable_bases_with_failing_mro():
if verbose:
- print "Testing mutable bases with failing mro..."
+ print("Testing mutable bases with failing mro...")
class WorkOnce(type):
def __new__(self, name, bases, ns):
self.flag = 0
@@ -3600,7 +3600,7 @@ def test_mutable_bases_with_failing_mro():
def test_mutable_bases_catch_mro_conflict():
if verbose:
- print "Testing mutable bases catch mro conflict..."
+ print("Testing mutable bases catch mro conflict...")
class A(object):
pass
@@ -3625,7 +3625,7 @@ def test_mutable_bases_catch_mro_conflict():
def mutable_names():
if verbose:
- print "Testing mutable names..."
+ print("Testing mutable names...")
class C(object):
pass
@@ -3640,7 +3640,7 @@ def mutable_names():
def subclass_right_op():
if verbose:
- print "Testing correct dispatch of subclass overloading __r<op>__..."
+ print("Testing correct dispatch of subclass overloading __r<op>__...")
# This code tests various cases where right-dispatch of a subclass
# should be preferred over left-dispatch of a base class.
@@ -3692,7 +3692,7 @@ def subclass_right_op():
def dict_type_with_metaclass():
if verbose:
- print "Testing type of __dict__ when __metaclass__ set..."
+ print("Testing type of __dict__ when __metaclass__ set...")
class B(object):
pass
@@ -3706,7 +3706,7 @@ def dict_type_with_metaclass():
def meth_class_get():
# Full coverage of descrobject.c::classmethod_get()
if verbose:
- print "Testing __get__ method of METH_CLASS C methods..."
+ print("Testing __get__ method of METH_CLASS C methods...")
# Baseline
arg = [1, 2, 3]
res = {1: None, 2: None, 3: None}
@@ -3745,7 +3745,7 @@ def meth_class_get():
def isinst_isclass():
if verbose:
- print "Testing proxy isinstance() and isclass()..."
+ print("Testing proxy isinstance() and isclass()...")
class Proxy(object):
def __init__(self, obj):
self.__obj = obj
@@ -3785,7 +3785,7 @@ def isinst_isclass():
def proxysuper():
if verbose:
- print "Testing super() for a proxy object..."
+ print("Testing super() for a proxy object...")
class Proxy(object):
def __init__(self, obj):
self.__obj = obj
@@ -3809,7 +3809,7 @@ def proxysuper():
def carloverre():
if verbose:
- print "Testing prohibition of Carlo Verre's hack..."
+ print("Testing prohibition of Carlo Verre's hack...")
try:
object.__setattr__(str, "foo", 42)
except TypeError:
@@ -3826,7 +3826,7 @@ def carloverre():
def weakref_segfault():
# SF 742911
if verbose:
- print "Testing weakref segfault..."
+ print("Testing weakref segfault...")
import weakref
@@ -3854,7 +3854,7 @@ def wrapper_segfault():
# Fix SF #762455, segfault when sys.stdout is changed in getattr
def filefault():
if verbose:
- print "Testing sys.stdout is changed in getattr..."
+ print("Testing sys.stdout is changed in getattr...")
import sys
class StdoutGuard:
def __getattr__(self, attr):
@@ -3862,7 +3862,7 @@ def filefault():
raise RuntimeError("Premature access to sys.stdout.%s" % attr)
sys.stdout = StdoutGuard()
try:
- print "Oops!"
+ print("Oops!")
except RuntimeError:
pass
@@ -3871,7 +3871,7 @@ def vicious_descriptor_nonsense():
# python-dev 2003-04-17, turned into an example & fixed by Michael
# Hudson just less than four months later...
if verbose:
- print "Testing vicious_descriptor_nonsense..."
+ print("Testing vicious_descriptor_nonsense...")
class Evil(object):
def __hash__(self):
@@ -3910,7 +3910,7 @@ def test_init():
def methodwrapper():
# <type 'method-wrapper'> did not support any reflection before 2.5
if verbose:
- print "Testing method-wrapper objects..."
+ print("Testing method-wrapper objects...")
return # XXX should methods really support __eq__?
@@ -3938,7 +3938,7 @@ def methodwrapper():
def notimplemented():
# all binary methods should be able to return a NotImplemented
if verbose:
- print "Testing NotImplemented..."
+ print("Testing NotImplemented...")
import sys
import types
@@ -4098,7 +4098,7 @@ def test_main():
methodwrapper()
notimplemented()
- if verbose: print "All OK"
+ if verbose: print("All OK")
if __name__ == "__main__":
test_main()
diff --git a/Lib/test/test_dis.py b/Lib/test/test_dis.py
index f9a6a07081..3916c32f9d 100644
--- a/Lib/test/test_dis.py
+++ b/Lib/test/test_dis.py
@@ -8,7 +8,7 @@ import StringIO
import unittest
def _f(a):
- print a
+ print(a)
return 1
dis_f = """\
diff --git a/Lib/test/test_dl.py b/Lib/test/test_dl.py
index 9c70427070..ba5d8bd3d3 100755
--- a/Lib/test/test_dl.py
+++ b/Lib/test/test_dl.py
@@ -16,19 +16,19 @@ sharedlibs = [
for s, func in sharedlibs:
try:
if verbose:
- print 'trying to open:', s,
+ print('trying to open:', s, end=' ')
l = dl.open(s)
except dl.error as err:
if verbose:
- print 'failed', repr(str(err))
+ print('failed', repr(str(err)))
pass
else:
if verbose:
- print 'succeeded...',
+ print('succeeded...', end=' ')
l.call(func)
l.close()
if verbose:
- print 'worked!'
+ print('worked!')
break
else:
raise TestSkipped, 'Could not open any shared libraries'
diff --git a/Lib/test/test_doctest.py b/Lib/test/test_doctest.py
index 56c244988d..ac9d00d6ae 100644
--- a/Lib/test/test_doctest.py
+++ b/Lib/test/test_doctest.py
@@ -143,7 +143,7 @@ class _FakeInput:
def readline(self):
line = self.lines.pop(0)
- print line
+ print(line)
return line+'\n'
######################################################################
@@ -2407,7 +2407,7 @@ def test_coverage(coverdir):
trace=0, count=1)
tracer.run('reload(doctest); test_main()')
r = tracer.results()
- print 'Writing coverage results...'
+ print('Writing coverage results...')
r.write_results(show_missing=True, summary=True,
coverdir=coverdir)
diff --git a/Lib/test/test_dummy_thread.py b/Lib/test/test_dummy_thread.py
index f274e0a0d0..288b6218c2 100644
--- a/Lib/test/test_dummy_thread.py
+++ b/Lib/test/test_dummy_thread.py
@@ -72,13 +72,13 @@ class LockTests(unittest.TestCase):
start_time = int(time.time())
_thread.start_new_thread(delay_unlock,(self.lock, DELAY))
if test_support.verbose:
- print
- print "*** Waiting for thread to release the lock "\
- "(approx. %s sec.) ***" % DELAY
+ print()
+ print("*** Waiting for thread to release the lock "\
+ "(approx. %s sec.) ***" % DELAY)
self.lock.acquire()
end_time = int(time.time())
if test_support.verbose:
- print "done"
+ print("done")
self.failUnless((end_time - start_time) >= DELAY,
"Blocking by unconditional acquiring failed.")
@@ -150,9 +150,9 @@ class ThreadTests(unittest.TestCase):
thread_count = 5
testing_queue = Queue.Queue(thread_count)
if test_support.verbose:
- print
- print "*** Testing multiple thread creation "\
- "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)
+ print()
+ print("*** Testing multiple thread creation "\
+ "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count))
for count in xrange(thread_count):
if DELAY:
local_delay = round(random.random(), 1)
@@ -162,7 +162,7 @@ class ThreadTests(unittest.TestCase):
(testing_queue, local_delay))
time.sleep(DELAY)
if test_support.verbose:
- print 'done'
+ print('done')
self.failUnless(testing_queue.qsize() == thread_count,
"Not all %s threads executed properly after %s sec." %
(thread_count, DELAY))
@@ -173,8 +173,8 @@ def test_main(imported_module=None):
_thread = imported_module
DELAY = 2
if test_support.verbose:
- print
- print "*** Using %s as _thread module ***" % _thread
+ print()
+ print("*** Using %s as _thread module ***" % _thread)
test_support.run_unittest(LockTests, MiscTests, ThreadTests)
if __name__ == '__main__':
diff --git a/Lib/test/test_dummy_threading.py b/Lib/test/test_dummy_threading.py
index 3724f1e5a4..90bf6e0ee9 100644
--- a/Lib/test/test_dummy_threading.py
+++ b/Lib/test/test_dummy_threading.py
@@ -17,20 +17,20 @@ class TestThread(_threading.Thread):
#delay = random.random() * 2
delay = 0
if verbose:
- print 'task', self.getName(), 'will run for', delay, 'sec'
+ print('task', self.getName(), 'will run for', delay, 'sec')
sema.acquire()
mutex.acquire()
running = running + 1
if verbose:
- print running, 'tasks are running'
+ print(running, 'tasks are running')
mutex.release()
time.sleep(delay)
if verbose:
- print 'task', self.getName(), 'done'
+ print('task', self.getName(), 'done')
mutex.acquire()
running = running - 1
if verbose:
- print self.getName(), 'is finished.', running, 'tasks are running'
+ print(self.getName(), 'is finished.', running, 'tasks are running')
mutex.release()
sema.release()
@@ -61,11 +61,11 @@ def test_main():
starttasks()
if verbose:
- print 'waiting for all tasks to complete'
+ print('waiting for all tasks to complete')
for t in threads:
t.join()
if verbose:
- print 'all tasks done'
+ print('all tasks done')
diff --git a/Lib/test/test_enumerate.py b/Lib/test/test_enumerate.py
index 4ee8680e8d..6290070460 100644
--- a/Lib/test/test_enumerate.py
+++ b/Lib/test/test_enumerate.py
@@ -208,7 +208,7 @@ def test_main(verbose=None):
for i in xrange(len(counts)):
test_support.run_unittest(*testclasses)
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_errno.py b/Lib/test/test_errno.py
index 6b02e25cf3..25937dc612 100755
--- a/Lib/test/test_errno.py
+++ b/Lib/test/test_errno.py
@@ -43,7 +43,7 @@ for error in errors:
a = getattr(errno, error)
except AttributeError:
if verbose:
- print '%s: not found' % error
+ print('%s: not found' % error)
else:
if verbose:
- print '%s: %d' % (error, a)
+ print('%s: %d' % (error, a))
diff --git a/Lib/test/test_extcall.py b/Lib/test/test_extcall.py
index 11cf43afb9..e67b3f8f41 100644
--- a/Lib/test/test_extcall.py
+++ b/Lib/test/test_extcall.py
@@ -2,16 +2,16 @@ from test.test_support import verify, verbose, TestFailed, sortdict
from UserList import UserList
def e(a, b):
- print a, b
+ print(a, b)
def f(*a, **k):
- print a, sortdict(k)
+ print(a, sortdict(k))
def g(x, *y, **z):
- print x, y, sortdict(z)
+ print(x, y, sortdict(z))
def h(j=1, a=2, h=3):
- print j, a, h
+ print(j, a, h)
f()
f(1)
@@ -31,28 +31,28 @@ try:
except TypeError:
pass
else:
- print "should raise TypeError: e() got an unexpected keyword argument 'c'"
+ print("should raise TypeError: e() got an unexpected keyword argument 'c'")
try:
g()
except TypeError as err:
- print "TypeError:", err
+ print("TypeError:", err)
else:
- print "should raise TypeError: not enough arguments; expected 1, got 0"
+ print("should raise TypeError: not enough arguments; expected 1, got 0")
try:
g(*())
except TypeError as err:
- print "TypeError:", err
+ print("TypeError:", err)
else:
- print "should raise TypeError: not enough arguments; expected 1, got 0"
+ print("should raise TypeError: not enough arguments; expected 1, got 0")
try:
g(*(), **{})
except TypeError as err:
- print "TypeError:", err
+ print("TypeError:", err)
else:
- print "should raise TypeError: not enough arguments; expected 1, got 0"
+ print("should raise TypeError: not enough arguments; expected 1, got 0")
g(1)
g(1, 2)
@@ -64,7 +64,7 @@ try:
except TypeError as attr:
pass
else:
- print "should raise TypeError"
+ print("should raise TypeError")
class Nothing:
def __len__(self):
@@ -74,7 +74,7 @@ try:
except TypeError as attr:
pass
else:
- print "should raise TypeError"
+ print("should raise TypeError")
class Nothing:
def __len__(self):
@@ -96,7 +96,7 @@ try:
except TypeError as attr:
pass
else:
- print "should raise TypeError"
+ print("should raise TypeError")
class Nothing:
def __init__(self):
@@ -116,8 +116,8 @@ d = {'a': 1, 'b': 2, 'c': 3}
d2 = d.copy()
verify(d == d2)
g(1, d=4, **d)
-print sortdict(d)
-print sortdict(d2)
+print(sortdict(d))
+print(sortdict(d2))
verify(d == d2, "function call modified dictionary")
# what about willful misconduct?
@@ -133,79 +133,79 @@ del kw['x']
try:
g(1, 2, 3, **{'x':4, 'y':5})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: keyword parameter redefined"
+ print("should raise TypeError: keyword parameter redefined")
try:
g(1, 2, 3, a=4, b=5, *(6, 7), **{'a':8, 'b':9})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: keyword parameter redefined"
+ print("should raise TypeError: keyword parameter redefined")
try:
f(**{1:2})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: keywords must be strings"
+ print("should raise TypeError: keywords must be strings")
try:
h(**{'e': 2})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: unexpected keyword argument: e"
+ print("should raise TypeError: unexpected keyword argument: e")
try:
h(*h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: * argument must be a tuple"
+ print("should raise TypeError: * argument must be a tuple")
try:
dir(*h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: * argument must be a tuple"
+ print("should raise TypeError: * argument must be a tuple")
try:
None(*h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: * argument must be a tuple"
+ print("should raise TypeError: * argument must be a tuple")
try:
h(**h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: ** argument must be a dictionary"
+ print("should raise TypeError: ** argument must be a dictionary")
try:
dir(**h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: ** argument must be a dictionary"
+ print("should raise TypeError: ** argument must be a dictionary")
try:
None(**h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: ** argument must be a dictionary"
+ print("should raise TypeError: ** argument must be a dictionary")
try:
dir(b=1,**{'b':1})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: dir() got multiple values for keyword argument 'b'"
+ print("should raise TypeError: dir() got multiple values for keyword argument 'b'")
def f2(*a, **b):
return a, b
@@ -215,27 +215,27 @@ for i in range(512):
key = 'k%d' % i
d[key] = i
a, b = f2(1, *(2, 3), **d)
-print len(a), len(b), b == d
+print(len(a), len(b), b == d)
class Foo:
def method(self, arg1, arg2):
return arg1 + arg2
x = Foo()
-print Foo.method(*(x, 1, 2))
-print Foo.method(x, *(1, 2))
+print(Foo.method(*(x, 1, 2)))
+print(Foo.method(x, *(1, 2)))
try:
- print Foo.method(*(1, 2, 3))
+ print(Foo.method(*(1, 2, 3)))
except TypeError as err:
pass
else:
- print 'expected a TypeError for unbound method call'
+ print('expected a TypeError for unbound method call')
try:
- print Foo.method(1, *(2, 3))
+ print(Foo.method(1, *(2, 3)))
except TypeError as err:
pass
else:
- print 'expected a TypeError for unbound method call'
+ print('expected a TypeError for unbound method call')
# A PyCFunction that takes only positional parameters should allow an
# empty keyword dictionary to pass without a complaint, but raise a
@@ -274,6 +274,6 @@ for name in ['za', 'zade', 'zabk', 'zabdv', 'zabdevk']:
for kwargs in ['', 'a', 'd', 'ad', 'abde']:
kwdict = {}
for k in kwargs: kwdict[k] = k + k
- print func.func_name, args, sortdict(kwdict), '->',
+ print(func.func_name, args, sortdict(kwdict), '->', end=' ')
try: func(*args, **kwdict)
- except TypeError as err: print err
+ except TypeError as err: print(err)
diff --git a/Lib/test/test_fcntl.py b/Lib/test/test_fcntl.py
index 2d800b2a5c..f544f1ff98 100755
--- a/Lib/test/test_fcntl.py
+++ b/Lib/test/test_fcntl.py
@@ -41,18 +41,18 @@ else:
lockdata = struct.pack('hh'+start_len+'hh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
if lockdata:
if verbose:
- print 'struct.pack: ', repr(lockdata)
+ print('struct.pack: ', repr(lockdata))
# the example from the library docs
f = open(filename, 'w')
rv = fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
if verbose:
- print 'Status from fcntl with O_NONBLOCK: ', rv
+ print('Status from fcntl with O_NONBLOCK: ', rv)
if sys.platform not in ['os2emx']:
rv = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, lockdata)
if verbose:
- print 'String from fcntl with F_SETLKW: ', repr(rv)
+ print('String from fcntl with F_SETLKW: ', repr(rv))
f.close()
os.unlink(filename)
diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py
index 52c4a02fd6..91f6e76c31 100644
--- a/Lib/test/test_file.py
+++ b/Lib/test/test_file.py
@@ -142,9 +142,9 @@ class OtherFileTests(unittest.TestCase):
if sys.platform != 'osf1V5':
self.assertRaises(IOError, sys.stdin.seek, -1)
else:
- print >>sys.__stdout__, (
+ print((
' Skipping sys.stdin.seek(-1), it may crash the interpreter.'
- ' Test manually.')
+ ' Test manually.'), file=sys.__stdout__)
self.assertRaises(IOError, sys.stdin.truncate)
def testUnicodeOpen(self):
diff --git a/Lib/test/test_fileinput.py b/Lib/test/test_fileinput.py
index 301769e4f5..2b7b255dae 100644
--- a/Lib/test/test_fileinput.py
+++ b/Lib/test/test_fileinput.py
@@ -34,7 +34,7 @@ def remove_tempfiles(*names):
def runTests(t1, t2, t3, t4, bs=0, round=0):
start = 1 + round*6
if verbose:
- print '%s. Simple iteration (bs=%s)' % (start+0, bs)
+ print('%s. Simple iteration (bs=%s)' % (start+0, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
lines = list(fi)
fi.close()
@@ -45,7 +45,7 @@ def runTests(t1, t2, t3, t4, bs=0, round=0):
verify(fi.filename() == t4)
if verbose:
- print '%s. Status variables (bs=%s)' % (start+1, bs)
+ print('%s. Status variables (bs=%s)' % (start+1, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
s = "x"
while s and s != 'Line 6 of file 2\n':
@@ -57,14 +57,14 @@ def runTests(t1, t2, t3, t4, bs=0, round=0):
verify(not fi.isstdin())
if verbose:
- print '%s. Nextfile (bs=%s)' % (start+2, bs)
+ print('%s. Nextfile (bs=%s)' % (start+2, bs))
fi.nextfile()
verify(fi.readline() == 'Line 1 of file 3\n')
verify(fi.lineno() == 22)
fi.close()
if verbose:
- print '%s. Stdin (bs=%s)' % (start+3, bs)
+ print('%s. Stdin (bs=%s)' % (start+3, bs))
fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs)
savestdin = sys.stdin
try:
@@ -78,7 +78,7 @@ def runTests(t1, t2, t3, t4, bs=0, round=0):
sys.stdin = savestdin
if verbose:
- print '%s. Boundary conditions (bs=%s)' % (start+4, bs)
+ print('%s. Boundary conditions (bs=%s)' % (start+4, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
verify(fi.lineno() == 0)
verify(fi.filename() == None)
@@ -87,13 +87,13 @@ def runTests(t1, t2, t3, t4, bs=0, round=0):
verify(fi.filename() == None)
if verbose:
- print '%s. Inplace (bs=%s)' % (start+5, bs)
+ print('%s. Inplace (bs=%s)' % (start+5, bs))
savestdout = sys.stdout
try:
fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs)
for line in fi:
line = line[:-1].upper()
- print line
+ print(line)
fi.close()
finally:
sys.stdout = savestdout
@@ -124,7 +124,7 @@ for round, bs in (0, 0), (1, 30):
# Next, check for proper behavior with 0-byte files.
if verbose:
- print "13. 0-byte files"
+ print("13. 0-byte files")
try:
t1 = writeTmp(1, [""])
t2 = writeTmp(2, [""])
@@ -146,7 +146,7 @@ finally:
remove_tempfiles(t1, t2, t3, t4)
if verbose:
- print "14. Files that don't end with newline"
+ print("14. Files that don't end with newline")
try:
t1 = writeTmp(1, ["A\nB\nC"])
t2 = writeTmp(2, ["D\nE\nF"])
@@ -159,7 +159,7 @@ finally:
remove_tempfiles(t1, t2)
if verbose:
- print "15. Unicode filenames"
+ print("15. Unicode filenames")
try:
t1 = writeTmp(1, ["A\nB"])
encoding = sys.getfilesystemencoding()
@@ -172,7 +172,7 @@ finally:
remove_tempfiles(t1)
if verbose:
- print "16. fileno()"
+ print("16. fileno()")
try:
t1 = writeTmp(1, ["A\nB"])
t2 = writeTmp(2, ["C\nD"])
@@ -188,7 +188,7 @@ finally:
remove_tempfiles(t1, t2)
if verbose:
- print "17. Specify opening mode"
+ print("17. Specify opening mode")
try:
# invalid mode, should raise ValueError
fi = FileInput(mode="w")
@@ -205,7 +205,7 @@ finally:
remove_tempfiles(t1)
if verbose:
- print "18. Test file opening hook"
+ print("18. Test file opening hook")
try:
# cannot use openhook and inplace mode
fi = FileInput(inplace=1, openhook=lambda f,m: None)
diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py
index df78a320ee..658a302206 100644
--- a/Lib/test/test_format.py
+++ b/Lib/test/test_format.py
@@ -11,26 +11,26 @@ overflowok = 1
def testformat(formatstr, args, output=None):
if verbose:
if output:
- print "%s %% %s =? %s ..." %\
- (repr(formatstr), repr(args), repr(output)),
+ print("%s %% %s =? %s ..." %\
+ (repr(formatstr), repr(args), repr(output)), end=' ')
else:
- print "%s %% %s works? ..." % (repr(formatstr), repr(args)),
+ print("%s %% %s works? ..." % (repr(formatstr), repr(args)), end=' ')
try:
result = formatstr % args
except OverflowError:
if not overflowok:
raise
if verbose:
- print 'overflow (this is fine)'
+ print('overflow (this is fine)')
else:
if output and result != output:
if verbose:
- print 'no'
- print "%s %% %s == %s != %s" %\
- (repr(formatstr), repr(args), repr(result), repr(output))
+ print('no')
+ print("%s %% %s == %s != %s" %\
+ (repr(formatstr), repr(args), repr(result), repr(output)))
else:
if verbose:
- print 'yes'
+ print('yes')
def testboth(formatstr, *args):
testformat(formatstr, *args)
@@ -194,7 +194,7 @@ testboth("%o", -042, "-42")
# Test exception for unknown format characters
if verbose:
- print 'Testing exceptions'
+ print('Testing exceptions')
def test_exc(formatstr, args, exception, excmsg):
try:
@@ -202,13 +202,13 @@ def test_exc(formatstr, args, exception, excmsg):
except exception as exc:
if str(exc) == excmsg:
if verbose:
- print "yes"
+ print("yes")
else:
- if verbose: print 'no'
- print 'Unexpected ', exception, ':', repr(str(exc))
+ if verbose: print('no')
+ print('Unexpected ', exception, ':', repr(str(exc)))
except:
- if verbose: print 'no'
- print 'Unexpected exception'
+ if verbose: print('no')
+ print('Unexpected exception')
raise
else:
raise TestFailed, 'did not get expected exception: %s' % excmsg
diff --git a/Lib/test/test_funcattrs.py b/Lib/test/test_funcattrs.py
index 930c85147e..2f4b67abe0 100644
--- a/Lib/test/test_funcattrs.py
+++ b/Lib/test/test_funcattrs.py
@@ -204,7 +204,7 @@ def bar():
pass
def temp():
- print 1
+ print(1)
if foo==bar:
raise TestFailed
@@ -235,7 +235,7 @@ def cantset(obj, name, value, exception=(AttributeError, TypeError)):
def test_func_closure():
a = 12
- def f(): print a
+ def f(): print(a)
c = f.func_closure
verify(isinstance(c, tuple))
verify(len(c) == 1)
@@ -284,10 +284,10 @@ def test_func_name():
def test_func_code():
a = b = 24
def f(): pass
- def g(): print 12
- def f1(): print a
- def g1(): print b
- def f2(): print a, b
+ def g(): print(12)
+ def f1(): print(a)
+ def g1(): print(b)
+ def f2(): print(a, b)
verify(type(f.func_code) is types.CodeType)
f.func_code = g.func_code
cantset(f, "func_code", None)
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index 828331e649..2d5e33c54b 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -356,7 +356,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == '__main__':
test_main(verbose=True)
diff --git a/Lib/test/test_gc.py b/Lib/test/test_gc.py
index 675b988db9..8068b35c21 100644
--- a/Lib/test/test_gc.py
+++ b/Lib/test/test_gc.py
@@ -14,10 +14,10 @@ def expect_nonzero(actual, name):
def run_test(name, thunk):
if verbose:
- print "testing %s..." % name,
+ print("testing %s..." % name, end=' ')
thunk()
if verbose:
- print "ok"
+ print("ok")
def test_list():
l = []
@@ -612,7 +612,7 @@ def test_all():
def test():
if verbose:
- print "disabling automatic collection"
+ print("disabling automatic collection")
enabled = gc.isenabled()
gc.disable()
verify(not gc.isenabled())
@@ -625,7 +625,7 @@ def test():
gc.set_debug(debug)
# test gc.enable() even if GC is disabled by default
if verbose:
- print "restoring automatic collection"
+ print("restoring automatic collection")
# make sure to always test gc.enable()
gc.enable()
verify(gc.isenabled())
diff --git a/Lib/test/test_gdbm.py b/Lib/test/test_gdbm.py
index a68957633a..ae76e39178 100755
--- a/Lib/test/test_gdbm.py
+++ b/Lib/test/test_gdbm.py
@@ -15,7 +15,7 @@ g['a'] = 'b'
g['12345678910'] = '019237410982340912840198242'
a = g.keys()
if verbose:
- print 'Test gdbm file keys: ', a
+ print('Test gdbm file keys: ', a)
'a' in g
g.close()
diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py
index a40d8ea9be..39d016c2cd 100644
--- a/Lib/test/test_generators.py
+++ b/Lib/test/test_generators.py
@@ -1082,12 +1082,12 @@ class Queens:
n = self.n
assert n == len(row2col)
sep = "+" + "-+" * n
- print sep
+ print(sep)
for i in range(n):
squares = [" " for j in range(n)]
squares[row2col[i]] = "Q"
- print "|" + "|".join(squares) + "|"
- print sep
+ print("|" + "|".join(squares) + "|")
+ print(sep)
# A conjoin-based Knight's Tour solver. This is pretty sophisticated
# (e.g., when used with flat_conjoin above, and passing hard=1 to the
@@ -1279,11 +1279,11 @@ class Knights:
k += 1
sep = "+" + ("-" * w + "+") * n
- print sep
+ print(sep)
for i in range(m):
row = squares[i]
- print "|" + "|".join(row) + "|"
- print sep
+ print("|" + "|".join(row) + "|")
+ print(sep)
conjoin_tests = """
diff --git a/Lib/test/test_genexps.py b/Lib/test/test_genexps.py
index 2598a7913a..5fd9c7b949 100644
--- a/Lib/test/test_genexps.py
+++ b/Lib/test/test_genexps.py
@@ -274,7 +274,7 @@ def test_main(verbose=None):
test_support.run_doctest(test_genexps, verbose)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_getopt.py b/Lib/test/test_getopt.py
index f565d2328a..10bd256494 100644
--- a/Lib/test/test_getopt.py
+++ b/Lib/test/test_getopt.py
@@ -21,14 +21,14 @@ if old_posixly_correct is not None:
del os.environ["POSIXLY_CORRECT"]
if verbose:
- print 'Running tests on getopt.short_has_arg'
+ print('Running tests on getopt.short_has_arg')
verify(getopt.short_has_arg('a', 'a:'))
verify(not getopt.short_has_arg('a', 'a'))
expectException("tmp = getopt.short_has_arg('a', 'b')", GetoptError)
expectException("tmp = getopt.short_has_arg('a', '')", GetoptError)
if verbose:
- print 'Running tests on getopt.long_has_args'
+ print('Running tests on getopt.long_has_args')
has_arg, option = getopt.long_has_args('abc', ['abc='])
verify(has_arg)
verify(option == 'abc')
@@ -47,7 +47,7 @@ expectException("has_arg, option = " + \
GetoptError)
if verbose:
- print 'Running tests on getopt.do_shorts'
+ print('Running tests on getopt.do_shorts')
opts, args = getopt.do_shorts([], 'a', 'a', [])
verify(opts == [('-a', '')])
verify(args == [])
@@ -69,7 +69,7 @@ expectException("opts, args = getopt.do_shorts([], 'a', 'a:', [])",
GetoptError)
if verbose:
- print 'Running tests on getopt.do_longs'
+ print('Running tests on getopt.do_longs')
opts, args = getopt.do_longs([], 'abc', ['abc'], [])
verify(opts == [('--abc', '')])
verify(args == [])
@@ -99,7 +99,7 @@ cmdline = ['-a', '1', '-b', '--alpha=2', '--beta', '-a', '3', '-a', '',
'--beta', 'arg1', 'arg2']
if verbose:
- print 'Running tests on getopt.getopt'
+ print('Running tests on getopt.getopt')
opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta'])
verify(opts == [('-a', '1'), ('-b', ''), ('--alpha', '2'), ('--beta', ''),
('-a', '3'), ('-a', ''), ('--beta', '')] )
@@ -113,7 +113,7 @@ expectException(
# Test handling of GNU style scanning mode.
if verbose:
- print 'Running tests on getopt.gnu_getopt'
+ print('Running tests on getopt.gnu_getopt')
cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2']
# GNU style
opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
@@ -177,4 +177,4 @@ run_doctest(sys.modules[__name__], verbose)
#------------------------------------------------------------------------------
if verbose:
- print "Module getopt: tests completed successfully."
+ print("Module getopt: tests completed successfully.")
diff --git a/Lib/test/test_gl.py b/Lib/test/test_gl.py
index c9cce77607..adae10eb09 100755
--- a/Lib/test/test_gl.py
+++ b/Lib/test/test_gl.py
@@ -91,60 +91,60 @@ def main():
# touch all the attributes of gl without doing anything
if verbose:
- print 'Touching gl module attributes...'
+ print('Touching gl module attributes...')
for attr in glattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(gl, attr)
# create a small 'Crisscross' window
if verbose:
- print 'Creating a small "CrissCross" window...'
- print 'foreground'
+ print('Creating a small "CrissCross" window...')
+ print('foreground')
gl.foreground()
if verbose:
- print 'prefposition'
+ print('prefposition')
gl.prefposition(500, 900, 500, 900)
if verbose:
- print 'winopen "CrissCross"'
+ print('winopen "CrissCross"')
w = gl.winopen('CrissCross')
if verbose:
- print 'clear'
+ print('clear')
gl.clear()
if verbose:
- print 'ortho2'
+ print('ortho2')
gl.ortho2(0.0, 400.0, 0.0, 400.0)
if verbose:
- print 'color WHITE'
+ print('color WHITE')
gl.color(GL.WHITE)
if verbose:
- print 'color RED'
+ print('color RED')
gl.color(GL.RED)
if verbose:
- print 'bgnline'
+ print('bgnline')
gl.bgnline()
if verbose:
- print 'v2f'
+ print('v2f')
gl.v2f(0.0, 0.0)
gl.v2f(400.0, 400.0)
if verbose:
- print 'endline'
+ print('endline')
gl.endline()
if verbose:
- print 'bgnline'
+ print('bgnline')
gl.bgnline()
if verbose:
- print 'v2i'
+ print('v2i')
gl.v2i(400, 0)
gl.v2i(0, 400)
if verbose:
- print 'endline'
+ print('endline')
gl.endline()
if verbose:
- print 'Displaying window for 2 seconds...'
+ print('Displaying window for 2 seconds...')
time.sleep(2)
if verbose:
- print 'winclose'
+ print('winclose')
gl.winclose(w)
main()
diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py
index 33bfd3269d..4a480aa14a 100644
--- a/Lib/test/test_grammar.py
+++ b/Lib/test/test_grammar.py
@@ -351,7 +351,7 @@ class GrammarTests(unittest.TestCase):
x = 1; pass; del x;
foo()
- ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
+ ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
# Tested below
def testExprStmt(self):
@@ -367,76 +367,6 @@ class GrammarTests(unittest.TestCase):
check_syntax_error(self, "x + 1 = 1")
check_syntax_error(self, "a + 1 = b + 2")
- def testPrintStmt(self):
- # 'print' (test ',')* [test]
- import StringIO
-
- # Can't test printing to real stdout without comparing output
- # which is not available in unittest.
- save_stdout = sys.stdout
- sys.stdout = StringIO.StringIO()
-
- print 1, 2, 3
- print 1, 2, 3,
- print
- print 0 or 1, 0 or 1,
- print 0 or 1
-
- # 'print' '>>' test ','
- print >> sys.stdout, 1, 2, 3
- print >> sys.stdout, 1, 2, 3,
- print >> sys.stdout
- print >> sys.stdout, 0 or 1, 0 or 1,
- print >> sys.stdout, 0 or 1
-
- # test printing to an instance
- class Gulp:
- def write(self, msg): pass
-
- gulp = Gulp()
- print >> gulp, 1, 2, 3
- print >> gulp, 1, 2, 3,
- print >> gulp
- print >> gulp, 0 or 1, 0 or 1,
- print >> gulp, 0 or 1
-
- # test print >> None
- def driver():
- oldstdout = sys.stdout
- sys.stdout = Gulp()
- try:
- tellme(Gulp())
- tellme()
- finally:
- sys.stdout = oldstdout
-
- # we should see this once
- def tellme(file=sys.stdout):
- print >> file, 'hello world'
-
- driver()
-
- # we should not see this at all
- def tellme(file=None):
- print >> file, 'goodbye universe'
-
- driver()
-
- self.assertEqual(sys.stdout.getvalue(), '''\
-1 2 3
-1 2 3
-1 1 1
-1 2 3
-1 2 3
-1 1 1
-hello world
-''')
- sys.stdout = save_stdout
-
- # syntax errors
- check_syntax_error(self, 'print ,')
- check_syntax_error(self, 'print >> x,')
-
def testDelStmt(self):
# 'del' exprlist
abc = [1,2,3]
@@ -902,7 +832,7 @@ hello world
# Test ifelse expressions in various cases
def _checkeval(msg, ret):
"helper to check that evaluation of expressions is done correctly"
- print x
+ print(x)
return ret
self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py
index b652d41fab..934f7b66b1 100644
--- a/Lib/test/test_heapq.py
+++ b/Lib/test/test_heapq.py
@@ -281,7 +281,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_imageop.py b/Lib/test/test_imageop.py
index b01e83fa28..d0794735fa 100755
--- a/Lib/test/test_imageop.py
+++ b/Lib/test/test_imageop.py
@@ -28,7 +28,7 @@ def main(use_rgbimg=1):
# Return the selected part of image, which should by width by height
# in size and consist of pixels of psize bytes.
if verbose:
- print 'crop'
+ print('crop')
newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1)
# Return image scaled to size newwidth by newheight. No interpolation
@@ -36,7 +36,7 @@ def main(use_rgbimg=1):
# Therefore, computer-generated images or dithered images will
# not look nice after scaling.
if verbose:
- print 'scale'
+ print('scale')
scaleimage = imageop.scale(image, 4, width, height, 1, 1)
# Run a vertical low-pass filter over an image. It does so by computing
@@ -44,34 +44,34 @@ def main(use_rgbimg=1):
# pixels. The main use of this routine is to forestall excessive flicker
# if the image two vertically-aligned source pixels, hence the name.
if verbose:
- print 'tovideo'
+ print('tovideo')
videoimage = imageop.tovideo (image, 4, width, height)
# Convert an rgb image to an 8 bit rgb
if verbose:
- print 'rgb2rgb8'
+ print('rgb2rgb8')
greyimage = imageop.rgb2rgb8(image, width, height)
# Convert an 8 bit rgb image to a 24 bit rgb image
if verbose:
- print 'rgb82rgb'
+ print('rgb82rgb')
image = imageop.rgb82rgb(greyimage, width, height)
# Convert an rgb image to an 8 bit greyscale image
if verbose:
- print 'rgb2grey'
+ print('rgb2grey')
greyimage = imageop.rgb2grey(image, width, height)
# Convert an 8 bit greyscale image to a 24 bit rgb image
if verbose:
- print 'grey2rgb'
+ print('grey2rgb')
image = imageop.grey2rgb(greyimage, width, height)
# Convert a 8-bit deep greyscale image to a 1-bit deep image by
# thresholding all the pixels. The resulting image is tightly packed
# and is probably only useful as an argument to mono2grey.
if verbose:
- print 'grey2mono'
+ print('grey2mono')
monoimage = imageop.grey2mono (greyimage, width, height, 0)
# monoimage, width, height = getimage('monotest.rgb')
@@ -81,42 +81,42 @@ def main(use_rgbimg=1):
# monochrome black-and-white image to greyscale pass the values 0 and
# 255 respectively.
if verbose:
- print 'mono2grey'
+ print('mono2grey')
greyimage = imageop.mono2grey (monoimage, width, height, 0, 255)
# Convert an 8-bit greyscale image to a 1-bit monochrome image using a
# (simple-minded) dithering algorithm.
if verbose:
- print 'dither2mono'
+ print('dither2mono')
monoimage = imageop.dither2mono (greyimage, width, height)
# Convert an 8-bit greyscale image to a 4-bit greyscale image without
# dithering.
if verbose:
- print 'grey2grey4'
+ print('grey2grey4')
grey4image = imageop.grey2grey4 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image without
# dithering.
if verbose:
- print 'grey2grey2'
+ print('grey2grey2')
grey2image = imageop.grey2grey2 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image with
# dithering. As for dither2mono, the dithering algorithm is currently
# very simple.
if verbose:
- print 'dither2grey2'
+ print('dither2grey2')
grey2image = imageop.dither2grey2 (greyimage, width, height)
# Convert a 4-bit greyscale image to an 8-bit greyscale image.
if verbose:
- print 'grey42grey'
+ print('grey42grey')
greyimage = imageop.grey42grey (grey4image, width, height)
# Convert a 2-bit greyscale image to an 8-bit greyscale image.
if verbose:
- print 'grey22grey'
+ print('grey22grey')
image = imageop.grey22grey (grey2image, width, height)
# Cleanup
@@ -134,7 +134,7 @@ def getrgbimage(name):
name = get_qualified_path(name)
sizes = rgbimg.sizeofimage(name)
if verbose:
- print 'rgbimg opening test image: %s, sizes: %s' % (name, str(sizes))
+ print('rgbimg opening test image: %s, sizes: %s' % (name, str(sizes)))
image = rgbimg.longimagedata(name)
return (image, sizes[0], sizes[1])
@@ -152,7 +152,7 @@ def getimage(name):
name = get_qualified_path(name)
sizes = imgfile.getsizes(name)
if verbose:
- print 'imgfile opening test image: %s, sizes: %s' % (name, str(sizes))
+ print('imgfile opening test image: %s, sizes: %s' % (name, str(sizes)))
image = imgfile.read(name)
return (image, sizes[0], sizes[1])
diff --git a/Lib/test/test_imgfile.py b/Lib/test/test_imgfile.py
index bdfd796b1e..4e31cb1a98 100755
--- a/Lib/test/test_imgfile.py
+++ b/Lib/test/test_imgfile.py
@@ -51,7 +51,7 @@ def testimage(name):
name = os.sep.join(parts)
sizes = imgfile.getsizes(name)
if verbose:
- print 'Opening test image: %s, sizes: %s' % (name, str(sizes))
+ print('Opening test image: %s, sizes: %s' % (name, str(sizes)))
# This function reads and decodes the image on the specified file,
# and returns it as a python string. The string has either 1 byte
# greyscale pixels or 4 byte RGBA pixels. The bottom left pixel
@@ -65,12 +65,12 @@ def testimage(name):
# are stored as 4 byte values of which only the lower three
# bytes are used). These are the formats returned by gl.lrectread.
if verbose:
- print 'Writing output file'
+ print('Writing output file')
imgfile.write (outputfile, image, sizes[0], sizes[1], sizes[2])
if verbose:
- print 'Opening scaled test image: %s, sizes: %s' % (name, str(sizes))
+ print('Opening scaled test image: %s, sizes: %s' % (name, str(sizes)))
# This function is identical to read but it returns an image that
# is scaled to the given x and y sizes. If the filter and blur
# parameters are omitted scaling is done by simply dropping
@@ -84,7 +84,7 @@ def testimage(name):
# makes no attempt to keep the aspect ratio correct, so that
# is the users' responsibility.
if verbose:
- print 'Filtering with "impulse"'
+ print('Filtering with "impulse"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'impulse', 2.0)
# This function sets a global flag which defines whether the
@@ -92,23 +92,23 @@ def testimage(name):
# top (flag is zero, compatible with SGI GL) or from top to
# bottom(flag is one, compatible with X). The default is zero.
if verbose:
- print 'Switching to X compatibility'
+ print('Switching to X compatibility')
imgfile.ttob (1)
if verbose:
- print 'Filtering with "triangle"'
+ print('Filtering with "triangle"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'triangle', 3.0)
if verbose:
- print 'Switching back to SGI compatibility'
+ print('Switching back to SGI compatibility')
imgfile.ttob (0)
- if verbose: print 'Filtering with "quadratic"'
+ if verbose: print('Filtering with "quadratic"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'quadratic')
- if verbose: print 'Filtering with "gaussian"'
+ if verbose: print('Filtering with "gaussian"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'gaussian', 1.0)
if verbose:
- print 'Writing output file'
+ print('Writing output file')
imgfile.write (outputfile, simage, sizes[0]/2, sizes[1]/2, sizes[2])
os.unlink(outputfile)
diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py
index f3d1d49cf3..a8f912fc8d 100644
--- a/Lib/test/test_import.py
+++ b/Lib/test/test_import.py
@@ -45,11 +45,11 @@ class ImportTest(unittest.TestCase):
pyc = TESTFN + os.extsep + "pyc"
f = open(source, "w")
- print >> f, "# This tests Python's ability to import a", ext, "file."
+ print("# This tests Python's ability to import a", ext, "file.", file=f)
a = random.randrange(1000)
b = random.randrange(1000)
- print >> f, "a =", a
- print >> f, "b =", b
+ print("a =", a, file=f)
+ print("b =", b, file=f)
f.close()
try:
@@ -130,7 +130,7 @@ class ImportTest(unittest.TestCase):
def test_failing_import_sticks(self):
source = TESTFN + os.extsep + "py"
f = open(source, "w")
- print >> f, "a = 1/0"
+ print("a = 1/0", file=f)
f.close()
# New in 2.4, we shouldn't be able to import that no matter how often
@@ -153,8 +153,8 @@ class ImportTest(unittest.TestCase):
# A failing reload should leave the module object in sys.modules.
source = TESTFN + os.extsep + "py"
f = open(source, "w")
- print >> f, "a = 1"
- print >> f, "b = 2"
+ print("a = 1", file=f)
+ print("b = 2", file=f)
f.close()
sys.path.insert(0, os.curdir)
@@ -172,8 +172,8 @@ class ImportTest(unittest.TestCase):
# Now damage the module.
f = open(source, "w")
- print >> f, "a = 10"
- print >> f, "b = 20//0"
+ print("a = 10", file=f)
+ print("b = 20//0", file=f)
f.close()
self.assertRaises(ZeroDivisionError, reload, mod)
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index 0b9f165ea1..5a1d4a1631 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -965,7 +965,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
# doctest the examples in the library reference
test_support.run_doctest(sys.modules[__name__], verbose)
diff --git a/Lib/test/test_largefile.py b/Lib/test/test_largefile.py
index d7ed1b3bcb..f4b51ffa7b 100644
--- a/Lib/test/test_largefile.py
+++ b/Lib/test/test_largefile.py
@@ -52,22 +52,22 @@ else:
def expect(got_this, expect_this):
if test_support.verbose:
- print '%r =?= %r ...' % (got_this, expect_this),
+ print('%r =?= %r ...' % (got_this, expect_this), end=' ')
if got_this != expect_this:
if test_support.verbose:
- print 'no'
+ print('no')
raise test_support.TestFailed, 'got %r, but expected %r' %\
(got_this, expect_this)
else:
if test_support.verbose:
- print 'yes'
+ print('yes')
# test that each file function works as expected for a large (i.e. >2GB, do
# we have to check >4GB) files
if test_support.verbose:
- print 'create large file via seek (may be sparse file) ...'
+ print('create large file via seek (may be sparse file) ...')
f = open(name, 'wb')
try:
f.write('z')
@@ -76,16 +76,16 @@ try:
f.write('a')
f.flush()
if test_support.verbose:
- print 'check file size with os.fstat'
+ print('check file size with os.fstat')
expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
finally:
f.close()
if test_support.verbose:
- print 'check file size with os.stat'
+ print('check file size with os.stat')
expect(os.stat(name)[stat.ST_SIZE], size+1)
if test_support.verbose:
- print 'play around with seek() and read() with the built largefile'
+ print('play around with seek() and read() with the built largefile')
f = open(name, 'rb')
try:
expect(f.tell(), 0)
@@ -119,7 +119,7 @@ finally:
f.close()
if test_support.verbose:
- print 'play around with os.lseek() with the built largefile'
+ print('play around with os.lseek() with the built largefile')
f = open(name, 'rb')
try:
expect(os.lseek(f.fileno(), 0, 0), 0)
@@ -136,7 +136,7 @@ finally:
if hasattr(f, 'truncate'):
if test_support.verbose:
- print 'try truncate'
+ print('try truncate')
f = open(name, 'r+b')
try:
f.seek(0, 2)
diff --git a/Lib/test/test_linuxaudiodev.py b/Lib/test/test_linuxaudiodev.py
index 05e4041662..eac204f711 100644
--- a/Lib/test/test_linuxaudiodev.py
+++ b/Lib/test/test_linuxaudiodev.py
@@ -22,7 +22,7 @@ def play_sound_file(path):
fp.close()
if enc != SND_FORMAT_MULAW_8:
- print "Expect .au file with 8-bit mu-law samples"
+ print("Expect .au file with 8-bit mu-law samples")
return
try:
@@ -63,27 +63,27 @@ def test_errors():
try:
a.setparameters(-1, size, nchannels, fmt)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, -2, nchannels, fmt)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, size, 3, fmt)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, size, nchannels, 177)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, 16, nchannels, fmt)
except ValueError as msg:
- print msg
+ print(msg)
def test():
play_sound_file(findfile('audiotest.au'))
diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py
index 711ac4b75c..5d9983f454 100644
--- a/Lib/test/test_list.py
+++ b/Lib/test/test_list.py
@@ -30,7 +30,7 @@ def test_main(verbose=None):
test_support.run_unittest(ListTest)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
diff --git a/Lib/test/test_locale.py b/Lib/test/test_locale.py
index 9e264b9c4e..ba7d653a46 100644
--- a/Lib/test/test_locale.py
+++ b/Lib/test/test_locale.py
@@ -23,19 +23,19 @@ else:
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format):
if verbose:
if output:
- print "%s %% %s =? %s ..." %\
- (repr(formatstr), repr(value), repr(output)),
+ print("%s %% %s =? %s ..." %\
+ (repr(formatstr), repr(value), repr(output)), end=' ')
else:
- print "%s %% %s works? ..." % (repr(formatstr), repr(value)),
+ print("%s %% %s works? ..." % (repr(formatstr), repr(value)), end=' ')
result = func(formatstr, value, grouping = grouping)
if output and result != output:
if verbose:
- print 'no'
- print "%s %% %s == %s != %s" %\
- (repr(formatstr), repr(value), repr(result), repr(output))
+ print('no')
+ print("%s %% %s == %s != %s" %\
+ (repr(formatstr), repr(value), repr(result), repr(output)))
else:
if verbose:
- print "yes"
+ print("yes")
try:
# On Solaris 10, the thousands_sep is the empty string
@@ -80,15 +80,15 @@ finally:
# Test BSD Rune locale's bug for isctype functions.
def teststrop(s, method, output):
if verbose:
- print "%s.%s() =? %s ..." % (repr(s), method, repr(output)),
+ print("%s.%s() =? %s ..." % (repr(s), method, repr(output)), end=' ')
result = getattr(s, method)()
if result != output:
if verbose:
- print "no"
- print "%s.%s() == %s != %s" % (repr(s), method, repr(result),
- repr(output))
+ print("no")
+ print("%s.%s() == %s != %s" % (repr(s), method, repr(result),
+ repr(output)))
elif verbose:
- print "yes"
+ print("yes")
try:
if sys.platform == 'sunos5':
diff --git a/Lib/test/test_long_future.py b/Lib/test/test_long_future.py
index 3f137d6a12..fc0100119e 100644
--- a/Lib/test/test_long_future.py
+++ b/Lib/test/test_long_future.py
@@ -7,7 +7,7 @@ from test.test_support import TestFailed, verify, verbose
def test_true_division():
if verbose:
- print "long true division"
+ print("long true division")
huge = 1 << 40000
mhuge = -huge
verify(huge / huge == 1.0)
diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py
index a6d309f7d9..d0a99a7fb9 100644
--- a/Lib/test/test_minidom.py
+++ b/Lib/test/test_minidom.py
@@ -24,7 +24,7 @@ del base
def confirm(test, testname = "Test"):
if not test:
- print "Failed " + testname
+ print("Failed " + testname)
raise Exception
def testParseFromFile():
@@ -140,29 +140,29 @@ def testLegalChildren():
try: dom.appendChild(text)
except xml.dom.HierarchyRequestErr: pass
else:
- print "dom.appendChild didn't raise HierarchyRequestErr"
+ print("dom.appendChild didn't raise HierarchyRequestErr")
dom.appendChild(elem)
try: dom.insertBefore(text, elem)
except xml.dom.HierarchyRequestErr: pass
else:
- print "dom.appendChild didn't raise HierarchyRequestErr"
+ print("dom.appendChild didn't raise HierarchyRequestErr")
try: dom.replaceChild(text, elem)
except xml.dom.HierarchyRequestErr: pass
else:
- print "dom.appendChild didn't raise HierarchyRequestErr"
+ print("dom.appendChild didn't raise HierarchyRequestErr")
nodemap = elem.attributes
try: nodemap.setNamedItem(text)
except xml.dom.HierarchyRequestErr: pass
else:
- print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr"
+ print("NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr")
try: nodemap.setNamedItemNS(text)
except xml.dom.HierarchyRequestErr: pass
else:
- print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr"
+ print("NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr")
elem.appendChild(text)
dom.unlink()
@@ -457,8 +457,8 @@ def testTooManyDocumentElements():
except xml.dom.HierarchyRequestErr:
pass
else:
- print "Failed to catch expected exception when" \
- " adding extra document element."
+ print("Failed to catch expected exception when" \
+ " adding extra document element.")
elem.unlink()
doc.unlink()
@@ -896,7 +896,7 @@ def testEncodings():
except UnicodeDecodeError:
pass
else:
- print 'parsing with bad encoding should raise a UnicodeDecodeError'
+ print('parsing with bad encoding should raise a UnicodeDecodeError')
doc.unlink()
@@ -1008,7 +1008,7 @@ def testRenameAttribute():
except xml.dom.NamespaceErr:
pass
else:
- print "expected NamespaceErr"
+ print("expected NamespaceErr")
checkRenameNodeSharedConstraints(doc, attr)
doc.unlink()
@@ -1063,7 +1063,7 @@ def checkRenameNodeSharedConstraints(doc, node):
except xml.dom.NamespaceErr:
pass
else:
- print "expected NamespaceErr"
+ print("expected NamespaceErr")
doc2 = parseString("<doc/>")
try:
@@ -1071,7 +1071,7 @@ def checkRenameNodeSharedConstraints(doc, node):
except xml.dom.WrongDocumentErr:
pass
else:
- print "expected WrongDocumentErr"
+ print("expected WrongDocumentErr")
def testRenameOther():
# We have to create a comment node explicitly since not all DOM
@@ -1084,7 +1084,7 @@ def testRenameOther():
except xml.dom.NotSupportedErr:
pass
else:
- print "expected NotSupportedErr when renaming comment node"
+ print("expected NotSupportedErr when renaming comment node")
doc.unlink()
def checkWholeText(node, s):
@@ -1368,13 +1368,13 @@ else:
confirm(len(Node.allnodes) == 0,
"assertion: len(Node.allnodes) == 0")
if len(Node.allnodes):
- print "Garbage left over:"
+ print("Garbage left over:")
if verbose:
- print Node.allnodes.items()[0:10]
+ print(Node.allnodes.items()[0:10])
else:
# Don't print specific nodes if repeatable results
# are needed
- print len(Node.allnodes)
+ print(len(Node.allnodes))
Node.allnodes = {}
for name in names:
@@ -1385,13 +1385,13 @@ for name in names:
check_allnodes()
except:
failed.append(name)
- print "Test Failed: ", name
+ print("Test Failed: ", name)
sys.stdout.flush()
traceback.print_exception(*sys.exc_info())
- print repr(sys.exc_info()[1])
+ print(repr(sys.exc_info()[1]))
Node.allnodes = {}
if failed:
- print "\n\n\n**** Check for failures in these tests:"
+ print("\n\n\n**** Check for failures in these tests:")
for name in failed:
- print " " + name
+ print(" " + name)
diff --git a/Lib/test/test_module.py b/Lib/test/test_module.py
index 2b35a531af..7911a0eb98 100644
--- a/Lib/test/test_module.py
+++ b/Lib/test/test_module.py
@@ -45,4 +45,4 @@ vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc", "bar": 42})
verify(foo.__dict__ is d)
if verbose:
- print "All OK"
+ print("All OK")
diff --git a/Lib/test/test_multibytecodec.py b/Lib/test/test_multibytecodec.py
index fb7f82d18e..2ac7061f69 100644
--- a/Lib/test/test_multibytecodec.py
+++ b/Lib/test/test_multibytecodec.py
@@ -48,7 +48,7 @@ class Test_MultibyteCodec(unittest.TestCase):
def test_codingspec(self):
try:
for enc in ALL_CJKENCODINGS:
- print >> open(TESTFN, 'w'), '# coding:', enc
+ print('# coding:', enc, file=open(TESTFN, 'w'))
execfile(TESTFN)
finally:
os.unlink(TESTFN)
diff --git a/Lib/test/test_mutants.py b/Lib/test/test_mutants.py
index 621522617a..a710248ac8 100644
--- a/Lib/test/test_mutants.py
+++ b/Lib/test/test_mutants.py
@@ -135,13 +135,13 @@ def test_one(n):
# same size.
mutate = 1
if verbose:
- print "trying w/ lengths", len(dict1), len(dict2),
+ print("trying w/ lengths", len(dict1), len(dict2), end=' ')
while dict1 and len(dict1) == len(dict2):
if verbose:
- print ".",
+ print(".", end=' ')
c = dict1 == dict2
if verbose:
- print
+ print()
# Run test_one n times. At the start (before the bugs were fixed), 20
# consecutive runs of this test each blew up on or before the sixth time
@@ -186,7 +186,7 @@ class Parent:
# the expected-output file doesn't need to change.
f = open(TESTFN, "w")
-print >> f, Parent().__dict__
+print(Parent().__dict__, file=f)
f.close()
os.unlink(TESTFN)
@@ -207,7 +207,7 @@ class Machiavelli:
# Michael sez: "doesn't crash without this. don't know why."
# Tim sez: "luck of the draw; crashes with or without for me."
- print >> f
+ print(file=f)
return repr("machiavelli")
@@ -216,7 +216,7 @@ class Machiavelli:
dict[Machiavelli()] = Machiavelli()
-print >> f, str(dict)
+print(str(dict), file=f)
f.close()
os.unlink(TESTFN)
del f, dict
@@ -280,7 +280,7 @@ dict[Machiavelli3(2)] = Machiavelli3(0)
f = open(TESTFN, "w")
try:
try:
- print >> f, dict[Machiavelli3(2)]
+ print(dict[Machiavelli3(2)], file=f)
except KeyError:
pass
finally:
diff --git a/Lib/test/test_normalization.py b/Lib/test/test_normalization.py
index 81bdfbd96c..d890067ea2 100644
--- a/Lib/test/test_normalization.py
+++ b/Lib/test/test_normalization.py
@@ -58,7 +58,7 @@ def test_main():
continue
if verbose:
- print line
+ print(line)
# Perform tests
verify(c2 == NFC(c1) == NFC(c2) == NFC(c3), line)
diff --git a/Lib/test/test_ntpath.py b/Lib/test/test_ntpath.py
index 6bc2a054de..939886d159 100644
--- a/Lib/test/test_ntpath.py
+++ b/Lib/test/test_ntpath.py
@@ -9,11 +9,11 @@ def tester(fn, wantResult):
fn = fn.replace("\\", "\\\\")
gotResult = eval(fn)
if wantResult != gotResult:
- print "error!"
- print "evaluated: " + str(fn)
- print "should be: " + str(wantResult)
- print " returned: " + str(gotResult)
- print ""
+ print("error!")
+ print("evaluated: " + str(fn))
+ print("should be: " + str(wantResult))
+ print(" returned: " + str(gotResult))
+ print("")
errors = errors + 1
tester('ntpath.splitext("foo.ext")', ('foo', '.ext'))
@@ -152,4 +152,4 @@ else:
if errors:
raise TestFailed(str(errors) + " errors.")
elif verbose:
- print "No errors. Thank your lucky stars."
+ print("No errors. Thank your lucky stars.")
diff --git a/Lib/test/test_operations.py b/Lib/test/test_operations.py
index 8baef4cd8a..e8b1ae80f9 100644
--- a/Lib/test/test_operations.py
+++ b/Lib/test/test_operations.py
@@ -1,11 +1,11 @@
# Python test set -- part 3, built-in operations.
-print '3. Operations'
-print 'XXX Mostly not yet implemented'
+print('3. Operations')
+print('XXX Mostly not yet implemented')
-print '3.1 Dictionary lookups fail if __cmp__() raises an exception'
+print('3.1 Dictionary lookups fail if __cmp__() raises an exception')
class BadDictKey:
@@ -14,7 +14,7 @@ class BadDictKey:
def __eq__(self, other):
if isinstance(other, self.__class__):
- print "raising error"
+ print("raising error")
raise RuntimeError, "gotcha"
return other
@@ -32,9 +32,9 @@ for stmt in ['d[x2] = 2',
try:
exec(stmt)
except RuntimeError:
- print "%s: caught the RuntimeError outside" % (stmt,)
+ print("%s: caught the RuntimeError outside" % (stmt,))
else:
- print "%s: No exception passed through!" % (stmt,) # old CPython behavior
+ print("%s: No exception passed through!" % (stmt,)) # old CPython behavior
# Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
@@ -74,4 +74,4 @@ d[X()] = 5
resizing = True
d[9] = 6
-print 'resize bugs not triggered.'
+print('resize bugs not triggered.')
diff --git a/Lib/test/test_operator.py b/Lib/test/test_operator.py
index c71a4e62aa..2183508bba 100644
--- a/Lib/test/test_operator.py
+++ b/Lib/test/test_operator.py
@@ -468,7 +468,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_ossaudiodev.py b/Lib/test/test_ossaudiodev.py
index 0377e9c4ea..e97e788d7b 100644
--- a/Lib/test/test_ossaudiodev.py
+++ b/Lib/test/test_ossaudiodev.py
@@ -33,7 +33,7 @@ def read_sound_file(path):
fp.close()
if enc != SND_FORMAT_MULAW_8:
- print "Expect .au file with 8-bit mu-law samples"
+ print("Expect .au file with 8-bit mu-law samples")
return
# Convert the data to 16-bit signed.
@@ -78,8 +78,8 @@ def play_sound_file(data, rate, ssize, nchannels):
# set parameters based on .au file headers
dsp.setparameters(AFMT_S16_NE, nchannels, rate)
- print ("playing test sound file (expected running time: %.2f sec)"
- % expected_time)
+ print(("playing test sound file (expected running time: %.2f sec)"
+ % expected_time))
t1 = time.time()
dsp.write(data)
dsp.close()
@@ -143,7 +143,7 @@ def test_bad_setparameters(dsp):
result = dsp.setparameters(fmt, channels, rate, True)
raise AssertionError("setparameters: expected OSSAudioError")
except ossaudiodev.OSSAudioError as err:
- print "setparameters: got OSSAudioError as expected"
+ print("setparameters: got OSSAudioError as expected")
def test():
(data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au'))
diff --git a/Lib/test/test_peepholer.py b/Lib/test/test_peepholer.py
index 779a20a512..213edd2ccb 100644
--- a/Lib/test/test_peepholer.py
+++ b/Lib/test/test_peepholer.py
@@ -211,7 +211,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_pep247.py b/Lib/test/test_pep247.py
index 88f246131b..cbd071bf69 100644
--- a/Lib/test/test_pep247.py
+++ b/Lib/test/test_pep247.py
@@ -41,7 +41,7 @@ def check_hash_module(module, key=None):
hd2 += "%02x" % ord(byte)
assert hd2 == hexdigest, "hexdigest doesn't appear correct"
- print 'Module', module.__name__, 'seems to comply with PEP 247'
+ print('Module', module.__name__, 'seems to comply with PEP 247')
if __name__ == '__main__':
diff --git a/Lib/test/test_pep277.py b/Lib/test/test_pep277.py
index ff71bf2fbb..8efa50a7c3 100644
--- a/Lib/test/test_pep277.py
+++ b/Lib/test/test_pep277.py
@@ -83,7 +83,7 @@ class UnicodeFileTests(unittest.TestCase):
f2 = os.listdir(unicode(test_support.TESTFN,
sys.getfilesystemencoding()))
f2.sort()
- print f2
+ print(f2)
def test_rename(self):
for name in self.files:
@@ -99,7 +99,7 @@ class UnicodeFileTests(unittest.TestCase):
f = open(filename, 'w')
f.write((filename + '\n').encode("utf-8"))
f.close()
- print repr(filename)
+ print(repr(filename))
os.access(filename,os.R_OK)
os.remove(filename)
os.chdir(oldwd)
diff --git a/Lib/test/test_pkg.py b/Lib/test/test_pkg.py
index c365742889..79c909882a 100644
--- a/Lib/test/test_pkg.py
+++ b/Lib/test/test_pkg.py
@@ -18,7 +18,7 @@ def mkhier(root, descr):
if contents is None:
mkdir(fullname)
else:
- if verbose: print "write", fullname
+ if verbose: print("write", fullname)
f = open(fullname, "w")
f.write(contents)
if contents and contents[-1] != '\n':
@@ -26,7 +26,7 @@ def mkhier(root, descr):
f.close()
def mkdir(x):
- if verbose: print "mkdir", x
+ if verbose: print("mkdir", x)
os.mkdir(x)
def cleanout(root):
@@ -40,7 +40,7 @@ def cleanout(root):
rmdir(root)
def rmdir(x):
- if verbose: print "rmdir", x
+ if verbose: print("rmdir", x)
os.rmdir(x)
def fixdir(lst):
@@ -61,7 +61,7 @@ def runtest(hier, code):
os.close(fd)
try:
sys.path.insert(0, root)
- if verbose: print "sys.path =", sys.path
+ if verbose: print("sys.path =", sys.path)
try:
execfile(fname, globals(), {})
except:
@@ -242,9 +242,9 @@ if __name__ == '__main__':
for name, hier, code in tests:
if args and name not in args:
- print "skipping test", name
+ print("skipping test", name)
continue
- print "running test", name
+ print("running test", name)
runtest(hier, code)
# Test
diff --git a/Lib/test/test_popen2.py b/Lib/test/test_popen2.py
index 2d54eb008d..008a67af8f 100644
--- a/Lib/test/test_popen2.py
+++ b/Lib/test/test_popen2.py
@@ -13,7 +13,7 @@ from test.test_support import TestSkipped, reap_children
# subprocess.
def main():
- print "Test popen2 module:"
+ print("Test popen2 module:")
if (sys.platform[:4] == 'beos' or sys.platform[:6] == 'atheos') \
and __name__ != '__main__':
# Locks get messed up or something. Generally we're supposed
@@ -33,7 +33,7 @@ def main():
def _test():
# same test as popen2._test(), but using the os.popen*() API
- print "Testing os module:"
+ print("Testing os module:")
import popen2
# When the test runs, there shouldn't be any open pipes
popen2._cleanup()
@@ -46,14 +46,14 @@ def _test():
# sometimes adding an extra newline at the start or the
# end. So we strip whitespace off both ends for comparison.
expected = teststr.strip()
- print "testing popen2..."
+ print("testing popen2...")
w, r = os.popen2(cmd)
w.write(teststr)
w.close()
got = r.read()
if got.strip() != expected:
raise ValueError("wrote %r read %r" % (teststr, got))
- print "testing popen3..."
+ print("testing popen3...")
try:
w, r, e = os.popen3([cmd])
except:
@@ -71,7 +71,7 @@ def _test():
popen2._cleanup()
if popen2._active:
raise ValueError("_active not empty")
- print "All OK"
+ print("All OK")
main()
_test()
diff --git a/Lib/test/test_pty.py b/Lib/test/test_pty.py
index 02290be71b..123c3f8173 100644
--- a/Lib/test/test_pty.py
+++ b/Lib/test/test_pty.py
@@ -6,7 +6,7 @@ TEST_STRING_2 = "For my pet fish, Eric.\n"
if verbose:
def debug(msg):
- print msg
+ print(msg)
else:
def debug(msg):
pass
diff --git a/Lib/test/test_pyclbr.py b/Lib/test/test_pyclbr.py
index a03daa9b4c..478083eb6c 100644
--- a/Lib/test/test_pyclbr.py
+++ b/Lib/test/test_pyclbr.py
@@ -28,13 +28,13 @@ class PyclbrTest(TestCase):
''' succeed iff {l1} - {ignore} == {l2} - {ignore} '''
missing = (set(l1) ^ set(l2)) - set(ignore)
if missing:
- print >>sys.stderr, "l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore)
+ print("l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore), file=sys.stderr)
self.fail("%r missing" % missing.pop())
def assertHasattr(self, obj, attr, ignore):
''' succeed iff hasattr(obj,attr) or attr in ignore. '''
if attr in ignore: return
- if not hasattr(obj, attr): print "???", attr
+ if not hasattr(obj, attr): print("???", attr)
self.failUnless(hasattr(obj, attr),
'expected hasattr(%r, %r)' % (obj, attr))
@@ -43,7 +43,7 @@ class PyclbrTest(TestCase):
''' succeed iff key in obj or key in ignore. '''
if key in ignore: return
if key not in obj:
- print >>sys.stderr, "***",key
+ print("***",key, file=sys.stderr)
self.failUnless(key in obj)
def assertEqualsOrIgnored(self, a, b, ignore):
@@ -110,7 +110,7 @@ class PyclbrTest(TestCase):
try:
self.assertListEq(real_bases, pyclbr_bases, ignore)
except:
- print >>sys.stderr, "class=%s" % py_item
+ print("class=%s" % py_item, file=sys.stderr)
raise
actualMethods = []
@@ -132,7 +132,7 @@ class PyclbrTest(TestCase):
ignore)
# can't check file or lineno
except:
- print >>sys.stderr, "class=%s" % py_item
+ print("class=%s" % py_item, file=sys.stderr)
raise
# Now check for missing stuff.
diff --git a/Lib/test/test_pyexpat.py b/Lib/test/test_pyexpat.py
index 73092c1ce2..fed1a9cf9b 100644
--- a/Lib/test/test_pyexpat.py
+++ b/Lib/test/test_pyexpat.py
@@ -10,50 +10,50 @@ from test.test_support import sortdict, TestFailed
class Outputter:
def StartElementHandler(self, name, attrs):
- print 'Start element:\n\t', repr(name), sortdict(attrs)
+ print('Start element:\n\t', repr(name), sortdict(attrs))
def EndElementHandler(self, name):
- print 'End element:\n\t', repr(name)
+ print('End element:\n\t', repr(name))
def CharacterDataHandler(self, data):
data = data.strip()
if data:
- print 'Character data:'
- print '\t', repr(data)
+ print('Character data:')
+ print('\t', repr(data))
def ProcessingInstructionHandler(self, target, data):
- print 'PI:\n\t', repr(target), repr(data)
+ print('PI:\n\t', repr(target), repr(data))
def StartNamespaceDeclHandler(self, prefix, uri):
- print 'NS decl:\n\t', repr(prefix), repr(uri)
+ print('NS decl:\n\t', repr(prefix), repr(uri))
def EndNamespaceDeclHandler(self, prefix):
- print 'End of NS decl:\n\t', repr(prefix)
+ print('End of NS decl:\n\t', repr(prefix))
def StartCdataSectionHandler(self):
- print 'Start of CDATA section'
+ print('Start of CDATA section')
def EndCdataSectionHandler(self):
- print 'End of CDATA section'
+ print('End of CDATA section')
def CommentHandler(self, text):
- print 'Comment:\n\t', repr(text)
+ print('Comment:\n\t', repr(text))
def NotationDeclHandler(self, *args):
name, base, sysid, pubid = args
- print 'Notation declared:', args
+ print('Notation declared:', args)
def UnparsedEntityDeclHandler(self, *args):
entityName, base, systemId, publicId, notationName = args
- print 'Unparsed entity decl:\n\t', args
+ print('Unparsed entity decl:\n\t', args)
def NotStandaloneHandler(self, userData):
- print 'Not standalone'
+ print('Not standalone')
return 1
def ExternalEntityRefHandler(self, *args):
context, base, sysId, pubId = args
- print 'External entity ref:', args[1:]
+ print('External entity ref:', args[1:])
return 1
def DefaultHandler(self, userData):
@@ -65,9 +65,9 @@ class Outputter:
def confirm(ok):
if ok:
- print "OK."
+ print("OK.")
else:
- print "Not OK."
+ print("Not OK.")
out = Outputter()
parser = expat.ParserCreate(namespace_separator='!')
@@ -131,10 +131,10 @@ parser.returns_unicode = 0
try:
parser.Parse(data, 1)
except expat.error:
- print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)
- print '** Line', parser.ErrorLineNumber
- print '** Column', parser.ErrorColumnNumber
- print '** Byte', parser.ErrorByteIndex
+ print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
+ print('** Line', parser.ErrorLineNumber)
+ print('** Column', parser.ErrorColumnNumber)
+ print('** Byte', parser.ErrorByteIndex)
# Try the parse again, this time producing Unicode output
parser = expat.ParserCreate(namespace_separator='!')
@@ -145,10 +145,10 @@ for name in HANDLER_NAMES:
try:
parser.Parse(data, 1)
except expat.error:
- print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)
- print '** Line', parser.ErrorLineNumber
- print '** Column', parser.ErrorColumnNumber
- print '** Byte', parser.ErrorByteIndex
+ print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
+ print('** Line', parser.ErrorLineNumber)
+ print('** Column', parser.ErrorColumnNumber)
+ print('** Byte', parser.ErrorByteIndex)
# Try parsing a file
parser = expat.ParserCreate(namespace_separator='!')
@@ -161,35 +161,35 @@ file = StringIO.StringIO(data)
try:
parser.ParseFile(file)
except expat.error:
- print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)
- print '** Line', parser.ErrorLineNumber
- print '** Column', parser.ErrorColumnNumber
- print '** Byte', parser.ErrorByteIndex
+ print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
+ print('** Line', parser.ErrorLineNumber)
+ print('** Column', parser.ErrorColumnNumber)
+ print('** Byte', parser.ErrorByteIndex)
# Tests that make sure we get errors when the namespace_separator value
# is illegal, and that we don't for good values:
-print
-print "Testing constructor for proper handling of namespace_separator values:"
+print()
+print("Testing constructor for proper handling of namespace_separator values:")
expat.ParserCreate()
expat.ParserCreate(namespace_separator=None)
expat.ParserCreate(namespace_separator=' ')
-print "Legal values tested o.k."
+print("Legal values tested o.k.")
try:
expat.ParserCreate(namespace_separator=42)
except TypeError as e:
- print "Caught expected TypeError:"
- print e
+ print("Caught expected TypeError:")
+ print(e)
else:
- print "Failed to catch expected TypeError."
+ print("Failed to catch expected TypeError.")
try:
expat.ParserCreate(namespace_separator='too long')
except ValueError as e:
- print "Caught expected ValueError:"
- print e
+ print("Caught expected ValueError:")
+ print(e)
else:
- print "Failed to catch expected ValueError."
+ print("Failed to catch expected ValueError.")
# ParserCreate() needs to accept a namespace_separator of zero length
# to satisfy the requirements of RDF applications that are required
@@ -211,12 +211,12 @@ p.EndElementHandler = collector
p.Parse("<e> <e/> <e></e> </e>", 1)
tag = L[0]
if len(L) != 6:
- print "L should only contain 6 entries; found", len(L)
+ print("L should only contain 6 entries; found", len(L))
for entry in L:
if tag is not entry:
- print "expected L to contain many references to the same string",
- print "(it didn't)"
- print "L =", repr(L)
+ print("expected L to contain many references to the same string", end=' ')
+ print("(it didn't)")
+ print("L =", repr(L))
break
# Tests of the buffer_text attribute.
@@ -323,9 +323,9 @@ try:
parser.Parse("<a><b><c/></b></a>", 1)
except RuntimeError as e:
if e.args[0] != "a":
- print "Expected RuntimeError for element 'a'; found %r" % e.args[0]
+ print("Expected RuntimeError for element 'a'; found %r" % e.args[0])
else:
- print "Expected RuntimeError for 'a'"
+ print("Expected RuntimeError for 'a'")
# Test Current* members:
class PositionTest:
diff --git a/Lib/test/test_queue.py b/Lib/test/test_queue.py
index 66977e64f8..ac382c14cf 100644
--- a/Lib/test/test_queue.py
+++ b/Lib/test/test_queue.py
@@ -271,11 +271,11 @@ def test():
SimpleQueueTest(q)
SimpleQueueTest(q)
if verbose:
- print "Simple Queue tests seemed to work"
+ print("Simple Queue tests seemed to work")
q = FailingQueue(QUEUE_SIZE)
FailingQueueTest(q)
FailingQueueTest(q)
if verbose:
- print "Failing Queue tests seemed to work"
+ print("Failing Queue tests seemed to work")
test()
diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py
index 5a76b1e2cb..e4a279256a 100644
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -547,7 +547,7 @@ def test_main(verbose=None):
for i in xrange(len(counts)):
test_support.run_unittest(*testclasses)
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py
index dafd82e98a..bb97433f40 100644
--- a/Lib/test/test_re.py
+++ b/Lib/test/test_re.py
@@ -603,7 +603,7 @@ class ReTests(unittest.TestCase):
def run_re_tests():
from test.re_tests import benchmarks, tests, SUCCEED, FAIL, SYNTAX_ERROR
if verbose:
- print 'Running re_tests test suite'
+ print('Running re_tests test suite')
else:
# To save time, only run the first and last 10 tests
#tests = tests[:10] + tests[-10:]
@@ -624,23 +624,23 @@ def run_re_tests():
except re.error:
if outcome == SYNTAX_ERROR: pass # Expected a syntax error
else:
- print '=== Syntax error:', t
+ print('=== Syntax error:', t)
except KeyboardInterrupt: raise KeyboardInterrupt
except:
- print '*** Unexpected error ***', t
+ print('*** Unexpected error ***', t)
if verbose:
traceback.print_exc(file=sys.stdout)
else:
try:
result = obj.search(s)
except re.error as msg:
- print '=== Unexpected exception', t, repr(msg)
+ print('=== Unexpected exception', t, repr(msg))
if outcome == SYNTAX_ERROR:
# This should have been a syntax error; forget it.
pass
elif outcome == FAIL:
if result is None: pass # No match, as expected
- else: print '=== Succeeded incorrectly', t
+ else: print('=== Succeeded incorrectly', t)
elif outcome == SUCCEED:
if result is not None:
# Matched, as expected, so now we compute the
@@ -668,17 +668,17 @@ def run_re_tests():
vardict[i] = gi
repl = eval(repl, vardict)
if repl != expected:
- print '=== grouping error', t,
- print repr(repl) + ' should be ' + repr(expected)
+ print('=== grouping error', t, end=' ')
+ print(repr(repl) + ' should be ' + repr(expected))
else:
- print '=== Failed incorrectly', t
+ print('=== Failed incorrectly', t)
# Try the match on a unicode string, and check that it
# still succeeds.
try:
result = obj.search(unicode(s, "latin-1"))
if result is None:
- print '=== Fails on unicode match', t
+ print('=== Fails on unicode match', t)
except NameError:
continue # 1.5.2
except TypeError:
@@ -689,7 +689,7 @@ def run_re_tests():
obj=re.compile(unicode(pattern, "latin-1"))
result = obj.search(s)
if result is None:
- print '=== Fails on unicode pattern match', t
+ print('=== Fails on unicode pattern match', t)
# Try the match with the search area limited to the extent
# of the match and see if it still succeeds. \B will
@@ -701,28 +701,28 @@ def run_re_tests():
obj = re.compile(pattern)
result = obj.search(s, result.start(0), result.end(0) + 1)
if result is None:
- print '=== Failed on range-limited match', t
+ print('=== Failed on range-limited match', t)
# Try the match with IGNORECASE enabled, and check that it
# still succeeds.
obj = re.compile(pattern, re.IGNORECASE)
result = obj.search(s)
if result is None:
- print '=== Fails on case-insensitive match', t
+ print('=== Fails on case-insensitive match', t)
# Try the match with LOCALE enabled, and check that it
# still succeeds.
obj = re.compile(pattern, re.LOCALE)
result = obj.search(s)
if result is None:
- print '=== Fails on locale-sensitive match', t
+ print('=== Fails on locale-sensitive match', t)
# Try the match with UNICODE locale enabled, and check
# that it still succeeds.
obj = re.compile(pattern, re.UNICODE)
result = obj.search(s)
if result is None:
- print '=== Fails on unicode-sensitive match', t
+ print('=== Fails on unicode-sensitive match', t)
def test_main():
run_unittest(ReTests)
diff --git a/Lib/test/test_rfc822.py b/Lib/test/test_rfc822.py
index d59e743e94..91e694a279 100644
--- a/Lib/test/test_rfc822.py
+++ b/Lib/test/test_rfc822.py
@@ -42,7 +42,7 @@ class MessageTestCase(unittest.TestCase):
try:
mn, ma = results[i][0], results[i][1]
except IndexError:
- print 'extra parsed address:', repr(n), repr(a)
+ print('extra parsed address:', repr(n), repr(a))
continue
i = i + 1
self.assertEqual(mn, n,
@@ -52,7 +52,7 @@ class MessageTestCase(unittest.TestCase):
if mn == n and ma == a:
pass
else:
- print 'not found:', repr(n), repr(a)
+ print('not found:', repr(n), repr(a))
out = m.getdate('date')
if out:
diff --git a/Lib/test/test_rgbimg.py b/Lib/test/test_rgbimg.py
index 650c02aa0f..65a0f422fa 100644
--- a/Lib/test/test_rgbimg.py
+++ b/Lib/test/test_rgbimg.py
@@ -14,7 +14,7 @@ from test.test_support import verbose, unlink, findfile
class error(Exception):
pass
-print 'RGBimg test suite:'
+print('RGBimg test suite:')
def testimg(rgb_file, raw_file):
rgb_file = findfile(rgb_file)
@@ -40,11 +40,11 @@ for source, target in table:
source = findfile(source)
target = findfile(target)
if verbose:
- print "uudecoding", source, "->", target, "..."
+ print("uudecoding", source, "->", target, "...")
uu.decode(source, target)
if verbose:
- print "testing..."
+ print("testing...")
ttob = rgbimg.ttob(0)
if ttob != 0:
diff --git a/Lib/test/test_runpy.py b/Lib/test/test_runpy.py
index a37ee7b7cd..e0fdabc913 100644
--- a/Lib/test/test_runpy.py
+++ b/Lib/test/test_runpy.py
@@ -92,22 +92,22 @@ class RunModuleTest(unittest.TestCase):
init_fname = "__init__"+os.extsep+"py"
test_fname = "runpy_test"+os.extsep+"py"
pkg_dir = sub_dir = tempfile.mkdtemp()
- if verbose: print " Package tree in:", sub_dir
+ if verbose: print(" Package tree in:", sub_dir)
sys.path.insert(0, pkg_dir)
- if verbose: print " Updated sys.path:", sys.path[0]
+ if verbose: print(" Updated sys.path:", sys.path[0])
for i in range(depth):
sub_dir = os.path.join(sub_dir, pkg_name)
os.mkdir(sub_dir)
- if verbose: print " Next level in:", sub_dir
+ if verbose: print(" Next level in:", sub_dir)
pkg_fname = os.path.join(sub_dir, init_fname)
pkg_file = open(pkg_fname, "w")
pkg_file.close()
- if verbose: print " Created:", pkg_fname
+ if verbose: print(" Created:", pkg_fname)
mod_fname = os.path.join(sub_dir, test_fname)
mod_file = open(mod_fname, "w")
mod_file.write(source)
mod_file.close()
- if verbose: print " Created:", mod_fname
+ if verbose: print(" Created:", mod_fname)
mod_name = (pkg_name+".")*depth + "runpy_test"
return pkg_dir, mod_fname, mod_name
@@ -118,49 +118,49 @@ class RunModuleTest(unittest.TestCase):
try:
del sys.modules[entry]
except KeyError as ex:
- if verbose: print ex # Persist with cleaning up
- if verbose: print " Removed sys.modules entries"
+ if verbose: print(ex) # Persist with cleaning up
+ if verbose: print(" Removed sys.modules entries")
del sys.path[0]
- if verbose: print " Removed sys.path entry"
+ if verbose: print(" Removed sys.path entry")
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
try:
os.remove(os.path.join(root, name))
except OSError as ex:
- if verbose: print ex # Persist with cleaning up
+ if verbose: print(ex) # Persist with cleaning up
for name in dirs:
fullname = os.path.join(root, name)
try:
os.rmdir(fullname)
except OSError as ex:
- if verbose: print ex # Persist with cleaning up
+ if verbose: print(ex) # Persist with cleaning up
try:
os.rmdir(top)
- if verbose: print " Removed package tree"
+ if verbose: print(" Removed package tree")
except OSError as ex:
- if verbose: print ex # Persist with cleaning up
+ if verbose: print(ex) # Persist with cleaning up
def _check_module(self, depth):
pkg_dir, mod_fname, mod_name = (
self._make_pkg("x=1\n", depth))
try:
- if verbose: print "Running from source:", mod_name
+ if verbose: print("Running from source:", mod_name)
d1 = run_module(mod_name) # Read from source
self.failUnless(d1["x"] == 1)
del d1 # Ensure __loader__ entry doesn't keep file open
__import__(mod_name)
os.remove(mod_fname)
- if verbose: print "Running from compiled:", mod_name
+ if verbose: print("Running from compiled:", mod_name)
d2 = run_module(mod_name) # Read from bytecode
self.failUnless(d2["x"] == 1)
del d2 # Ensure __loader__ entry doesn't keep file open
finally:
self._del_pkg(pkg_dir, depth, mod_name)
- if verbose: print "Module executed successfully"
+ if verbose: print("Module executed successfully")
def test_run_module(self):
for depth in range(4):
- if verbose: print "Testing package depth:", depth
+ if verbose: print("Testing package depth:", depth)
self._check_module(depth)
diff --git a/Lib/test/test_sax.py b/Lib/test/test_sax.py
index d3939c06cf..5715d67d54 100644
--- a/Lib/test/test_sax.py
+++ b/Lib/test/test_sax.py
@@ -27,7 +27,7 @@ def confirm(outcome, name):
tests = tests + 1
if outcome:
if verbose:
- print "Passed", name
+ print("Passed", name)
else:
failures.append(name)
@@ -745,7 +745,7 @@ for (name, value) in items:
del items
if verbose:
- print "%d tests, %d failures" % (tests, len(failures))
+ print("%d tests, %d failures" % (tests, len(failures)))
if failures:
raise TestFailed("%d of %d tests failed: %s"
% (len(failures), tests, ", ".join(failures)))
diff --git a/Lib/test/test_scope.py b/Lib/test/test_scope.py
index 777e85a18c..31e57e5209 100644
--- a/Lib/test/test_scope.py
+++ b/Lib/test/test_scope.py
@@ -269,7 +269,7 @@ def noproblem3():
def testUnboundLocal(self):
def errorInOuter():
- print y
+ print(y)
def inner():
return y
y = 1
@@ -530,18 +530,18 @@ self.assert_(X.passed)
def testListCompLocalVars(self):
try:
- print bad
+ print(bad)
except NameError:
pass
else:
- print "bad should not be defined"
+ print("bad should not be defined")
def x():
[bad for s in 'a b' for bad in s.split()]
x()
try:
- print bad
+ print(bad)
except NameError:
pass
diff --git a/Lib/test/test_select.py b/Lib/test/test_select.py
index d341324094..fd766746f7 100644
--- a/Lib/test/test_select.py
+++ b/Lib/test/test_select.py
@@ -9,7 +9,7 @@ try:
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
class Nope:
pass
@@ -23,47 +23,47 @@ try:
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
try:
rfd, wfd, xfd = select.select([Almost()], [], [])
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
try:
rfd, wfd, xfd = select.select([], [], [], 'not a number')
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
def test():
import sys
if sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'):
if verbose:
- print "Can't test select easily on", sys.platform
+ print("Can't test select easily on", sys.platform)
return
cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done'
p = os.popen(cmd, 'r')
for tout in (0, 1, 2, 4, 8, 16) + (None,)*10:
if verbose:
- print 'timeout =', tout
+ print('timeout =', tout)
rfd, wfd, xfd = select.select([p], [], [], tout)
if (rfd, wfd, xfd) == ([], [], []):
continue
if (rfd, wfd, xfd) == ([p], [], []):
line = p.readline()
if verbose:
- print repr(line)
+ print(repr(line))
if not line:
if verbose:
- print 'EOF'
+ print('EOF')
break
continue
- print 'Unexpected return values from select():', rfd, wfd, xfd
+ print('Unexpected return values from select():', rfd, wfd, xfd)
p.close()
reap_children()
diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py
index 13d02bbc26..9093965b56 100644
--- a/Lib/test/test_signal.py
+++ b/Lib/test/test_signal.py
@@ -15,7 +15,7 @@ else:
pid = os.getpid()
if verbose:
- print "test runner's pid is", pid
+ print("test runner's pid is", pid)
# Shell script that will send us asynchronous signals
script = """
@@ -36,7 +36,7 @@ def handlerA(*args):
global a_called
a_called = True
if verbose:
- print "handlerA invoked", args
+ print("handlerA invoked", args)
class HandlerBCalled(Exception):
pass
@@ -45,7 +45,7 @@ def handlerB(*args):
global b_called
b_called = True
if verbose:
- print "handlerB invoked", args
+ print("handlerB invoked", args)
raise HandlerBCalled, args
# Set up a child to send signals to us (the parent) after waiting long
@@ -69,10 +69,10 @@ def force_test_exit():
# time for the normal sequence of events to occur. This is
# just a stop-gap to try to prevent the test from hanging.
time.sleep(MAX_DURATION + 5)
- print >> sys.__stdout__, ' child should not have to kill parent'
+ print(' child should not have to kill parent', file=sys.__stdout__)
for signame in "SIGHUP", "SIGUSR1", "SIGUSR2", "SIGALRM":
os.kill(pid, getattr(signal, signame))
- print >> sys.__stdout__, " child sent", signame, "to", pid
+ print(" child sent", signame, "to", pid, file=sys.__stdout__)
time.sleep(1)
finally:
os._exit(0)
@@ -126,27 +126,27 @@ try:
# KeyboardInterrupt, finally getting us out of the loop.
os.system(script)
try:
- print "starting pause() loop..."
+ print("starting pause() loop...")
while 1:
try:
if verbose:
- print "call pause()..."
+ print("call pause()...")
signal.pause()
if verbose:
- print "pause() returned"
+ print("pause() returned")
except HandlerBCalled:
if verbose:
- print "HandlerBCalled exception caught"
+ print("HandlerBCalled exception caught")
except KeyboardInterrupt:
if verbose:
- print "KeyboardInterrupt (the alarm() went off)"
+ print("KeyboardInterrupt (the alarm() went off)")
if not a_called:
- print 'HandlerA not called'
+ print('HandlerA not called')
if not b_called:
- print 'HandlerB not called'
+ print('HandlerB not called')
finally:
# Forcibly kill the child we created to ping us if there was a test error.
diff --git a/Lib/test/test_site.py b/Lib/test/test_site.py
index d379ab5c21..6f32fcaa0b 100644
--- a/Lib/test/test_site.py
+++ b/Lib/test/test_site.py
@@ -119,11 +119,11 @@ class PthFile(object):
"""
FILE = open(self.file_path, 'w')
try:
- print>>FILE, "#import @bad module name"
- print>>FILE, "\n"
- print>>FILE, "import %s" % self.imported
- print>>FILE, self.good_dirname
- print>>FILE, self.bad_dirname
+ print("#import @bad module name", file=FILE)
+ print("\n", file=FILE)
+ print("import %s" % self.imported, file=FILE)
+ print(self.good_dirname, file=FILE)
+ print(self.bad_dirname, file=FILE)
finally:
FILE.close()
os.mkdir(self.good_dir_path)
diff --git a/Lib/test/test_socket_ssl.py b/Lib/test/test_socket_ssl.py
index 5d308c5848..b04effea28 100644
--- a/Lib/test/test_socket_ssl.py
+++ b/Lib/test/test_socket_ssl.py
@@ -16,7 +16,7 @@ def test_basic():
import urllib
if test_support.verbose:
- print "test_basic ..."
+ print("test_basic ...")
socket.RAND_status()
try:
@@ -24,7 +24,7 @@ def test_basic():
except TypeError:
pass
else:
- print "didn't raise TypeError"
+ print("didn't raise TypeError")
socket.RAND_add("this is a random string", 75.0)
f = urllib.urlopen('https://sf.net')
@@ -35,14 +35,14 @@ def test_timeout():
test_support.requires('network')
def error_msg(extra_msg):
- print >> sys.stderr, """\
+ print("""\
WARNING: an attempt to connect to %r %s, in
test_timeout. That may be legitimate, but is not the outcome we hoped
for. If this message is seen often, test_timeout should be changed to
- use a more reliable address.""" % (ADDR, extra_msg)
+ use a more reliable address.""" % (ADDR, extra_msg), file=sys.stderr)
if test_support.verbose:
- print "test_timeout ..."
+ print("test_timeout ...")
# A service which issues a welcome banner (without need to write
# anything).
@@ -73,7 +73,7 @@ def test_timeout():
def test_rude_shutdown():
if test_support.verbose:
- print "test_rude_shutdown ..."
+ print("test_rude_shutdown ...")
try:
import threading
diff --git a/Lib/test/test_socketserver.py b/Lib/test/test_socketserver.py
index 202f2da2e7..062be650f8 100644
--- a/Lib/test/test_socketserver.py
+++ b/Lib/test/test_socketserver.py
@@ -77,16 +77,16 @@ class ServerThread(threading.Thread):
def run(self):
class svrcls(MyMixinServer, self.__svrcls):
pass
- if verbose: print "thread: creating server"
+ if verbose: print("thread: creating server")
svr = svrcls(self.__addr, self.__hdlrcls)
# pull the address out of the server in case it changed
# this can happen if another process is using the port
addr = getattr(svr, 'server_address')
if addr:
self.__addr = addr
- if verbose: print "thread: serving three times"
+ if verbose: print("thread: serving three times")
svr.serve_a_few()
- if verbose: print "thread: done"
+ if verbose: print("thread: done")
seed = 0
def pickport():
@@ -129,19 +129,19 @@ def testloop(proto, servers, hdlrcls, testfunc):
for svrcls in servers:
addr = pickaddr(proto)
if verbose:
- print "ADDR =", addr
- print "CLASS =", svrcls
+ print("ADDR =", addr)
+ print("CLASS =", svrcls)
t = ServerThread(addr, svrcls, hdlrcls)
- if verbose: print "server created"
+ if verbose: print("server created")
t.start()
- if verbose: print "server running"
+ if verbose: print("server running")
for i in range(NREQ):
time.sleep(DELAY)
- if verbose: print "test client", i
+ if verbose: print("test client", i)
testfunc(proto, addr)
- if verbose: print "waiting for server"
+ if verbose: print("waiting for server")
t.join()
- if verbose: print "done"
+ if verbose: print("done")
class ForgivingTCPServer(TCPServer):
# prevent errors if another process is using the port we want
@@ -159,8 +159,7 @@ class ForgivingTCPServer(TCPServer):
(err, msg) = e
if err != errno.EADDRINUSE:
raise
- print >>sys.__stderr__, \
- ' WARNING: failed to listen on port %d, trying another' % port
+ print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__)
tcpservers = [ForgivingTCPServer, ThreadingTCPServer]
if hasattr(os, 'fork') and os.name not in ('os2',):
diff --git a/Lib/test/test_softspace.py b/Lib/test/test_softspace.py
index 5405ba3fe9..c0b4e8f3c3 100644
--- a/Lib/test/test_softspace.py
+++ b/Lib/test/test_softspace.py
@@ -5,10 +5,10 @@ import StringIO
f = StringIO.StringIO()
class C:
def __str__(self):
- print >> f, 'a'
+ print('a', file=f)
return 'b'
-print >> f, C(), 'c ', 'd\t', 'e'
-print >> f, 'f', 'g'
+print(C(), 'c ', 'd\t', 'e', file=f)
+print('f', 'g', file=f)
# In 2.2 & earlier, this printed ' a\nbc d\te\nf g\n'
test_support.vereq(f.getvalue(), 'a\nb c d\te\nf g\n')
diff --git a/Lib/test/test_sort.py b/Lib/test/test_sort.py
index 031780adb8..ad3a817ec1 100644
--- a/Lib/test/test_sort.py
+++ b/Lib/test/test_sort.py
@@ -10,7 +10,7 @@ def check(tag, expected, raw, compare=None):
global nerrors
if verbose:
- print " checking", tag
+ print(" checking", tag)
orig = raw[:] # save input in case of error
if compare:
@@ -19,22 +19,22 @@ def check(tag, expected, raw, compare=None):
raw.sort()
if len(expected) != len(raw):
- print "error in", tag
- print "length mismatch;", len(expected), len(raw)
- print expected
- print orig
- print raw
+ print("error in", tag)
+ print("length mismatch;", len(expected), len(raw))
+ print(expected)
+ print(orig)
+ print(raw)
nerrors += 1
return
for i, good in enumerate(expected):
maybe = raw[i]
if good is not maybe:
- print "error in", tag
- print "out of order at index", i, good, maybe
- print expected
- print orig
- print raw
+ print("error in", tag)
+ print("out of order at index", i, good, maybe)
+ print(expected)
+ print(orig)
+ print(raw)
nerrors += 1
return
@@ -56,7 +56,7 @@ class TestBase(unittest.TestCase):
def __lt__(self, other):
if Complains.maybe_complain and random.random() < 0.001:
if verbose:
- print " complaining at", self, other
+ print(" complaining at", self, other)
raise RuntimeError
return self.i < other.i
@@ -77,7 +77,7 @@ class TestBase(unittest.TestCase):
for n in sizes:
x = range(n)
if verbose:
- print "Testing size", n
+ print("Testing size", n)
s = x[:]
check("identity", x, s)
@@ -96,8 +96,8 @@ class TestBase(unittest.TestCase):
check("reversed via function", y, s, lambda a, b: cmp(b, a))
if verbose:
- print " Checking against an insane comparison function."
- print " If the implementation isn't careful, this may segfault."
+ print(" Checking against an insane comparison function.")
+ print(" If the implementation isn't careful, this may segfault.")
s = x[:]
s.sort(lambda a, b: int(random.random() * 3) - 1)
check("an insane function left some permutation", x, s)
@@ -285,7 +285,7 @@ def test_main(verbose=None):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_strftime.py b/Lib/test/test_strftime.py
index 26bae1bb79..c6db3dd00c 100755
--- a/Lib/test/test_strftime.py
+++ b/Lib/test/test_strftime.py
@@ -40,7 +40,7 @@ def escapestr(text, ampm):
def strftest(now):
if verbose:
- print "strftime test for", time.ctime(now)
+ print("strftime test for", time.ctime(now))
nowsecs = str(int(now))[:-1]
gmt = time.gmtime(now)
now = time.localtime(now)
@@ -113,42 +113,42 @@ def strftest(now):
)
if verbose:
- print "Strftime test, platform: %s, Python version: %s" % \
- (sys.platform, sys.version.split()[0])
+ print("Strftime test, platform: %s, Python version: %s" % \
+ (sys.platform, sys.version.split()[0]))
for e in expectations:
try:
result = time.strftime(e[0], now)
except ValueError as error:
- print "Standard '%s' format gave error:" % e[0], error
+ print("Standard '%s' format gave error:" % e[0], error)
continue
if re.match(escapestr(e[1], ampm), result): continue
if not result or result[0] == '%':
- print "Does not support standard '%s' format (%s)" % (e[0], e[2])
+ print("Does not support standard '%s' format (%s)" % (e[0], e[2]))
else:
- print "Conflict for %s (%s):" % (e[0], e[2])
- print " Expected %s, but got %s" % (e[1], result)
+ print("Conflict for %s (%s):" % (e[0], e[2]))
+ print(" Expected %s, but got %s" % (e[1], result))
for e in nonstandard_expectations:
try:
result = time.strftime(e[0], now)
except ValueError as result:
if verbose:
- print "Error for nonstandard '%s' format (%s): %s" % \
- (e[0], e[2], str(result))
+ print("Error for nonstandard '%s' format (%s): %s" % \
+ (e[0], e[2], str(result)))
continue
if re.match(escapestr(e[1], ampm), result):
if verbose:
- print "Supports nonstandard '%s' format (%s)" % (e[0], e[2])
+ print("Supports nonstandard '%s' format (%s)" % (e[0], e[2]))
elif not result or result[0] == '%':
if verbose:
- print "Does not appear to support '%s' format (%s)" % (e[0],
- e[2])
+ print("Does not appear to support '%s' format (%s)" % (e[0],
+ e[2]))
else:
if verbose:
- print "Conflict for nonstandard '%s' format (%s):" % (e[0],
- e[2])
- print " Expected %s, but got %s" % (e[1], result)
+ print("Conflict for nonstandard '%s' format (%s):" % (e[0],
+ e[2]))
+ print(" Expected %s, but got %s" % (e[1], result))
def fixasctime(s):
if s[8] == ' ':
diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py
index e0f0971eac..21cba890c2 100644
--- a/Lib/test/test_struct.py
+++ b/Lib/test/test_struct.py
@@ -114,7 +114,7 @@ for prefix in ('', '@', '<', '>', '=', '!'):
for format in ('xcbhilfdt', 'xcBHILfdt'):
format = prefix + format
if verbose:
- print "trying:", format
+ print("trying:", format)
s = struct.pack(format, c, b, h, i, l, f, d, t)
cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s)
if (cp != c or bp != b or hp != h or ip != i or lp != l or
@@ -169,7 +169,7 @@ tests = [
for fmt, arg, big, lil, asy in tests:
if verbose:
- print "%r %r %r %r" % (fmt, arg, big, lil)
+ print("%r %r %r %r" % (fmt, arg, big, lil))
for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
('='+fmt, ISBIGENDIAN and big or lil)]:
res = struct.pack(xfmt, arg)
@@ -195,7 +195,7 @@ except struct.error:
has_native_qQ = 0
if verbose:
- print "Platform has native q/Q?", has_native_qQ and "Yes." or "No."
+ print("Platform has native q/Q?", has_native_qQ and "Yes." or "No.")
any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless
simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless
@@ -258,7 +258,7 @@ class IntTester:
unpack=struct.unpack,
unhexlify=binascii.unhexlify):
if verbose:
- print "trying std", self.formatpair, "on", x, "==", hex(x)
+ print("trying std", self.formatpair, "on", x, "==", hex(x))
# Try signed.
code = self.signed_code
@@ -313,7 +313,7 @@ class IntTester:
# x is out of range -- verify pack realizes that.
if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK:
if verbose:
- print "Skipping buggy range check for code", code
+ print("Skipping buggy range check for code", code)
else:
deprecated_err(pack, ">" + code, x)
deprecated_err(pack, "<" + code, x)
@@ -368,7 +368,7 @@ class IntTester:
# x is out of range -- verify pack realizes that.
if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK:
if verbose:
- print "Skipping buggy range check for code", code
+ print("Skipping buggy range check for code", code)
else:
deprecated_err(pack, ">" + code, x)
deprecated_err(pack, "<" + code, x)
@@ -627,13 +627,13 @@ def test_bool():
falseFormat = prefix + 't' * len(false)
if verbose:
- print 'trying bool pack/unpack on', false, 'using format', falseFormat
+ print('trying bool pack/unpack on', false, 'using format', falseFormat)
packedFalse = struct.pack(falseFormat, *false)
unpackedFalse = struct.unpack(falseFormat, packedFalse)
trueFormat = prefix + 't' * len(true)
if verbose:
- print 'trying bool pack/unpack on', true, 'using format', trueFormat
+ print('trying bool pack/unpack on', true, 'using format', trueFormat)
packedTrue = struct.pack(trueFormat, *true)
unpackedTrue = struct.unpack(trueFormat, packedTrue)
@@ -650,7 +650,7 @@ def test_bool():
raise TestFailed('%r did not unpack as false' % t)
if prefix and verbose:
- print 'trying size of bool with format %r' % (prefix+'t')
+ print('trying size of bool with format %r' % (prefix+'t'))
packed = struct.pack(prefix+'t', 1)
if len(packed) != struct.calcsize(prefix+'t'):
@@ -659,7 +659,7 @@ def test_bool():
if len(packed) != 1 and prefix:
raise TestFailed('encoded bool is not one byte: %r' % packed)
elif not prefix and verbose:
- print 'size of bool in native format is %i' % (len(packed))
+ print('size of bool in native format is %i' % (len(packed)))
for c in '\x01\x7f\xff\x0f\xf0':
if struct.unpack('>t', c)[0] is not True:
diff --git a/Lib/test/test_sundry.py b/Lib/test/test_sundry.py
index f19467c767..dcc21ac2b6 100644
--- a/Lib/test/test_sundry.py
+++ b/Lib/test/test_sundry.py
@@ -68,7 +68,7 @@ try:
import tty # not available on Windows
except ImportError:
if verbose:
- print "skipping tty"
+ print("skipping tty")
# Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
# can screw up all sorts of things (esp. if it prints!).
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py
index 0b37306a62..6cc52ea05b 100644
--- a/Lib/test/test_support.py
+++ b/Lib/test/test_support.py
@@ -106,8 +106,7 @@ def bind_port(sock, host='', preferred_port=54321):
(err, msg) = e
if err != errno.EADDRINUSE:
raise
- print >>sys.__stderr__, \
- ' WARNING: failed to listen on port %d, trying another' % port
+ print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__)
raise TestFailed, 'unable to find port to listen on'
FUZZ = 1e-6
@@ -178,10 +177,9 @@ else:
except UnicodeEncodeError:
pass
else:
- print \
- 'WARNING: The filename %r CAN be encoded by the filesystem. ' \
+ print('WARNING: The filename %r CAN be encoded by the filesystem. ' \
'Unicode filename tests may not be effective' \
- % TESTFN_UNICODE_UNENCODEABLE
+ % TESTFN_UNICODE_UNENCODEABLE)
# Make sure we can write to TESTFN, try in /tmp if we can't
fp = None
@@ -194,8 +192,8 @@ except IOError:
TESTFN = TMP_TESTFN
del TMP_TESTFN
except IOError:
- print ('WARNING: tests will fail, unable to write to: %s or %s' %
- (TESTFN, TMP_TESTFN))
+ print(('WARNING: tests will fail, unable to write to: %s or %s' %
+ (TESTFN, TMP_TESTFN)))
if fp is not None:
fp.close()
unlink(TESTFN)
@@ -267,7 +265,7 @@ def open_urlresource(url):
return open(fn)
requires('urlfetch')
- print >> get_original_stdout(), '\tfetching %s ...' % url
+ print('\tfetching %s ...' % url, file=get_original_stdout())
fn, _ = urllib.urlretrieve(url, filename)
return open(fn)
@@ -514,7 +512,7 @@ def run_doctest(module, verbosity=None):
finally:
sys.stdout = save_stdout
if verbose:
- print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
+ print('doctest (%s) ... %d tests with zero failures' % (module.__name__, t))
return f, t
#=======================================================================
diff --git a/Lib/test/test_thread.py b/Lib/test/test_thread.py
index c4c21fed00..57057986c9 100644
--- a/Lib/test/test_thread.py
+++ b/Lib/test/test_thread.py
@@ -21,10 +21,10 @@ def task(ident):
delay = random.random() * numtasks
rmutex.release()
if verbose:
- print 'task', ident, 'will run for', round(delay, 1), 'sec'
+ print('task', ident, 'will run for', round(delay, 1), 'sec')
time.sleep(delay)
if verbose:
- print 'task', ident, 'done'
+ print('task', ident, 'done')
mutex.acquire()
running = running - 1
if running == 0:
@@ -37,7 +37,7 @@ def newtask():
mutex.acquire()
next_ident = next_ident + 1
if verbose:
- print 'creating task', next_ident
+ print('creating task', next_ident)
thread.start_new_thread(task, (next_ident,))
running = running + 1
mutex.release()
@@ -45,9 +45,9 @@ def newtask():
for i in range(numtasks):
newtask()
-print 'waiting for all tasks to complete'
+print('waiting for all tasks to complete')
done.acquire()
-print 'all tasks done'
+print('all tasks done')
class barrier:
def __init__(self, n):
@@ -89,13 +89,13 @@ def task2(ident):
delay = random.random() * numtasks
rmutex.release()
if verbose:
- print 'task', ident, 'will run for', round(delay, 1), 'sec'
+ print('task', ident, 'will run for', round(delay, 1), 'sec')
time.sleep(delay)
if verbose:
- print 'task', ident, 'entering barrier', i
+ print('task', ident, 'entering barrier', i)
bar.enter()
if verbose:
- print 'task', ident, 'leaving barrier', i
+ print('task', ident, 'leaving barrier', i)
mutex.acquire()
running -= 1
# Must release mutex before releasing done, else the main thread can
@@ -106,7 +106,7 @@ def task2(ident):
if finished:
done.release()
-print '\n*** Barrier Test ***'
+print('\n*** Barrier Test ***')
if done.acquire(0):
raise ValueError, "'done' should have remained acquired"
bar = barrier(numtasks)
@@ -114,10 +114,10 @@ running = numtasks
for i in range(numtasks):
thread.start_new_thread(task2, (i,))
done.acquire()
-print 'all tasks done'
+print('all tasks done')
# not all platforms support changing thread stack size
-print '\n*** Changing thread stack size ***'
+print('\n*** Changing thread stack size ***')
if thread.stack_size() != 0:
raise ValueError, "initial stack_size not 0"
@@ -132,10 +132,10 @@ if os_name in ("nt", "os2", "posix"):
try:
thread.stack_size(4096)
except ValueError:
- print 'caught expected ValueError setting stack_size(4096)'
+ print('caught expected ValueError setting stack_size(4096)')
except thread.error:
tss_supported = 0
- print 'platform does not support changing thread stack size'
+ print('platform does not support changing thread stack size')
if tss_supported:
failed = lambda s, e: s != e
@@ -144,17 +144,17 @@ if os_name in ("nt", "os2", "posix"):
thread.stack_size(tss)
if failed(thread.stack_size(), tss):
raise ValueError, fail_msg % tss
- print 'successfully set stack_size(%d)' % tss
+ print('successfully set stack_size(%d)' % tss)
for tss in (262144, 0x100000):
- print 'trying stack_size = %d' % tss
+ print('trying stack_size = %d' % tss)
next_ident = 0
for i in range(numtasks):
newtask()
- print 'waiting for all tasks to complete'
+ print('waiting for all tasks to complete')
done.acquire()
- print 'all tasks done'
+ print('all tasks done')
# reset stack size to default
thread.stack_size(0)
diff --git a/Lib/test/test_threaded_import.py b/Lib/test/test_threaded_import.py
index 602ad2af90..41a2b9099f 100644
--- a/Lib/test/test_threaded_import.py
+++ b/Lib/test/test_threaded_import.py
@@ -28,14 +28,14 @@ def task():
def test_import_hangers():
import sys
if verbose:
- print "testing import hangers ...",
+ print("testing import hangers ...", end=' ')
import test.threaded_import_hangers
try:
if test.threaded_import_hangers.errors:
raise TestFailed(test.threaded_import_hangers.errors)
elif verbose:
- print "OK."
+ print("OK.")
finally:
# In case this test is run again, make sure the helper module
# gets loaded from scratch again.
@@ -61,12 +61,12 @@ def test_main(): # magic name! see above
done.acquire()
for N in (20, 50) * 3:
if verbose:
- print "Trying", N, "threads ...",
+ print("Trying", N, "threads ...", end=' ')
for i in range(N):
thread.start_new_thread(task, ())
done.acquire()
if verbose:
- print "OK."
+ print("OK.")
done.release()
test_import_hangers()
diff --git a/Lib/test/test_threadedtempfile.py b/Lib/test/test_threadedtempfile.py
index 974333b486..75d719dd06 100644
--- a/Lib/test/test_threadedtempfile.py
+++ b/Lib/test/test_threadedtempfile.py
@@ -50,26 +50,26 @@ def test_main():
threads = []
thread_info = threading_setup()
- print "Creating"
+ print("Creating")
for i in range(NUM_THREADS):
t = TempFileGreedy()
threads.append(t)
t.start()
- print "Starting"
+ print("Starting")
startEvent.set()
- print "Reaping"
+ print("Reaping")
ok = errors = 0
for t in threads:
t.join()
ok += t.ok_count
errors += t.error_count
if t.error_count:
- print '%s errors:\n%s' % (t.getName(), t.errors.getvalue())
+ print('%s errors:\n%s' % (t.getName(), t.errors.getvalue()))
msg = "Done: errors %d ok %d" % (errors, ok)
- print msg
+ print(msg)
if errors:
raise TestFailed(msg)
diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
index 8614ecb49c..95557c0ce1 100644
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -30,27 +30,27 @@ class TestThread(threading.Thread):
def run(self):
delay = random.random() * 2
if verbose:
- print 'task', self.getName(), 'will run for', delay, 'sec'
+ print('task', self.getName(), 'will run for', delay, 'sec')
self.sema.acquire()
self.mutex.acquire()
self.nrunning.inc()
if verbose:
- print self.nrunning.get(), 'tasks are running'
+ print(self.nrunning.get(), 'tasks are running')
self.testcase.assert_(self.nrunning.get() <= 3)
self.mutex.release()
time.sleep(delay)
if verbose:
- print 'task', self.getName(), 'done'
+ print('task', self.getName(), 'done')
self.mutex.acquire()
self.nrunning.dec()
self.testcase.assert_(self.nrunning.get() >= 0)
if verbose:
- print self.getName(), 'is finished.', self.nrunning.get(), \
- 'tasks are running'
+ print(self.getName(), 'is finished.', self.nrunning.get(), \
+ 'tasks are running')
self.mutex.release()
self.sema.release()
@@ -77,23 +77,23 @@ class ThreadTests(unittest.TestCase):
t.start()
if verbose:
- print 'waiting for all tasks to complete'
+ print('waiting for all tasks to complete')
for t in threads:
t.join(NUMTASKS)
self.assert_(not t.isAlive())
if verbose:
- print 'all tasks done'
+ print('all tasks done')
self.assertEqual(numrunning.get(), 0)
# run with a small(ish) thread stack size (256kB)
def test_various_ops_small_stack(self):
if verbose:
- print 'with 256kB thread stack size...'
+ print('with 256kB thread stack size...')
try:
threading.stack_size(262144)
except thread.error:
if verbose:
- print 'platform does not support changing thread stack size'
+ print('platform does not support changing thread stack size')
return
self.test_various_ops()
threading.stack_size(0)
@@ -101,12 +101,12 @@ class ThreadTests(unittest.TestCase):
# run with a large thread stack size (1MB)
def test_various_ops_large_stack(self):
if verbose:
- print 'with 1MB thread stack size...'
+ print('with 1MB thread stack size...')
try:
threading.stack_size(0x100000)
except thread.error:
if verbose:
- print 'platform does not support changing thread stack size'
+ print('platform does not support changing thread stack size')
return
self.test_various_ops()
threading.stack_size(0)
@@ -138,7 +138,7 @@ class ThreadTests(unittest.TestCase):
import ctypes
except ImportError:
if verbose:
- print "test_PyThreadState_SetAsyncExc can't import ctypes"
+ print("test_PyThreadState_SetAsyncExc can't import ctypes")
return # can't do anything
set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
@@ -172,31 +172,31 @@ class ThreadTests(unittest.TestCase):
t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
t.start()
if verbose:
- print " started worker thread"
+ print(" started worker thread")
# Try a thread id that doesn't make sense.
if verbose:
- print " trying nonsensical thread id"
+ print(" trying nonsensical thread id")
result = set_async_exc(ctypes.c_long(-1), exception)
self.assertEqual(result, 0) # no thread states modified
# Now raise an exception in the worker thread.
if verbose:
- print " waiting for worker thread to get started"
+ print(" waiting for worker thread to get started")
worker_started.wait()
if verbose:
- print " verifying worker hasn't exited"
+ print(" verifying worker hasn't exited")
self.assert_(not t.finished)
if verbose:
- print " attempting to raise asynch exception in worker"
+ print(" attempting to raise asynch exception in worker")
result = set_async_exc(ctypes.c_long(t.id), exception)
self.assertEqual(result, 1) # one thread state modified
if verbose:
- print " waiting for worker to say it caught the exception"
+ print(" waiting for worker to say it caught the exception")
worker_saw_exception.wait(timeout=10)
self.assert_(t.finished)
if verbose:
- print " all OK -- joining worker"
+ print(" all OK -- joining worker")
if t.finished:
t.join()
# else the thread is still running, and we have no way to kill it
diff --git a/Lib/test/test_tokenize.py b/Lib/test/test_tokenize.py
index de6e888ca2..7d6a81813b 100644
--- a/Lib/test/test_tokenize.py
+++ b/Lib/test/test_tokenize.py
@@ -118,12 +118,12 @@ def dump_tokens(s):
if type == ENDMARKER:
break
type = tok_name[type]
- print "%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals()
+ print("%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals())
def roundtrip(s):
f = StringIO(s)
source = untokenize(generate_tokens(f.readline))
- print source,
+ print(source, end=' ')
# This is an example from the docs, set up as a doctest.
def decistmt(s):
@@ -165,7 +165,7 @@ def decistmt(s):
def test_main():
if verbose:
- print 'starting...'
+ print('starting...')
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
@@ -191,7 +191,7 @@ def test_main():
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, ' test_main still working, be patient...'
+ print(' test_main still working, be patient...', file=sys.__stdout__)
sys.__stdout__.flush()
test_roundtrip(f)
@@ -217,7 +217,7 @@ def foo():
run_doctest(test_tokenize, verbose)
if verbose:
- print 'finished'
+ print('finished')
def test_rarrow():
"""
diff --git a/Lib/test/test_trace.py b/Lib/test/test_trace.py
index 42d1a4a197..7b5ac7d1b2 100644
--- a/Lib/test/test_trace.py
+++ b/Lib/test/test_trace.py
@@ -309,7 +309,7 @@ class RaisingTraceFuncTestCase(unittest.TestCase):
def test_trash_stack(self):
def f():
for i in range(5):
- print i # line tracing will raise an exception at this line
+ print(i) # line tracing will raise an exception at this line
def g(frame, why, extra):
if (why == 'line' and
diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py
index 5c8a4e4858..1ccb2b29c6 100644
--- a/Lib/test/test_traceback.py
+++ b/Lib/test/test_traceback.py
@@ -60,9 +60,9 @@ class TracebackCases(unittest.TestCase):
try:
sys.path.insert(0, testdir)
testfile = os.path.join(testdir, 'test_bug737473.py')
- print >> open(testfile, 'w'), """
+ print("""
def test():
- raise ValueError"""
+ raise ValueError""", file=open(testfile, 'w'))
if 'test_bug737473' in sys.modules:
del sys.modules['test_bug737473']
@@ -82,9 +82,9 @@ def test():
# three seconds are needed for this test to pass reliably :-(
time.sleep(4)
- print >> open(testfile, 'w'), """
+ print("""
def test():
- raise NotImplementedError"""
+ raise NotImplementedError""", file=open(testfile, 'w'))
reload(test_bug737473)
try:
test_bug737473.test()
diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py
index 5c70df15f7..bb3338b450 100644
--- a/Lib/test/test_unicode.py
+++ b/Lib/test/test_unicode.py
@@ -732,15 +732,15 @@ class UnicodeTest(
pass
out = BitBucket()
- print >>out, u'abc'
- print >>out, u'abc', u'def'
- print >>out, u'abc', 'def'
- print >>out, 'abc', u'def'
- print >>out, u'abc\n'
- print >>out, u'abc\n',
- print >>out, u'abc\n',
- print >>out, u'def\n'
- print >>out, u'def\n'
+ print(u'abc', file=out)
+ print(u'abc', u'def', file=out)
+ print(u'abc', 'def', file=out)
+ print('abc', u'def', file=out)
+ print(u'abc\n', file=out)
+ print(u'abc\n', end=' ', file=out)
+ print(u'abc\n', end=' ', file=out)
+ print(u'def\n', file=out)
+ print(u'def\n', file=out)
def test_ucs4(self):
if sys.maxunicode == 0xFFFF:
diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py
index 25aa307abe..a7fc60aa5d 100644
--- a/Lib/test/test_userdict.py
+++ b/Lib/test/test_userdict.py
@@ -79,7 +79,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
self.assertEqual(u2b, u2c)
class MyUserDict(UserDict.UserDict):
- def display(self): print self
+ def display(self): print(self)
m2 = MyUserDict(u2)
m2a = m2.copy()
diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py
index f1d1d1c7fa..3e5f77d4c9 100644
--- a/Lib/test/test_uuid.py
+++ b/Lib/test/test_uuid.py
@@ -307,9 +307,8 @@ class TestUUID(TestCase):
def test_ifconfig_getnode(self):
import sys
- print >>sys.__stdout__, \
-""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms.
- It is disabled until the code and/or test can be fixed properly."""
+ print(""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms.
+ It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__)
return
import os
@@ -336,9 +335,8 @@ class TestUUID(TestCase):
def test_unixdll_getnode(self):
import sys
- print >>sys.__stdout__, \
-""" WARNING: uuid._unixdll_getnode is unreliable on many platforms.
- It is disabled until the code and/or test can be fixed properly."""
+ print(""" WARNING: uuid._unixdll_getnode is unreliable on many platforms.
+ It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__)
return
import os
@@ -352,9 +350,8 @@ class TestUUID(TestCase):
def test_getnode(self):
import sys
- print >>sys.__stdout__, \
-""" WARNING: uuid.getnode is unreliable on many platforms.
- It is disabled until the code and/or test can be fixed properly."""
+ print(""" WARNING: uuid.getnode is unreliable on many platforms.
+ It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__)
return
node1 = uuid.getnode()
diff --git a/Lib/test/test_winreg.py b/Lib/test/test_winreg.py
index 81bd7601f6..08de67c490 100644
--- a/Lib/test/test_winreg.py
+++ b/Lib/test/test_winreg.py
@@ -133,7 +133,7 @@ def TestAll(root_key):
# Test on my local machine.
TestAll(HKEY_CURRENT_USER)
-print "Local registry tests worked"
+print("Local registry tests worked")
try:
remote_name = sys.argv[sys.argv.index("--remote")+1]
except (IndexError, ValueError):
@@ -143,14 +143,14 @@ if remote_name is not None:
try:
remote_key = ConnectRegistry(remote_name, HKEY_CURRENT_USER)
except EnvironmentError as exc:
- print "Could not connect to the remote machine -", exc.strerror
+ print("Could not connect to the remote machine -", exc.strerror)
remote_key = None
if remote_key is not None:
TestAll(remote_key)
- print "Remote registry tests worked"
+ print("Remote registry tests worked")
else:
- print "Remote registry calls can be tested using",
- print "'test_winreg.py --remote \\\\machine_name'"
+ print("Remote registry calls can be tested using", end=' ')
+ print("'test_winreg.py --remote \\\\machine_name'")
# perform minimal ConnectRegistry test which just invokes it
h = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
h.Close()
diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py
index 78adb42e19..6df19c411c 100644
--- a/Lib/test/test_xml_etree.py
+++ b/Lib/test/test_xml_etree.py
@@ -37,7 +37,7 @@ def sanity():
def check_method(method):
if not callable(method):
- print method, "not callable"
+ print(method, "not callable")
def serialize(ET, elem, encoding=None):
import StringIO
diff --git a/Lib/test/test_xml_etree_c.py b/Lib/test/test_xml_etree_c.py
index 250f791073..75b5a82226 100644
--- a/Lib/test/test_xml_etree_c.py
+++ b/Lib/test/test_xml_etree_c.py
@@ -35,7 +35,7 @@ def sanity():
def check_method(method):
if not callable(method):
- print method, "not callable"
+ print(method, "not callable")
def serialize(ET, elem, encoding=None):
import StringIO
diff --git a/Lib/test/test_zipfile64.py b/Lib/test/test_zipfile64.py
index 449cf39d75..445e23d52d 100644
--- a/Lib/test/test_zipfile64.py
+++ b/Lib/test/test_zipfile64.py
@@ -57,9 +57,9 @@ class TestsWithSourceFile(unittest.TestCase):
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, (
+ print((
' zipTest still writing %d of %d, be patient...' %
- (num, filecount))
+ (num, filecount)), file=sys.__stdout__)
sys.__stdout__.flush()
zipfp.close()
@@ -70,9 +70,9 @@ class TestsWithSourceFile(unittest.TestCase):
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, (
+ print((
' zipTest still reading %d of %d, be patient...' %
- (num, filecount))
+ (num, filecount)), file=sys.__stdout__)
sys.__stdout__.flush()
zipfp.close()
diff --git a/Lib/test/time_hashlib.py b/Lib/test/time_hashlib.py
index de25cfd391..c210bd22aa 100644
--- a/Lib/test/time_hashlib.py
+++ b/Lib/test/time_hashlib.py
@@ -18,7 +18,7 @@ def test_scaled_msg(scale, name):
x = localCF(longStr).digest()
end = time.time()
- print ('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name
+ print(('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name)
def test_create():
start = time.time()
@@ -26,7 +26,7 @@ def test_create():
d = creatorFunc()
end = time.time()
- print ('%2.2f' % (end-start)), "seconds", '[20000 creations]'
+ print(('%2.2f' % (end-start)), "seconds", '[20000 creations]')
def test_zero():
start = time.time()
@@ -34,7 +34,7 @@ def test_zero():
x = creatorFunc().digest()
end = time.time()
- print ('%2.2f' % (end-start)), "seconds", '[20000 "" digests]'
+ print(('%2.2f' % (end-start)), "seconds", '[20000 "" digests]')
@@ -46,33 +46,33 @@ hName = sys.argv[1]
if hName in ('_md5', '_sha'):
exec('import '+hName)
exec('creatorFunc = '+hName+'.new')
- print "testing speed of old", hName, "legacy interface"
+ print("testing speed of old", hName, "legacy interface")
elif hName == '_hashlib' and len(sys.argv) > 3:
import _hashlib
exec('creatorFunc = _hashlib.%s' % sys.argv[2])
- print "testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])
+ print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2]))
elif hName == '_hashlib' and len(sys.argv) == 3:
import _hashlib
exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2])
- print "testing speed of _hashlib.new(%r)" % sys.argv[2]
+ print("testing speed of _hashlib.new(%r)" % sys.argv[2])
elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)):
creatorFunc = getattr(hashlib, hName)
- print "testing speed of hashlib."+hName, getattr(hashlib, hName)
+ print("testing speed of hashlib."+hName, getattr(hashlib, hName))
else:
exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName)
- print "testing speed of hashlib.new(%r)" % hName
+ print("testing speed of hashlib.new(%r)" % hName)
try:
test_create()
except ValueError:
- print
- print "pass argument(s) naming the hash to run a speed test on:"
- print " '_md5' and '_sha' test the legacy builtin md5 and sha"
- print " '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib"
- print " '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)"
- print " 'hName' tests the hashlib.hName() implementation if it exists"
- print " otherwise it uses hashlib.new(hName)."
- print
+ print()
+ print("pass argument(s) naming the hash to run a speed test on:")
+ print(" '_md5' and '_sha' test the legacy builtin md5 and sha")
+ print(" '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib")
+ print(" '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)")
+ print(" 'hName' tests the hashlib.hName() implementation if it exists")
+ print(" otherwise it uses hashlib.new(hName).")
+ print()
raise
test_zero()
diff --git a/Lib/textwrap.py b/Lib/textwrap.py
index ccff2aba12..0917d759b7 100644
--- a/Lib/textwrap.py
+++ b/Lib/textwrap.py
@@ -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."))
diff --git a/Lib/this.py b/Lib/this.py
index 37754b785a..e68dd3ff39 100644
--- a/Lib/this.py
+++ b/Lib/this.py
@@ -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]))
diff --git a/Lib/threading.py b/Lib/threading.py
index fecd3cc304..e23007e92f 100644
--- a/Lib/threading.py
+++ b/Lib/threading.py
@@ -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
diff --git a/Lib/timeit.py b/Lib/timeit.py
index 5dd3ca9249..e760c62353 100644
--- a/Lib/timeit.py
+++ b/Lib/timeit.py
@@ -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__":
diff --git a/Lib/tokenize.py b/Lib/tokenize.py
index 152bfdb85b..e502da96bc 100644
--- a/Lib/tokenize.py
+++ b/Lib/tokenize.py
@@ -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):
"""
diff --git a/Lib/trace.py b/Lib/trace.py
index ca44eae927..b2ec557461 100644
--- a/Lib/trace.py
+++ b/Lib/trace.py
@@ -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):
diff --git a/Lib/unittest.py b/Lib/unittest.py
index 9163e84cd5..cde310f8a7 100644
--- a/Lib/unittest.py
+++ b/Lib/unittest.py
@@ -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):
diff --git a/Lib/urllib.py b/Lib/urllib.py
index bb9472bbe0..d2ae1becf0 100644
--- a/Lib/urllib.py
+++ b/Lib/urllib.py
@@ -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__':
diff --git a/Lib/urlparse.py b/Lib/urlparse.py
index eade040ff6..9c9af451e1 100644
--- a/Lib/urlparse.py
+++ b/Lib/urlparse.py
@@ -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()
diff --git a/Lib/uu.py b/Lib/uu.py
index 887d99a35e..4d3cbd603f 100755
--- 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)
diff --git a/Lib/warnings.py b/Lib/warnings.py
index c0a96d6de4..87ae8494a2 100644
--- a/Lib/warnings.py
+++ b/Lib/warnings.py
@@ -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):
diff --git a/Lib/webbrowser.py b/Lib/webbrowser.py
index 28e6bdebbe..55aa04c863 100644
--- a/Lib/webbrowser.py
+++ b/Lib/webbrowser.py
@@ -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()
diff --git a/Lib/whichdb.py b/Lib/whichdb.py
index f077f87531..4d7a5602b4 100644
--- a/Lib/whichdb.py
+++ b/Lib/whichdb.py
@@ -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)
diff --git a/Lib/wsgiref/simple_server.py b/Lib/wsgiref/simple_server.py
index e6c9f38bae..abb3620510 100644
--- a/Lib/wsgiref/simple_server.py
+++ b/Lib/wsgiref/simple_server.py
@@ -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
diff --git a/Lib/xml/dom/pulldom.py b/Lib/xml/dom/pulldom.py
index 18f49b5019..f0245c49c3 100644
--- a/Lib/xml/dom/pulldom.py
+++ b/Lib/xml/dom/pulldom.py
@@ -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):
diff --git a/Lib/xml/sax/handler.py b/Lib/xml/sax/handler.py
index f9e91b6d47..481733d2cb 100644
--- a/Lib/xml/sax/handler.py
+++ b/Lib/xml/sax/handler.py
@@ -39,7 +39,7 @@ class ErrorHandler:
def warning(self, exception):
"Handle a warning."
- print exception
+ print(exception)
# ===== CONTENTHANDLER =====
diff --git a/Lib/xmllib.py b/Lib/xmllib.py
index 59fbcd189b..6663a23b80 100644
--- a/Lib/xmllib.py
+++ b/Lib/xmllib.py
@@ -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__':
diff --git a/Lib/xmlrpclib.py b/Lib/xmlrpclib.py
index 16e2b3b276..494100124c 100644
--- a/Lib/xmlrpclib.py
+++ b/Lib/xmlrpclib.py
@@ -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)
diff --git a/Lib/zipfile.py b/Lib/zipfile.py
index cae04f4869..c6162ff37c 100644
--- a/Lib/zipfile.py
+++ b/Lib/zipfile.py
@@ -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):