Fix most trivially-findable print statements.

There's one major and one minor category still unfixed:
doctests are the major category (and I hope to be able to augment the
refactoring tool to refactor bona fide doctests soon);
other code generating print statements in strings is the minor category.

(Oh, and I don't know if the compiler package works.)
This commit is contained in:
Guido van Rossum 2007-02-09 05:37:30 +00:00
parent 452bf519a7
commit be19ed77dd
331 changed files with 2567 additions and 2648 deletions

View file

@ -570,7 +570,7 @@ def test(HandlerClass = BaseHTTPRequestHandler,
httpd = ServerClass(server_address, HandlerClass) httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname() 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() httpd.serve_forever()

View file

@ -165,7 +165,7 @@ def total(self):
print "accessible" print "accessible"
\n""" \n"""
exec(testcode) exec(testcode)
print '='*20, "Using rexec:", '='*20 print('='*20, "Using rexec:", '='*20)
import rexec import rexec
r = rexec.RExec() r = rexec.RExec()
m = r.add_module('__main__') m = r.add_module('__main__')

View file

@ -80,9 +80,9 @@
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C["rocky"] = "road" >>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie" >>> C["rocky"]["path"] = "/cookie"
>>> print C.output(header="Cookie:") >>> print(C.output(header="Cookie:"))
Cookie: rocky=road; Path=/cookie Cookie: rocky=road; Path=/cookie
>>> print C.output(attrs=[], header="Cookie:") >>> print(C.output(attrs=[], header="Cookie:"))
Cookie: rocky=road Cookie: rocky=road
The load() method of a Cookie extracts cookies from a string. In a The load() method of a Cookie extracts cookies from a string. In a
@ -100,7 +100,7 @@
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> print C >>> print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Each element of the Cookie also supports all of the RFC 2109 Each element of the Cookie also supports all of the RFC 2109
@ -110,7 +110,7 @@
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C["oreo"] = "doublestuff" >>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/" >>> C["oreo"]["path"] = "/"
>>> print C >>> print(C)
Set-Cookie: oreo=doublestuff; Path=/ Set-Cookie: oreo=doublestuff; Path=/
Each dictionary element has a 'value' attribute, which gives you Each dictionary element has a 'value' attribute, which gives you
@ -198,7 +198,7 @@
fact, this simply returns a SmartCookie. fact, this simply returns a SmartCookie.
>>> C = Cookie.Cookie() >>> C = Cookie.Cookie()
>>> print C.__class__.__name__ >>> print(C.__class__.__name__)
SmartCookie SmartCookie

View file

@ -270,9 +270,9 @@ def handle_get(self):
response = self.generate_html_documentation() response = self.generate_html_documentation()
print 'Content-Type: text/html' print('Content-Type: text/html')
print 'Content-Length: %d' % len(response) print('Content-Length: %d' % len(response))
print print()
sys.stdout.write(response) sys.stdout.write(response)
def __init__(self): def __init__(self):

View file

@ -543,9 +543,9 @@ def handle_xmlrpc(self, request_text):
response = self._marshaled_dispatch(request_text) response = self._marshaled_dispatch(request_text)
print 'Content-Type: text/xml' print('Content-Type: text/xml')
print 'Content-Length: %d' % len(response) print('Content-Length: %d' % len(response))
print print()
sys.stdout.write(response) sys.stdout.write(response)
def handle_get(self): def handle_get(self):
@ -565,10 +565,10 @@ def handle_get(self):
'message' : message, 'message' : message,
'explain' : explain 'explain' : explain
} }
print 'Status: %d %s' % (code, message) print('Status: %d %s' % (code, message))
print 'Content-Type: text/html' print('Content-Type: text/html')
print 'Content-Length: %d' % len(response) print('Content-Length: %d' % len(response))
print print()
sys.stdout.write(response) sys.stdout.write(response)
def handle_request(self, request_text = None): def handle_request(self, request_text = None):
@ -590,7 +590,7 @@ def handle_request(self, request_text = None):
self.handle_xmlrpc(request_text) self.handle_xmlrpc(request_text)
if __name__ == '__main__': if __name__ == '__main__':
print 'Running XML-RPC server on port 8000' print('Running XML-RPC server on port 8000')
server = SimpleXMLRPCServer(("localhost", 8000)) server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(pow) server.register_function(pow)
server.register_function(lambda x,y: x+y, 'add') server.register_function(lambda x,y: x+y, 'add')

View file

@ -263,12 +263,12 @@ def handle_error(self, request, client_address):
The default is to print a traceback and continue. The default is to print a traceback and continue.
""" """
print '-'*40 print('-'*40)
print 'Exception happened during processing of request from', print('Exception happened during processing of request from', end=' ')
print client_address print(client_address)
import traceback import traceback
traceback.print_exc() # XXX But this goes to stderr! traceback.print_exc() # XXX But this goes to stderr!
print '-'*40 print('-'*40)
class TCPServer(BaseServer): class TCPServer(BaseServer):

View file

@ -291,14 +291,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()))
print 'Position =', f.tell() print('Position =', 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:
@ -310,13 +310,13 @@ 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.truncate(length/2) f.truncate(length/2)
f.seek(0, 2) f.seek(0, 2)
print 'Truncated length =', f.tell() print('Truncated length =', f.tell())
if f.tell() != length/2: if f.tell() != length/2:
raise RuntimeError, 'truncate did not adjust length' raise RuntimeError, 'truncate did not adjust length'
f.close() f.close()

View file

@ -453,7 +453,7 @@ def _read_comm_chunk(self, chunk):
kludge = 0 kludge = 0
if chunk.chunksize == 18: if chunk.chunksize == 18:
kludge = 1 kludge = 1
print 'Warning: bad COMM chunk size' print('Warning: bad COMM chunk size')
chunk.chunksize = 23 chunk.chunksize = 23
#DEBUG end #DEBUG end
self._comptype = chunk.read(4) self._comptype = chunk.read(4)
@ -518,11 +518,11 @@ def _readmark(self, chunk):
# a position 0 and name '' # a position 0 and name ''
self._markers.append((id, pos, name)) self._markers.append((id, pos, name))
except EOFError: except EOFError:
print 'Warning: MARK chunk contains only', print('Warning: MARK chunk contains only', end=' ')
print len(self._markers), print(len(self._markers), end=' ')
if len(self._markers) == 1: print 'marker', if len(self._markers) == 1: print('marker', end=' ')
else: print 'markers', else: print('markers', end=' ')
print 'instead of', nmarkers print('instead of', nmarkers)
class Aifc_write: class Aifc_write:
# Variables used in this class: # Variables used in this class:
@ -939,16 +939,16 @@ def open(f, mode=None):
sys.argv.append('/usr/demos/data/audio/bach.aiff') sys.argv.append('/usr/demos/data/audio/bach.aiff')
fn = sys.argv[1] fn = sys.argv[1]
f = open(fn, 'r') f = open(fn, 'r')
print "Reading", fn print("Reading", fn)
print "nchannels =", f.getnchannels() print("nchannels =", f.getnchannels())
print "nframes =", f.getnframes() print("nframes =", f.getnframes())
print "sampwidth =", f.getsampwidth() print("sampwidth =", f.getsampwidth())
print "framerate =", f.getframerate() print("framerate =", f.getframerate())
print "comptype =", f.getcomptype() print("comptype =", f.getcomptype())
print "compname =", f.getcompname() print("compname =", f.getcompname())
if sys.argv[2:]: if sys.argv[2:]:
gn = sys.argv[2] gn = sys.argv[2]
print "Writing", gn print("Writing", gn)
g = open(gn, 'w') g = open(gn, 'w')
g.setparams(f.getparams()) g.setparams(f.getparams())
while 1: while 1:
@ -958,4 +958,4 @@ def open(f, mode=None):
g.writeframes(data) g.writeframes(data)
g.close() g.close()
f.close() f.close()
print "Done." print("Done.")

View file

@ -373,7 +373,7 @@ def log(self, message):
def log_info(self, message, type='info'): def log_info(self, message, type='info'):
if __debug__ or type != 'info': if __debug__ or type != 'info':
print '%s: %s' % (type, message) print('%s: %s' % (type, message))
def handle_read_event(self): def handle_read_event(self):
if self.accepting: if self.accepting:

View file

@ -26,7 +26,7 @@ def _run_exitfuncs():
exc_info = sys.exc_info() exc_info = sys.exc_info()
except: except:
import traceback import traceback
print >> sys.stderr, "Error in atexit._run_exitfuncs:" print("Error in atexit._run_exitfuncs:", file=sys.stderr)
traceback.print_exc() traceback.print_exc()
exc_info = sys.exc_info() exc_info = sys.exc_info()
@ -53,11 +53,11 @@ def register(func, *targs, **kargs):
if __name__ == "__main__": if __name__ == "__main__":
def x1(): def x1():
print "running x1" print("running x1")
def x2(n): def x2(n):
print "running x2(%r)" % (n,) print("running x2(%r)" % (n,))
def x3(n, kwd=None): def x3(n, kwd=None):
print "running x3(%r, kwd=%r)" % (n, kwd) print("running x3(%r, kwd=%r)" % (n, kwd))
register(x1) register(x1)
register(x2, 12) register(x2, 12)

View file

@ -240,7 +240,7 @@ def test(fn = None):
fn = 'f:just samples:just.aif' fn = 'f:just samples:just.aif'
import aifc import aifc
af = aifc.open(fn, 'r') af = aifc.open(fn, 'r')
print fn, af.getparams() print(fn, af.getparams())
p = AudioDev() p = AudioDev()
p.setoutrate(af.getframerate()) p.setoutrate(af.getframerate())
p.setsampwidth(af.getsampwidth()) p.setsampwidth(af.getsampwidth())
@ -249,7 +249,7 @@ def test(fn = None):
while 1: while 1:
data = af.readframes(BUFSIZ) data = af.readframes(BUFSIZ)
if not data: break if not data: break
print len(data) print(len(data))
p.writeframes(data) p.writeframes(data)
p.wait() p.wait()

View file

@ -330,11 +330,11 @@ def test():
opts, args = getopt.getopt(sys.argv[1:], 'deut') opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error as msg: except getopt.error as msg:
sys.stdout = sys.stderr sys.stdout = sys.stderr
print msg print(msg)
print """usage: %s [-d|-e|-u|-t] [file|-] print("""usage: %s [-d|-e|-u|-t] [file|-]
-d, -u: decode -d, -u: decode
-e: encode (default) -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) sys.exit(2)
func = encode func = encode
for o, a in opts: for o, a in opts:
@ -352,7 +352,7 @@ def test1():
s0 = "Aladdin:open sesame" s0 = "Aladdin:open sesame"
s1 = encodestring(s0) s1 = encodestring(s0)
s2 = decodestring(s1) s2 = decodestring(s1)
print s0, repr(s1), s2 print(s0, repr(s1), s2)
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -58,7 +58,7 @@ def trace_dispatch(self, frame, event, arg):
return self.trace_dispatch return self.trace_dispatch
if event == 'c_return': if event == 'c_return':
return self.trace_dispatch 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 return self.trace_dispatch
def dispatch_line(self, frame): def dispatch_line(self, frame):
@ -483,17 +483,17 @@ def bpprint(self, out=None):
disp = disp + 'yes ' disp = disp + 'yes '
else: else:
disp = disp + 'no ' disp = disp + 'no '
print >>out, '%-4dbreakpoint %s at %s:%d' % (self.number, disp, print('%-4dbreakpoint %s at %s:%d' % (self.number, disp,
self.file, self.line) self.file, self.line), file=out)
if self.cond: if self.cond:
print >>out, '\tstop only if %s' % (self.cond,) print('\tstop only if %s' % (self.cond,), file=out)
if self.ignore: 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):
if (self.hits > 1): ss = 's' if (self.hits > 1): ss = 's'
else: ss = '' else: ss = ''
print >>out, ('\tbreakpoint already hit %d time%s' % print(('\tbreakpoint already hit %d time%s' %
(self.hits, ss)) (self.hits, ss)), file=out)
# -----------end of Breakpoint class---------- # -----------end of Breakpoint class----------
@ -582,27 +582,27 @@ class Tdb(Bdb):
def user_call(self, frame, args): def user_call(self, frame, args):
name = frame.f_code.co_name name = frame.f_code.co_name
if not name: name = '???' if not name: name = '???'
print '+++ call', name, args print('+++ call', name, args)
def user_line(self, frame): def user_line(self, frame):
import linecache import linecache
name = frame.f_code.co_name name = frame.f_code.co_name
if not name: name = '???' if not name: name = '???'
fn = self.canonic(frame.f_code.co_filename) fn = self.canonic(frame.f_code.co_filename)
line = linecache.getline(fn, frame.f_lineno) 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): def user_return(self, frame, retval):
print '+++ return', retval print('+++ return', retval)
def user_exception(self, frame, exc_stuff): def user_exception(self, frame, exc_stuff):
print '+++ exception', exc_stuff print('+++ exception', exc_stuff)
self.set_continue() self.set_continue()
def foo(n): def foo(n):
print 'foo(', n, ')' print('foo(', n, ')')
x = bar(n*10) x = bar(n*10)
print 'bar returned', x print('bar returned', x)
def bar(a): def bar(a):
print 'bar(', a, ')' print('bar(', a, ')')
return a/2 return a/2
def test(): def test():

View file

@ -208,12 +208,12 @@ def sync(self):
def _db_print(self) : def _db_print(self) :
"""Print the database to stdout for debugging""" """Print the database to stdout for debugging"""
print "******** Printing raw database for debugging ********" print("******** Printing raw database for debugging ********")
cur = self.db.cursor() cur = self.db.cursor()
try: try:
key, data = cur.first() key, data = cur.first()
while 1: while 1:
print repr({key: data}) print(repr({key: data}))
next = cur.next() next = cur.next()
if next: if next:
key, data = next key, data = next

View file

@ -22,15 +22,15 @@
def print_versions(): def print_versions():
print print()
print '-=' * 38 print('-=' * 38)
print db.DB_VERSION_STRING print(db.DB_VERSION_STRING)
print 'bsddb.db.version(): %s' % (db.version(), ) print('bsddb.db.version(): %s' % (db.version(), ))
print 'bsddb.db.__version__: %s' % db.__version__ print('bsddb.db.__version__: %s' % db.__version__)
print 'bsddb.db.cvsid: %s' % db.cvsid print('bsddb.db.cvsid: %s' % db.cvsid)
print 'python version: %s' % sys.version print('python version: %s' % sys.version)
print 'My pid: %s' % os.getpid() print('My pid: %s' % os.getpid())
print '-=' * 38 print('-=' * 38)
class PrintInfoFakeTest(unittest.TestCase): class PrintInfoFakeTest(unittest.TestCase):

View file

@ -114,9 +114,9 @@ def tearDown(self):
def test00_associateDBError(self): def test00_associateDBError(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test00_associateDBError..." % \ print("Running %s.test00_associateDBError..." % \
self.__class__.__name__ self.__class__.__name__)
dupDB = db.DB(self.env) dupDB = db.DB(self.env)
dupDB.set_flags(db.DB_DUP) dupDB.set_flags(db.DB_DUP)
@ -207,9 +207,9 @@ def getDB(self):
def test01_associateWithDB(self): def test01_associateWithDB(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test01_associateWithDB..." % \ print("Running %s.test01_associateWithDB..." % \
self.__class__.__name__ self.__class__.__name__)
self.createDB() self.createDB()
@ -227,9 +227,9 @@ def test01_associateWithDB(self):
def test02_associateAfterDB(self): def test02_associateAfterDB(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test02_associateAfterDB..." % \ print("Running %s.test02_associateAfterDB..." % \
self.__class__.__name__ self.__class__.__name__)
self.createDB() self.createDB()
self.addDataToDB(self.getDB()) self.addDataToDB(self.getDB())
@ -257,7 +257,7 @@ def finish_test(self, secDB, txn=None):
vals[1].index('unknown') vals[1].index('unknown')
if verbose: if verbose:
print "Primary key traversal:" print("Primary key traversal:")
self.cur = self.getDB().cursor(txn) self.cur = self.getDB().cursor(txn)
count = 0 count = 0
rec = self.cur.first() rec = self.cur.first()
@ -268,13 +268,13 @@ def finish_test(self, secDB, txn=None):
assert rec[0] and type(rec[0]) == type(0) assert rec[0] and type(rec[0]) == type(0)
count = count + 1 count = count + 1
if verbose: if verbose:
print rec print(rec)
rec = self.cur.next() rec = self.cur.next()
assert count == len(musicdata) # all items accounted for assert count == len(musicdata) # all items accounted for
if verbose: if verbose:
print "Secondary key traversal:" print("Secondary key traversal:")
self.cur = secDB.cursor(txn) self.cur = secDB.cursor(txn)
count = 0 count = 0
@ -294,7 +294,7 @@ def finish_test(self, secDB, txn=None):
while rec is not None: while rec is not None:
count = count + 1 count = count + 1
if verbose: if verbose:
print rec print(rec)
rec = self.cur.next() rec = self.cur.next()
# all items accounted for EXCEPT for 1 with "Blues" genre # all items accounted for EXCEPT for 1 with "Blues" genre
assert count == len(musicdata)-1 assert count == len(musicdata)-1
@ -304,7 +304,7 @@ def finish_test(self, secDB, txn=None):
def getGenre(self, priKey, priData): def getGenre(self, priKey, priData):
assert type(priData) == type("") assert type(priData) == type("")
if verbose: if verbose:
print 'getGenre key: %r data: %r' % (priKey, priData) print('getGenre key: %r data: %r' % (priKey, priData))
genre = string.split(priData, '|')[2] genre = string.split(priData, '|')[2]
if genre == 'Blues': if genre == 'Blues':
return db.DB_DONOTINDEX return db.DB_DONOTINDEX
@ -343,9 +343,9 @@ def txn_finish_test(self, sDB, txn):
def test13_associate_in_transaction(self): def test13_associate_in_transaction(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test13_associateAutoCommit..." % \ print("Running %s.test13_associateAutoCommit..." % \
self.__class__.__name__ self.__class__.__name__)
txn = self.env.txn_begin() txn = self.env.txn_begin()
try: try:
@ -389,7 +389,7 @@ def addDataToDB(self, d):
def getGenre(self, priKey, priData): def getGenre(self, priKey, priData):
assert type(priData) == type(()) assert type(priData) == type(())
if verbose: if verbose:
print 'getGenre key: %r data: %r' % (priKey, priData) print('getGenre key: %r data: %r' % (priKey, priData))
genre = priData[2] genre = priData[2]
if genre == 'Blues': if genre == 'Blues':
return db.DB_DONOTINDEX return db.DB_DONOTINDEX

View file

@ -31,10 +31,10 @@ class VersionTestCase(unittest.TestCase):
def test00_version(self): def test00_version(self):
info = db.version() info = db.version()
if verbose: if verbose:
print '\n', '-=' * 20 print('\n', '-=' * 20)
print 'bsddb.db.version(): %s' % (info, ) print('bsddb.db.version(): %s' % (info, ))
print db.DB_VERSION_STRING print(db.DB_VERSION_STRING)
print '-=' * 20 print('-=' * 20)
assert info == (db.DB_VERSION_MAJOR, db.DB_VERSION_MINOR, assert info == (db.DB_VERSION_MAJOR, db.DB_VERSION_MINOR,
db.DB_VERSION_PATCH) db.DB_VERSION_PATCH)
@ -131,7 +131,7 @@ def populateDB(self, _txn=None):
num = len(d) num = len(d)
if verbose: if verbose:
print "created %d records" % num print("created %d records" % num)
def makeData(self, key): def makeData(self, key):
@ -145,13 +145,13 @@ def test01_GetsAndPuts(self):
d = self.d d = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test01_GetsAndPuts..." % self.__class__.__name__ print("Running %s.test01_GetsAndPuts..." % self.__class__.__name__)
for key in ['0001', '0100', '0400', '0700', '0999']: for key in ['0001', '0100', '0400', '0700', '0999']:
data = d.get(key) data = d.get(key)
if verbose: if verbose:
print data print(data)
assert d.get('0321') == '0321-0321-0321-0321-0321' assert d.get('0321') == '0321-0321-0321-0321-0321'
@ -164,7 +164,7 @@ def test01_GetsAndPuts(self):
d.delete('abcd') d.delete('abcd')
except db.DBNotFoundError as val: except db.DBNotFoundError as val:
assert val[0] == db.DB_NOTFOUND assert val[0] == db.DB_NOTFOUND
if verbose: print val if verbose: print(val)
else: else:
self.fail("expected exception") self.fail("expected exception")
@ -183,7 +183,7 @@ def test01_GetsAndPuts(self):
d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE) d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE)
except db.DBKeyExistError as val: except db.DBKeyExistError as val:
assert val[0] == db.DB_KEYEXIST assert val[0] == db.DB_KEYEXIST
if verbose: print val if verbose: print(val)
else: else:
self.fail("expected exception") self.fail("expected exception")
@ -212,7 +212,7 @@ def test01_GetsAndPuts(self):
rec = d.get_both('0555', '0555-0555-0555-0555-0555') rec = d.get_both('0555', '0555-0555-0555-0555-0555')
if verbose: if verbose:
print rec print(rec)
assert d.get_both('0555', 'bad data') == None assert d.get_both('0555', 'bad data') == None
@ -227,7 +227,7 @@ def test01_GetsAndPuts(self):
s = d.stat() s = d.stat()
assert type(s) == type({}) assert type(s) == type({})
if verbose: if verbose:
print 'd.stat() returned this dictionary:' print('d.stat() returned this dictionary:')
pprint(s) pprint(s)
@ -237,15 +237,15 @@ def test02_DictionaryMethods(self):
d = self.d d = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test02_DictionaryMethods..." % \ print("Running %s.test02_DictionaryMethods..." % \
self.__class__.__name__ self.__class__.__name__)
for key in ['0002', '0101', '0401', '0701', '0998']: for key in ['0002', '0101', '0401', '0701', '0998']:
data = d[key] data = d[key]
assert data == self.makeData(key) assert data == self.makeData(key)
if verbose: if verbose:
print data print(data)
assert len(d) == self._numKeys assert len(d) == self._numKeys
keys = d.keys() keys = d.keys()
@ -263,7 +263,7 @@ def test02_DictionaryMethods(self):
assert len(keys) == self._numKeys+1 assert len(keys) == self._numKeys+1
if verbose: if verbose:
print "the first 10 keys are:" print("the first 10 keys are:")
pprint(keys[:10]) pprint(keys[:10])
assert d['new record'] == 'a replacement record' assert d['new record'] == 'a replacement record'
@ -278,7 +278,7 @@ def test02_DictionaryMethods(self):
assert len(items[0]) == 2 assert len(items[0]) == 2
if verbose: if verbose:
print "the first 10 items are:" print("the first 10 items are:")
pprint(items[:10]) pprint(items[:10])
values = d.values() values = d.values()
@ -286,7 +286,7 @@ def test02_DictionaryMethods(self):
assert type(values) == type([]) assert type(values) == type([])
if verbose: if verbose:
print "the first 10 values are:" print("the first 10 values are:")
pprint(values[:10]) pprint(values[:10])
@ -295,9 +295,9 @@ def test02_DictionaryMethods(self):
def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0): def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \ print("Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \
(self.__class__.__name__, get_raises_error, set_raises_error) (self.__class__.__name__, get_raises_error, set_raises_error))
if self.env and self.dbopenflags & db.DB_AUTO_COMMIT: if self.env and self.dbopenflags & db.DB_AUTO_COMMIT:
txn = self.env.txn_begin() txn = self.env.txn_begin()
@ -310,13 +310,13 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
while rec is not None: while rec is not None:
count = count + 1 count = count + 1
if verbose and count % 100 == 0: if verbose and count % 100 == 0:
print rec print(rec)
try: try:
rec = c.next() rec = c.next()
except db.DBNotFoundError as val: except db.DBNotFoundError as val:
if get_raises_error: if get_raises_error:
assert val[0] == db.DB_NOTFOUND assert val[0] == db.DB_NOTFOUND
if verbose: print val if verbose: print(val)
rec = None rec = None
else: else:
self.fail("unexpected DBNotFoundError") self.fail("unexpected DBNotFoundError")
@ -330,13 +330,13 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
while rec is not None: while rec is not None:
count = count + 1 count = count + 1
if verbose and count % 100 == 0: if verbose and count % 100 == 0:
print rec print(rec)
try: try:
rec = c.prev() rec = c.prev()
except db.DBNotFoundError as val: except db.DBNotFoundError as val:
if get_raises_error: if get_raises_error:
assert val[0] == db.DB_NOTFOUND assert val[0] == db.DB_NOTFOUND
if verbose: print val if verbose: print(val)
rec = None rec = None
else: else:
self.fail("unexpected DBNotFoundError") self.fail("unexpected DBNotFoundError")
@ -359,7 +359,7 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
n = c.set('bad key') n = c.set('bad key')
except db.DBNotFoundError as val: except db.DBNotFoundError as val:
assert val[0] == db.DB_NOTFOUND assert val[0] == db.DB_NOTFOUND
if verbose: print val if verbose: print(val)
else: else:
if set_raises_error: if set_raises_error:
self.fail("expected exception") self.fail("expected exception")
@ -373,7 +373,7 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
n = c.get_both('0404', 'bad data') n = c.get_both('0404', 'bad data')
except db.DBNotFoundError as val: except db.DBNotFoundError as val:
assert val[0] == db.DB_NOTFOUND assert val[0] == db.DB_NOTFOUND
if verbose: print val if verbose: print(val)
else: else:
if get_raises_error: if get_raises_error:
self.fail("expected exception") self.fail("expected exception")
@ -383,16 +383,16 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
if self.d.get_type() == db.DB_BTREE: if self.d.get_type() == db.DB_BTREE:
rec = c.set_range('011') rec = c.set_range('011')
if verbose: if verbose:
print "searched for '011', found: ", rec print("searched for '011', found: ", rec)
rec = c.set_range('011',dlen=0,doff=0) rec = c.set_range('011',dlen=0,doff=0)
if verbose: 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') if rec[1] != '': self.fail('expected empty data portion')
ev = c.set_range('empty value') ev = c.set_range('empty value')
if verbose: 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') if ev[1] != '': self.fail('empty value lookup failed')
c.set('0499') c.set('0499')
@ -402,7 +402,7 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
except db.DBKeyEmptyError as val: except db.DBKeyEmptyError as val:
if get_raises_error: if get_raises_error:
assert val[0] == db.DB_KEYEMPTY assert val[0] == db.DB_KEYEMPTY
if verbose: print val if verbose: print(val)
else: else:
self.fail("unexpected DBKeyEmptyError") self.fail("unexpected DBKeyEmptyError")
else: else:
@ -441,13 +441,13 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
for method, args in methods_to_test.items(): for method, args in methods_to_test.items():
try: try:
if verbose: if verbose:
print "attempting to use a closed cursor's %s method" % \ print("attempting to use a closed cursor's %s method" % \
method method)
# a bug may cause a NULL pointer dereference... # a bug may cause a NULL pointer dereference...
getattr(c, method)(*args) getattr(c, method)(*args)
except db.DBError as val: except db.DBError as val:
assert val[0] == 0 assert val[0] == 0
if verbose: print val if verbose: print(val)
else: else:
self.fail("no exception raised when using a buggy cursor's" self.fail("no exception raised when using a buggy cursor's"
"%s method" % method) "%s method" % method)
@ -466,9 +466,9 @@ def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
def test03b_SimpleCursorWithoutGetReturnsNone0(self): def test03b_SimpleCursorWithoutGetReturnsNone0(self):
# same test but raise exceptions instead of returning None # same test but raise exceptions instead of returning None
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
self.__class__.__name__ self.__class__.__name__)
old = self.d.set_get_returns_none(0) old = self.d.set_get_returns_none(0)
assert old == 2 assert old == 2
@ -477,9 +477,9 @@ def test03b_SimpleCursorWithoutGetReturnsNone0(self):
def test03b_SimpleCursorWithGetReturnsNone1(self): def test03b_SimpleCursorWithGetReturnsNone1(self):
# same test but raise exceptions instead of returning None # same test but raise exceptions instead of returning None
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \ print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
self.__class__.__name__ self.__class__.__name__)
old = self.d.set_get_returns_none(1) old = self.d.set_get_returns_none(1)
self.test03_SimpleCursorStuff(get_raises_error=0, set_raises_error=1) self.test03_SimpleCursorStuff(get_raises_error=0, set_raises_error=1)
@ -488,9 +488,9 @@ def test03b_SimpleCursorWithGetReturnsNone1(self):
def test03c_SimpleCursorGetReturnsNone2(self): def test03c_SimpleCursorGetReturnsNone2(self):
# same test but raise exceptions instead of returning None # same test but raise exceptions instead of returning None
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \ print("Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \
self.__class__.__name__ self.__class__.__name__)
old = self.d.set_get_returns_none(1) old = self.d.set_get_returns_none(1)
assert old == 2 assert old == 2
@ -503,9 +503,9 @@ def test03c_SimpleCursorGetReturnsNone2(self):
def test04_PartialGetAndPut(self): def test04_PartialGetAndPut(self):
d = self.d d = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test04_PartialGetAndPut..." % \ print("Running %s.test04_PartialGetAndPut..." % \
self.__class__.__name__ self.__class__.__name__)
key = "partialTest" key = "partialTest"
data = "1" * 1000 + "2" * 1000 data = "1" * 1000 + "2" * 1000
@ -533,8 +533,8 @@ def test04_PartialGetAndPut(self):
def test05_GetSize(self): def test05_GetSize(self):
d = self.d d = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test05_GetSize..." % self.__class__.__name__ print("Running %s.test05_GetSize..." % self.__class__.__name__)
for i in range(1, 50000, 500): for i in range(1, 50000, 500):
key = "size%s" % i key = "size%s" % i
@ -553,8 +553,8 @@ def test06_Truncate(self):
d = self.d d = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test99_Truncate..." % self.__class__.__name__ print("Running %s.test99_Truncate..." % self.__class__.__name__)
d.put("abcde", "ABCDE"); d.put("abcde", "ABCDE");
num = d.truncate() num = d.truncate()
@ -598,8 +598,8 @@ def test07_EnvRemoveAndRename(self):
return return
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__ print("Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__)
# can't rename or remove an open DB # can't rename or remove an open DB
self.d.close() self.d.close()
@ -647,8 +647,8 @@ def populateDB(self):
def test06_Transactions(self): def test06_Transactions(self):
d = self.d d = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test06_Transactions..." % self.__class__.__name__ print("Running %s.test06_Transactions..." % self.__class__.__name__)
assert d.get('new rec', txn=self.txn) == None assert d.get('new rec', txn=self.txn) == None
d.put('new rec', 'this is a new record', self.txn) d.put('new rec', 'this is a new record', self.txn)
@ -671,7 +671,7 @@ def test06_Transactions(self):
while rec is not None: while rec is not None:
count = count + 1 count = count + 1
if verbose and count % 100 == 0: if verbose and count % 100 == 0:
print rec print(rec)
rec = c.next() rec = c.next()
assert count == self._numKeys+1 assert count == self._numKeys+1
@ -696,7 +696,7 @@ def test06_Transactions(self):
assert logs != None assert logs != None
for log in logs: for log in logs:
if verbose: if verbose:
print 'log file: ' + log print('log file: ' + log)
if db.version() >= (4,2): if db.version() >= (4,2):
logs = self.env.log_archive(db.DB_ARCH_REMOVE) logs = self.env.log_archive(db.DB_ARCH_REMOVE)
assert not logs assert not logs
@ -712,8 +712,8 @@ def test07_TxnTruncate(self):
d = self.d d = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test07_TxnTruncate..." % self.__class__.__name__ print("Running %s.test07_TxnTruncate..." % self.__class__.__name__)
d.put("abcde", "ABCDE"); d.put("abcde", "ABCDE");
txn = self.env.txn_begin() txn = self.env.txn_begin()
@ -762,21 +762,21 @@ class BTreeRecnoTestCase(BasicTestCase):
def test07_RecnoInBTree(self): def test07_RecnoInBTree(self):
d = self.d d = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test07_RecnoInBTree..." % self.__class__.__name__ print("Running %s.test07_RecnoInBTree..." % self.__class__.__name__)
rec = d.get(200) rec = d.get(200)
assert type(rec) == type(()) assert type(rec) == type(())
assert len(rec) == 2 assert len(rec) == 2
if verbose: if verbose:
print "Record #200 is ", rec print("Record #200 is ", rec)
c = d.cursor() c = d.cursor()
c.set('0200') c.set('0200')
num = c.get_recno() num = c.get_recno()
assert type(num) == type(1) assert type(num) == type(1)
if verbose: if verbose:
print "recno of d['0200'] is ", num print("recno of d['0200'] is ", num)
rec = c.current() rec = c.current()
assert c.set_recno(num) == rec assert c.set_recno(num) == rec
@ -796,9 +796,9 @@ class BasicDUPTestCase(BasicTestCase):
def test08_DuplicateKeys(self): def test08_DuplicateKeys(self):
d = self.d d = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test08_DuplicateKeys..." % \ print("Running %s.test08_DuplicateKeys..." % \
self.__class__.__name__ self.__class__.__name__)
d.put("dup0", "before") d.put("dup0", "before")
for x in "The quick brown fox jumped over the lazy dog.".split(): for x in "The quick brown fox jumped over the lazy dog.".split():
@ -808,7 +808,7 @@ def test08_DuplicateKeys(self):
data = d.get("dup1") data = d.get("dup1")
assert data == "The" assert data == "The"
if verbose: if verbose:
print data print(data)
c = d.cursor() c = d.cursor()
rec = c.set("dup1") rec = c.set("dup1")
@ -827,14 +827,14 @@ def test08_DuplicateKeys(self):
rec = c.set('dup1') rec = c.set('dup1')
while rec is not None: while rec is not None:
if verbose: if verbose:
print rec print(rec)
rec = c.next_dup() rec = c.next_dup()
c.set('dup1') c.set('dup1')
rec = c.next_nodup() rec = c.next_nodup()
assert rec[0] != 'dup1' assert rec[0] != 'dup1'
if verbose: if verbose:
print rec print(rec)
c.close() c.close()
@ -869,8 +869,8 @@ def otherType(self):
def test09_MultiDB(self): def test09_MultiDB(self):
d1 = self.d d1 = self.d
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test09_MultiDB..." % self.__class__.__name__ print("Running %s.test09_MultiDB..." % self.__class__.__name__)
d2 = db.DB(self.env) d2 = db.DB(self.env)
d2.open(self.filename, "second", self.dbtype, d2.open(self.filename, "second", self.dbtype,
@ -910,7 +910,7 @@ def test09_MultiDB(self):
while rec is not None: while rec is not None:
count = count + 1 count = count + 1
if verbose and (count % 50) == 0: if verbose and (count % 50) == 0:
print rec print(rec)
rec = c1.next() rec = c1.next()
assert count == self._numKeys assert count == self._numKeys
@ -919,7 +919,7 @@ def test09_MultiDB(self):
while rec is not None: while rec is not None:
count = count + 1 count = count + 1
if verbose: if verbose:
print rec print(rec)
rec = c2.next() rec = c2.next()
assert count == 9 assert count == 9
@ -928,7 +928,7 @@ def test09_MultiDB(self):
while rec is not None: while rec is not None:
count = count + 1 count = count + 1
if verbose: if verbose:
print rec print(rec)
rec = c3.next() rec = c3.next()
assert count == 52 assert count == 52

View file

@ -37,7 +37,7 @@ def test02_hashopen(self):
def test03_rnopen(self): def test03_rnopen(self):
data = string.split("The quick brown fox jumped over the lazy dog.") data = string.split("The quick brown fox jumped over the lazy dog.")
if verbose: if verbose:
print "\nTesting: rnopen" print("\nTesting: rnopen")
f = rnopen(self.filename, 'c') f = rnopen(self.filename, 'c')
for x in range(len(data)): for x in range(len(data)):
@ -45,7 +45,7 @@ def test03_rnopen(self):
getTest = (f[1], f[2], f[3]) getTest = (f[1], f[2], f[3])
if verbose: if verbose:
print '%s %s %s' % getTest print('%s %s %s' % getTest)
assert getTest[1] == 'quick', 'data mismatch!' assert getTest[1] == 'quick', 'data mismatch!'
@ -73,7 +73,7 @@ def badKey(f):
rec = f.first() rec = f.first()
while rec: while rec:
if verbose: if verbose:
print rec print(rec)
try: try:
rec = f.next() rec = f.next()
except KeyError: except KeyError:
@ -89,17 +89,17 @@ def test04_n_flag(self):
def do_bthash_test(self, factory, what): def do_bthash_test(self, factory, what):
if verbose: if verbose:
print '\nTesting: ', what print('\nTesting: ', what)
f = factory(self.filename, 'c') f = factory(self.filename, 'c')
if verbose: if verbose:
print 'creation...' print('creation...')
# truth test # truth test
if f: if f:
if verbose: print "truth test: true" if verbose: print("truth test: true")
else: else:
if verbose: print "truth test: false" if verbose: print("truth test: false")
f['0'] = '' f['0'] = ''
f['a'] = 'Guido' f['a'] = 'Guido'
@ -109,10 +109,10 @@ def do_bthash_test(self, factory, what):
# 'e' intentionally left out # 'e' intentionally left out
f['f'] = 'Python' f['f'] = 'Python'
if verbose: if verbose:
print '%s %s %s' % (f['a'], f['b'], f['c']) print('%s %s %s' % (f['a'], f['b'], f['c']))
if verbose: if verbose:
print 'key ordering...' print('key ordering...')
start = f.set_location(f.first()[0]) start = f.set_location(f.first()[0])
if start != ('0', ''): if start != ('0', ''):
self.fail("incorrect first() result: "+repr(start)) self.fail("incorrect first() result: "+repr(start))
@ -124,7 +124,7 @@ def do_bthash_test(self, factory, what):
f.previous() f.previous()
break break
if verbose: if verbose:
print rec print(rec)
assert f.has_key('f'), 'Error, missing key!' assert f.has_key('f'), 'Error, missing key!'
@ -147,9 +147,9 @@ def do_bthash_test(self, factory, what):
# truth test # truth test
try: try:
if f: if f:
if verbose: print "truth test: true" if verbose: print("truth test: true")
else: else:
if verbose: print "truth test: false" if verbose: print("truth test: false")
except db.DBError: except db.DBError:
pass pass
else: else:
@ -158,16 +158,16 @@ def do_bthash_test(self, factory, what):
del f del f
if verbose: if verbose:
print 'modification...' print('modification...')
f = factory(self.filename, 'w') f = factory(self.filename, 'w')
f['d'] = 'discovered' f['d'] = 'discovered'
if verbose: if verbose:
print 'access...' print('access...')
for key in f.keys(): for key in f.keys():
word = f[key] word = f[key]
if verbose: if verbose:
print word print(word)
def noRec(f): def noRec(f):
rec = f['no such key'] rec = f['no such key']

View file

@ -79,8 +79,8 @@ def do_close(self):
def test01_basics(self): def test01_basics(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test01_basics..." % self.__class__.__name__ print("Running %s.test01_basics..." % self.__class__.__name__)
self.populateDB(self.d) self.populateDB(self.d)
self.d.sync() self.d.sync()
@ -94,9 +94,9 @@ def test01_basics(self):
f = d.fd() f = d.fd()
if verbose: if verbose:
print "length:", l print("length:", l)
print "keys:", k print("keys:", k)
print "stats:", s print("stats:", s)
assert 0 == d.has_key('bad key') assert 0 == d.has_key('bad key')
assert 1 == d.has_key('IA') assert 1 == d.has_key('IA')
@ -113,7 +113,7 @@ def test01_basics(self):
value = d[key] value = d[key]
values.append(value) values.append(value)
if verbose: if verbose:
print "%s: %s" % (key, value) print("%s: %s" % (key, value))
self.checkrec(key, value) self.checkrec(key, value)
dbvalues = sorted(d.values(), key=lambda x: (str(type(x)), x)) dbvalues = sorted(d.values(), key=lambda x: (str(type(x)), x))
@ -144,8 +144,8 @@ def test01_basics(self):
def test02_cursors(self): def test02_cursors(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test02_cursors..." % self.__class__.__name__ print("Running %s.test02_cursors..." % self.__class__.__name__)
self.populateDB(self.d) self.populateDB(self.d)
d = self.d d = self.d
@ -156,7 +156,7 @@ def test02_cursors(self):
while rec is not None: while rec is not None:
count = count + 1 count = count + 1
if verbose: if verbose:
print rec print(rec)
key, value = rec key, value = rec
self.checkrec(key, value) self.checkrec(key, value)
rec = c.next() rec = c.next()
@ -170,7 +170,7 @@ def test02_cursors(self):
while rec is not None: while rec is not None:
count = count + 1 count = count + 1
if verbose: if verbose:
print rec print(rec)
key, value = rec key, value = rec
self.checkrec(key, value) self.checkrec(key, value)
rec = c.prev() rec = c.prev()

View file

@ -110,7 +110,7 @@ def test02(self):
assert values[1]['Species'] == 'Penguin' assert values[1]['Species'] == 'Penguin'
else : else :
if verbose: if verbose:
print "values= %r" % (values,) print("values= %r" % (values,))
raise "Wrong values returned!" raise "Wrong values returned!"
def test03(self): def test03(self):
@ -120,15 +120,15 @@ def test03(self):
except dbtables.TableDBError: except dbtables.TableDBError:
pass pass
if verbose: if verbose:
print '...before CreateTable...' print('...before CreateTable...')
self.tdb._db_print() self.tdb._db_print()
self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e']) self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e'])
if verbose: if verbose:
print '...after CreateTable...' print('...after CreateTable...')
self.tdb._db_print() self.tdb._db_print()
self.tdb.Drop(tabname) self.tdb.Drop(tabname)
if verbose: if verbose:
print '...after Drop...' print('...after Drop...')
self.tdb._db_print() self.tdb._db_print()
self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e']) self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e'])

View file

@ -65,9 +65,9 @@ def tearDown(self):
def test01_join(self): def test01_join(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test01_join..." % \ print("Running %s.test01_join..." % \
self.__class__.__name__ self.__class__.__name__)
# create and populate primary index # create and populate primary index
priDB = db.DB(self.env) priDB = db.DB(self.env)

View file

@ -49,27 +49,27 @@ def tearDown(self):
def test01_simple(self): def test01_simple(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test01_simple..." % self.__class__.__name__ print("Running %s.test01_simple..." % self.__class__.__name__)
anID = self.env.lock_id() anID = self.env.lock_id()
if verbose: 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) lock = self.env.lock_get(anID, "some locked thing", db.DB_LOCK_WRITE)
if verbose: if verbose:
print "Aquired lock: %s" % lock print("Aquired lock: %s" % lock)
time.sleep(1) time.sleep(1)
self.env.lock_put(lock) self.env.lock_put(lock)
if verbose: if verbose:
print "Released lock: %s" % lock print("Released lock: %s" % lock)
def test02_threaded(self): def test02_threaded(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test02_threaded..." % self.__class__.__name__ print("Running %s.test02_threaded..." % self.__class__.__name__)
threads = [] threads = []
threads.append(Thread(target = self.theThread, threads.append(Thread(target = self.theThread,
@ -113,17 +113,17 @@ def theThread(self, sleepTime, lockType):
anID = self.env.lock_id() anID = self.env.lock_id()
if verbose: 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) lock = self.env.lock_get(anID, "some locked thing", lockType)
if verbose: if verbose:
print "%s: Aquired %s lock: %s" % (name, lt, lock) print("%s: Aquired %s lock: %s" % (name, lt, lock))
time.sleep(sleepTime) time.sleep(sleepTime)
self.env.lock_put(lock) self.env.lock_put(lock)
if verbose: if verbose:
print "%s: Released %s lock: %s" % (name, lt, lock) print("%s: Released %s lock: %s" % (name, lt, lock))
#---------------------------------------------------------------------- #----------------------------------------------------------------------

View file

@ -34,15 +34,15 @@ def test01_basic(self):
# Basic Queue tests using the deprecated DBCursor.consume method. # Basic Queue tests using the deprecated DBCursor.consume method.
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test01_basic..." % self.__class__.__name__ print("Running %s.test01_basic..." % self.__class__.__name__)
d = db.DB() d = db.DB()
d.set_re_len(40) # Queues must be fixed length d.set_re_len(40) # Queues must be fixed length
d.open(self.filename, db.DB_QUEUE, db.DB_CREATE) d.open(self.filename, db.DB_QUEUE, db.DB_CREATE)
if verbose: if verbose:
print "before appends" + '-' * 30 print("before appends" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
for x in string.letters: for x in string.letters:
@ -58,7 +58,7 @@ def test01_basic(self):
assert len(d) == 55 assert len(d) == 55
if verbose: if verbose:
print "before close" + '-' * 30 print("before close" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
d.close() d.close()
@ -67,25 +67,25 @@ def test01_basic(self):
d.open(self.filename) d.open(self.filename)
if verbose: if verbose:
print "after open" + '-' * 30 print("after open" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
d.append("one more") d.append("one more")
c = d.cursor() c = d.cursor()
if verbose: if verbose:
print "after append" + '-' * 30 print("after append" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
rec = c.consume() rec = c.consume()
while rec: while rec:
if verbose: if verbose:
print rec print(rec)
rec = c.consume() rec = c.consume()
c.close() c.close()
if verbose: if verbose:
print "after consume loop" + '-' * 30 print("after consume loop" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
assert len(d) == 0, \ assert len(d) == 0, \
@ -101,12 +101,12 @@ def test02_basicPost32(self):
# (No cursor needed) # (No cursor needed)
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test02_basicPost32..." % self.__class__.__name__ print("Running %s.test02_basicPost32..." % self.__class__.__name__)
if db.version() < (3, 2, 0): if db.version() < (3, 2, 0):
if verbose: if verbose:
print "Test not run, DB not new enough..." print("Test not run, DB not new enough...")
return return
d = db.DB() d = db.DB()
@ -114,7 +114,7 @@ def test02_basicPost32(self):
d.open(self.filename, db.DB_QUEUE, db.DB_CREATE) d.open(self.filename, db.DB_QUEUE, db.DB_CREATE)
if verbose: if verbose:
print "before appends" + '-' * 30 print("before appends" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
for x in string.letters: for x in string.letters:
@ -130,7 +130,7 @@ def test02_basicPost32(self):
assert len(d) == 55 assert len(d) == 55
if verbose: if verbose:
print "before close" + '-' * 30 print("before close" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
d.close() d.close()
@ -140,23 +140,23 @@ def test02_basicPost32(self):
#d.set_get_returns_none(true) #d.set_get_returns_none(true)
if verbose: if verbose:
print "after open" + '-' * 30 print("after open" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
d.append("one more") d.append("one more")
if verbose: if verbose:
print "after append" + '-' * 30 print("after append" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
rec = d.consume() rec = d.consume()
while rec: while rec:
if verbose: if verbose:
print rec print(rec)
rec = d.consume() rec = d.consume()
if verbose: if verbose:
print "after consume loop" + '-' * 30 print("after consume loop" + '-' * 30)
pprint(d.stat()) pprint(d.stat())
d.close() d.close()

View file

@ -45,9 +45,9 @@ def test01_basic(self):
assert type(recno) == type(0) assert type(recno) == type(0)
assert recno >= 1 assert recno >= 1
if verbose: if verbose:
print recno, print(recno, end=' ')
if verbose: print if verbose: print()
stat = d.stat() stat = d.stat()
if verbose: if verbose:
@ -56,7 +56,7 @@ def test01_basic(self):
for recno in range(1, len(d)+1): for recno in range(1, len(d)+1):
data = d[recno] data = d[recno]
if verbose: if verbose:
print data print(data)
assert type(data) == type("") assert type(data) == type("")
assert data == d.get(recno) assert data == d.get(recno)
@ -65,7 +65,7 @@ def test01_basic(self):
data = d[0] # This should raise a KeyError!?!?! data = d[0] # This should raise a KeyError!?!?!
except db.DBInvalidArgError as val: except db.DBInvalidArgError as val:
assert val[0] == db.EINVAL assert val[0] == db.EINVAL
if verbose: print val if verbose: print(val)
else: else:
self.fail("expected exception") self.fail("expected exception")
@ -94,7 +94,7 @@ def test01_basic(self):
keys = d.keys() keys = d.keys()
if verbose: if verbose:
print keys print(keys)
assert type(keys) == type([]) assert type(keys) == type([])
assert type(keys[0]) == type(123) assert type(keys[0]) == type(123)
assert len(keys) == len(d) assert len(keys) == len(d)
@ -120,23 +120,23 @@ def test01_basic(self):
data = d.get_both(26, "z" * 60) data = d.get_both(26, "z" * 60)
assert data == "z" * 60 assert data == "z" * 60
if verbose: if verbose:
print data print(data)
fd = d.fd() fd = d.fd()
if verbose: if verbose:
print fd print(fd)
c = d.cursor() c = d.cursor()
rec = c.first() rec = c.first()
while rec: while rec:
if verbose: if verbose:
print rec print(rec)
rec = c.next() rec = c.next()
c.set(50) c.set(50)
rec = c.current() rec = c.current()
if verbose: if verbose:
print rec print(rec)
c.put(-1, "a replacement record", db.DB_CURRENT) c.put(-1, "a replacement record", db.DB_CURRENT)
@ -144,18 +144,18 @@ def test01_basic(self):
rec = c.current() rec = c.current()
assert rec == (50, "a replacement record") assert rec == (50, "a replacement record")
if verbose: if verbose:
print rec print(rec)
rec = c.set_range(30) rec = c.set_range(30)
if verbose: if verbose:
print rec print(rec)
# test that non-existant key lookups work (and that # test that non-existant key lookups work (and that
# DBC_set_range doesn't have a memleak under valgrind) # DBC_set_range doesn't have a memleak under valgrind)
rec = c.set_range(999999) rec = c.set_range(999999)
assert rec == None assert rec == None
if verbose: if verbose:
print rec print(rec)
c.close() c.close()
d.close() d.close()
@ -182,7 +182,7 @@ def test01_basic(self):
self.fail("unexpected DBKeyEmptyError exception") self.fail("unexpected DBKeyEmptyError exception")
else: else:
assert val[0] == db.DB_KEYEMPTY assert val[0] == db.DB_KEYEMPTY
if verbose: print val if verbose: print(val)
else: else:
if not get_returns_none: if not get_returns_none:
self.fail("expected exception") self.fail("expected exception")
@ -190,7 +190,7 @@ def test01_basic(self):
rec = c.set(40) rec = c.set(40)
while rec: while rec:
if verbose: if verbose:
print rec print(rec)
rec = c.next() rec = c.next()
c.close() c.close()
@ -227,9 +227,9 @@ def test02_WithSource(self):
text = open(source, 'r').read() text = open(source, 'r').read()
text = text.strip() text = text.strip()
if verbose: if verbose:
print text print(text)
print data print(data)
print text.split('\n') print(text.split('\n'))
assert text.split('\n') == data assert text.split('\n') == data
@ -247,8 +247,8 @@ def test02_WithSource(self):
text = open(source, 'r').read() text = open(source, 'r').read()
text = text.strip() text = text.strip()
if verbose: if verbose:
print text print(text)
print text.split('\n') print(text.split('\n'))
assert text.split('\n') == \ assert text.split('\n') == \
"The quick reddish-brown fox jumped over the comatose dog".split() "The quick reddish-brown fox jumped over the comatose dog".split()
@ -269,7 +269,7 @@ def test03_FixedLength(self):
d.append('bad' * 20) d.append('bad' * 20)
except db.DBInvalidArgError as val: except db.DBInvalidArgError as val:
assert val[0] == db.EINVAL assert val[0] == db.EINVAL
if verbose: print val if verbose: print(val)
else: else:
self.fail("expected exception") self.fail("expected exception")
@ -277,7 +277,7 @@ def test03_FixedLength(self):
rec = c.first() rec = c.first()
while rec: while rec:
if verbose: if verbose:
print rec print(rec)
rec = c.next() rec = c.next()
c.close() c.close()

View file

@ -93,9 +93,9 @@ class ConcurrentDataStoreBase(BaseThreadedTestCase):
def test01_1WriterMultiReaders(self): def test01_1WriterMultiReaders(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test01_1WriterMultiReaders..." % \ print("Running %s.test01_1WriterMultiReaders..." % \
self.__class__.__name__ self.__class__.__name__)
threads = [] threads = []
for x in range(self.writers): for x in range(self.writers):
@ -123,17 +123,17 @@ def writerThread(self, d, howMany, writerNum):
start = howMany * writerNum start = howMany * writerNum
stop = howMany * (writerNum + 1) - 1 stop = howMany * (writerNum + 1) - 1
if verbose: 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): for x in range(start, stop):
key = '%04d' % x key = '%04d' % x
dbutils.DeadlockWrap(d.put, key, self.makeData(key), dbutils.DeadlockWrap(d.put, key, self.makeData(key),
max_retries=12) max_retries=12)
if verbose and x % 100 == 0: 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: 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... ## # Each write-cursor will be exclusive, the only one that can update the DB...
## if verbose: print "%s: deleting a few records" % name ## if verbose: print "%s: deleting a few records" % name
@ -147,7 +147,7 @@ def writerThread(self, d, howMany, writerNum):
## c.close() ## c.close()
if verbose: if verbose:
print "%s: thread finished" % name print("%s: thread finished" % name)
def readerThread(self, d, readerNum): def readerThread(self, d, readerNum):
time.sleep(0.01 * readerNum) time.sleep(0.01 * readerNum)
@ -163,12 +163,12 @@ def readerThread(self, d, readerNum):
self.assertEqual(self.makeData(key), data) self.assertEqual(self.makeData(key), data)
rec = c.next() rec = c.next()
if verbose: if verbose:
print "%s: found %d records" % (name, count) print("%s: found %d records" % (name, count))
c.close() c.close()
time.sleep(0.05) time.sleep(0.05)
if verbose: if verbose:
print "%s: thread finished" % name print("%s: thread finished" % name)
class BTreeConcurrentDataStore(ConcurrentDataStoreBase): class BTreeConcurrentDataStore(ConcurrentDataStoreBase):
@ -199,8 +199,8 @@ def setEnvOpts(self):
def test02_SimpleLocks(self): def test02_SimpleLocks(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test02_SimpleLocks..." % self.__class__.__name__ print("Running %s.test02_SimpleLocks..." % self.__class__.__name__)
threads = [] threads = []
for x in range(self.writers): for x in range(self.writers):
@ -226,7 +226,7 @@ def writerThread(self, d, howMany, writerNum):
start = howMany * writerNum start = howMany * writerNum
stop = howMany * (writerNum + 1) - 1 stop = howMany * (writerNum + 1) - 1
if verbose: 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 # create a bunch of records
for x in xrange(start, stop): for x in xrange(start, stop):
@ -235,7 +235,7 @@ def writerThread(self, d, howMany, writerNum):
max_retries=12) max_retries=12)
if verbose and x % 100 == 0: 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 # do a bit or reading too
if random() <= 0.05: if random() <= 0.05:
@ -249,22 +249,22 @@ def writerThread(self, d, howMany, writerNum):
dbutils.DeadlockWrap(d.sync, max_retries=12) dbutils.DeadlockWrap(d.sync, max_retries=12)
except db.DBIncompleteError as val: except db.DBIncompleteError as val:
if verbose: if verbose:
print "could not complete sync()..." print("could not complete sync()...")
# read them back, deleting a few # read them back, deleting a few
for x in xrange(start, stop): for x in xrange(start, stop):
key = '%04d' % x key = '%04d' % x
data = dbutils.DeadlockWrap(d.get, key, max_retries=12) data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
if verbose and x % 100 == 0: 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)) self.assertEqual(data, self.makeData(key))
if random() <= 0.10: if random() <= 0.10:
dbutils.DeadlockWrap(d.delete, key, max_retries=12) dbutils.DeadlockWrap(d.delete, key, max_retries=12)
if verbose: if verbose:
print "%s: deleted record %s" % (name, key) print("%s: deleted record %s" % (name, key))
if verbose: if verbose:
print "%s: thread finished" % name print("%s: thread finished" % name)
def readerThread(self, d, readerNum): def readerThread(self, d, readerNum):
time.sleep(0.01 * readerNum) time.sleep(0.01 * readerNum)
@ -280,12 +280,12 @@ def readerThread(self, d, readerNum):
self.assertEqual(self.makeData(key), data) self.assertEqual(self.makeData(key), data)
rec = dbutils.DeadlockWrap(c.next, max_retries=10) rec = dbutils.DeadlockWrap(c.next, max_retries=10)
if verbose: if verbose:
print "%s: found %d records" % (name, count) print("%s: found %d records" % (name, count))
c.close() c.close()
time.sleep(0.05) time.sleep(0.05)
if verbose: if verbose:
print "%s: thread finished" % name print("%s: thread finished" % name)
class BTreeSimpleThreaded(SimpleThreadedBase): class BTreeSimpleThreaded(SimpleThreadedBase):
@ -318,9 +318,9 @@ def setEnvOpts(self):
def test03_ThreadedTransactions(self): def test03_ThreadedTransactions(self):
if verbose: if verbose:
print '\n', '-=' * 30 print('\n', '-=' * 30)
print "Running %s.test03_ThreadedTransactions..." % \ print("Running %s.test03_ThreadedTransactions..." % \
self.__class__.__name__ self.__class__.__name__)
threads = [] threads = []
for x in range(self.writers): for x in range(self.writers):
@ -357,12 +357,12 @@ def doWrite(self, d, name, start, stop):
key = '%04d' % x key = '%04d' % x
d.put(key, self.makeData(key), txn) d.put(key, self.makeData(key), txn)
if verbose and x % 100 == 0: 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() txn.commit()
finished = True finished = True
except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val:
if verbose: if verbose:
print "%s: Aborting transaction (%s)" % (name, val[1]) print("%s: Aborting transaction (%s)" % (name, val[1]))
txn.abort() txn.abort()
time.sleep(0.05) time.sleep(0.05)
@ -371,16 +371,16 @@ def writerThread(self, d, howMany, writerNum):
start = howMany * writerNum start = howMany * writerNum
stop = howMany * (writerNum + 1) - 1 stop = howMany * (writerNum + 1) - 1
if verbose: if verbose:
print "%s: creating records %d - %d" % (name, start, stop) print("%s: creating records %d - %d" % (name, start, stop))
step = 100 step = 100
for x in range(start, stop, step): for x in range(start, stop, step):
self.doWrite(d, name, x, min(stop, x+step)) self.doWrite(d, name, x, min(stop, x+step))
if verbose: if verbose:
print "%s: finished creating records" % name print("%s: finished creating records" % name)
if verbose: if verbose:
print "%s: deleting a few records" % name print("%s: deleting a few records" % name)
finished = False finished = False
while not finished: while not finished:
@ -397,15 +397,15 @@ def writerThread(self, d, howMany, writerNum):
txn.commit() txn.commit()
finished = True finished = True
if verbose: if verbose:
print "%s: deleted records %s" % (name, recs) print("%s: deleted records %s" % (name, recs))
except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val:
if verbose: if verbose:
print "%s: Aborting transaction (%s)" % (name, val[1]) print("%s: Aborting transaction (%s)" % (name, val[1]))
txn.abort() txn.abort()
time.sleep(0.05) time.sleep(0.05)
if verbose: if verbose:
print "%s: thread finished" % name print("%s: thread finished" % name)
def readerThread(self, d, readerNum): def readerThread(self, d, readerNum):
time.sleep(0.01 * readerNum + 0.05) time.sleep(0.01 * readerNum + 0.05)
@ -424,13 +424,13 @@ def readerThread(self, d, readerNum):
key, data = rec key, data = rec
self.assertEqual(self.makeData(key), data) self.assertEqual(self.makeData(key), data)
rec = c.next() rec = c.next()
if verbose: print "%s: found %d records" % (name, count) if verbose: print("%s: found %d records" % (name, count))
c.close() c.close()
txn.commit() txn.commit()
finished = True finished = True
except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val:
if verbose: if verbose:
print "%s: Aborting transaction (%s)" % (name, val[1]) print("%s: Aborting transaction (%s)" % (name, val[1]))
c.close() c.close()
txn.abort() txn.abort()
time.sleep(0.05) time.sleep(0.05)
@ -438,7 +438,7 @@ def readerThread(self, d, readerNum):
time.sleep(0.05) time.sleep(0.05)
if verbose: if verbose:
print "%s: thread finished" % name print("%s: thread finished" % name)
def deadlockThread(self): def deadlockThread(self):
self.doLockDetect = True self.doLockDetect = True
@ -448,8 +448,8 @@ def deadlockThread(self):
aborted = self.env.lock_detect( aborted = self.env.lock_detect(
db.DB_LOCK_RANDOM, db.DB_LOCK_CONFLICT) db.DB_LOCK_RANDOM, db.DB_LOCK_CONFLICT)
if verbose and aborted: if verbose and aborted:
print "deadlock: Aborted %d deadlocked transaction(s)" \ print("deadlock: Aborted %d deadlocked transaction(s)" \
% aborted % aborted)
except db.DBError: except db.DBError:
pass pass
@ -497,7 +497,7 @@ def test_suite():
suite.addTest(unittest.makeSuite(HashThreadedNoWaitTransactions)) suite.addTest(unittest.makeSuite(HashThreadedNoWaitTransactions))
else: else:
print "Threads not available, skipping thread tests." print("Threads not available, skipping thread tests.")
return suite return suite

View file

@ -58,8 +58,8 @@ def runctx(statement, globals, locals, filename=None):
# Backwards compatibility. # Backwards compatibility.
def help(): def help():
print "Documentation for the profile/cProfile modules can be found " print("Documentation for the profile/cProfile modules can be found ")
print "in the Python Library Reference, section 'The Python Profiler'." print("in the Python Library Reference, section 'The Python Profiler'.")
# ____________________________________________________________ # ____________________________________________________________

View file

@ -261,7 +261,7 @@ def prweek(self, theweek, width):
""" """
Print a single week (no newline). Print a single week (no newline).
""" """
print self.week(theweek, width), print(self.week(theweek, width), end=' ')
def formatday(self, day, weekday, width): def formatday(self, day, weekday, width):
""" """
@ -308,7 +308,7 @@ def prmonth(self, theyear, themonth, w=0, l=0):
""" """
Print a month's 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): def formatmonth(self, theyear, themonth, w=0, l=0):
""" """
@ -365,7 +365,7 @@ def formatyear(self, theyear, w=2, l=1, c=6, m=3):
def pryear(self, theyear, w=0, l=0, c=6, m=3): def pryear(self, theyear, w=0, l=0, c=6, m=3):
"""Print a year's calendar.""" """Print a year's calendar."""
print self.formatyear(theyear, w, l, c, m) print(self.formatyear(theyear, w, l, c, m))
class HTMLCalendar(Calendar): class HTMLCalendar(Calendar):
@ -584,7 +584,7 @@ def setfirstweekday(firstweekday):
def format(cols, colwidth=_colwidth, spacing=_spacing): def format(cols, colwidth=_colwidth, spacing=_spacing):
"""Prints multi-column formatting for year calendars""" """Prints multi-column formatting for year calendars"""
print formatstring(cols, colwidth, spacing) print(formatstring(cols, colwidth, spacing))
def formatstring(cols, colwidth=_colwidth, spacing=_spacing): def formatstring(cols, colwidth=_colwidth, spacing=_spacing):
@ -668,9 +668,9 @@ def main(args):
encoding = sys.getdefaultencoding() encoding = sys.getdefaultencoding()
optdict = dict(encoding=encoding, css=options.css) optdict = dict(encoding=encoding, css=options.css)
if len(args) == 1: if len(args) == 1:
print cal.formatyearpage(datetime.date.today().year, **optdict) print(cal.formatyearpage(datetime.date.today().year, **optdict))
elif len(args) == 2: elif len(args) == 2:
print cal.formatyearpage(int(args[1]), **optdict) print(cal.formatyearpage(int(args[1]), **optdict))
else: else:
parser.error("incorrect number of arguments") parser.error("incorrect number of arguments")
sys.exit(1) sys.exit(1)
@ -694,7 +694,7 @@ def main(args):
sys.exit(1) sys.exit(1)
if options.encoding: if options.encoding:
result = result.encode(options.encoding) result = result.encode(options.encoding)
print result print(result)
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -901,8 +901,8 @@ def test(environ=os.environ):
the script in HTML form. the script in HTML form.
""" """
print "Content-type: text/html" print("Content-type: text/html")
print print()
sys.stderr = sys.stdout sys.stderr = sys.stdout
try: try:
form = FieldStorage() # Replace with other classes to test those form = FieldStorage() # Replace with other classes to test those
@ -915,12 +915,12 @@ def f():
exec("testing print_exception() -- <I>italics?</I>") exec("testing print_exception() -- <I>italics?</I>")
def g(f=f): def g(f=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() g()
except: except:
print_exception() print_exception()
print "<H1>Second try with a small maxlen...</H1>" print("<H1>Second try with a small maxlen...</H1>")
global maxlen global maxlen
maxlen = 50 maxlen = 50
@ -937,67 +937,67 @@ def print_exception(type=None, value=None, tb=None, limit=None):
if type is None: if type is None:
type, value, tb = sys.exc_info() type, value, tb = sys.exc_info()
import traceback import traceback
print print()
print "<H3>Traceback (most recent call last):</H3>" print("<H3>Traceback (most recent call last):</H3>")
list = traceback.format_tb(tb, limit) + \ list = traceback.format_tb(tb, limit) + \
traceback.format_exception_only(type, value) 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("".join(list[:-1])),
escape(list[-1]), escape(list[-1]),
) ))
del tb del tb
def print_environ(environ=os.environ): def print_environ(environ=os.environ):
"""Dump the shell environment as HTML.""" """Dump the shell environment as HTML."""
keys = environ.keys() keys = environ.keys()
keys.sort() keys.sort()
print print()
print "<H3>Shell Environment:</H3>" print("<H3>Shell Environment:</H3>")
print "<DL>" print("<DL>")
for key in keys: for key in keys:
print "<DT>", escape(key), "<DD>", escape(environ[key]) print("<DT>", escape(key), "<DD>", escape(environ[key]))
print "</DL>" print("</DL>")
print print()
def print_form(form): def print_form(form):
"""Dump the contents of a form as HTML.""" """Dump the contents of a form as HTML."""
keys = form.keys() keys = form.keys()
keys.sort() keys.sort()
print print()
print "<H3>Form Contents:</H3>" print("<H3>Form Contents:</H3>")
if not keys: if not keys:
print "<P>No form fields." print("<P>No form fields.")
print "<DL>" print("<DL>")
for key in keys: for key in keys:
print "<DT>" + escape(key) + ":", print("<DT>" + escape(key) + ":", end=' ')
value = form[key] value = form[key]
print "<i>" + escape(repr(type(value))) + "</i>" print("<i>" + escape(repr(type(value))) + "</i>")
print "<DD>" + escape(repr(value)) print("<DD>" + escape(repr(value)))
print "</DL>" print("</DL>")
print print()
def print_directory(): def print_directory():
"""Dump the current directory as HTML.""" """Dump the current directory as HTML."""
print print()
print "<H3>Current Working Directory:</H3>" print("<H3>Current Working Directory:</H3>")
try: try:
pwd = os.getcwd() pwd = os.getcwd()
except os.error as msg: except os.error as msg:
print "os.error:", escape(str(msg)) print("os.error:", escape(str(msg)))
else: else:
print escape(pwd) print(escape(pwd))
print print()
def print_arguments(): def print_arguments():
print print()
print "<H3>Command Line Arguments:</H3>" print("<H3>Command Line Arguments:</H3>")
print print()
print sys.argv print(sys.argv)
print print()
def print_environ_usage(): def print_environ_usage():
"""Dump a list of environment variables used by CGI as HTML.""" """Dump a list of environment variables used by CGI as HTML."""
print """ print("""
<H3>These environment variables could have been set:</H3> <H3>These environment variables could have been set:</H3>
<UL> <UL>
<LI>AUTH_TYPE <LI>AUTH_TYPE
@ -1036,7 +1036,7 @@ def print_environ_usage():
<LI>HTTP_REFERER <LI>HTTP_REFERER
<LI>HTTP_USER_AGENT <LI>HTTP_USER_AGENT
</UL> </UL>
""" """)
# Utilities # Utilities

View file

@ -107,7 +107,7 @@ def runcode(self, code):
self.showtraceback() self.showtraceback()
else: else:
if softspace(sys.stdout, 0): if softspace(sys.stdout, 0):
print print()
def showsyntaxerror(self, filename=None): def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred. """Display the syntax error that just occurred.

View file

@ -33,11 +33,11 @@ def compile_dir(dir, maxlevels=10, ddir=None,
""" """
if not quiet: if not quiet:
print 'Listing', dir, '...' print('Listing', dir, '...')
try: try:
names = os.listdir(dir) names = os.listdir(dir)
except os.error: except os.error:
print "Can't list", dir print("Can't list", dir)
names = [] names = []
names.sort() names.sort()
success = 1 success = 1
@ -60,18 +60,18 @@ def compile_dir(dir, maxlevels=10, ddir=None,
except os.error: ctime = 0 except os.error: ctime = 0
if (ctime > ftime) and not force: continue if (ctime > ftime) and not force: continue
if not quiet: if not quiet:
print 'Compiling', fullname, '...' print('Compiling', fullname, '...')
try: try:
ok = py_compile.compile(fullname, None, dfile, True) ok = py_compile.compile(fullname, None, dfile, True)
except KeyboardInterrupt: except KeyboardInterrupt:
raise KeyboardInterrupt raise KeyboardInterrupt
except py_compile.PyCompileError as err: except py_compile.PyCompileError as err:
if quiet: if quiet:
print 'Compiling', fullname, '...' print('Compiling', fullname, '...')
print err.msg print(err.msg)
success = 0 success = 0
except IOError as e: except IOError as e:
print "Sorry", e print("Sorry", e)
success = 0 success = 0
else: else:
if ok == 0: if ok == 0:
@ -98,7 +98,7 @@ def compile_path(skip_curdir=1, maxlevels=0, force=0, quiet=0):
success = 1 success = 1
for dir in sys.path: for dir in sys.path:
if (not dir or dir == os.curdir) and skip_curdir: if (not dir or dir == os.curdir) and skip_curdir:
print 'Skipping current directory' print('Skipping current directory')
else: else:
success = success and compile_dir(dir, maxlevels, None, success = success and compile_dir(dir, maxlevels, None,
force, quiet=quiet) force, quiet=quiet)
@ -110,16 +110,16 @@ def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:') opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:')
except getopt.error as msg: except getopt.error as msg:
print msg print(msg)
print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ print("usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
"[-x regexp] [directory ...]" "[-x regexp] [directory ...]")
print "-l: don't recurse down" print("-l: don't recurse down")
print "-f: force rebuild even if timestamps are up-to-date" print("-f: force rebuild even if timestamps are up-to-date")
print "-q: quiet operation" print("-q: quiet operation")
print "-d destdir: purported directory name for error messages" print("-d destdir: purported directory name for error messages")
print " if no directory arguments, -l sys.path is assumed" print(" if no directory arguments, -l sys.path is assumed")
print "-x regexp: skip files matching the regular expression regexp" print("-x regexp: skip files matching the regular expression regexp")
print " the regexp is search for in the full path of the file" print(" the regexp is search for in the full path of the file")
sys.exit(2) sys.exit(2)
maxlevels = 10 maxlevels = 10
ddir = None ddir = None
@ -136,7 +136,7 @@ def main():
rx = re.compile(a) rx = re.compile(a)
if ddir: if ddir:
if len(args) != 1: if len(args) != 1:
print "-d destdir require exactly one directory argument" print("-d destdir require exactly one directory argument")
sys.exit(2) sys.exit(2)
success = 1 success = 1
try: try:
@ -148,7 +148,7 @@ def main():
else: else:
success = compile_path() success = compile_path()
except KeyboardInterrupt: except KeyboardInterrupt:
print "\n[interrupt]" print("\n[interrupt]")
success = 0 success = 0
return success return success

View file

@ -65,9 +65,9 @@ def find_futures(node):
from compiler import parseFile, walk from compiler import parseFile, walk
for file in sys.argv[1:]: for file in sys.argv[1:]:
print file print(file)
tree = parseFile(file) tree = parseFile(file)
v = FutureParser() v = FutureParser()
walk(tree, v) walk(tree, v)
print v.found print(v.found)
print print()

View file

@ -19,10 +19,10 @@ def __init__(self):
def startBlock(self, block): def startBlock(self, block):
if self._debug: if self._debug:
if self.current: if self.current:
print "end", repr(self.current) print("end", repr(self.current))
print " next", self.current.next print(" next", self.current.next)
print " ", self.current.get_children() print(" ", self.current.get_children())
print repr(block) print(repr(block))
self.current = block self.current = block
def nextBlock(self, block=None): def nextBlock(self, block=None):
@ -68,7 +68,7 @@ def _disable_debug(self):
def emit(self, *inst): def emit(self, *inst):
if self._debug: if self._debug:
print "\t", inst print("\t", inst)
if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']: if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']:
self.current.addOutEdge(self.exit) self.current.addOutEdge(self.exit)
if len(inst) == 2 and isinstance(inst[1], Block): if len(inst) == 2 and isinstance(inst[1], Block):
@ -400,12 +400,12 @@ def dump(self, io=None):
for t in self.insts: for t in self.insts:
opname = t[0] opname = t[0]
if opname == "SET_LINENO": if opname == "SET_LINENO":
print print()
if len(t) == 1: if len(t) == 1:
print "\t", "%3d" % pc, opname print("\t", "%3d" % pc, opname)
pc = pc + 1 pc = pc + 1
else: else:
print "\t", "%3d" % pc, opname, t[1] print("\t", "%3d" % pc, opname, t[1])
pc = pc + 3 pc = pc + 3
if io: if io:
sys.stdout = save sys.stdout = save
@ -601,8 +601,8 @@ def makeByteCode(self):
try: try:
lnotab.addCode(self.opnum[opname], lo, hi) lnotab.addCode(self.opnum[opname], lo, hi)
except ValueError: except ValueError:
print opname, oparg print(opname, oparg)
print self.opnum[opname], lo, hi print(self.opnum[opname], lo, hi)
raise raise
self.stage = DONE self.stage = DONE
@ -744,7 +744,7 @@ def findDepth(self, insts, debug=0):
for i in insts: for i in insts:
opname = i[0] opname = i[0]
if debug: if debug:
print i, print(i, end=' ')
delta = self.effect.get(opname, None) delta = self.effect.get(opname, None)
if delta is not None: if delta is not None:
depth = depth + delta depth = depth + delta
@ -763,7 +763,7 @@ def findDepth(self, insts, debug=0):
if depth > maxDepth: if depth > maxDepth:
maxDepth = depth maxDepth = depth
if debug: if debug:
print depth, maxDepth print(depth, maxDepth)
return maxDepth return maxDepth
effect = { effect = {

View file

@ -112,7 +112,7 @@ def compile(self, display=0):
gen = ModuleCodeGenerator(tree) gen = ModuleCodeGenerator(tree)
if display: if display:
import pprint import pprint
print pprint.pprint(tree) print(pprint.pprint(tree))
self.code = gen.getCode() self.code = gen.getCode()
def dump(self, f): def dump(self, f):
@ -1018,7 +1018,7 @@ def visitAssName(self, node):
self.set_lineno(node) self.set_lineno(node)
self.delName(node.name) self.delName(node.name)
else: else:
print "oops", node.flags print("oops", node.flags)
def visitAssAttr(self, node): def visitAssAttr(self, node):
self.visit(node.expr) self.visit(node.expr)
@ -1027,8 +1027,8 @@ def visitAssAttr(self, node):
elif node.flags == 'OP_DELETE': elif node.flags == 'OP_DELETE':
self.emit('DELETE_ATTR', self.mangle(node.attrname)) self.emit('DELETE_ATTR', self.mangle(node.attrname))
else: else:
print "warning: unexpected flags:", node.flags print("warning: unexpected flags:", node.flags)
print node print(node)
def _visitAssSequence(self, node, op='UNPACK_SEQUENCE'): def _visitAssSequence(self, node, op='UNPACK_SEQUENCE'):
if findOp(node) != 'OP_DELETE': if findOp(node) != 'OP_DELETE':
@ -1189,7 +1189,7 @@ def visitSlice(self, node, aug_flag=None):
elif node.flags == 'OP_DELETE': elif node.flags == 'OP_DELETE':
self.emit('DELETE_SLICE+%d' % slice) self.emit('DELETE_SLICE+%d' % slice)
else: else:
print "weird slice", node.flags print("weird slice", node.flags)
raise raise
def visitSubscript(self, node, aug_flag=None): def visitSubscript(self, node, aug_flag=None):

View file

@ -76,12 +76,12 @@ def get_children(self):
return self.children return self.children
def DEBUG(self): def DEBUG(self):
print >> sys.stderr, self.name, self.nested and "nested" or "" print(self.name, self.nested and "nested" or "", file=sys.stderr)
print >> sys.stderr, "\tglobals: ", self.globals print("\tglobals: ", self.globals, file=sys.stderr)
print >> sys.stderr, "\tcells: ", self.cells print("\tcells: ", self.cells, file=sys.stderr)
print >> sys.stderr, "\tdefs: ", self.defs print("\tdefs: ", self.defs, file=sys.stderr)
print >> sys.stderr, "\tuses: ", self.uses print("\tuses: ", self.uses, file=sys.stderr)
print >> sys.stderr, "\tfrees:", self.frees print("\tfrees:", self.frees, file=sys.stderr)
def check_name(self, name): def check_name(self, name):
"""Return scope of name. """Return scope of name.
@ -429,7 +429,7 @@ def get_names(syms):
if not (s.startswith('_[') or s.startswith('.'))] if not (s.startswith('_[') or s.startswith('.'))]
for file in sys.argv[1:]: for file in sys.argv[1:]:
print file print(file)
f = open(file) f = open(file)
buf = f.read() buf = f.read()
f.close() f.close()
@ -443,10 +443,10 @@ def get_names(syms):
names2 = s.scopes[tree].get_names() names2 = s.scopes[tree].get_names()
if not list_eq(mod_names, names2): if not list_eq(mod_names, names2):
print print()
print "oops", file print("oops", file)
print sorted(mod_names) print(sorted(mod_names))
print sorted(names2) print(sorted(names2))
sys.exit(-1) sys.exit(-1)
d = {} d = {}
@ -460,11 +460,11 @@ def get_names(syms):
l = [sc for sc in scopes l = [sc for sc in scopes
if sc.name == s.get_name()] if sc.name == s.get_name()]
if len(l) > 1: if len(l) > 1:
print "skipping", s.get_name() print("skipping", s.get_name())
else: else:
if not list_eq(get_names(s.get_namespace()), if not list_eq(get_names(s.get_namespace()),
l[0].get_names()): l[0].get_names()):
print s.get_name() print(s.get_name())
print sorted(get_names(s.get_namespace())) print(sorted(get_names(s.get_namespace())))
print sorted(l[0].get_names()) print(sorted(l[0].get_names()))
sys.exit(-1) sys.exit(-1)

View file

@ -32,7 +32,7 @@ def __init__(self, multi=None):
def error(self, node, msg): def error(self, node, msg):
self.errors = self.errors + 1 self.errors = self.errors + 1
if self.multi is not None: 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: else:
raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno)

View file

@ -86,7 +86,7 @@ def Node(*args):
try: try:
return nodes[kind](*args[1:]) return nodes[kind](*args[1:])
except TypeError: except TypeError:
print nodes[kind], len(args), args print(nodes[kind], len(args), args)
raise raise
else: else:
raise WalkerError, "Can't find appropriate Node type: %s" % str(args) raise WalkerError, "Can't find appropriate Node type: %s" % str(args)

View file

@ -79,20 +79,20 @@ def dispatch(self, node, *args):
meth = getattr(self.visitor, 'visit' + className, 0) meth = getattr(self.visitor, 'visit' + className, 0)
self._cache[node.__class__] = meth self._cache[node.__class__] = meth
if self.VERBOSE > 1: if self.VERBOSE > 1:
print "dispatch", className, (meth and meth.__name__ or '') print("dispatch", className, (meth and meth.__name__ or ''))
if meth: if meth:
meth(node, *args) meth(node, *args)
elif self.VERBOSE > 0: elif self.VERBOSE > 0:
klass = node.__class__ klass = node.__class__
if klass not in self.examples: if klass not in self.examples:
self.examples[klass] = klass self.examples[klass] = klass
print print()
print self.visitor print(self.visitor)
print klass print(klass)
for attr in dir(node): for attr in dir(node):
if attr[0] != '_': if attr[0] != '_':
print "\t", "%-12.12s" % attr, getattr(node, attr) print("\t", "%-12.12s" % attr, getattr(node, attr))
print print()
return self.default(node, *args) return self.default(node, *args)
# XXX this is an API change # XXX this is an API change
@ -107,7 +107,7 @@ def walk(tree, visitor, walker=None, verbose=None):
return walker.visitor return walker.visitor
def dumpNode(node): def dumpNode(node):
print node.__class__ print(node.__class__)
for attr in dir(node): for attr in dir(node):
if attr[0] != '_': if attr[0] != '_':
print "\t", "%-10.10s" % attr, getattr(node, attr) print("\t", "%-10.10s" % attr, getattr(node, attr))

View file

@ -318,11 +318,11 @@ def _test():
l = [None, 1, 2, 3.14, 'xyzzy', (1, 2), [3.14, 'abc'], l = [None, 1, 2, 3.14, 'xyzzy', (1, 2), [3.14, 'abc'],
{'abc': 'ABC'}, (), [], {}] {'abc': 'ABC'}, (), [], {}]
l1 = copy(l) l1 = copy(l)
print l1==l print(l1==l)
l1 = map(copy, l) l1 = map(copy, l)
print l1==l print(l1==l)
l1 = deepcopy(l) l1 = deepcopy(l)
print l1==l print(l1==l)
class C: class C:
def __init__(self, arg=None): def __init__(self, arg=None):
self.a = 1 self.a = 1
@ -346,26 +346,26 @@ def __deepcopy__(self, memo=None):
c = C('argument sketch') c = C('argument sketch')
l.append(c) l.append(c)
l2 = copy(l) l2 = copy(l)
print l == l2 print(l == l2)
print l print(l)
print l2 print(l2)
l2 = deepcopy(l) l2 = deepcopy(l)
print l == l2 print(l == l2)
print l print(l)
print l2 print(l2)
l.append({l[1]: l, 'xyz': l[2]}) l.append({l[1]: l, 'xyz': l[2]})
l3 = copy(l) l3 = copy(l)
import repr import repr
print map(repr.repr, l) print(map(repr.repr, l))
print map(repr.repr, l1) print(map(repr.repr, l1))
print map(repr.repr, l2) print(map(repr.repr, l2))
print map(repr.repr, l3) print(map(repr.repr, l3))
l3 = deepcopy(l) l3 = deepcopy(l)
import repr import repr
print map(repr.repr, l) print(map(repr.repr, l))
print map(repr.repr, l1) print(map(repr.repr, l1))
print map(repr.repr, l2) print(map(repr.repr, l2))
print map(repr.repr, l3) print(map(repr.repr, l3))
if __name__ == '__main__': if __name__ == '__main__':
_test() _test()

View file

@ -60,10 +60,10 @@ def get_tests(package, mask, verbosity):
except ResourceDenied as detail: except ResourceDenied as detail:
skipped.append(modname) skipped.append(modname)
if verbosity > 1: if verbosity > 1:
print >> sys.stderr, "Skipped %s: %s" % (modname, detail) print("Skipped %s: %s" % (modname, detail), file=sys.stderr)
continue continue
except Exception as detail: 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 continue
for name in dir(mod): for name in dir(mod):
if name.startswith("_"): if name.startswith("_"):
@ -74,7 +74,7 @@ def get_tests(package, mask, verbosity):
return skipped, tests return skipped, tests
def usage(): def usage():
print __doc__ print(__doc__)
return 1 return 1
def test_with_refcounts(runner, verbosity, testcase): def test_with_refcounts(runner, verbosity, testcase):
@ -106,9 +106,9 @@ def cleanup():
cleanup() cleanup()
refcounts[i] = sys.gettotalrefcount() - rc refcounts[i] = sys.gettotalrefcount() - rc
if filter(None, refcounts): if filter(None, refcounts):
print "%s leaks:\n\t" % testcase, refcounts print("%s leaks:\n\t" % testcase, refcounts)
elif verbosity: elif verbosity:
print "%s: ok." % testcase print("%s: ok." % testcase)
class TestRunner(unittest.TextTestRunner): class TestRunner(unittest.TextTestRunner):
def run(self, test, skipped): def run(self, test, skipped):
@ -166,7 +166,7 @@ def main(*packages):
try: try:
sys.gettotalrefcount sys.gettotalrefcount
except AttributeError: except AttributeError:
print >> sys.stderr, "-r flag requires Python debug build" print("-r flag requires Python debug build", file=sys.stderr)
return -1 return -1
search_leaks = True search_leaks = True
elif flag == "-u": elif flag == "-u":

View file

@ -15,7 +15,7 @@ def bin(s):
class Test(unittest.TestCase): class Test(unittest.TestCase):
def X_test(self): def X_test(self):
print >> sys.stderr, sys.byteorder print(sys.byteorder, file=sys.stderr)
for i in range(32): for i in range(32):
bits = BITS() bits = BITS()
setattr(bits, "i%s" % i, 1) setattr(bits, "i%s" % i, 1)

View file

@ -22,12 +22,12 @@
## print, for debugging ## print, for debugging
if is_resource_enabled("printing"): if is_resource_enabled("printing"):
if lib_gl or lib_glu or lib_glut or lib_gle: if lib_gl or lib_glu or lib_glut or lib_gle:
print "OpenGL libraries:" print("OpenGL libraries:")
for item in (("GL", lib_gl), for item in (("GL", lib_gl),
("GLU", lib_glu), ("GLU", lib_glu),
("glut", lib_glut), ("glut", lib_glut),
("gle", lib_gle)): ("gle", lib_gle)):
print "\t", item print("\t", item)
# On some systems, loading the OpenGL libraries needs the RTLD_GLOBAL mode. # On some systems, loading the OpenGL libraries needs the RTLD_GLOBAL mode.

View file

@ -100,13 +100,13 @@ class X(Structure):
x = X() x = X()
i = c_char_p("abc def") i = c_char_p("abc def")
from sys import getrefcount as grc from sys import getrefcount as grc
print "2?", grc(i) print("2?", grc(i))
x.p = pointer(i) x.p = pointer(i)
print "3?", grc(i) print("3?", grc(i))
for i in range(320): for i in range(320):
c_int(99) c_int(99)
x.p[0] x.p[0]
print x.p[0] print(x.p[0])
## del x ## del x
## print "2?", grc(i) ## print "2?", grc(i)
## del i ## del i
@ -115,14 +115,14 @@ class X(Structure):
for i in range(320): for i in range(320):
c_int(99) c_int(99)
x.p[0] x.p[0]
print x.p[0] print(x.p[0])
print x.p.contents print(x.p.contents)
## print x._objects ## print x._objects
x.p[0] = "spam spam" x.p[0] = "spam spam"
## print x.p[0] ## print x.p[0]
print "+" * 42 print("+" * 42)
print x._objects print(x._objects)
class PointerToStructure(unittest.TestCase): class PointerToStructure(unittest.TestCase):
def test(self): def test(self):

View file

@ -15,7 +15,7 @@
libc_name = find_library("c") libc_name = find_library("c")
if is_resource_enabled("printing"): if is_resource_enabled("printing"):
print "libc_name is", libc_name print("libc_name is", libc_name)
class LoaderTest(unittest.TestCase): class LoaderTest(unittest.TestCase):
@ -44,8 +44,8 @@ def test_find(self):
if os.name in ("nt", "ce"): if os.name in ("nt", "ce"):
def test_load_library(self): def test_load_library(self):
if is_resource_enabled("printing"): if is_resource_enabled("printing"):
print find_library("kernel32") print(find_library("kernel32"))
print find_library("user32") print(find_library("user32"))
if os.name == "nt": if os.name == "nt":
windll.kernel32.GetModuleHandleW windll.kernel32.GetModuleHandleW

View file

@ -192,7 +192,7 @@ def run_test(rep, msg, func, arg=None):
for i in items: for i in items:
func(); func(); func(); func(); func() func(); func(); func(); func(); func()
stop = clock() 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(): def check_perf():
# Construct 5 objects # Construct 5 objects

View file

@ -189,7 +189,7 @@ def run_test(rep, msg, func, arg):
for i in items: for i in items:
func(arg); func(arg); func(arg); func(arg); func(arg) func(arg); func(arg); func(arg); func(arg); func(arg)
stop = clock() 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(): def check_perf():
# Construct 5 objects # Construct 5 objects

View file

@ -125,15 +125,15 @@ def find_library(name):
def test(): def test():
from ctypes import cdll from ctypes import cdll
if os.name == "nt": if os.name == "nt":
print cdll.msvcrt print(cdll.msvcrt)
print cdll.load("msvcrt") print(cdll.load("msvcrt"))
print find_library("msvcrt") print(find_library("msvcrt"))
if os.name == "posix": if os.name == "posix":
# find and load_version # find and load_version
print find_library("m") print(find_library("m"))
print find_library("c") print(find_library("c"))
print find_library("bz2") print(find_library("bz2"))
# getattr # getattr
## print cdll.m ## print cdll.m
@ -141,14 +141,14 @@ def test():
# load # load
if sys.platform == "darwin": if sys.platform == "darwin":
print cdll.LoadLibrary("libm.dylib") print(cdll.LoadLibrary("libm.dylib"))
print cdll.LoadLibrary("libcrypto.dylib") print(cdll.LoadLibrary("libcrypto.dylib"))
print cdll.LoadLibrary("libSystem.dylib") print(cdll.LoadLibrary("libSystem.dylib"))
print cdll.LoadLibrary("System.framework/System") print(cdll.LoadLibrary("System.framework/System"))
else: else:
print cdll.LoadLibrary("libm.so") print(cdll.LoadLibrary("libm.so"))
print cdll.LoadLibrary("libcrypt.so") print(cdll.LoadLibrary("libcrypt.so"))
print find_library("crypt") print(find_library("crypt"))
if __name__ == "__main__": if __name__ == "__main__":
test() test()

View file

@ -189,4 +189,4 @@ def has_key(ch):
% (_curses.keyname( key ), system, python) ) % (_curses.keyname( key ), system, python) )
finally: finally:
_curses.endwin() _curses.endwin()
for i in L: print i for i in L: print(i)

View file

@ -170,4 +170,4 @@ def test_editbox(stdscr):
return Textbox(win).edit() return Textbox(win).edit()
str = curses.wrapper(test_editbox) str = curses.wrapper(test_editbox)
print 'Contents of text box:', repr(str) print('Contents of text box:', repr(str))

View file

@ -76,7 +76,7 @@ class SequenceMatcher:
sequences. As a rule of thumb, a .ratio() value over 0.6 means the sequences. As a rule of thumb, a .ratio() value over 0.6 means the
sequences are close matches: sequences are close matches:
>>> print round(s.ratio(), 3) >>> print(round(s.ratio(), 3))
0.866 0.866
>>> >>>
@ -84,7 +84,7 @@ class SequenceMatcher:
.get_matching_blocks() is handy: .get_matching_blocks() is handy:
>>> for block in s.get_matching_blocks(): >>> 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[0] and b[0] match for 8 elements
a[8] and b[17] match for 21 elements a[8] and b[17] match for 21 elements
a[29] and b[38] match for 0 elements a[29] and b[38] match for 0 elements
@ -97,7 +97,7 @@ class SequenceMatcher:
use .get_opcodes(): use .get_opcodes():
>>> for opcode in s.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] equal a[0:8] b[0:8]
insert a[8:8] b[8:17] insert a[8:8] b[8:17]
equal a[8:29] b[17:38] equal a[8:29] b[17:38]
@ -545,8 +545,8 @@ def get_opcodes(self):
>>> b = "abycdf" >>> b = "abycdf"
>>> s = SequenceMatcher(None, a, b) >>> s = SequenceMatcher(None, a, b)
>>> for tag, i1, i2, j1, j2 in s.get_opcodes(): >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])) ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
delete a[0:1] (q) b[0:0] () delete a[0:1] (q) b[0:0] ()
equal a[1:3] (ab) b[0:2] (ab) equal a[1:3] (ab) b[0:2] (ab)
replace a[3:4] (x) b[2:3] (y) 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: As a single multi-line string it looks like this:
>>> print ''.join(result), >>> print(''.join(result), end="")
1. Beautiful is better than ugly. 1. Beautiful is better than ugly.
- 2. Explicit is better than implicit. - 2. Explicit is better than implicit.
- 3. Simple is better than complex. - 3. Simple is better than complex.
@ -889,8 +889,9 @@ def compare(self, a, b):
Example: 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))), ... 'ore\ntree\nemu\n'.splitlines(1))),
... end="")
- one - one
? ^ ? ^
+ ore + ore
@ -950,7 +951,7 @@ def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
>>> d = Differ() >>> d = Differ()
>>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1, >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
... ['abcdefGhijkl\n'], 0, 1) ... ['abcdefGhijkl\n'], 0, 1)
>>> print ''.join(results), >>> print(''.join(results), end="")
- abcDefghiJkl - abcDefghiJkl
? ^ ^ ^ ? ^ ^ ^
+ abcdefGhijkl + abcdefGhijkl
@ -1058,7 +1059,7 @@ def _qformat(self, aline, bline, atags, btags):
>>> d = Differ() >>> d = Differ()
>>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n', >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n',
... ' ^ ^ ^ ', '+ ^ ^ ^ ') ... ' ^ ^ ^ ', '+ ^ ^ ^ ')
>>> for line in results: print repr(line) >>> for line in results: print(repr(line))
... ...
'- \tabcDefghiJkl\n' '- \tabcDefghiJkl\n'
'? \t ^ ^ ^\n' '? \t ^ ^ ^\n'
@ -1164,7 +1165,7 @@ def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
... 'zero one tree four'.split(), 'Original', 'Current', ... 'zero one tree four'.split(), 'Original', 'Current',
... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003',
... lineterm=''): ... lineterm=''):
... print line ... print(line)
--- Original Sat Jan 26 23:30:50 1991 --- Original Sat Jan 26 23:30:50 1991
+++ Current Fri Jun 06 10:20:52 2003 +++ Current Fri Jun 06 10:20:52 2003
@@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
@ -1223,9 +1224,10 @@ def context_diff(a, b, fromfile='', tofile='',
Example: 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', ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current',
... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')), ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')),
... end="")
*** Original Sat Jan 26 23:30:50 1991 *** Original Sat Jan 26 23:30:50 1991
--- Current Fri Jun 06 10:22:46 2003 --- 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), >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1)) ... 'ore\ntree\nemu\n'.splitlines(1))
>>> print ''.join(diff), >>> print(''.join(diff), end="")
- one - one
? ^ ? ^
+ ore + ore
@ -1992,11 +1994,11 @@ def restore(delta, which):
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1)) ... 'ore\ntree\nemu\n'.splitlines(1))
>>> diff = list(diff) >>> diff = list(diff)
>>> print ''.join(restore(diff, 1)), >>> print(''.join(restore(diff, 1)), end="")
one one
two two
three three
>>> print ''.join(restore(diff, 2)), >>> print(''.join(restore(diff, 2)), end="")
ore ore
tree tree
emu emu

View file

@ -30,12 +30,12 @@ def dis(x=None):
types.FunctionType, types.FunctionType,
types.CodeType, types.CodeType,
types.ClassType): types.ClassType):
print "Disassembly of %s:" % name print("Disassembly of %s:" % name)
try: try:
dis(x1) dis(x1)
except TypeError as msg: except TypeError as msg:
print "Sorry:", msg print("Sorry:", msg)
print print()
elif hasattr(x, 'co_code'): elif hasattr(x, 'co_code'):
disassemble(x) disassemble(x)
elif isinstance(x, str): elif isinstance(x, str):
@ -69,17 +69,17 @@ def disassemble(co, lasti=-1):
op = ord(c) op = ord(c)
if i in linestarts: if i in linestarts:
if i > 0: if i > 0:
print print()
print "%3d" % linestarts[i], print("%3d" % linestarts[i], end=' ')
else: else:
print ' ', print(' ', end=' ')
if i == lasti: print '-->', if i == lasti: print('-->', end=' ')
else: print ' ', else: print(' ', end=' ')
if i in labels: print '>>', if i in labels: print('>>', end=' ')
else: print ' ', else: print(' ', end=' ')
print repr(i).rjust(4), print(repr(i).rjust(4), end=' ')
print opname[op].ljust(20), print(opname[op].ljust(20), end=' ')
i = i+1 i = i+1
if op >= HAVE_ARGUMENT: if op >= HAVE_ARGUMENT:
oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg
@ -87,22 +87,22 @@ def disassemble(co, lasti=-1):
i = i+2 i = i+2
if op == EXTENDED_ARG: if op == EXTENDED_ARG:
extended_arg = oparg*65536 extended_arg = oparg*65536
print repr(oparg).rjust(5), print(repr(oparg).rjust(5), end=' ')
if op in hasconst: if op in hasconst:
print '(' + repr(co.co_consts[oparg]) + ')', print('(' + repr(co.co_consts[oparg]) + ')', end=' ')
elif op in hasname: elif op in hasname:
print '(' + co.co_names[oparg] + ')', print('(' + co.co_names[oparg] + ')', end=' ')
elif op in hasjrel: elif op in hasjrel:
print '(to ' + repr(i + oparg) + ')', print('(to ' + repr(i + oparg) + ')', end=' ')
elif op in haslocal: elif op in haslocal:
print '(' + co.co_varnames[oparg] + ')', print('(' + co.co_varnames[oparg] + ')', end=' ')
elif op in hascompare: elif op in hascompare:
print '(' + cmp_op[oparg] + ')', print('(' + cmp_op[oparg] + ')', end=' ')
elif op in hasfree: elif op in hasfree:
if free is None: if free is None:
free = co.co_cellvars + co.co_freevars free = co.co_cellvars + co.co_freevars
print '(' + free[oparg] + ')', print('(' + free[oparg] + ')', end=' ')
print print()
def disassemble_string(code, lasti=-1, varnames=None, names=None, def disassemble_string(code, lasti=-1, varnames=None, names=None,
constants=None): constants=None):
@ -112,37 +112,37 @@ def disassemble_string(code, lasti=-1, varnames=None, names=None,
while i < n: while i < n:
c = code[i] c = code[i]
op = ord(c) op = ord(c)
if i == lasti: print '-->', if i == lasti: print('-->', end=' ')
else: print ' ', else: print(' ', end=' ')
if i in labels: print '>>', if i in labels: print('>>', end=' ')
else: print ' ', else: print(' ', end=' ')
print repr(i).rjust(4), print(repr(i).rjust(4), end=' ')
print opname[op].ljust(15), print(opname[op].ljust(15), end=' ')
i = i+1 i = i+1
if op >= HAVE_ARGUMENT: if op >= HAVE_ARGUMENT:
oparg = ord(code[i]) + ord(code[i+1])*256 oparg = ord(code[i]) + ord(code[i+1])*256
i = i+2 i = i+2
print repr(oparg).rjust(5), print(repr(oparg).rjust(5), end=' ')
if op in hasconst: if op in hasconst:
if constants: if constants:
print '(' + repr(constants[oparg]) + ')', print('(' + repr(constants[oparg]) + ')', end=' ')
else: else:
print '(%d)'%oparg, print('(%d)'%oparg, end=' ')
elif op in hasname: elif op in hasname:
if names is not None: if names is not None:
print '(' + names[oparg] + ')', print('(' + names[oparg] + ')', end=' ')
else: else:
print '(%d)'%oparg, print('(%d)'%oparg, end=' ')
elif op in hasjrel: elif op in hasjrel:
print '(to ' + repr(i + oparg) + ')', print('(to ' + repr(i + oparg) + ')', end=' ')
elif op in haslocal: elif op in haslocal:
if varnames: if varnames:
print '(' + varnames[oparg] + ')', print('(' + varnames[oparg] + ')', end=' ')
else: else:
print '(%d)' % oparg, print('(%d)' % oparg, end=' ')
elif op in hascompare: elif op in hascompare:
print '(' + cmp_op[oparg] + ')', print('(' + cmp_op[oparg] + ')', end=' ')
print print()
disco = disassemble # XXX For backwards compatibility disco = disassemble # XXX For backwards compatibility

View file

@ -392,7 +392,7 @@ def preprocess (self,
try: try:
self.spawn(pp_args) self.spawn(pp_args)
except DistutilsExecError as msg: except DistutilsExecError as msg:
print msg print(msg)
raise CompileError, msg raise CompileError, msg
# preprocess() # preprocess()

View file

@ -1026,7 +1026,7 @@ def announce (self, msg, level=1):
def debug_print (self, msg): def debug_print (self, msg):
from distutils.debug import DEBUG from distutils.debug import DEBUG
if DEBUG: if DEBUG:
print msg print(msg)
def warn (self, msg): def warn (self, msg):
sys.stderr.write ("warning: %s\n" % msg) sys.stderr.write ("warning: %s\n" % msg)

View file

@ -163,14 +163,14 @@ def dump_options (self, header=None, indent=""):
from distutils.fancy_getopt import longopt_xlate from distutils.fancy_getopt import longopt_xlate
if header is None: if header is None:
header = "command options for '%s':" % self.get_command_name() header = "command options for '%s':" % self.get_command_name()
print indent + header print(indent + header)
indent = indent + " " indent = indent + " "
for (option, _, _) in self.user_options: for (option, _, _) in self.user_options:
option = string.translate(option, longopt_xlate) option = string.translate(option, longopt_xlate)
if option[-1] == "=": if option[-1] == "=":
option = option[:-1] option = option[:-1]
value = getattr(self, option) value = getattr(self, option)
print indent + "%s = %s" % (option, value) print(indent + "%s = %s" % (option, value))
def run (self): def run (self):
@ -199,7 +199,7 @@ def debug_print (self, msg):
""" """
from distutils.debug import DEBUG from distutils.debug import DEBUG
if DEBUG: if DEBUG:
print msg print(msg)
sys.stdout.flush() sys.stdout.flush()
@ -475,4 +475,4 @@ def get_outputs (self):
if __name__ == "__main__": if __name__ == "__main__":
print "ok" print("ok")

View file

@ -267,11 +267,11 @@ def finalize_package_data (self):
def run (self): def run (self):
if DEBUG: if DEBUG:
print "before _get_package_data():" print("before _get_package_data():")
print "vendor =", self.vendor print("vendor =", self.vendor)
print "packager =", self.packager print("packager =", self.packager)
print "doc_files =", self.doc_files print("doc_files =", self.doc_files)
print "changelog =", self.changelog print("changelog =", self.changelog)
# make directories # make directories
if self.spec_only: if self.spec_only:

View file

@ -359,9 +359,9 @@ def check_header (self, header, include_dirs=None,
def dump_file (filename, head=None): def dump_file (filename, head=None):
if head is None: if head is None:
print filename + ":" print(filename + ":")
else: else:
print head print(head)
file = open(filename) file = open(filename)
sys.stdout.write(file.read()) sys.stdout.write(file.read())

View file

@ -292,7 +292,7 @@ def finalize_options (self):
if DEBUG: if DEBUG:
from pprint import pprint from pprint import pprint
print "config vars:" print("config vars:")
pprint(self.config_vars) pprint(self.config_vars)
# Expand "~" and configuration variables in the installation # Expand "~" and configuration variables in the installation
@ -347,7 +347,7 @@ def finalize_options (self):
def dump_dirs (self, msg): def dump_dirs (self, msg):
if DEBUG: if DEBUG:
from distutils.fancy_getopt import longopt_xlate from distutils.fancy_getopt import longopt_xlate
print msg + ":" print(msg + ":")
for opt in self.user_options: for opt in self.user_options:
opt_name = opt[0] opt_name = opt[0]
if opt_name[-1] == "=": if opt_name[-1] == "=":
@ -359,7 +359,7 @@ def dump_dirs (self, msg):
else: else:
opt_name = string.translate(opt_name, longopt_xlate) opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name) val = getattr(self, opt_name)
print " %s: %s" % (opt_name, val) print(" %s: %s" % (opt_name, val))
def finalize_unix (self): def finalize_unix (self):

View file

@ -86,14 +86,14 @@ def classifiers(self):
''' Fetch the list of classifiers from the server. ''' Fetch the list of classifiers from the server.
''' '''
response = urllib2.urlopen(self.repository+'?:action=list_classifiers') response = urllib2.urlopen(self.repository+'?:action=list_classifiers')
print response.read() print(response.read())
def verify_metadata(self): def verify_metadata(self):
''' Send the metadata to the package index server to be checked. ''' Send the metadata to the package index server to be checked.
''' '''
# send the info to the server and report the result # send the info to the server and report the result
(code, result) = self.post_to_server(self.build_post_data('verify')) (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): def send_metadata(self):
''' Send the metadata to the package index server. ''' Send the metadata to the package index server.
@ -128,7 +128,7 @@ def send_metadata(self):
if os.environ.has_key('HOME'): if os.environ.has_key('HOME'):
rc = os.path.join(os.environ['HOME'], '.pypirc') rc = os.path.join(os.environ['HOME'], '.pypirc')
if os.path.exists(rc): if os.path.exists(rc):
print 'Using PyPI login from %s'%rc print('Using PyPI login from %s'%rc)
config = ConfigParser.ConfigParser() config = ConfigParser.ConfigParser()
config.read(rc) config.read(rc)
username = config.get('server-login', 'username') username = config.get('server-login', 'username')
@ -138,17 +138,17 @@ def send_metadata(self):
# get the user's login info # get the user's login info
choices = '1 2 3 4'.split() choices = '1 2 3 4'.split()
while choice not in choices: 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, 1. use your existing login,
2. register as a new user, 2. register as a new user,
3. have the server generate a new password for you (and email it to you), or 3. have the server generate a new password for you (and email it to you), or
4. quit 4. quit
Your selection [default 1]: ''', Your selection [default 1]: ''', end=' ')
choice = raw_input() choice = raw_input()
if not choice: if not choice:
choice = '1' choice = '1'
elif choice not in choices: elif choice not in choices:
print 'Please choose one of the four options!' print('Please choose one of the four options!')
if choice == '1': if choice == '1':
# get the username and password # get the username and password
@ -165,13 +165,13 @@ def send_metadata(self):
# send the info to the server and report the result # send the info to the server and report the result
code, result = self.post_to_server(self.build_post_data('submit'), code, result = self.post_to_server(self.build_post_data('submit'),
auth) auth)
print 'Server response (%s): %s'%(code, result) print('Server response (%s): %s'%(code, result))
# possibly save the login # possibly save the login
if os.environ.has_key('HOME') and config is None and code == 200: if os.environ.has_key('HOME') and config is None and code == 200:
rc = os.path.join(os.environ['HOME'], '.pypirc') rc = os.path.join(os.environ['HOME'], '.pypirc')
print 'I can store your PyPI login so future submissions will be faster.' print('I can store your PyPI login so future submissions will be faster.')
print '(the login will be stored in %s)'%rc print('(the login will be stored in %s)'%rc)
choice = 'X' choice = 'X'
while choice.lower() not in 'yn': while choice.lower() not in 'yn':
choice = raw_input('Save your login (y/N)?') choice = raw_input('Save your login (y/N)?')
@ -200,22 +200,22 @@ def send_metadata(self):
if data['password'] != data['confirm']: if data['password'] != data['confirm']:
data['password'] = '' data['password'] = ''
data['confirm'] = None data['confirm'] = None
print "Password and confirm don't match!" print("Password and confirm don't match!")
while not data['email']: while not data['email']:
data['email'] = raw_input(' EMail: ') data['email'] = raw_input(' EMail: ')
code, result = self.post_to_server(data) code, result = self.post_to_server(data)
if code != 200: if code != 200:
print 'Server response (%s): %s'%(code, result) print('Server response (%s): %s'%(code, result))
else: else:
print 'You will receive an email shortly.' print('You will receive an email shortly.')
print 'Follow the instructions in it to complete registration.' print('Follow the instructions in it to complete registration.')
elif choice == '3': elif choice == '3':
data = {':action': 'password_reset'} data = {':action': 'password_reset'}
data['email'] = '' data['email'] = ''
while not data['email']: while not data['email']:
data['email'] = raw_input('Your email address: ') data['email'] = raw_input('Your email address: ')
code, result = self.post_to_server(data) 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): def build_post_data(self, action):
# figure the data to send - the metadata plus some additional # figure the data to send - the metadata plus some additional
@ -295,5 +295,5 @@ def post_to_server(self, data, auth=None):
data = result.read() data = result.read()
result = 200, 'OK' result = 200, 'OK'
if self.show_response: if self.show_response:
print '-'*75, data, '-'*75 print('-'*75, data, '-'*75)
return result return result

View file

@ -196,4 +196,4 @@ def upload_file(self, command, pyversion, filename):
self.announce('Upload failed (%s): %s' % (r.status, r.reason), self.announce('Upload failed (%s): %s' % (r.status, r.reason),
log.ERROR) log.ERROR)
if self.show_response: if self.show_response:
print '-'*75, r.read(), '-'*75 print('-'*75, r.read(), '-'*75)

View file

@ -125,7 +125,7 @@ class found in 'cmdclass' is used in place of the default, which is
dist.parse_config_files() dist.parse_config_files()
if DEBUG: if DEBUG:
print "options (after parsing config files):" print("options (after parsing config files):")
dist.dump_option_dicts() dist.dump_option_dicts()
if _setup_stop_after == "config": if _setup_stop_after == "config":
@ -139,7 +139,7 @@ class found in 'cmdclass' is used in place of the default, which is
raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg
if DEBUG: if DEBUG:
print "options (after parsing command line):" print("options (after parsing command line):")
dist.dump_option_dicts() dist.dump_option_dicts()
if _setup_stop_after == "commandline": if _setup_stop_after == "commandline":

View file

@ -290,22 +290,22 @@ def dump_option_dicts (self, header=None, commands=None, indent=""):
commands.sort() commands.sort()
if header is not None: if header is not None:
print indent + header print(indent + header)
indent = indent + " " indent = indent + " "
if not commands: if not commands:
print indent + "no commands known yet" print(indent + "no commands known yet")
return return
for cmd_name in commands: for cmd_name in commands:
opt_dict = self.command_options.get(cmd_name) opt_dict = self.command_options.get(cmd_name)
if opt_dict is None: 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: else:
print indent + "option dict for '%s' command:" % cmd_name print(indent + "option dict for '%s' command:" % cmd_name)
out = pformat(opt_dict) out = pformat(opt_dict)
for line in string.split(out, "\n"): for line in string.split(out, "\n"):
print indent + " " + line print(indent + " " + line)
# dump_option_dicts () # dump_option_dicts ()
@ -365,11 +365,11 @@ def parse_config_files (self, filenames=None):
if filenames is None: if filenames is None:
filenames = self.find_config_files() filenames = self.find_config_files()
if DEBUG: print "Distribution.parse_config_files():" if DEBUG: print("Distribution.parse_config_files():")
parser = ConfigParser() parser = ConfigParser()
for filename in filenames: for filename in filenames:
if DEBUG: print " reading", filename if DEBUG: print(" reading", filename)
parser.read(filename) parser.read(filename)
for section in parser.sections(): for section in parser.sections():
options = parser.options(section) options = parser.options(section)
@ -636,14 +636,14 @@ def _show_help (self,
options = self.global_options options = self.global_options
parser.set_option_table(options) parser.set_option_table(options)
parser.print_help(self.common_usage + "\nGlobal options:") parser.print_help(self.common_usage + "\nGlobal options:")
print print()
if display_options: if display_options:
parser.set_option_table(self.display_options) parser.set_option_table(self.display_options)
parser.print_help( parser.print_help(
"Information display options (just display " + "Information display options (just display " +
"information, ignore any commands)") "information, ignore any commands)")
print print()
for command in self.commands: for command in self.commands:
if type(command) is ClassType and issubclass(command, Command): if type(command) is ClassType and issubclass(command, Command):
@ -657,9 +657,9 @@ def _show_help (self,
else: else:
parser.set_option_table(klass.user_options) parser.set_option_table(klass.user_options)
parser.print_help("Options for '%s' command:" % klass.__name__) parser.print_help("Options for '%s' command:" % klass.__name__)
print print()
print gen_usage(self.script_name) print(gen_usage(self.script_name))
return return
# _show_help () # _show_help ()
@ -678,8 +678,8 @@ def handle_display_options (self, option_order):
# we ignore "foo bar"). # we ignore "foo bar").
if self.help_commands: if self.help_commands:
self.print_commands() self.print_commands()
print print()
print gen_usage(self.script_name) print(gen_usage(self.script_name))
return 1 return 1
# If user supplied any of the "display metadata" options, then # If user supplied any of the "display metadata" options, then
@ -695,12 +695,12 @@ def handle_display_options (self, option_order):
opt = translate_longopt(opt) opt = translate_longopt(opt)
value = getattr(self.metadata, "get_"+opt)() value = getattr(self.metadata, "get_"+opt)()
if opt in ['keywords', 'platforms']: if opt in ['keywords', 'platforms']:
print string.join(value, ',') print(string.join(value, ','))
elif opt in ('classifiers', 'provides', 'requires', elif opt in ('classifiers', 'provides', 'requires',
'obsoletes'): 'obsoletes'):
print string.join(value, '\n') print(string.join(value, '\n'))
else: else:
print value print(value)
any_display_options = 1 any_display_options = 1
return any_display_options return any_display_options
@ -712,7 +712,7 @@ def print_command_list (self, commands, header, max_length):
'print_commands()'. 'print_commands()'.
""" """
print header + ":" print(header + ":")
for cmd in commands: for cmd in commands:
klass = self.cmdclass.get(cmd) klass = self.cmdclass.get(cmd)
@ -723,7 +723,7 @@ def print_command_list (self, commands, header, max_length):
except AttributeError: except AttributeError:
description = "(no description available)" description = "(no description available)"
print " %-*s %s" % (max_length, cmd, description) print(" %-*s %s" % (max_length, cmd, description))
# print_command_list () # print_command_list ()
@ -757,7 +757,7 @@ def print_commands (self):
"Standard commands", "Standard commands",
max_length) max_length)
if extra_commands: if extra_commands:
print print()
self.print_command_list(extra_commands, self.print_command_list(extra_commands,
"Extra commands", "Extra commands",
max_length) max_length)
@ -862,8 +862,8 @@ def get_command_obj (self, command, create=1):
cmd_obj = self.command_obj.get(command) cmd_obj = self.command_obj.get(command)
if not cmd_obj and create: if not cmd_obj and create:
if DEBUG: if DEBUG:
print "Distribution.get_command_obj(): " \ print("Distribution.get_command_obj(): " \
"creating '%s' command object" % command "creating '%s' command object" % command)
klass = self.get_command_class(command) klass = self.get_command_class(command)
cmd_obj = self.command_obj[command] = klass(self) cmd_obj = self.command_obj[command] = klass(self)
@ -893,9 +893,9 @@ def _set_command_options (self, command_obj, option_dict=None):
if option_dict is None: if option_dict is None:
option_dict = self.get_option_dict(command_name) 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(): 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: try:
bool_opts = map(translate_longopt, command_obj.boolean_options) bool_opts = map(translate_longopt, command_obj.boolean_options)
except AttributeError: except AttributeError:
@ -1219,4 +1219,4 @@ def fix_help_options (options):
if __name__ == "__main__": if __name__ == "__main__":
dist = Distribution() dist = Distribution()
print "ok" print("ok")

View file

@ -497,6 +497,6 @@ def __init__ (self, options=[]):
say, "How should I know?"].)""" say, "How should I know?"].)"""
for w in (10, 20, 30, 40): for w in (10, 20, 30, 40):
print "width: %d" % w print("width: %d" % w)
print string.join(wrap_text(text, w), "\n") print(string.join(wrap_text(text, w), "\n"))
print print()

View file

@ -53,7 +53,7 @@ def debug_print (self, msg):
""" """
from distutils.debug import DEBUG from distutils.debug import DEBUG
if DEBUG: if DEBUG:
print msg print(msg)
# -- List-like methods --------------------------------------------- # -- List-like methods ---------------------------------------------

View file

@ -23,9 +23,9 @@ def _log(self, level, msg, args):
if not args: if not args:
# msg may contain a '%'. If args is empty, # msg may contain a '%'. If args is empty,
# don't even try to string-format # don't even try to string-format
print msg print(msg)
else: else:
print msg % args print(msg % args)
sys.stdout.flush() sys.stdout.flush()
def log(self, level, msg, *args): def log(self, level, msg, *args):

View file

@ -160,9 +160,9 @@ def link (self,
settings['libraries'] = libraries settings['libraries'] = libraries
settings['extrasearchdirs'] = sourcefiledirs + include_dirs + library_dirs settings['extrasearchdirs'] = sourcefiledirs + include_dirs + library_dirs
if self.dry_run: if self.dry_run:
print 'CALLING LINKER IN', os.getcwd() print('CALLING LINKER IN', os.getcwd())
for key, value in settings.items(): for key, value in settings.items():
print '%20.20s %s'%(key, value) print('%20.20s %s'%(key, value))
return return
# Build the export file # Build the export file
exportfilename = os.path.join(build_temp, exportname) exportfilename = os.path.join(build_temp, exportname)

View file

@ -109,7 +109,7 @@ def _spawn_os2 (cmd,
"command '%s' failed: %s" % (cmd[0], exc[-1]) "command '%s' failed: %s" % (cmd[0], exc[-1])
if rc != 0: if rc != 0:
# and this reflects the command running but failing # 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, \ raise DistutilsExecError, \
"command '%s' failed with exit status %d" % (cmd[0], rc) "command '%s' failed with exit status %d" % (cmd[0], rc)

View file

@ -74,8 +74,8 @@ def test_command_packages_configfile(self):
sys.argv.append("build") sys.argv.append("build")
f = open(TESTFN, "w") f = open(TESTFN, "w")
try: try:
print >>f, "[global]" print("[global]", file=f)
print >>f, "command_packages = foo.bar, splat" print("command_packages = foo.bar, splat", file=f)
f.close() f.close()
d = self.create_distribution([TESTFN]) d = self.create_distribution([TESTFN])
self.assertEqual(d.get_command_packages(), self.assertEqual(d.get_command_packages(),

View file

@ -342,13 +342,13 @@ def test_input (count, description, file, expected_result):
result = file.readlines () result = file.readlines ()
# result = string.join (result, '') # result = string.join (result, '')
if result == expected_result: if result == expected_result:
print "ok %d (%s)" % (count, description) print("ok %d (%s)" % (count, description))
else: else:
print "not ok %d (%s):" % (count, description) print("not ok %d (%s):" % (count, description))
print "** expected:" print("** expected:")
print expected_result print(expected_result)
print "** received:" print("** received:")
print result print(result)
filename = "test.txt" filename = "test.txt"

View file

@ -855,7 +855,7 @@ def _find(self, tests, obj, name, module, source_lines, globs, seen):
add them to `tests`. add them to `tests`.
""" """
if self._verbose: 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 we've already processed this object, then ignore it.
if id(obj) in seen: if id(obj) in seen:
@ -1384,28 +1384,28 @@ def summarize(self, verbose=None):
failed.append(x) failed.append(x)
if verbose: if verbose:
if notests: if notests:
print len(notests), "items had no tests:" print(len(notests), "items had no tests:")
notests.sort() notests.sort()
for thing in notests: for thing in notests:
print " ", thing print(" ", thing)
if passed: if passed:
print len(passed), "items passed all tests:" print(len(passed), "items passed all tests:")
passed.sort() passed.sort()
for thing, count in passed: for thing, count in passed:
print " %3d tests in %s" % (count, thing) print(" %3d tests in %s" % (count, thing))
if failed: if failed:
print self.DIVIDER print(self.DIVIDER)
print len(failed), "items had failures:" print(len(failed), "items had failures:")
failed.sort() failed.sort()
for thing, (f, t) in failed: 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: if verbose:
print totalt, "tests in", len(self._name2ft), "items." print(totalt, "tests in", len(self._name2ft), "items.")
print totalt - totalf, "passed and", totalf, "failed." print(totalt - totalf, "passed and", totalf, "failed.")
if totalf: if totalf:
print "***Test Failed***", totalf, "failures." print("***Test Failed***", totalf, "failures.")
elif verbose: elif verbose:
print "Test passed." print("Test passed.")
return totalf, totalt return totalf, totalt
#///////////////////////////////////////////////////////////////// #/////////////////////////////////////////////////////////////////
@ -1415,8 +1415,8 @@ def merge(self, other):
d = self._name2ft d = self._name2ft
for name, (f, t) in other._name2ft.items(): for name, (f, t) in other._name2ft.items():
if name in d: if name in d:
print "*** DocTestRunner.merge: '" + name + "' in both" \ print("*** DocTestRunner.merge: '" + name + "' in both" \
" testers; summing outcomes." " testers; summing outcomes.")
f2, t2 = d[name] f2, t2 = d[name]
f = f + f2 f = f + f2
t = t + t2 t = t + t2
@ -1985,10 +1985,10 @@ def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
def runstring(self, s, name): def runstring(self, s, name):
test = DocTestParser().get_doctest(s, self.globs, name, None, None) test = DocTestParser().get_doctest(s, self.globs, name, None, None)
if self.verbose: if self.verbose:
print "Running string", name print("Running string", name)
(f,t) = self.testrunner.run(test) (f,t) = self.testrunner.run(test)
if self.verbose: if self.verbose:
print f, "of", t, "examples failed in string", name print(f, "of", t, "examples failed in string", name)
return (f,t) return (f,t)
def rundoc(self, object, name=None, module=None): def rundoc(self, object, name=None, module=None):
@ -2512,7 +2512,7 @@ def debug_script(src, pm=False, globs=None):
try: try:
execfile(srcfilename, globs, globs) execfile(srcfilename, globs, globs)
except: except:
print sys.exc_info()[1] print(sys.exc_info()[1])
pdb.post_mortem(sys.exc_info()[2]) pdb.post_mortem(sys.exc_info()[2])
else: else:
# Note that %r is vital here. '%s' instead can, e.g., cause # Note that %r is vital here. '%s' instead can, e.g., cause

View file

@ -80,7 +80,7 @@ def flatten(self, msg, unixfrom=False):
ufrom = msg.get_unixfrom() ufrom = msg.get_unixfrom()
if not ufrom: if not ufrom:
ufrom = 'From nobody ' + time.ctime(time.time()) ufrom = 'From nobody ' + time.ctime(time.time())
print >> self._fp, ufrom print(ufrom, file=self._fp)
self._write(msg) self._write(msg)
def clone(self, fp): def clone(self, fp):
@ -140,13 +140,13 @@ def _dispatch(self, msg):
def _write_headers(self, msg): def _write_headers(self, msg):
for h, v in msg.items(): for h, v in msg.items():
print >> self._fp, '%s:' % h, print('%s:' % h, end=' ', file=self._fp)
if self._maxheaderlen == 0: if self._maxheaderlen == 0:
# Explicit no-wrapping # Explicit no-wrapping
print >> self._fp, v print(v, file=self._fp)
elif isinstance(v, Header): elif isinstance(v, Header):
# Header instances know what to do # Header instances know what to do
print >> self._fp, v.encode() print(v.encode(), file=self._fp)
elif _is8bitstring(v): elif _is8bitstring(v):
# If we have raw 8bit data in a byte string, we have no idea # 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 # what the encoding is. There is no safe way to split this
@ -154,14 +154,14 @@ def _write_headers(self, msg):
# ascii split, but if it's multibyte then we could break the # 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 # 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. # be to not split the string and risk it being too long.
print >> self._fp, v print(v, file=self._fp)
else: else:
# Header's got lots of smarts, so use it. # Header's got lots of smarts, so use it.
print >> self._fp, Header( print(Header(
v, maxlinelen=self._maxheaderlen, 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 # A blank line always separates headers from body
print >> self._fp print(file=self._fp)
# #
# Handlers for writing types and subtypes # Handlers for writing types and subtypes
@ -215,9 +215,9 @@ def _handle_multipart(self, msg):
msg.set_boundary(boundary) msg.set_boundary(boundary)
# If there's a preamble, write it out, with a trailing CRLF # If there's a preamble, write it out, with a trailing CRLF
if msg.preamble is not None: if msg.preamble is not None:
print >> self._fp, msg.preamble print(msg.preamble, file=self._fp)
# dash-boundary transport-padding CRLF # dash-boundary transport-padding CRLF
print >> self._fp, '--' + boundary print('--' + boundary, file=self._fp)
# body-part # body-part
if msgtexts: if msgtexts:
self._fp.write(msgtexts.pop(0)) self._fp.write(msgtexts.pop(0))
@ -226,13 +226,13 @@ def _handle_multipart(self, msg):
# --> CRLF body-part # --> CRLF body-part
for body_part in msgtexts: for body_part in msgtexts:
# delimiter transport-padding CRLF # delimiter transport-padding CRLF
print >> self._fp, '\n--' + boundary print('\n--' + boundary, file=self._fp)
# body-part # body-part
self._fp.write(body_part) self._fp.write(body_part)
# close-delimiter transport-padding # close-delimiter transport-padding
self._fp.write('\n--' + boundary + '--') self._fp.write('\n--' + boundary + '--')
if msg.epilogue is not None: if msg.epilogue is not None:
print >> self._fp print(file=self._fp)
self._fp.write(msg.epilogue) self._fp.write(msg.epilogue)
def _handle_message_delivery_status(self, msg): def _handle_message_delivery_status(self, msg):
@ -308,12 +308,12 @@ def _dispatch(self, msg):
for part in msg.walk(): for part in msg.walk():
maintype = part.get_content_maintype() maintype = part.get_content_maintype()
if maintype == 'text': if maintype == 'text':
print >> self, part.get_payload(decode=True) print(part.get_payload(decode=True), file=self)
elif maintype == 'multipart': elif maintype == 'multipart':
# Just skip this # Just skip this
pass pass
else: else:
print >> self, self._fmt % { print(self._fmt % {
'type' : part.get_content_type(), 'type' : part.get_content_type(),
'maintype' : part.get_content_maintype(), 'maintype' : part.get_content_maintype(),
'subtype' : part.get_content_subtype(), 'subtype' : part.get_content_subtype(),
@ -322,7 +322,7 @@ def _dispatch(self, msg):
'[no description]'), '[no description]'),
'encoding' : part.get('Content-Transfer-Encoding', 'encoding' : part.get('Content-Transfer-Encoding',
'[no encoding]'), '[no encoding]'),
} }, file=self)

View file

@ -63,11 +63,11 @@ def _structure(msg, fp=None, level=0, include_default=False):
if fp is None: if fp is None:
fp = sys.stdout fp = sys.stdout
tab = ' ' * (level * 4) tab = ' ' * (level * 4)
print >> fp, tab + msg.get_content_type(), print(tab + msg.get_content_type(), end=' ', file=fp)
if include_default: if include_default:
print >> fp, '[%s]' % msg.get_default_type() print('[%s]' % msg.get_default_type(), file=fp)
else: else:
print >> fp print(file=fp)
if msg.is_multipart(): if msg.is_multipart():
for subpart in msg.get_payload(): for subpart in msg.get_payload():
_structure(subpart, fp, level+1, include_default) _structure(subpart, fp, level+1, include_default)

View file

@ -56,7 +56,7 @@ def ndiffAssertEqual(self, first, second):
ssecond = str(second) ssecond = str(second)
diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
fp = StringIO() fp = StringIO()
print >> fp, NL, NL.join(diff) print(NL, NL.join(diff), file=fp)
raise self.failureException, fp.getvalue() raise self.failureException, fp.getvalue()
def _msgobj(self, filename): def _msgobj(self, filename):

View file

@ -57,7 +57,7 @@ def ndiffAssertEqual(self, first, second):
ssecond = str(second) ssecond = str(second)
diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
fp = StringIO() fp = StringIO()
print >> fp, NL, NL.join(diff) print(NL, NL.join(diff), file=fp)
raise self.failureException, fp.getvalue() raise self.failureException, fp.getvalue()
def _msgobj(self, filename): def _msgobj(self, filename):

View file

@ -192,39 +192,39 @@ def phase4_closure(self): # Recursively call phase4() on subdirectories
def report(self): # Print a report on the differences between a and b def report(self): # Print a report on the differences between a and b
# Output format is purposely lousy # Output format is purposely lousy
print 'diff', self.left, self.right print('diff', self.left, self.right)
if self.left_only: if self.left_only:
self.left_only.sort() self.left_only.sort()
print 'Only in', self.left, ':', self.left_only print('Only in', self.left, ':', self.left_only)
if self.right_only: if self.right_only:
self.right_only.sort() self.right_only.sort()
print 'Only in', self.right, ':', self.right_only print('Only in', self.right, ':', self.right_only)
if self.same_files: if self.same_files:
self.same_files.sort() self.same_files.sort()
print 'Identical files :', self.same_files print('Identical files :', self.same_files)
if self.diff_files: if self.diff_files:
self.diff_files.sort() self.diff_files.sort()
print 'Differing files :', self.diff_files print('Differing files :', self.diff_files)
if self.funny_files: if self.funny_files:
self.funny_files.sort() self.funny_files.sort()
print 'Trouble with common files :', self.funny_files print('Trouble with common files :', self.funny_files)
if self.common_dirs: if self.common_dirs:
self.common_dirs.sort() self.common_dirs.sort()
print 'Common subdirectories :', self.common_dirs print('Common subdirectories :', self.common_dirs)
if self.common_funny: if self.common_funny:
self.common_funny.sort() 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 def report_partial_closure(self): # Print reports on self and on subdirs
self.report() self.report()
for sd in self.subdirs.itervalues(): for sd in self.subdirs.itervalues():
print print()
sd.report() sd.report()
def report_full_closure(self): # Report on self and subdirs recursively def report_full_closure(self): # Report on self and subdirs recursively
self.report() self.report()
for sd in self.subdirs.itervalues(): for sd in self.subdirs.itervalues():
print print()
sd.report_full_closure() sd.report_full_closure()
methodmap = dict(subdirs=phase4, methodmap = dict(subdirs=phase4,

View file

@ -405,9 +405,9 @@ def _test():
for line in input(args, inplace=inplace, backup=backup): for line in input(args, inplace=inplace, backup=backup):
if line[-1:] == '\n': line = line[:-1] if line[-1:] == '\n': line = line[:-1]
if line[-1:] == '\r': line = line[:-1] if line[-1:] == '\r': line = line[:-1]
print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(), print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
isfirstline() and "*" or "", line) isfirstline() and "*" or "", line))
print "%d: %s[%d]" % (lineno(), filename(), filelineno()) print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
if __name__ == '__main__': if __name__ == '__main__':
_test() _test()

View file

@ -323,37 +323,37 @@ class AbstractWriter(NullWriter):
""" """
def new_alignment(self, align): def new_alignment(self, align):
print "new_alignment(%r)" % (align,) print("new_alignment(%r)" % (align,))
def new_font(self, font): def new_font(self, font):
print "new_font(%r)" % (font,) print("new_font(%r)" % (font,))
def new_margin(self, margin, level): 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): def new_spacing(self, spacing):
print "new_spacing(%r)" % (spacing,) print("new_spacing(%r)" % (spacing,))
def new_styles(self, styles): def new_styles(self, styles):
print "new_styles(%r)" % (styles,) print("new_styles(%r)" % (styles,))
def send_paragraph(self, blankline): def send_paragraph(self, blankline):
print "send_paragraph(%r)" % (blankline,) print("send_paragraph(%r)" % (blankline,))
def send_line_break(self): def send_line_break(self):
print "send_line_break()" print("send_line_break()")
def send_hor_rule(self, *args, **kw): def send_hor_rule(self, *args, **kw):
print "send_hor_rule()" print("send_hor_rule()")
def send_label_data(self, data): def send_label_data(self, data):
print "send_label_data(%r)" % (data,) print("send_label_data(%r)" % (data,))
def send_flowing_data(self, 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): def send_literal_data(self, data):
print "send_literal_data(%r)" % (data,) print("send_literal_data(%r)" % (data,))
class DumbWriter(NullWriter): class DumbWriter(NullWriter):

View file

@ -137,6 +137,6 @@ def test():
try: try:
while 1: while 1:
x, digs = input('Enter (x, digs): ') 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): except (EOFError, KeyboardInterrupt):
pass pass

View file

@ -137,7 +137,7 @@ def getwelcome(self):
'''Get the welcome message from the server. '''Get the welcome message from the server.
(this is read and squirreled away by connect())''' (this is read and squirreled away by connect())'''
if self.debugging: if self.debugging:
print '*welcome*', self.sanitize(self.welcome) print('*welcome*', self.sanitize(self.welcome))
return self.welcome return self.welcome
def set_debuglevel(self, level): def set_debuglevel(self, level):
@ -167,12 +167,12 @@ def sanitize(self, s):
# Internal: send one line to the server, appending CRLF # Internal: send one line to the server, appending CRLF
def putline(self, line): def putline(self, line):
line = line + CRLF 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) self.sock.sendall(line)
# Internal: send one command to the server (through putline()) # Internal: send one command to the server (through putline())
def putcmd(self, line): def putcmd(self, line):
if self.debugging: print '*cmd*', self.sanitize(line) if self.debugging: print('*cmd*', self.sanitize(line))
self.putline(line) self.putline(line)
# Internal: return one line from the server, stripping CRLF. # Internal: return one line from the server, stripping CRLF.
@ -180,7 +180,7 @@ def putcmd(self, line):
def getline(self): def getline(self):
line = self.file.readline() line = self.file.readline()
if self.debugging > 1: if self.debugging > 1:
print '*get*', self.sanitize(line) print('*get*', self.sanitize(line))
if not line: raise EOFError if not line: raise EOFError
if line[-2:] == CRLF: line = line[:-2] if line[-2:] == CRLF: line = line[:-2]
elif line[-1:] in CRLF: line = line[:-1] elif line[-1:] in CRLF: line = line[:-1]
@ -206,7 +206,7 @@ def getmultiline(self):
# Raise various errors if the response indicates an error # Raise various errors if the response indicates an error
def getresp(self): def getresp(self):
resp = self.getmultiline() resp = self.getmultiline()
if self.debugging: print '*resp*', self.sanitize(resp) if self.debugging: print('*resp*', self.sanitize(resp))
self.lastresp = resp[:3] self.lastresp = resp[:3]
c = resp[:1] c = resp[:1]
if c in ('1', '2', '3'): if c in ('1', '2', '3'):
@ -230,7 +230,7 @@ def abort(self):
IP and Synch; that doesn't seem to work with the servers I've IP and Synch; that doesn't seem to work with the servers I've
tried. Instead, just send the ABOR command as OOB data.''' tried. Instead, just send the ABOR command as OOB data.'''
line = 'ABOR' + CRLF 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) self.sock.sendall(line, MSG_OOB)
resp = self.getmultiline() resp = self.getmultiline()
if resp[:3] not in ('426', '226'): if resp[:3] not in ('426', '226'):
@ -409,7 +409,7 @@ def retrlines(self, cmd, callback = None):
fp = conn.makefile('rb') fp = conn.makefile('rb')
while 1: while 1:
line = fp.readline() line = fp.readline()
if self.debugging > 2: print '*retr*', repr(line) if self.debugging > 2: print('*retr*', repr(line))
if not line: if not line:
break break
if line[-2:] == CRLF: if line[-2:] == CRLF:
@ -636,7 +636,7 @@ def parse257(resp):
def print_line(line): def print_line(line):
'''Default retrlines callback to print a line.''' '''Default retrlines callback to print a line.'''
print line print(line)
def ftpcp(source, sourcename, target, targetname = '', type = 'I'): def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
@ -775,7 +775,7 @@ def test():
''' '''
if len(sys.argv) < 2: if len(sys.argv) < 2:
print test.__doc__ print(test.__doc__)
sys.exit(0) sys.exit(0)
debugging = 0 debugging = 0

View file

@ -208,4 +208,4 @@ def short_has_arg(opt, shortopts):
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]))

View file

@ -67,7 +67,7 @@ def win_getpass(prompt='Password: ', stream=None):
def default_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) return _raw_input(prompt, stream)

View file

@ -103,7 +103,7 @@ def get_directory(f):
while 1: while 1:
line = f.readline() line = f.readline()
if not line: if not line:
print '(Unexpected EOF from server)' print('(Unexpected EOF from server)')
break break
if line[-2:] == CRLF: if line[-2:] == CRLF:
line = line[:-2] line = line[:-2]
@ -112,17 +112,17 @@ def get_directory(f):
if line == '.': if line == '.':
break break
if not line: if not line:
print '(Empty line from server)' print('(Empty line from server)')
continue continue
gtype = line[0] gtype = line[0]
parts = line[1:].split(TAB) parts = line[1:].split(TAB)
if len(parts) < 4: if len(parts) < 4:
print '(Bad line from server: %r)' % (line,) print('(Bad line from server: %r)' % (line,))
continue continue
if len(parts) > 4: if len(parts) > 4:
if parts[4:] != ['+']: if parts[4:] != ['+']:
print '(Extra info from server:', print('(Extra info from server:', end=' ')
print parts[4:], ')' print(parts[4:], ')')
else: else:
parts.append('') parts.append('')
parts.insert(0, gtype) parts.insert(0, gtype)
@ -140,7 +140,7 @@ def get_alt_textfile(f, func):
while 1: while 1:
line = f.readline() line = f.readline()
if not line: if not line:
print '(Unexpected EOF from server)' print('(Unexpected EOF from server)')
break break
if line[-2:] == CRLF: if line[-2:] == CRLF:
line = line[:-2] line = line[:-2]
@ -196,13 +196,13 @@ def test():
f = send_selector(selector, host) f = send_selector(selector, host)
if type == A_TEXT: if type == A_TEXT:
lines = get_textfile(f) lines = get_textfile(f)
for item in lines: print item for item in lines: print(item)
elif type in (A_MENU, A_INDEX): elif type in (A_MENU, A_INDEX):
entries = get_directory(f) entries = get_directory(f)
for item in entries: print item for item in entries: print(item)
else: else:
data = get_binary(f) 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 # Run the test when run as script
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -470,7 +470,7 @@ def _test():
g = sys.stdout g = sys.stdout
else: else:
if arg[-3:] != ".gz": if arg[-3:] != ".gz":
print "filename doesn't end in .gz:", repr(arg) print("filename doesn't end in .gz:", repr(arg))
continue continue
f = open(arg, "rb") f = open(arg, "rb")
g = __builtin__.open(arg[:-3], "wb") g = __builtin__.open(arg[:-3], "wb")

View file

@ -340,4 +340,4 @@ def nlargest(n, iterable, key=None):
sort = [] sort = []
while heap: while heap:
sort.append(heappop(heap)) sort.append(heappop(heap))
print sort print(sort)

View file

@ -159,7 +159,7 @@ def _loadfile(self, fileno):
try: try:
filename = self._filemap[fileno] filename = self._filemap[fileno]
except KeyError: except KeyError:
print "Could not identify fileId", fileno print("Could not identify fileId", fileno)
return 1 return 1
if filename is None: if filename is None:
return 1 return 1

View file

@ -10,9 +10,9 @@ def main(logfile):
benchtime, stones = p.runcall(test.pystone.pystones) benchtime, stones = p.runcall(test.pystone.pystones)
p.close() p.close()
print "Pystone(%s) time for %d passes = %g" % \ print("Pystone(%s) time for %d passes = %g" % \
(test.pystone.__version__, test.pystone.LOOPS, benchtime) (test.pystone.__version__, test.pystone.LOOPS, benchtime))
print "This machine benchmarks at %g pystones/second" % stones print("This machine benchmarks at %g pystones/second" % stones)
stats = hotshot.stats.load(logfile) stats = hotshot.stats.load(logfile)
stats.strip_dirs() stats.strip_dirs()

View file

@ -464,7 +464,7 @@ def test(args = None):
try: try:
f = open(file, 'r') f = open(file, 'r')
except IOError as msg: except IOError as msg:
print file, ":", msg print(file, ":", msg)
sys.exit(1) sys.exit(1)
data = f.read() data = f.read()

View file

@ -342,7 +342,7 @@ def _read_status(self):
# Initialize with Simple-Response defaults # Initialize with Simple-Response defaults
line = self.fp.readline() line = self.fp.readline()
if self.debuglevel > 0: if self.debuglevel > 0:
print "reply:", repr(line) print("reply:", repr(line))
if not line: if not line:
# Presumably, the server closed the connection before # Presumably, the server closed the connection before
# sending a valid response. # sending a valid response.
@ -391,7 +391,7 @@ def begin(self):
if not skip: if not skip:
break break
if self.debuglevel > 0: if self.debuglevel > 0:
print "header:", skip print("header:", skip)
self.status = status self.status = status
self.reason = reason.strip() self.reason = reason.strip()
@ -414,7 +414,7 @@ def begin(self):
self.msg = HTTPMessage(self.fp, 0) self.msg = HTTPMessage(self.fp, 0)
if self.debuglevel > 0: if self.debuglevel > 0:
for hdr in self.msg.headers: for hdr in self.msg.headers:
print "header:", hdr, print("header:", hdr, end=' ')
# don't let the msg keep an fp # don't let the msg keep an fp
self.msg.fp = None self.msg.fp = None
@ -665,11 +665,11 @@ def connect(self):
try: try:
self.sock = socket.socket(af, socktype, proto) self.sock = socket.socket(af, socktype, proto)
if self.debuglevel > 0: if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port) print("connect: (%s, %s)" % (self.host, self.port))
self.sock.connect(sa) self.sock.connect(sa)
except socket.error as msg: except socket.error as msg:
if self.debuglevel > 0: if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port) print('connect fail:', (self.host, self.port))
if self.sock: if self.sock:
self.sock.close() self.sock.close()
self.sock = None self.sock = None
@ -702,11 +702,11 @@ def send(self, str):
# NOTE: we DO propagate the error, though, because we cannot simply # NOTE: we DO propagate the error, though, because we cannot simply
# ignore the error... the caller will know if they can retry. # ignore the error... the caller will know if they can retry.
if self.debuglevel > 0: if self.debuglevel > 0:
print "send:", repr(str) print("send:", repr(str))
try: try:
blocksize=8192 blocksize=8192
if hasattr(str,'read') : 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) data=str.read(blocksize)
while data: while data:
self.sock.sendall(data) self.sock.sendall(data)
@ -898,7 +898,7 @@ def _send_request(self, method, url, body, headers):
thelen = str(os.fstat(body.fileno()).st_size) thelen = str(os.fstat(body.fileno()).st_size)
except (AttributeError, OSError): except (AttributeError, OSError):
# Don't send a length if this failed # 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: if thelen is not None:
self.putheader('Content-Length',thelen) self.putheader('Content-Length',thelen)
@ -1408,13 +1408,13 @@ def test():
h.putrequest('GET', selector) h.putrequest('GET', selector)
h.endheaders() h.endheaders()
status, reason, headers = h.getreply() status, reason, headers = h.getreply()
print 'status =', status print('status =', status)
print 'reason =', reason print('reason =', reason)
print "read", len(h.getfile().read()) print("read", len(h.getfile().read()))
print print()
if headers: if headers:
for header in headers.headers: print header.strip() for header in headers.headers: print(header.strip())
print print()
# minimal test that code to extract host from url works # minimal test that code to extract host from url works
class HTTP11(HTTP): class HTTP11(HTTP):
@ -1431,20 +1431,20 @@ class HTTP11(HTTP):
for host, selector in (('sourceforge.net', '/projects/python'), for host, selector in (('sourceforge.net', '/projects/python'),
): ):
print "https://%s%s" % (host, selector) print("https://%s%s" % (host, selector))
hs = HTTPS() hs = HTTPS()
hs.set_debuglevel(dl) hs.set_debuglevel(dl)
hs.connect(host) hs.connect(host)
hs.putrequest('GET', selector) hs.putrequest('GET', selector)
hs.endheaders() hs.endheaders()
status, reason, headers = hs.getreply() status, reason, headers = hs.getreply()
print 'status =', status print('status =', status)
print 'reason =', reason print('reason =', reason)
print "read", len(hs.getfile().read()) print("read", len(hs.getfile().read()))
print print()
if headers: if headers:
for header in headers.headers: print header.strip() for header in headers.headers: print(header.strip())
print print()
if __name__ == '__main__': if __name__ == '__main__':
test() test()

View file

@ -201,9 +201,9 @@ def test(tests):
arg_text = ct.fetch_tip(name) arg_text = ct.fetch_tip(name)
if arg_text != expected: if arg_text != expected:
failed.append(t) failed.append(t)
print "%s - expected %s, but got %s" % (t, expected, print("%s - expected %s, but got %s" % (t, expected,
get_arg_text(entity)) get_arg_text(entity)))
print "%d of %d tests failed" % (len(failed), len(tests)) print("%d of %d tests failed" % (len(failed), len(tests)))
tc = TC() tc = TC()
tests = (t1, t2, t3, t4, t5, t6, tests = (t1, t2, t3, t4, t5, t6,

View file

@ -72,7 +72,7 @@ def LoadTagDefs(self):
"hit": idleConf.GetHighlight(theme, "hit"), "hit": idleConf.GetHighlight(theme, "hit"),
} }
if DEBUG: print 'tagdefs',self.tagdefs if DEBUG: print('tagdefs',self.tagdefs)
def insert(self, index, chars, tags=None): def insert(self, index, chars, tags=None):
index = self.index(index) index = self.index(index)
@ -91,13 +91,13 @@ def delete(self, index1, index2=None):
def notify_range(self, index1, index2=None): def notify_range(self, index1, index2=None):
self.tag_add("TODO", index1, index2) self.tag_add("TODO", index1, index2)
if self.after_id: if self.after_id:
if DEBUG: print "colorizing already scheduled" if DEBUG: print("colorizing already scheduled")
return return
if self.colorizing: if self.colorizing:
self.stop_colorizing = True self.stop_colorizing = True
if DEBUG: print "stop colorizing" if DEBUG: print("stop colorizing")
if self.allow_colorizing: if self.allow_colorizing:
if DEBUG: print "schedule colorizing" if DEBUG: print("schedule colorizing")
self.after_id = self.after(1, self.recolorize) self.after_id = self.after(1, self.recolorize)
close_when_done = None # Window to be closed when done colorizing close_when_done = None # Window to be closed when done colorizing
@ -106,7 +106,7 @@ def close(self, close_when_done=None):
if self.after_id: if self.after_id:
after_id = self.after_id after_id = self.after_id
self.after_id = None self.after_id = None
if DEBUG: print "cancel scheduled recolorizer" if DEBUG: print("cancel scheduled recolorizer")
self.after_cancel(after_id) self.after_cancel(after_id)
self.allow_colorizing = False self.allow_colorizing = False
self.stop_colorizing = True self.stop_colorizing = True
@ -120,42 +120,42 @@ def toggle_colorize_event(self, event):
if self.after_id: if self.after_id:
after_id = self.after_id after_id = self.after_id
self.after_id = None self.after_id = None
if DEBUG: print "cancel scheduled recolorizer" if DEBUG: print("cancel scheduled recolorizer")
self.after_cancel(after_id) self.after_cancel(after_id)
if self.allow_colorizing and self.colorizing: if self.allow_colorizing and self.colorizing:
if DEBUG: print "stop colorizing" if DEBUG: print("stop colorizing")
self.stop_colorizing = True self.stop_colorizing = True
self.allow_colorizing = not self.allow_colorizing self.allow_colorizing = not self.allow_colorizing
if self.allow_colorizing and not self.colorizing: if self.allow_colorizing and not self.colorizing:
self.after_id = self.after(1, self.recolorize) self.after_id = self.after(1, self.recolorize)
if DEBUG: if DEBUG:
print "auto colorizing turned",\ print("auto colorizing turned",\
self.allow_colorizing and "on" or "off" self.allow_colorizing and "on" or "off")
return "break" return "break"
def recolorize(self): def recolorize(self):
self.after_id = None self.after_id = None
if not self.delegate: if not self.delegate:
if DEBUG: print "no delegate" if DEBUG: print("no delegate")
return return
if not self.allow_colorizing: if not self.allow_colorizing:
if DEBUG: print "auto colorizing is off" if DEBUG: print("auto colorizing is off")
return return
if self.colorizing: if self.colorizing:
if DEBUG: print "already colorizing" if DEBUG: print("already colorizing")
return return
try: try:
self.stop_colorizing = False self.stop_colorizing = False
self.colorizing = True self.colorizing = True
if DEBUG: print "colorizing..." if DEBUG: print("colorizing...")
t0 = time.clock() t0 = time.clock()
self.recolorize_main() self.recolorize_main()
t1 = time.clock() t1 = time.clock()
if DEBUG: print "%.3f seconds" % (t1-t0) if DEBUG: print("%.3f seconds" % (t1-t0))
finally: finally:
self.colorizing = False self.colorizing = False
if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): 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) self.after_id = self.after(1, self.recolorize)
if self.close_when_done: if self.close_when_done:
top = self.close_when_done top = self.close_when_done
@ -240,7 +240,7 @@ def recolorize_main(self):
self.tag_add("TODO", next) self.tag_add("TODO", next)
self.update() self.update()
if self.stop_colorizing: if self.stop_colorizing:
if DEBUG: print "colorizing stopped" if DEBUG: print("colorizing stopped")
return return
def removecolors(self): def removecolors(self):

View file

@ -23,7 +23,7 @@ def resetcache(self):
def cachereport(self): def cachereport(self):
keys = self.__cache.keys() keys = self.__cache.keys()
keys.sort() keys.sort()
print keys print(keys)
def setdelegate(self, delegate): def setdelegate(self, delegate):
self.resetcache() self.resetcache()

View file

@ -859,7 +859,7 @@ def load_standard_extensions(self):
try: try:
self.load_extension(name) self.load_extension(name)
except: except:
print "Failed to load extension", repr(name) print("Failed to load extension", repr(name))
import traceback import traceback
traceback.print_exc() traceback.print_exc()
@ -870,7 +870,7 @@ def load_extension(self, name):
try: try:
mod = __import__(name, globals(), locals(), []) mod = __import__(name, globals(), locals(), [])
except ImportError: except ImportError:
print "\nFailed to import extension: ", name print("\nFailed to import extension: ", name)
return return
cls = getattr(mod, name) cls = getattr(mod, name)
keydefs = idleConf.GetExtensionBindings(name) keydefs = idleConf.GetExtensionBindings(name)

View file

@ -54,7 +54,7 @@ def close_edit(self, edit):
try: try:
key = self.inversedict[edit] key = self.inversedict[edit]
except KeyError: except KeyError:
print "Don't know this EditorWindow object. (close)" print("Don't know this EditorWindow object. (close)")
return return
if key: if key:
del self.dict[key] del self.dict[key]
@ -67,7 +67,7 @@ def filename_changed_edit(self, edit):
try: try:
key = self.inversedict[edit] key = self.inversedict[edit]
except KeyError: except KeyError:
print "Don't know this EditorWindow object. (rename)" print("Don't know this EditorWindow object. (rename)")
return return
filename = edit.io.filename filename = edit.io.filename
if not filename: if not filename:

View file

@ -77,13 +77,13 @@ def grep_it(self, prog, path):
list.sort() list.sort()
self.close() self.close()
pat = self.engine.getpat() pat = self.engine.getpat()
print "Searching %r in %s ..." % (pat, path) print("Searching %r in %s ..." % (pat, path))
hits = 0 hits = 0
for fn in list: for fn in list:
try: try:
f = open(fn) f = open(fn)
except IOError as msg: except IOError as msg:
print msg print(msg)
continue continue
lineno = 0 lineno = 0
while 1: while 1:
@ -102,16 +102,16 @@ def grep_it(self, prog, path):
s = "" s = ""
else: else:
s = "s" s = "s"
print "Found", hits, "hit%s." % s print("Found", hits, "hit%s." % s)
print "(Hint: right-click to open locations.)" print("(Hint: right-click to open locations.)")
else: else:
print "No hits." print("No hits.")
def findfiles(self, dir, base, rec): def findfiles(self, dir, base, rec):
try: try:
names = os.listdir(dir or os.curdir) names = os.listdir(dir or os.curdir)
except os.error as msg: except os.error as msg:
print msg print(msg)
return [] return []
list = [] list = []
subdirs = [] subdirs = []

View file

@ -388,7 +388,7 @@ def __del__(self):
text.pack() text.pack()
def bindseq(seq, n=[0]): def bindseq(seq, n=[0]):
def handler(event): def handler(event):
print seq print(seq)
text.bind("<<handler%d>>"%n[0], handler) text.bind("<<handler%d>>"%n[0], handler)
text.event_add("<<handler%d>>"%n[0], seq) text.event_add("<<handler%d>>"%n[0], seq)
n[0] += 1 n[0] += 1

View file

@ -58,10 +58,10 @@ def __init__(self, name):
self.name = name self.name = name
Delegator.__init__(self, None) Delegator.__init__(self, None)
def insert(self, *args): def insert(self, *args):
print self.name, ": insert", args print(self.name, ": insert", args)
self.delegate.insert(*args) self.delegate.insert(*args)
def delete(self, *args): def delete(self, *args):
print self.name, ": delete", args print(self.name, ": delete", args)
self.delegate.delete(*args) self.delegate.delete(*args)
root = Tk() root = Tk()
root.wm_protocol("WM_DELETE_WINDOW", root.quit) root.wm_protocol("WM_DELETE_WINDOW", root.quit)

View file

@ -19,8 +19,8 @@
try: try:
from Tkinter import * from Tkinter import *
except ImportError: except ImportError:
print>>sys.__stderr__, "** IDLE can't import Tkinter. " \ print("** IDLE can't import Tkinter. " \
"Your Python may not be configured for Tk. **" "Your Python may not be configured for Tk. **", file=sys.__stderr__)
sys.exit(1) sys.exit(1)
import tkMessageBox import tkMessageBox
@ -504,14 +504,14 @@ def poll_subprocess(self):
console = self.tkconsole.console console = self.tkconsole.console
if how == "OK": if how == "OK":
if what is not None: if what is not None:
print >>console, repr(what) print(repr(what), file=console)
elif how == "EXCEPTION": elif how == "EXCEPTION":
if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"): if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
self.remote_stack_viewer() self.remote_stack_viewer()
elif how == "ERROR": elif how == "ERROR":
errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n" errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n"
print >>sys.__stderr__, errmsg, what print(errmsg, what, file=sys.__stderr__)
print >>console, errmsg, what print(errmsg, what, file=console)
# we received a response to the currently active seq number: # we received a response to the currently active seq number:
try: try:
self.tkconsole.endexecuting() self.tkconsole.endexecuting()
@ -576,8 +576,8 @@ def execfile(self, filename, source=None):
except (OverflowError, SyntaxError): except (OverflowError, SyntaxError):
self.tkconsole.resetoutput() self.tkconsole.resetoutput()
tkerr = self.tkconsole.stderr tkerr = self.tkconsole.stderr
print>>tkerr, '*** Error in script or command!\n' print('*** Error in script or command!\n', file=tkerr)
print>>tkerr, 'Traceback (most recent call last):' print('Traceback (most recent call last):', file=tkerr)
InteractiveInterpreter.showsyntaxerror(self, filename) InteractiveInterpreter.showsyntaxerror(self, filename)
self.tkconsole.showprompt() self.tkconsole.showprompt()
else: else:
@ -730,8 +730,7 @@ def runcode(self, code):
if use_subprocess: if use_subprocess:
# When run w/o subprocess, both user and IDLE errors # When run w/o subprocess, both user and IDLE errors
# are printed here; skip message in that case. # are printed here; skip message in that case.
print >> self.tkconsole.stderr, \ print("IDLE internal error in runcode()", file=self.tkconsole.stderr)
"IDLE internal error in runcode()"
self.showtraceback() self.showtraceback()
if use_subprocess: if use_subprocess:
self.tkconsole.endexecuting() self.tkconsole.endexecuting()
@ -1349,7 +1348,7 @@ def main():
if os.path.isfile(script): if os.path.isfile(script):
pass pass
else: else:
print "No script file: ", script print("No script file: ", script)
sys.exit() sys.exit()
enable_shell = True enable_shell = True
if o == '-s': if o == '-s':

View file

@ -124,8 +124,8 @@ def test():
root.protocol("WM_DELETE_WINDOW", root.destroy) root.protocol("WM_DELETE_WINDOW", root.destroy)
class MyScrolledList(ScrolledList): class MyScrolledList(ScrolledList):
def fill_menu(self): self.menu.add_command(label="pass") def fill_menu(self): self.menu.add_command(label="pass")
def on_select(self, index): print "select", self.get(index) def on_select(self, index): print("select", self.get(index))
def on_double(self, index): print "double", self.get(index) def on_double(self, index): print("double", self.get(index))
s = MyScrolledList(root) s = MyScrolledList(root)
for i in range(30): for i in range(30):
s.append("item %02d" % i) s.append("item %02d" % i)

View file

@ -38,10 +38,10 @@ def setdelegate(self, delegate):
def dump_event(self, event): def dump_event(self, event):
from pprint import pprint from pprint import pprint
pprint(self.undolist[:self.pointer]) pprint(self.undolist[:self.pointer])
print "pointer:", self.pointer, print("pointer:", self.pointer, end=' ')
print "saved:", self.saved, print("saved:", self.saved, end=' ')
print "can_merge:", self.can_merge, print("can_merge:", self.can_merge, end=' ')
print "get_saved():", self.get_saved() print("get_saved():", self.get_saved())
pprint(self.undolist[self.pointer:]) pprint(self.undolist[self.pointer:])
return "break" return "break"

View file

@ -83,7 +83,7 @@ def main():
redir = WidgetRedirector(text) redir = WidgetRedirector(text)
global orig_insert global orig_insert
def my_insert(*args): def my_insert(*args):
print "insert", args print("insert", args)
orig_insert(*args) orig_insert(*args)
orig_insert = redir.register("insert", my_insert) orig_insert = redir.register("insert", my_insert)
root.mainloop() root.mainloop()

View file

@ -46,7 +46,7 @@ def call_callbacks(self):
callback() callback()
except: except:
t, v, tb = sys.exc_info() t, v, tb = sys.exc_info()
print "warning: callback failed in WindowList", t, ":", v print("warning: callback failed in WindowList", t, ":", v)
registry = WindowList() registry = WindowList()

View file

@ -679,18 +679,18 @@ def SaveUserCfgFiles(self):
### module test ### module test
if __name__ == '__main__': if __name__ == '__main__':
def dumpCfg(cfg): def dumpCfg(cfg):
print '\n',cfg,'\n' print('\n',cfg,'\n')
for key in cfg.keys(): for key in cfg.keys():
sections=cfg[key].sections() sections=cfg[key].sections()
print key print(key)
print sections print(sections)
for section in sections: for section in sections:
options=cfg[key].options(section) options=cfg[key].options(section)
print section print(section)
print options print(options)
for option in options: for option in options:
print option, '=', cfg[key].Get(section,option) print(option, '=', cfg[key].Get(section,option))
dumpCfg(idleConf.defaultCfg) dumpCfg(idleConf.defaultCfg)
dumpCfg(idleConf.userCfg) dumpCfg(idleConf.userCfg)
print idleConf.userCfg['main'].Get('Theme','name') print(idleConf.userCfg['main'].Get('Theme','name'))
#print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal') #print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal')

Some files were not shown because too many files have changed in this diff Show more