Kaydet (Commit) 752abd0d authored tarafından Neal Norwitz's avatar Neal Norwitz

Convert a lot of print statements to print functions in docstrings,

documentation, and unused/rarely used functions.
üst 8321f978
...@@ -222,10 +222,10 @@ These two statements are equivalent:: ...@@ -222,10 +222,10 @@ These two statements are equivalent::
for i in iter(obj): for i in iter(obj):
print i print(i)
for i in obj: for i in obj:
print i print(i)
Iterators can be materialized as lists or tuples by using the :func:`list` or Iterators can be materialized as lists or tuples by using the :func:`list` or
:func:`tuple` constructor functions: :func:`tuple` constructor functions:
...@@ -709,7 +709,7 @@ obvious :keyword:`for` loop:: ...@@ -709,7 +709,7 @@ obvious :keyword:`for` loop::
containing the count and each element. :: containing the count and each element. ::
>>> for item in enumerate(['subject', 'verb', 'object']): >>> for item in enumerate(['subject', 'verb', 'object']):
... print item ... print(item)
(0, 'subject') (0, 'subject')
(1, 'verb') (1, 'verb')
(2, 'object') (2, 'object')
......
...@@ -232,7 +232,7 @@ Example: ...@@ -232,7 +232,7 @@ Example:
>>> from collections import deque >>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items >>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements >>> for elem in d: # iterate over the deque's elements
... print elem.upper() ... print(elem.upper())
G G
H H
I I
......
...@@ -532,7 +532,7 @@ Example of working with :class:`date`: ...@@ -532,7 +532,7 @@ Example of working with :class:`date`:
datetime.date(2002, 3, 11) datetime.date(2002, 3, 11)
>>> t = d.timetuple() >>> t = d.timetuple()
>>> for i in t: # doctest: +SKIP >>> for i in t: # doctest: +SKIP
... print i ... print(i)
2002 # year 2002 # year
3 # month 3 # month
11 # day 11 # day
...@@ -544,7 +544,7 @@ Example of working with :class:`date`: ...@@ -544,7 +544,7 @@ Example of working with :class:`date`:
-1 -1
>>> ic = d.isocalendar() >>> ic = d.isocalendar()
>>> for i in ic: # doctest: +SKIP >>> for i in ic: # doctest: +SKIP
... print i ... print(i)
2002 # ISO year 2002 # ISO year
11 # ISO week number 11 # ISO week number
1 # ISO day number ( 1 = Monday ) 1 # ISO day number ( 1 = Monday )
...@@ -1011,7 +1011,7 @@ Examples of working with datetime objects: ...@@ -1011,7 +1011,7 @@ Examples of working with datetime objects:
>>> # Using datetime.timetuple() to get tuple of all attributes >>> # Using datetime.timetuple() to get tuple of all attributes
>>> tt = dt.timetuple() >>> tt = dt.timetuple()
>>> for it in tt: # doctest: +SKIP >>> for it in tt: # doctest: +SKIP
... print it ... print(it)
... ...
2006 # year 2006 # year
11 # month 11 # month
...@@ -1025,7 +1025,7 @@ Examples of working with datetime objects: ...@@ -1025,7 +1025,7 @@ Examples of working with datetime objects:
>>> # Date in ISO format >>> # Date in ISO format
>>> ic = dt.isocalendar() >>> ic = dt.isocalendar()
>>> for it in ic: # doctest: +SKIP >>> for it in ic: # doctest: +SKIP
... print it ... print(it)
... ...
2006 # ISO year 2006 # ISO year
47 # ISO week 47 # ISO week
......
...@@ -17,13 +17,13 @@ Encoding basic Python object hierarchies:: ...@@ -17,13 +17,13 @@ Encoding basic Python object hierarchies::
>>> import json >>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]' '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar") >>> print(json.dumps("\"foo\bar"))
"\"foo\bar" "\"foo\bar"
>>> print json.dumps(u'\u1234') >>> print(json.dumps(u'\u1234'))
"\u1234" "\u1234"
>>> print json.dumps('\\') >>> print(json.dumps('\\'))
"\\" "\\"
>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0} {"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO >>> from StringIO import StringIO
>>> io = StringIO() >>> io = StringIO()
...@@ -40,7 +40,7 @@ Compact encoding:: ...@@ -40,7 +40,7 @@ Compact encoding::
Pretty printing:: Pretty printing::
>>> import json >>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
{ {
"4": 5, "4": 5,
"6": 7 "6": 7
......
...@@ -82,14 +82,14 @@ The script that will output the report of bacon.py:: ...@@ -82,14 +82,14 @@ The script that will output the report of bacon.py::
finder = ModuleFinder() finder = ModuleFinder()
finder.run_script('bacon.py') finder.run_script('bacon.py')
print 'Loaded modules:' print('Loaded modules:')
for name, mod in finder.modules.iteritems(): for name, mod in finder.modules.items():
print '%s: ' % name, print('%s: ' % name, end='')
print ','.join(mod.globalnames.keys()[:3]) print(','.join(mod.globalnames.keys()[:3]))
print '-'*50 print('-'*50)
print 'Modules not imported:' print('Modules not imported:')
print '\n'.join(finder.badmodules.iterkeys()) print('\n'.join(finder.badmodules.keys()))
Sample output (may vary depending on the architecture):: Sample output (may vary depending on the architecture)::
......
...@@ -104,4 +104,4 @@ Generating a plist:: ...@@ -104,4 +104,4 @@ Generating a plist::
Parsing a plist:: Parsing a plist::
pl = readPlist(pathOrFile) pl = readPlist(pathOrFile)
print pl["aKey"] print(pl["aKey"])
...@@ -52,14 +52,14 @@ Example:: ...@@ -52,14 +52,14 @@ Example::
>>> import time >>> import time
>>> from threading import Timer >>> from threading import Timer
>>> def print_time(): >>> def print_time():
... print "From print_time", time.time() ... print("From print_time", time.time())
... ...
>>> def print_some_times(): >>> def print_some_times():
... print time.time() ... print(time.time())
... Timer(5, print_time, ()).start() ... Timer(5, print_time, ()).start()
... Timer(10, print_time, ()).start() ... Timer(10, print_time, ()).start()
... time.sleep(11) # sleep while time-delay events execute ... time.sleep(11) # sleep while time-delay events execute
... print time.time() ... print(time.time())
... ...
>>> print_some_times() >>> print_some_times()
930343690.257 930343690.257
......
...@@ -866,7 +866,7 @@ the interface:: ...@@ -866,7 +866,7 @@ the interface::
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
# receive a package # receive a package
print s.recvfrom(65565) print(s.recvfrom(65565))
# disabled promiscuous mode # disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
...@@ -132,7 +132,7 @@ parameter expect a WSGI-compliant dictionary to be supplied; please see ...@@ -132,7 +132,7 @@ parameter expect a WSGI-compliant dictionary to be supplied; please see
return ret return ret
httpd = make_server('', 8000, simple_app) httpd = make_server('', 8000, simple_app)
print "Serving on port 8000..." print("Serving on port 8000...")
httpd.serve_forever() httpd.serve_forever()
......
...@@ -63,9 +63,10 @@ def get_version_info(): ...@@ -63,9 +63,10 @@ def get_version_info():
return get_header_version_info('.') return get_header_version_info('.')
except (IOError, OSError): except (IOError, OSError):
version, release = get_sys_version_info() version, release = get_sys_version_info()
print >>sys.stderr, 'Can\'t get version info from Include/patchlevel.h, ' \ print('Can\'t get version info from Include/patchlevel.h, '
'using version of this interpreter (%s).' % release 'using version of this interpreter (%s).' % release,
file=sys.stderr)
return version, release return version, release
if __name__ == '__main__': if __name__ == '__main__':
print get_header_version_info('.')[1] print(get_header_version_info('.')[1])
...@@ -239,7 +239,7 @@ lists, one list per row:: ...@@ -239,7 +239,7 @@ lists, one list per row::
Now, if you wanted to swap rows and columns, you could use a list Now, if you wanted to swap rows and columns, you could use a list
comprehension:: comprehension::
>>> print [[row[i] for row in mat] for i in [0, 1, 2]] >>> print([[row[i] for row in mat] for i in [0, 1, 2]])
[[1, 4, 7], [2, 5, 8], [3, 6, 9]] [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Special care has to be taken for the *nested* list comprehension: Special care has to be taken for the *nested* list comprehension:
...@@ -251,7 +251,7 @@ A more verbose version of this snippet shows the flow explicitly:: ...@@ -251,7 +251,7 @@ A more verbose version of this snippet shows the flow explicitly::
for i in [0, 1, 2]: for i in [0, 1, 2]:
for row in mat: for row in mat:
print row[i], print(row[i], end="")
print print
In real world, you should prefer builtin functions to complex flow statements. In real world, you should prefer builtin functions to complex flow statements.
......
...@@ -132,7 +132,7 @@ the exception (allowing a caller to handle the exception as well):: ...@@ -132,7 +132,7 @@ the exception (allowing a caller to handle the exception as well)::
s = f.readline() s = f.readline()
i = int(s.strip()) i = int(s.strip())
except IOError as (errno, strerror): except IOError as (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror) print("I/O error(%s): %s" % (errno, strerror))
except ValueError: except ValueError:
print("Could not convert data to an integer.") print("Could not convert data to an integer.")
except: except:
......
...@@ -158,14 +158,14 @@ def _test(): ...@@ -158,14 +158,14 @@ def _test():
if f.getvalue() != text: if f.getvalue() != text:
raise RuntimeError, 'write failed' raise RuntimeError, 'write failed'
length = f.tell() length = f.tell()
print 'File length =', length print('File length =', length)
f.seek(len(lines[0])) f.seek(len(lines[0]))
f.write(lines[1]) f.write(lines[1])
f.seek(0) f.seek(0)
print 'First line =', repr(f.readline()) print('First line =', repr(f.readline()))
here = f.tell() here = f.tell()
line = f.readline() line = f.readline()
print 'Second line =', repr(line) print('Second line =', repr(line))
f.seek(-len(line), 1) f.seek(-len(line), 1)
line2 = f.read(len(line)) line2 = f.read(len(line))
if line != line2: if line != line2:
...@@ -177,8 +177,8 @@ def _test(): ...@@ -177,8 +177,8 @@ def _test():
line2 = f.read() line2 = f.read()
if line != line2: if line != line2:
raise RuntimeError, 'bad result after seek back from EOF' raise RuntimeError, 'bad result after seek back from EOF'
print 'Read', len(list), 'more lines' print('Read', len(list), 'more lines')
print 'File length =', f.tell() print('File length =', f.tell())
if f.tell() != length: if f.tell() != length:
raise RuntimeError, 'bad length' raise RuntimeError, 'bad length'
f.close() f.close()
......
...@@ -1273,7 +1273,7 @@ idle -est "Baz" foo.py ...@@ -1273,7 +1273,7 @@ idle -est "Baz" foo.py
Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
window with the title "Baz". window with the title "Baz".
idle -c "import sys; print sys.argv" "foo" idle -c "import sys; print(sys.argv)" "foo"
Open a shell window and run the command, passing "-c" in sys.argv[0] Open a shell window and run the command, passing "-c" in sys.argv[0]
and "foo" in sys.argv[1]. and "foo" in sys.argv[1].
...@@ -1282,7 +1282,7 @@ idle -d -s -r foo.py "Hello World" ...@@ -1282,7 +1282,7 @@ idle -d -s -r foo.py "Hello World"
run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
sys.argv[1]. sys.argv[1].
echo "import sys; print sys.argv" | idle - "foobar" echo "import sys; print(sys.argv)" | idle - "foobar"
Open a shell window, run the script piped in, passing '' in sys.argv[0] Open a shell window, run the script piped in, passing '' in sys.argv[0]
and "foobar" in sys.argv[1]. and "foobar" in sys.argv[1].
""" """
......
...@@ -254,9 +254,9 @@ def walk(top, topdown=True, onerror=None, followlinks=False): ...@@ -254,9 +254,9 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
import os import os
from os.path import join, getsize from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'): for root, dirs, files in os.walk('python/Lib/email'):
print root, "consumes", print(root, "consumes", end="")
print sum([getsize(join(root, name)) for name in files]), print(sum([getsize(join(root, name)) for name in files]), end="")
print "bytes in", len(files), "non-directory files" print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs: if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories dirs.remove('CVS') # don't visit CVS directories
""" """
......
...@@ -500,7 +500,8 @@ class Pdb(bdb.Bdb, cmd.Cmd): ...@@ -500,7 +500,8 @@ class Pdb(bdb.Bdb, cmd.Cmd):
try: try:
bp = bdb.Breakpoint.bpbynumber[bpnum] bp = bdb.Breakpoint.bpbynumber[bpnum]
except IndexError: except IndexError:
print >>self.stdout, 'Breakpoint index %r is not valid' % args[0] print('Breakpoint index %r is not valid' % args[0],
file=self.stdout)
return return
if bp: if bp:
bp.cond = cond bp.cond = cond
...@@ -524,7 +525,8 @@ class Pdb(bdb.Bdb, cmd.Cmd): ...@@ -524,7 +525,8 @@ class Pdb(bdb.Bdb, cmd.Cmd):
try: try:
bp = bdb.Breakpoint.bpbynumber[bpnum] bp = bdb.Breakpoint.bpbynumber[bpnum]
except IndexError: except IndexError:
print >>self.stdout, 'Breakpoint index %r is not valid' % args[0] print('Breakpoint index %r is not valid' % args[0],
file=self.stdout)
return return
if bp: if bp:
bp.ignore = count bp.ignore = count
......
...@@ -21,7 +21,7 @@ def wrong1(): ...@@ -21,7 +21,7 @@ def wrong1():
def test2(self): def test2(self):
prog_text_2 = """\ prog_text_2 = """\
def wrong2(): def wrong2():
print x print(x)
global x global x
""" """
check_syntax_error(self, prog_text_2) check_syntax_error(self, prog_text_2)
...@@ -29,7 +29,7 @@ def wrong2(): ...@@ -29,7 +29,7 @@ def wrong2():
def test3(self): def test3(self):
prog_text_3 = """\ prog_text_3 = """\
def wrong3(): def wrong3():
print x print(x)
x = 2 x = 2
global x global x
""" """
......
...@@ -10,7 +10,7 @@ import os, sys ...@@ -10,7 +10,7 @@ import os, sys
# Test that command-lines get down as we expect. # Test that command-lines get down as we expect.
# To do this we execute: # To do this we execute:
# python -c "import sys;print sys.argv" {rest_of_commandline} # python -c "import sys;print(sys.argv)" {rest_of_commandline}
# This results in Python being spawned and printing the sys.argv list. # This results in Python being spawned and printing the sys.argv list.
# We can then eval() the result of this, and see what each argv was. # We can then eval() the result of this, and see what each argv was.
python = sys.executable python = sys.executable
......
...@@ -481,7 +481,7 @@ def captured_output(stream_name): ...@@ -481,7 +481,7 @@ def captured_output(stream_name):
Example use (with 'stream_name=stdout'):: Example use (with 'stream_name=stdout')::
with captured_stdout() as s: with captured_stdout() as s:
print "hello" print("hello")
assert s.getvalue() == "hello" assert s.getvalue() == "hello"
""" """
import io import io
......
...@@ -89,7 +89,7 @@ Some error-handling code ...@@ -89,7 +89,7 @@ Some error-handling code
>>> roundtrip("try: import somemodule\\n" >>> roundtrip("try: import somemodule\\n"
... "except ImportError: # comment\\n" ... "except ImportError: # comment\\n"
... " print('Can not import' # comment2\\n)" ... " print('Can not import' # comment2\\n)"
... "else: print 'Loaded'\\n") ... "else: print('Loaded')\\n")
True True
Balancing continuation Balancing continuation
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment