summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rwxr-xr-xDemo/cgi/cgi1.py8
-rwxr-xr-xDemo/cgi/cgi2.py12
-rw-r--r--Demo/cgi/wiki.py54
-rwxr-xr-xDemo/classes/Complex.py30
-rwxr-xr-xDemo/classes/Dates.py40
-rwxr-xr-xDemo/classes/Dbm.py26
-rwxr-xr-xDemo/classes/Range.py10
-rwxr-xr-xDemo/classes/Rat.py72
-rwxr-xr-xDemo/classes/Vec.py16
-rwxr-xr-xDemo/classes/bitvec.py75
-rwxr-xr-xDemo/comparisons/regextest.py6
-rwxr-xr-xDemo/comparisons/sortingtest.py6
-rwxr-xr-xDemo/comparisons/systemtest.py14
-rwxr-xr-xDemo/curses/life.py12
-rwxr-xr-xDemo/curses/repeat.py6
-rw-r--r--Demo/imputil/importers.py8
-rw-r--r--Demo/imputil/knee.py10
-rwxr-xr-xDemo/md5test/md5driver.py18
-rw-r--r--Demo/metaclasses/Enum.py45
-rw-r--r--Demo/metaclasses/Meta.py18
-rw-r--r--Demo/metaclasses/Simple.py6
-rw-r--r--Demo/metaclasses/Synch.py41
-rw-r--r--Demo/metaclasses/Trace.py42
-rw-r--r--Demo/newmetaclasses/Eiffel.py2
-rw-r--r--Demo/newmetaclasses/Enum.py64
-rw-r--r--Demo/parser/example.py6
-rwxr-xr-xDemo/parser/test_parser.py14
-rw-r--r--Demo/parser/unparse.py17
-rwxr-xr-xDemo/pdist/FSProxy.py18
-rwxr-xr-xDemo/pdist/RCSProxy.py12
-rwxr-xr-xDemo/pdist/client.py26
-rwxr-xr-xDemo/pdist/cmdfw.py30
-rwxr-xr-xDemo/pdist/cmptree.py86
-rwxr-xr-xDemo/pdist/cvslib.py40
-rwxr-xr-xDemo/pdist/cvslock.py32
-rwxr-xr-xDemo/pdist/mac.py2
-rwxr-xr-xDemo/pdist/makechangelog.py16
-rwxr-xr-xDemo/pdist/rcslib.py18
-rwxr-xr-xDemo/pdist/rcvs.py70
-rwxr-xr-xDemo/pdist/rrcs.py58
-rwxr-xr-xDemo/pdist/security.py8
-rwxr-xr-xDemo/pdist/server.py30
-rwxr-xr-xDemo/pdist/sumtree.py4
-rwxr-xr-xDemo/pysvr/pysvr.py18
-rw-r--r--Demo/rpc/mountclient.py4
-rw-r--r--Demo/rpc/nfsclient.py8
-rw-r--r--Demo/rpc/rnusersclient.py10
-rw-r--r--Demo/rpc/rpc.py92
-rw-r--r--Demo/rpc/xdr.py26
-rw-r--r--Demo/scripts/beer.py8
-rwxr-xr-xDemo/scripts/eqfix.py12
-rwxr-xr-xDemo/scripts/fact.py6
-rw-r--r--Demo/scripts/find-uname.py6
-rwxr-xr-xDemo/scripts/from.py6
-rwxr-xr-xDemo/scripts/ftpstats.py24
-rwxr-xr-xDemo/scripts/lpwatch.py8
-rwxr-xr-xDemo/scripts/makedir.py2
-rwxr-xr-xDemo/scripts/markov.py56
-rwxr-xr-xDemo/scripts/mboxconvert.py14
-rwxr-xr-xDemo/scripts/mkrcs.py16
-rwxr-xr-xDemo/scripts/newslist.py72
-rwxr-xr-xDemo/scripts/pi.py6
-rwxr-xr-xDemo/scripts/pp.py2
-rwxr-xr-xDemo/scripts/primes.py4
-rwxr-xr-xDemo/scripts/queens.py14
-rwxr-xr-xDemo/scripts/script.py2
-rwxr-xr-xDemo/scripts/unbirthday.py42
-rwxr-xr-xDemo/scripts/update.py34
-rwxr-xr-xDemo/sockets/echosvr.py2
-rwxr-xr-xDemo/sockets/ftp.py12
-rwxr-xr-xDemo/sockets/gopher.py92
-rwxr-xr-xDemo/sockets/mcast.py4
-rwxr-xr-xDemo/sockets/rpython.py4
-rwxr-xr-xDemo/sockets/rpythond.py8
-rwxr-xr-xDemo/sockets/telnet.py14
-rwxr-xr-xDemo/sockets/throughput.py20
-rwxr-xr-xDemo/sockets/udpecho.py12
-rw-r--r--Demo/sockets/unixclient.py2
-rw-r--r--Demo/sockets/unixserver.py2
-rw-r--r--Demo/threads/Coroutine.py14
-rw-r--r--Demo/threads/Generator.py18
-rw-r--r--Demo/threads/fcmp.py26
-rw-r--r--Demo/threads/find.py8
-rw-r--r--Demo/threads/squasher.py4
-rw-r--r--Demo/threads/sync.py52
-rw-r--r--Demo/threads/telnet.py14
-rwxr-xr-xDemo/tix/samples/OptMenu.py2
-rw-r--r--Demo/tix/tixwidgets.py2
-rwxr-xr-xDemo/tkinter/guido/AttrDialog.py22
-rwxr-xr-xDemo/tkinter/guido/ManPage.py4
-rwxr-xr-xDemo/tkinter/guido/ShellWindow.py2
-rwxr-xr-xDemo/tkinter/guido/dialog.py4
-rwxr-xr-xDemo/tkinter/guido/mbox.py6
-rwxr-xr-xDemo/tkinter/guido/rmt.py2
-rwxr-xr-xDemo/tkinter/guido/solitaire.py4
-rw-r--r--Demo/tkinter/guido/sortvisu.py2
-rw-r--r--Demo/tkinter/guido/ss1.py28
-rwxr-xr-xDemo/tkinter/guido/svkill.py2
-rwxr-xr-xDemo/tkinter/guido/tkman.py8
-rwxr-xr-xDemo/tkinter/guido/wish.py4
-rw-r--r--Demo/tkinter/matt/00-HELLO-WORLD.py2
-rw-r--r--Demo/tkinter/matt/animation-simple.py2
-rw-r--r--Demo/tkinter/matt/animation-w-velocity-ctrl.py2
-rw-r--r--Demo/tkinter/matt/bind-w-mult-calls-p-type.py4
-rw-r--r--Demo/tkinter/matt/canvas-demo-simple.py2
-rw-r--r--Demo/tkinter/matt/canvas-gridding.py2
-rw-r--r--Demo/tkinter/matt/canvas-reading-tag-info.py10
-rw-r--r--Demo/tkinter/matt/canvas-w-widget-draw-el.py2
-rw-r--r--Demo/tkinter/matt/canvas-with-scrollbars.py6
-rw-r--r--Demo/tkinter/matt/dialog-box.py2
-rw-r--r--Demo/tkinter/matt/entry-simple.py2
-rw-r--r--Demo/tkinter/matt/entry-with-shared-variable.py2
-rw-r--r--Demo/tkinter/matt/killing-window-w-wm.py4
-rw-r--r--Demo/tkinter/matt/menu-all-types-of-entries.py8
-rw-r--r--Demo/tkinter/matt/menu-simple.py4
-rw-r--r--Demo/tkinter/matt/packer-and-placer-together.py2
-rw-r--r--Demo/tkinter/matt/packer-simple.py2
-rw-r--r--Demo/tkinter/matt/placer-simple.py2
-rw-r--r--Demo/tkinter/matt/printing-coords-of-items.py2
-rw-r--r--Demo/tkinter/matt/radiobutton-simple.py2
-rw-r--r--Demo/tkinter/matt/rubber-band-box-demo-1.py2
-rw-r--r--Demo/tkinter/matt/rubber-line-demo-1.py2
-rw-r--r--Demo/tkinter/matt/slider-demo-1.py2
-rw-r--r--Demo/tkinter/matt/subclass-existing-widgets.py2
-rw-r--r--Demo/tkinter/matt/two-radio-groups.py6
-rw-r--r--Demo/tkinter/matt/window-creation-more.py2
-rw-r--r--Demo/tkinter/matt/window-creation-simple.py2
-rw-r--r--Demo/tkinter/matt/window-creation-w-location.py4
-rw-r--r--Demo/xml/elem_count.py18
-rw-r--r--Demo/xml/roundtrip.py2
-rwxr-xr-xDemo/zlib/minigzip.py12
-rwxr-xr-xDemo/zlib/zlibdemo.py14
132 files changed, 1071 insertions, 1081 deletions
diff --git a/Demo/cgi/cgi1.py b/Demo/cgi/cgi1.py
index 9d25c7d..842fef2 100755
--- a/Demo/cgi/cgi1.py
+++ b/Demo/cgi/cgi1.py
@@ -8,7 +8,7 @@
# If cgi0.sh works but cgi1.py doesn't, check the #! line and the file
# permissions. The docs for the cgi.py module have debugging tips.
-print "Content-type: text/html"
-print
-print "<h1>Hello world</h1>"
-print "<p>This is cgi1.py"
+print("Content-type: text/html")
+print()
+print("<h1>Hello world</h1>")
+print("<p>This is cgi1.py")
diff --git a/Demo/cgi/cgi2.py b/Demo/cgi/cgi2.py
index d956f65..239fb6b 100755
--- a/Demo/cgi/cgi2.py
+++ b/Demo/cgi/cgi2.py
@@ -8,15 +8,15 @@ import cgi
def main():
form = cgi.FieldStorage()
- print "Content-type: text/html"
- print
+ print("Content-type: text/html")
+ print()
if not form:
- print "<h1>No Form Keys</h1>"
+ print("<h1>No Form Keys</h1>")
else:
- print "<h1>Form Keys</h1>"
- for key in form.keys():
+ print("<h1>Form Keys</h1>")
+ for key in list(form.keys()):
value = form[key].value
- print "<p>", cgi.escape(key), ":", cgi.escape(value)
+ print("<p>", cgi.escape(key), ":", cgi.escape(value))
if __name__ == "__main__":
main()
diff --git a/Demo/cgi/wiki.py b/Demo/cgi/wiki.py
index 2f944d6..6b97113 100644
--- a/Demo/cgi/wiki.py
+++ b/Demo/cgi/wiki.py
@@ -5,8 +5,8 @@ escape = cgi.escape
def main():
form = cgi.FieldStorage()
- print "Content-type: text/html"
- print
+ print("Content-type: text/html")
+ print()
cmd = form.getvalue("cmd", "view")
page = form.getvalue("page", "FrontPage")
wiki = WikiPage(page)
@@ -20,22 +20,22 @@ class WikiPage:
def __init__(self, name):
if not self.iswikiword(name):
- raise ValueError, "page name is not a wiki word"
+ raise ValueError("page name is not a wiki word")
self.name = name
self.load()
def cmd_view(self, form):
- print "<h1>", escape(self.splitwikiword(self.name)), "</h1>"
- print "<p>"
+ print("<h1>", escape(self.splitwikiword(self.name)), "</h1>")
+ print("<p>")
for line in self.data.splitlines():
line = line.rstrip()
if not line:
- print "<p>"
+ print("<p>")
else:
- print self.formatline(line)
- print "<hr>"
- print "<p>", self.mklink("edit", self.name, "Edit this page") + ";"
- print self.mklink("view", "FrontPage", "go to front page") + "."
+ print(self.formatline(line))
+ print("<hr>")
+ print("<p>", self.mklink("edit", self.name, "Edit this page") + ";")
+ print(self.mklink("view", "FrontPage", "go to front page") + ".")
def formatline(self, line):
words = []
@@ -51,32 +51,32 @@ class WikiPage:
return "".join(words)
def cmd_edit(self, form, label="Change"):
- print "<h1>", label, self.name, "</h1>"
- print '<form method="POST" action="%s">' % self.scripturl
+ print("<h1>", label, self.name, "</h1>")
+ print('<form method="POST" action="%s">' % self.scripturl)
s = '<textarea cols="70" rows="20" name="text">%s</textarea>'
- print s % self.data
- print '<input type="hidden" name="cmd" value="create">'
- print '<input type="hidden" name="page" value="%s">' % self.name
- print '<br>'
- print '<input type="submit" value="%s Page">' % label
- print "</form>"
+ print(s % self.data)
+ print('<input type="hidden" name="cmd" value="create">')
+ print('<input type="hidden" name="page" value="%s">' % self.name)
+ print('<br>')
+ print('<input type="submit" value="%s Page">' % label)
+ print("</form>")
def cmd_create(self, form):
self.data = form.getvalue("text", "").strip()
error = self.store()
if error:
- print "<h1>I'm sorry. That didn't work</h1>"
- print "<p>An error occurred while attempting to write the file:"
- print "<p>", escape(error)
+ print("<h1>I'm sorry. That didn't work</h1>")
+ print("<p>An error occurred while attempting to write the file:")
+ print("<p>", escape(error))
else:
# Use a redirect directive, to avoid "reload page" problems
- print "<head>"
+ print("<head>")
s = '<meta http-equiv="refresh" content="1; URL=%s">'
- print s % (self.scripturl + "?cmd=view&page=" + self.name)
- print "<head>"
- print "<h1>OK</h1>"
- print "<p>If nothing happens, please click here:",
- print self.mklink("view", self.name, self.name)
+ print(s % (self.scripturl + "?cmd=view&page=" + self.name))
+ print("<head>")
+ print("<h1>OK</h1>")
+ print("<p>If nothing happens, please click here:", end=' ')
+ print(self.mklink("view", self.name, self.name))
def cmd_new(self, form):
self.cmd_edit(form, label="Create")
diff --git a/Demo/classes/Complex.py b/Demo/classes/Complex.py
index 2019cdf..b6c4b10 100755
--- a/Demo/classes/Complex.py
+++ b/Demo/classes/Complex.py
@@ -114,7 +114,7 @@ class Complex:
self.__dict__['im'] = _im
def __setattr__(self, name, value):
- raise TypeError, 'Complex numbers are immutable'
+ raise TypeError('Complex numbers are immutable')
def __hash__(self):
if not self.im:
@@ -144,17 +144,17 @@ class Complex:
def __int__(self):
if self.im:
- raise ValueError, "can't convert Complex with nonzero im to int"
+ raise ValueError("can't convert Complex with nonzero im to int")
return int(self.re)
def __long__(self):
if self.im:
- raise ValueError, "can't convert Complex with nonzero im to long"
- return long(self.re)
+ raise ValueError("can't convert Complex with nonzero im to long")
+ return int(self.re)
def __float__(self):
if self.im:
- raise ValueError, "can't convert Complex with nonzero im to float"
+ raise ValueError("can't convert Complex with nonzero im to float")
return float(self.re)
def __cmp__(self, other):
@@ -199,7 +199,7 @@ class Complex:
def __div__(self, other):
other = ToComplex(other)
d = float(other.re*other.re + other.im*other.im)
- if not d: raise ZeroDivisionError, 'Complex division'
+ if not d: raise ZeroDivisionError('Complex division')
return Complex((self.re*other.re + self.im*other.im) / d,
(self.im*other.re - self.re*other.im) / d)
@@ -209,10 +209,10 @@ class Complex:
def __pow__(self, n, z=None):
if z is not None:
- raise TypeError, 'Complex does not support ternary pow()'
+ raise TypeError('Complex does not support ternary pow()')
if IsComplex(n):
if n.im:
- if self.im: raise TypeError, 'Complex to the Complex power'
+ if self.im: raise TypeError('Complex to the Complex power')
else: return exp(math.log(self.re)*n)
n = n.re
r = pow(self.abs(), n)
@@ -229,21 +229,21 @@ def exp(z):
def checkop(expr, a, b, value, fuzz = 1e-6):
- print ' ', a, 'and', b,
+ print(' ', a, 'and', b, end=' ')
try:
result = eval(expr)
except:
result = sys.exc_info()[0]
- print '->', result
+ print('->', result)
if isinstance(result, str) or isinstance(value, str):
ok = (result == value)
else:
ok = abs(result - value) <= fuzz
if not ok:
- print '!!\t!!\t!! should be', value, 'diff', abs(result - value)
+ print('!!\t!!\t!! should be', value, 'diff', abs(result - value))
def test():
- print 'test constructors'
+ print('test constructors')
constructor_test = (
# "expect" is an array [re,im] "got" the Complex.
( (0,0), Complex() ),
@@ -260,9 +260,9 @@ def test():
for t in constructor_test:
cnt[0] += 1
if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)):
- print " expected", t[0], "got", t[1]
+ print(" expected", t[0], "got", t[1])
cnt[1] += 1
- print " ", cnt[1], "of", cnt[0], "tests failed"
+ print(" ", cnt[1], "of", cnt[0], "tests failed")
# test operators
testsuite = {
'a+b': [
@@ -310,7 +310,7 @@ def test():
],
}
for expr in sorted(testsuite):
- print expr + ':'
+ print(expr + ':')
t = (expr,)
for item in testsuite[expr]:
checkop(*(t+item))
diff --git a/Demo/classes/Dates.py b/Demo/classes/Dates.py
index 6494b6a..afb0ff2 100755
--- a/Demo/classes/Dates.py
+++ b/Demo/classes/Dates.py
@@ -57,7 +57,7 @@ for dim in _DAYS_IN_MONTH:
dbm = dbm + dim
del dbm, dim
-_INT_TYPES = type(1), type(1L)
+_INT_TYPES = type(1), type(1)
def _is_leap(year): # 1 if leap year, else 0
if year % 4 != 0: return 0
@@ -68,7 +68,7 @@ def _days_in_year(year): # number of days in year
return 365 + _is_leap(year)
def _days_before_year(year): # number of days before year
- return year*365L + (year+3)/4 - (year+99)/100 + (year+399)/400
+ return year*365 + (year+3)/4 - (year+99)/100 + (year+399)/400
def _days_in_month(month, year): # number of days in month of year
if month == 2 and _is_leap(year): return 29
@@ -86,7 +86,7 @@ _DI400Y = _days_before_year(400) # number of days in 400 years
def _num2date(n): # return date with ordinal n
if type(n) not in _INT_TYPES:
- raise TypeError, 'argument must be integer: %r' % type(n)
+ raise TypeError('argument must be integer: %r' % type(n))
ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj
del ans.ord, ans.month, ans.day, ans.year # un-initialize it
@@ -120,17 +120,17 @@ def _num2day(n): # return weekday name of day with ordinal n
class Date:
def __init__(self, month, day, year):
if not 1 <= month <= 12:
- raise ValueError, 'month must be in 1..12: %r' % (month,)
+ raise ValueError('month must be in 1..12: %r' % (month,))
dim = _days_in_month(month, year)
if not 1 <= day <= dim:
- raise ValueError, 'day must be in 1..%r: %r' % (dim, day)
+ raise ValueError('day must be in 1..%r: %r' % (dim, day))
self.month, self.day, self.year = month, day, year
self.ord = _date2num(self)
# don't allow setting existing attributes
def __setattr__(self, name, value):
- if self.__dict__.has_key(name):
- raise AttributeError, 'read-only attribute ' + name
+ if name in self.__dict__:
+ raise AttributeError('read-only attribute ' + name)
self.__dict__[name] = value
def __cmp__(self, other):
@@ -151,7 +151,7 @@ class Date:
# Python 1.1 coerces neither int+date nor date+int
def __add__(self, n):
if type(n) not in _INT_TYPES:
- raise TypeError, 'can\'t add %r to date' % type(n)
+ raise TypeError('can\'t add %r to date' % type(n))
return _num2date(self.ord + n)
__radd__ = __add__ # handle int+date
@@ -164,7 +164,7 @@ class Date:
# complain about int-date
def __rsub__(self, other):
- raise TypeError, 'Can\'t subtract date from integer'
+ raise TypeError('Can\'t subtract date from integer')
def weekday(self):
return _num2day(self.ord)
@@ -179,30 +179,30 @@ def test(firstyear, lastyear):
a = Date(9,30,1913)
b = Date(9,30,1914)
if repr(a) != 'Tue 30 Sep 1913':
- raise DateTestError, '__repr__ failure'
+ raise DateTestError('__repr__ failure')
if (not a < b) or a == b or a > b or b != b:
- raise DateTestError, '__cmp__ failure'
+ raise DateTestError('__cmp__ failure')
if a+365 != b or 365+a != b:
- raise DateTestError, '__add__ failure'
+ raise DateTestError('__add__ failure')
if b-a != 365 or b-365 != a:
- raise DateTestError, '__sub__ failure'
+ raise DateTestError('__sub__ failure')
try:
x = 1 - a
- raise DateTestError, 'int-date should have failed'
+ raise DateTestError('int-date should have failed')
except TypeError:
pass
try:
x = a + b
- raise DateTestError, 'date+date should have failed'
+ raise DateTestError('date+date should have failed')
except TypeError:
pass
if a.weekday() != 'Tuesday':
- raise DateTestError, 'weekday() failure'
+ raise DateTestError('weekday() failure')
if max(a,b) is not b or min(a,b) is not a:
- raise DateTestError, 'min/max failure'
+ raise DateTestError('min/max failure')
d = {a-1:b, b:a+1}
if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913):
- raise DateTestError, 'dictionary failure'
+ raise DateTestError('dictionary failure')
# verify date<->number conversions for first and last days for
# all years in firstyear .. lastyear
@@ -214,9 +214,9 @@ def test(firstyear, lastyear):
lord = ford + _days_in_year(y) - 1
fd, ld = Date(1,1,y), Date(12,31,y)
if (fd.ord,ld.ord) != (ford,lord):
- raise DateTestError, ('date->num failed', y)
+ raise DateTestError('date->num failed', y)
fd, ld = _num2date(ford), _num2date(lord)
if (1,1,y,12,31,y) != \
(fd.month,fd.day,fd.year,ld.month,ld.day,ld.year):
- raise DateTestError, ('num->date failed', y)
+ raise DateTestError('num->date failed', y)
y = y + 1
diff --git a/Demo/classes/Dbm.py b/Demo/classes/Dbm.py
index 482806a..fd73571 100755
--- a/Demo/classes/Dbm.py
+++ b/Demo/classes/Dbm.py
@@ -12,7 +12,7 @@ class Dbm:
def __repr__(self):
s = ''
- for key in self.keys():
+ for key in list(self.keys()):
t = repr(key) + ': ' + repr(self[key])
if s: t = ', ' + t
s = s + t
@@ -32,35 +32,35 @@ class Dbm:
def keys(self):
res = []
- for key in self.db.keys():
+ for key in list(self.db.keys()):
res.append(eval(key))
return res
def has_key(self, key):
- return self.db.has_key(repr(key))
+ return repr(key) in self.db
def test():
- d = Dbm('@dbm', 'rw', 0600)
- print d
+ d = Dbm('@dbm', 'rw', 0o600)
+ print(d)
while 1:
try:
- key = input('key: ')
- if d.has_key(key):
+ key = eval(input('key: '))
+ if key in d:
value = d[key]
- print 'currently:', value
- value = input('value: ')
+ print('currently:', value)
+ value = eval(input('value: '))
if value == None:
del d[key]
else:
d[key] = value
except KeyboardInterrupt:
- print ''
- print d
+ print('')
+ print(d)
except EOFError:
- print '[eof]'
+ print('[eof]')
break
- print d
+ print(d)
test()
diff --git a/Demo/classes/Range.py b/Demo/classes/Range.py
index 3f1daae..0f84157 100755
--- a/Demo/classes/Range.py
+++ b/Demo/classes/Range.py
@@ -60,7 +60,7 @@ class oldrange:
if 0 <= i <= self.len:
return self.start + self.step * i
else:
- raise IndexError, 'range[i] index out of range'
+ raise IndexError('range[i] index out of range')
def test():
@@ -73,7 +73,7 @@ def test():
raise Exception("error in implementation:\ncorrect = %s"
"\nold-style = %s\ngenerator = %s" %
(correct_result, oldrange_result, genrange_result))
- print "Timings for range(1000):"
+ print("Timings for range(1000):")
t1 = time.time()
for i in oldrange(1000):
pass
@@ -84,9 +84,9 @@ def test():
for i in __builtin__.range(1000):
pass
t4 = time.time()
- print t2-t1, 'sec (old-style class)'
- print t3-t2, 'sec (generator)'
- print t4-t3, 'sec (built-in)'
+ print(t2-t1, 'sec (old-style class)')
+ print(t3-t2, 'sec (generator)')
+ print(t4-t3, 'sec (built-in)')
if __name__ == '__main__':
diff --git a/Demo/classes/Rat.py b/Demo/classes/Rat.py
index 24670b6..8caf1c5 100755
--- a/Demo/classes/Rat.py
+++ b/Demo/classes/Rat.py
@@ -42,7 +42,7 @@ class Rat:
def __init__(self, num, den = 1):
if den == 0:
- raise ZeroDivisionError, 'rat(x, 0)'
+ raise ZeroDivisionError('rat(x, 0)')
# normalize
@@ -106,9 +106,9 @@ class Rat:
return rat(a.__num * b.__den + b.__num * a.__den,
a.__den * b.__den)
except OverflowError:
- return rat(long(a.__num) * long(b.__den) +
- long(b.__num) * long(a.__den),
- long(a.__den) * long(b.__den))
+ return rat(int(a.__num) * int(b.__den) +
+ int(b.__num) * int(a.__den),
+ int(a.__den) * int(b.__den))
def __radd__(b, a):
return Rat(a) + b
@@ -119,9 +119,9 @@ class Rat:
return rat(a.__num * b.__den - b.__num * a.__den,
a.__den * b.__den)
except OverflowError:
- return rat(long(a.__num) * long(b.__den) -
- long(b.__num) * long(a.__den),
- long(a.__den) * long(b.__den))
+ return rat(int(a.__num) * int(b.__den) -
+ int(b.__num) * int(a.__den),
+ int(a.__den) * int(b.__den))
def __rsub__(b, a):
return Rat(a) - b
@@ -131,8 +131,8 @@ class Rat:
try:
return rat(a.__num * b.__num, a.__den * b.__den)
except OverflowError:
- return rat(long(a.__num) * long(b.__num),
- long(a.__den) * long(b.__den))
+ return rat(int(a.__num) * int(b.__num),
+ int(a.__den) * int(b.__den))
def __rmul__(b, a):
return Rat(a) * b
@@ -142,8 +142,8 @@ class Rat:
try:
return rat(a.__num * b.__den, a.__den * b.__num)
except OverflowError:
- return rat(long(a.__num) * long(b.__den),
- long(a.__den) * long(b.__num))
+ return rat(int(a.__num) * int(b.__den),
+ int(a.__den) * int(b.__num))
def __rdiv__(b, a):
return Rat(a) / b
@@ -154,7 +154,7 @@ class Rat:
try:
div = int(div)
except OverflowError:
- div = long(div)
+ div = int(div)
return a - b * div
def __rmod__(b, a):
@@ -175,8 +175,8 @@ class Rat:
try:
return rat(a.__num ** b.__num, a.__den ** b.__num)
except OverflowError:
- return rat(long(a.__num) ** b.__num,
- long(a.__den) ** b.__num)
+ return rat(int(a.__num) ** b.__num,
+ int(a.__den) ** b.__num)
def __rpow__(b, a):
return Rat(a) ** b
@@ -187,7 +187,7 @@ class Rat:
return rat(-a.__num, a.__den)
except OverflowError:
# a.__num == sys.maxint
- return rat(-long(a.__num), a.__den)
+ return rat(-int(a.__num), a.__den)
# abs(a)
def __abs__(a):
@@ -199,7 +199,7 @@ class Rat:
# long(a)
def __long__(a):
- return long(a.__num) / long(a.__den)
+ return int(a.__num) / int(a.__den)
# float(a)
def __float__(a):
@@ -272,38 +272,38 @@ def test():
(3+1.5j) 1.5j (2.25+2.25j) (1+1j) (1.18235814075+2.85446505899j) 1
(3+3j) 0j 4.5j (1+0j) (-0.638110484918+0.705394566962j) 0
'''
- print rat(-1L, 1)
- print rat(1, -1)
+ print(rat(-1, 1))
+ print(rat(1, -1))
a = rat(1, 10)
- print int(a), long(a), float(a), complex(a)
+ print(int(a), int(a), float(a), complex(a))
b = rat(2, 5)
l = [a+b, a-b, a*b, a/b]
- print l
+ print(l)
l.sort()
- print l
- print rat(0, 1)
- print a+1
- print a+1L
- print a+1.0
+ print(l)
+ print(rat(0, 1))
+ print(a+1)
+ print(a+1)
+ print(a+1.0)
try:
- print rat(1, 0)
- raise SystemError, 'should have been ZeroDivisionError'
+ print(rat(1, 0))
+ raise SystemError('should have been ZeroDivisionError')
except ZeroDivisionError:
- print 'OK'
- print rat(2), rat(1.5), rat(3, 2), rat(1.5+1.5j), rat(31415926,10000000)
+ print('OK')
+ print(rat(2), rat(1.5), rat(3, 2), rat(1.5+1.5j), rat(31415926,10000000))
list = [2, 1.5, rat(3,2), 1.5+1.5j]
for i in list:
- print i,
+ print(i, end=' ')
if not isinstance(i, complex):
- print int(i), float(i),
- print complex(i)
- print
+ print(int(i), float(i), end=' ')
+ print(complex(i))
+ print()
for j in list:
- print i + j, i - j, i * j, i / j, i ** j,
+ print(i + j, i - j, i * j, i / j, i ** j, end=' ')
if not (isinstance(i, complex) or
isinstance(j, complex)):
- print cmp(i, j)
- print
+ print(cmp(i, j))
+ print()
if __name__ == '__main__':
diff --git a/Demo/classes/Vec.py b/Demo/classes/Vec.py
index 56cb839..edb3147 100755
--- a/Demo/classes/Vec.py
+++ b/Demo/classes/Vec.py
@@ -27,17 +27,17 @@ class Vec:
def __add__(self, other):
# Element-wise addition
- v = map(lambda x, y: x+y, self, other)
+ v = list(map(lambda x, y: x+y, self, other))
return Vec().fromlist(v)
def __sub__(self, other):
# Element-wise subtraction
- v = map(lambda x, y: x-y, self, other)
+ v = list(map(lambda x, y: x-y, self, other))
return Vec().fromlist(v)
def __mul__(self, scalar):
# Multiply by scalar
- v = map(lambda x: x*scalar, self.v)
+ v = [x*scalar for x in self.v]
return Vec().fromlist(v)
@@ -45,10 +45,10 @@ class Vec:
def test():
a = vec(1, 2, 3)
b = vec(3, 2, 1)
- print a
- print b
- print a+b
- print a-b
- print a*3.0
+ print(a)
+ print(b)
+ print(a+b)
+ print(a-b)
+ print(a*3.0)
test()
diff --git a/Demo/classes/bitvec.py b/Demo/classes/bitvec.py
index 934d33a..97921f2 100755
--- a/Demo/classes/bitvec.py
+++ b/Demo/classes/bitvec.py
@@ -11,14 +11,14 @@ error = 'bitvec.error'
def _check_value(value):
if type(value) != type(0) or not 0 <= value < 2:
- raise error, 'bitvec() items must have int value 0 or 1'
+ raise error('bitvec() items must have int value 0 or 1')
import math
def _compute_len(param):
mant, l = math.frexp(float(param))
- bitmask = 1L << l
+ bitmask = 1 << l
if bitmask <= param:
raise 'FATAL', '(param, l) = %r' % ((param, l),)
while l:
@@ -31,11 +31,11 @@ def _compute_len(param):
def _check_key(len, key):
if type(key) != type(0):
- raise TypeError, 'sequence subscript not int'
+ raise TypeError('sequence subscript not int')
if key < 0:
key = key + len
if not 0 <= key < len:
- raise IndexError, 'list index out of range'
+ raise IndexError('list index out of range')
return key
def _check_slice(len, i, j):
@@ -49,15 +49,15 @@ def _check_slice(len, i, j):
class BitVec:
def __init__(self, *params):
- self._data = 0L
+ self._data = 0
self._len = 0
if not len(params):
pass
elif len(params) == 1:
param, = params
if type(param) == type([]):
- value = 0L
- bit_mask = 1L
+ value = 0
+ bit_mask = 1
for item in param:
# strict check
#_check_value(item)
@@ -66,39 +66,38 @@ class BitVec:
bit_mask = bit_mask << 1
self._data = value
self._len = len(param)
- elif type(param) == type(0L):
+ elif type(param) == type(0):
if param < 0:
- raise error, 'bitvec() can\'t handle negative longs'
+ raise error('bitvec() can\'t handle negative longs')
self._data = param
self._len = _compute_len(param)
else:
- raise error, 'bitvec() requires array or long parameter'
+ raise error('bitvec() requires array or long parameter')
elif len(params) == 2:
param, length = params
- if type(param) == type(0L):
+ if type(param) == type(0):
if param < 0:
- raise error, \
- 'can\'t handle negative longs'
+ raise error('can\'t handle negative longs')
self._data = param
if type(length) != type(0):
- raise error, 'bitvec()\'s 2nd parameter must be int'
+ raise error('bitvec()\'s 2nd parameter must be int')
computed_length = _compute_len(param)
if computed_length > length:
- print 'warning: bitvec() value is longer than the length indicates, truncating value'
+ print('warning: bitvec() value is longer than the length indicates, truncating value')
self._data = self._data & \
- ((1L << length) - 1)
+ ((1 << length) - 1)
self._len = length
else:
- raise error, 'bitvec() requires array or long parameter'
+ raise error('bitvec() requires array or long parameter')
else:
- raise error, 'bitvec() requires 0 -- 2 parameter(s)'
+ raise error('bitvec() requires 0 -- 2 parameter(s)')
def append(self, item):
#_check_value(item)
#self[self._len:self._len] = [item]
self[self._len:self._len] = \
- BitVec(long(not not item), 1)
+ BitVec(int(not not item), 1)
def count(self, value):
@@ -121,7 +120,7 @@ class BitVec:
data = (~self)._data
index = 0
if not data:
- raise ValueError, 'list.index(x): x not in list'
+ raise ValueError('list.index(x): x not in list')
while not (data & 1):
data, index = data >> 1, index + 1
return index
@@ -130,7 +129,7 @@ class BitVec:
def insert(self, index, item):
#_check_value(item)
#self[index:index] = [item]
- self[index:index] = BitVec(long(not not item), 1)
+ self[index:index] = BitVec(int(not not item), 1)
def remove(self, value):
@@ -140,7 +139,7 @@ class BitVec:
def reverse(self):
#ouch, this one is expensive!
#for i in self._len>>1: self[i], self[l-i] = self[l-i], self[i]
- data, result = self._data, 0L
+ data, result = self._data, 0
for i in range(self._len):
if not data:
result = result << (self._len - i)
@@ -151,7 +150,7 @@ class BitVec:
def sort(self):
c = self.count(1)
- self._data = ((1L << c) - 1) << (self._len - c)
+ self._data = ((1 << c) - 1) << (self._len - c)
def copy(self):
@@ -199,16 +198,16 @@ class BitVec:
def __getitem__(self, key):
#rprt('%r.__getitem__(%r)\n' % (self, key))
key = _check_key(self._len, key)
- return self._data & (1L << key) != 0
+ return self._data & (1 << key) != 0
def __setitem__(self, key, value):
#rprt('%r.__setitem__(%r, %r)\n' % (self, key, value))
key = _check_key(self._len, key)
#_check_value(value)
if value:
- self._data = self._data | (1L << key)
+ self._data = self._data | (1 << key)
else:
- self._data = self._data & ~(1L << key)
+ self._data = self._data & ~(1 << key)
def __delitem__(self, key):
#rprt('%r.__delitem__(%r)\n' % (self, key))
@@ -221,7 +220,7 @@ class BitVec:
#rprt('%r.__getslice__(%r, %r)\n' % (self, i, j))
i, j = _check_slice(self._len, i, j)
if i >= j:
- return BitVec(0L, 0)
+ return BitVec(0, 0)
if i:
ndata = self._data >> i
else:
@@ -230,7 +229,7 @@ class BitVec:
if j != self._len:
#we'll have to invent faster variants here
#e.g. mod_2exp
- ndata = ndata & ((1L << nlength) - 1)
+ ndata = ndata & ((1 << nlength) - 1)
return BitVec(ndata, nlength)
def __setslice__(self, i, j, sequence, *rest):
@@ -250,7 +249,7 @@ class BitVec:
#rprt('%r.__delslice__(%r, %r)\n' % (self, i, j))
i, j = _check_slice(self._len, i, j)
if i == 0 and j == self._len:
- self._data, self._len = 0L, 0
+ self._data, self._len = 0, 0
elif i < j:
self._data = self[:i]._data | (self[j:]._data >> i)
self._len = self._len - j + i
@@ -264,18 +263,18 @@ class BitVec:
def __mul__(self, multiplier):
#rprt('%r.__mul__(%r)\n' % (self, multiplier))
if type(multiplier) != type(0):
- raise TypeError, 'sequence subscript not int'
+ raise TypeError('sequence subscript not int')
if multiplier <= 0:
- return BitVec(0L, 0)
+ return BitVec(0, 0)
elif multiplier == 1:
return self.copy()
#handle special cases all 0 or all 1...
- if self._data == 0L:
- return BitVec(0L, self._len * multiplier)
- elif (~self)._data == 0L:
- return ~BitVec(0L, self._len * multiplier)
+ if self._data == 0:
+ return BitVec(0, self._len * multiplier)
+ elif (~self)._data == 0:
+ return ~BitVec(0, self._len * multiplier)
#otherwise el cheapo again...
- retval = BitVec(0L, 0)
+ retval = BitVec(0, 0)
while multiplier:
retval, multiplier = retval + self, multiplier - 1
return retval
@@ -309,7 +308,7 @@ class BitVec:
def __invert__(self):
#rprt('%r.__invert__()\n' % (self,))
- return BitVec(~self._data & ((1L << self._len) - 1), \
+ return BitVec(~self._data & ((1 << self._len) - 1), \
self._len)
def __coerce__(self, otherseq, *rest):
@@ -323,7 +322,7 @@ class BitVec:
return int(self._data)
def __long__(self):
- return long(self._data)
+ return int(self._data)
def __float__(self):
return float(self._data)
diff --git a/Demo/comparisons/regextest.py b/Demo/comparisons/regextest.py
index 1fab052..d2c534d 100755
--- a/Demo/comparisons/regextest.py
+++ b/Demo/comparisons/regextest.py
@@ -21,7 +21,7 @@ import sys
import re
def main():
- pats = map(chomp, sys.stdin.readlines())
+ pats = list(map(chomp, sys.stdin.readlines()))
bigpat = '(' + '|'.join(pats) + ')'
prog = re.compile(bigpat)
@@ -29,7 +29,7 @@ def main():
try:
fp = open(file, 'r')
except IOError as msg:
- print "%s: %s" % (file, msg)
+ print("%s: %s" % (file, msg))
continue
lineno = 0
while 1:
@@ -38,7 +38,7 @@ def main():
break
lineno = lineno + 1
if prog.search(line):
- print "%s:%s:%s" % (file, lineno, line),
+ print("%s:%s:%s" % (file, lineno, line), end=' ')
def chomp(s):
return s.rstrip('\n')
diff --git a/Demo/comparisons/sortingtest.py b/Demo/comparisons/sortingtest.py
index cabf626..464eb5c 100755
--- a/Demo/comparisons/sortingtest.py
+++ b/Demo/comparisons/sortingtest.py
@@ -42,10 +42,10 @@ def main():
if not line:
break
items = line.split()
- items = map(makekey, items)
+ items = list(map(makekey, items))
items.sort()
for num, var in items:
- print "%s=%s" % (var, num),
- print
+ print("%s=%s" % (var, num), end=' ')
+ print()
main()
diff --git a/Demo/comparisons/systemtest.py b/Demo/comparisons/systemtest.py
index d3fc72b..e3d840e 100755
--- a/Demo/comparisons/systemtest.py
+++ b/Demo/comparisons/systemtest.py
@@ -25,7 +25,7 @@ def main():
# Note: can't test for presence of lstat -- it's always there
dummy = os.readlink
except AttributeError:
- print "This system doesn't have symbolic links"
+ print("This system doesn't have symbolic links")
sys.exit(0)
if sys.argv[1:]:
prefix = sys.argv[1]
@@ -42,7 +42,7 @@ def reportboguslinks(prefix):
try:
names = os.listdir('.')
except os.error as msg:
- print "%s%s: can't list: %s" % (prefix, '.', msg)
+ print("%s%s: can't list: %s" % (prefix, '.', msg))
return
names.sort()
for name in names:
@@ -51,20 +51,20 @@ def reportboguslinks(prefix):
try:
mode = os.lstat(name)[ST_MODE]
except os.error:
- print "%s%s: can't stat: %s" % (prefix, name, msg)
+ print("%s%s: can't stat: %s" % (prefix, name, msg))
continue
if S_ISLNK(mode):
try:
os.stat(name)
except os.error:
- print "%s%s -> %s" % \
- (prefix, name, os.readlink(name))
+ print("%s%s -> %s" % \
+ (prefix, name, os.readlink(name)))
elif S_ISDIR(mode):
try:
os.chdir(name)
except os.error as msg:
- print "%s%s: can't chdir: %s" % \
- (prefix, name, msg)
+ print("%s%s: can't chdir: %s" % \
+ (prefix, name, msg))
continue
try:
reportboguslinks(prefix + name + '/')
diff --git a/Demo/curses/life.py b/Demo/curses/life.py
index a5bbed2..ec79f9e 100755
--- a/Demo/curses/life.py
+++ b/Demo/curses/life.py
@@ -63,14 +63,14 @@ class LifeBoard:
def set(self, y, x):
"""Set a cell to the live state"""
if x<0 or self.X<=x or y<0 or self.Y<=y:
- raise ValueError, "Coordinates out of range %i,%i"% (y,x)
+ raise ValueError("Coordinates out of range %i,%i"% (y,x))
self.state[x,y] = 1
def toggle(self, y, x):
"""Toggle a cell's state between live and dead"""
if x<0 or self.X<=x or y<0 or self.Y<=y:
- raise ValueError, "Coordinates out of range %i,%i"% (y,x)
- if self.state.has_key( (x,y) ):
+ raise ValueError("Coordinates out of range %i,%i"% (y,x))
+ if (x,y) in self.state:
del self.state[x,y]
self.scr.addch(y+1, x+1, ' ')
else:
@@ -89,7 +89,7 @@ class LifeBoard:
if not update_board:
for i in range(0, M):
for j in range(0, N):
- if self.state.has_key( (i,j) ):
+ if (i,j) in self.state:
self.scr.addch(j+1, i+1, self.char)
else:
self.scr.addch(j+1, i+1, ' ')
@@ -102,10 +102,10 @@ class LifeBoard:
L = range( max(0, i-1), min(M, i+2) )
for j in range(0, N):
s = 0
- live = self.state.has_key( (i,j) )
+ live = (i,j) in self.state
for k in range( max(0, j-1), min(N, j+2) ):
for l in L:
- if self.state.has_key( (l,k) ):
+ if (l,k) in self.state:
s += 1
s -= live
if s == 3:
diff --git a/Demo/curses/repeat.py b/Demo/curses/repeat.py
index fa7daac..1083239 100755
--- a/Demo/curses/repeat.py
+++ b/Demo/curses/repeat.py
@@ -27,14 +27,14 @@ import curses
def main():
if not sys.argv[1:]:
- print __doc__
+ print(__doc__)
sys.exit(0)
cmd = " ".join(sys.argv[1:])
p = os.popen(cmd, "r")
text = p.read()
sts = p.close()
if sts:
- print >>sys.stderr, "Exit code:", sts
+ print("Exit code:", sts, file=sys.stderr)
sys.exit(sts)
w = curses.initscr()
try:
@@ -50,7 +50,7 @@ def main():
text = p.read()
sts = p.close()
if sts:
- print >>sys.stderr, "Exit code:", sts
+ print("Exit code:", sts, file=sys.stderr)
sys.exit(sts)
finally:
curses.endwin()
diff --git a/Demo/imputil/importers.py b/Demo/imputil/importers.py
index 864ff02..b617ba0 100644
--- a/Demo/imputil/importers.py
+++ b/Demo/imputil/importers.py
@@ -31,7 +31,7 @@ _suffix_char = __debug__ and 'c' or 'o'
_suffix = '.py' + _suffix_char
# the C_EXTENSION suffixes
-_c_suffixes = filter(lambda x: x[2] == imp.C_EXTENSION, imp.get_suffixes())
+_c_suffixes = [x for x in imp.get_suffixes() if x[2] == imp.C_EXTENSION]
def _timestamp(pathname):
"Return the file modification time as a Long."
@@ -39,7 +39,7 @@ def _timestamp(pathname):
s = os.stat(pathname)
except OSError:
return None
- return long(s[8])
+ return int(s[8])
def _fs_import(dir, modname, fqname):
"Fetch a module from the filesystem."
@@ -149,7 +149,7 @@ class PackageArchiveImporter(imputil.Importer):
Return None if the archive was not found.
"""
- raise RuntimeError, "get_archive not implemented"
+ raise RuntimeError("get_archive not implemented")
def get_subfile(self, archive, modname):
"""Get code from a subfile in the specified archive.
@@ -162,7 +162,7 @@ class PackageArchiveImporter(imputil.Importer):
Return None if the subfile was not found.
"""
- raise RuntimeError, "get_subfile not implemented"
+ raise RuntimeError("get_subfile not implemented")
class PackageArchive(PackageArchiveImporter):
diff --git a/Demo/imputil/knee.py b/Demo/imputil/knee.py
index 26119e8..49fdf2b 100644
--- a/Demo/imputil/knee.py
+++ b/Demo/imputil/knee.py
@@ -22,10 +22,10 @@ def import_hook(name, globals=None, locals=None, fromlist=None):
return m
def determine_parent(globals):
- if not globals or not globals.has_key("__name__"):
+ if not globals or "__name__" not in globals:
return None
pname = globals['__name__']
- if globals.has_key("__path__"):
+ if "__path__" in globals:
parent = sys.modules[pname]
assert globals is parent.__dict__
return parent
@@ -56,7 +56,7 @@ def find_head_package(parent, name):
parent = None
q = import_module(head, qname, parent)
if q: return q, tail
- raise ImportError, "No module named " + qname
+ raise ImportError("No module named " + qname)
def load_tail(q, tail):
m = q
@@ -67,7 +67,7 @@ def load_tail(q, tail):
mname = "%s.%s" % (m.__name__, head)
m = import_module(head, mname, m)
if not m:
- raise ImportError, "No module named " + mname
+ raise ImportError("No module named " + mname)
return m
def ensure_fromlist(m, fromlist, recursive=0):
@@ -85,7 +85,7 @@ def ensure_fromlist(m, fromlist, recursive=0):
subname = "%s.%s" % (m.__name__, sub)
submod = import_module(sub, subname, m)
if not submod:
- raise ImportError, "No module named " + subname
+ raise ImportError("No module named " + subname)
def import_module(partname, fqname, parent):
try:
diff --git a/Demo/md5test/md5driver.py b/Demo/md5test/md5driver.py
index 4c7cfcb..242d0a5 100755
--- a/Demo/md5test/md5driver.py
+++ b/Demo/md5test/md5driver.py
@@ -9,7 +9,7 @@ def MDPrint(str):
outstr = (outstr
+ string.hexdigits[(o >> 4) & 0xF]
+ string.hexdigits[o & 0xF])
- print outstr,
+ print(outstr, end=' ')
from time import time
@@ -39,7 +39,7 @@ def MDTimeTrial():
# start timer
- print 'MD5 time trial. Processing', TEST_BYTES, 'characters...'
+ print('MD5 time trial. Processing', TEST_BYTES, 'characters...')
t1 = time()
mdContext = md5.new()
@@ -51,14 +51,14 @@ def MDTimeTrial():
t2 = time()
MDPrint(str)
- print 'is digest of test input.'
- print 'Seconds to process test input:', t2 - t1
- print 'Characters processed per second:', TEST_BYTES / (t2 - t1)
+ print('is digest of test input.')
+ print('Seconds to process test input:', t2 - t1)
+ print('Characters processed per second:', TEST_BYTES / (t2 - t1))
def MDString(str):
MDPrint(md5.new(str).digest())
- print '"' + str + '"'
+ print('"' + str + '"')
def MDFile(filename):
@@ -72,7 +72,7 @@ def MDFile(filename):
mdContext.update(data)
MDPrint(mdContext.digest())
- print filename
+ print(filename)
import sys
@@ -87,11 +87,11 @@ def MDFilter():
mdContext.update(data)
MDPrint(mdContext.digest())
- print
+ print()
def MDTestSuite():
- print 'MD5 test suite results:'
+ print('MD5 test suite results:')
MDString('')
MDString('a')
MDString('abc')
diff --git a/Demo/metaclasses/Enum.py b/Demo/metaclasses/Enum.py
index df1d814..8d402db 100644
--- a/Demo/metaclasses/Enum.py
+++ b/Demo/metaclasses/Enum.py
@@ -37,12 +37,12 @@ class EnumMetaClass:
"""
for base in bases:
if base.__class__ is not EnumMetaClass:
- raise TypeError, "Enumeration base class must be enumeration"
- bases = filter(lambda x: x is not Enum, bases)
+ raise TypeError("Enumeration base class must be enumeration")
+ bases = [x for x in bases if x is not Enum]
self.__name__ = name
self.__bases__ = bases
self.__dict = {}
- for key, value in dict.items():
+ for key, value in list(dict.items()):
self.__dict[key] = EnumInstance(name, key, value)
def __getattr__(self, name):
@@ -61,7 +61,7 @@ class EnumMetaClass:
"""
if name == '__members__':
- return self.__dict.keys()
+ return list(self.__dict.keys())
try:
return self.__dict[name]
@@ -72,16 +72,15 @@ class EnumMetaClass:
except AttributeError:
continue
- raise AttributeError, name
+ raise AttributeError(name)
def __repr__(self):
s = self.__name__
if self.__bases__:
- s = s + '(' + string.join(map(lambda x: x.__name__,
- self.__bases__), ", ") + ')'
+ s = s + '(' + string.join([x.__name__ for x in self.__bases__], ", ") + ')'
if self.__dict:
list = []
- for key, value in self.__dict.items():
+ for key, value in list(self.__dict.items()):
list.append("%s: %s" % (key, int(value)))
s = "%s: {%s}" % (s, string.join(list, ", "))
return s
@@ -130,13 +129,13 @@ def _test():
green = 2
blue = 3
- print Color.red
- print dir(Color)
+ print(Color.red)
+ print(dir(Color))
- print Color.red == Color.red
- print Color.red == Color.blue
- print Color.red == 1
- print Color.red == 2
+ print(Color.red == Color.red)
+ print(Color.red == Color.blue)
+ print(Color.red == 1)
+ print(Color.red == 2)
class ExtendedColor(Color):
white = 0
@@ -145,10 +144,10 @@ def _test():
purple = 6
black = 7
- print ExtendedColor.orange
- print ExtendedColor.red
+ print(ExtendedColor.orange)
+ print(ExtendedColor.red)
- print Color.red == ExtendedColor.red
+ print(Color.red == ExtendedColor.red)
class OtherColor(Enum):
white = 4
@@ -157,13 +156,13 @@ def _test():
class MergedColor(Color, OtherColor):
pass
- print MergedColor.red
- print MergedColor.white
+ print(MergedColor.red)
+ print(MergedColor.white)
- print Color
- print ExtendedColor
- print OtherColor
- print MergedColor
+ print(Color)
+ print(ExtendedColor)
+ print(OtherColor)
+ print(MergedColor)
if __name__ == '__main__':
_test()
diff --git a/Demo/metaclasses/Meta.py b/Demo/metaclasses/Meta.py
index 9529e0f..90bfd97 100644
--- a/Demo/metaclasses/Meta.py
+++ b/Demo/metaclasses/Meta.py
@@ -31,7 +31,7 @@ class MetaHelper:
try:
ga = self.__formalclass__.__getattr__('__usergetattr__')
except (KeyError, AttributeError):
- raise AttributeError, name
+ raise AttributeError(name)
return ga(self, name)
if type(raw) != types.FunctionType:
return raw
@@ -71,7 +71,7 @@ class MetaClass:
return base.__getattr__(name)
except AttributeError:
pass
- raise AttributeError, name
+ raise AttributeError(name)
def __setattr__(self, name, value):
if not self.__inited:
@@ -96,20 +96,20 @@ Meta = MetaClass('Meta', (), {})
def _test():
class C(Meta):
def __init__(self, *args):
- print "__init__, args =", args
+ print("__init__, args =", args)
def m1(self, x):
- print "m1(x=%r)" % (x,)
- print C
+ print("m1(x=%r)" % (x,))
+ print(C)
x = C()
- print x
+ print(x)
x.m1(12)
class D(C):
def __getattr__(self, name):
- if name[:2] == '__': raise AttributeError, name
+ if name[:2] == '__': raise AttributeError(name)
return "getattr:%s" % name
x = D()
- print x.foo
- print x._foo
+ print(x.foo)
+ print(x._foo)
## print x.__foo
## print x.__foo__
diff --git a/Demo/metaclasses/Simple.py b/Demo/metaclasses/Simple.py
index e3e54f7..8878ade 100644
--- a/Demo/metaclasses/Simple.py
+++ b/Demo/metaclasses/Simple.py
@@ -17,7 +17,7 @@ class Instance:
try:
value = self.__klass__.__namespace__[name]
except KeyError:
- raise AttributeError, name
+ raise AttributeError(name)
if type(value) is not types.FunctionType:
return value
return BoundMethod(value, self)
@@ -27,7 +27,7 @@ class BoundMethod:
self.function = function
self.instance = instance
def __call__(self, *args):
- print "calling", self.function, "for", self.instance, "with", args
+ print("calling", self.function, "for", self.instance, "with", args)
return self.function(self.instance, *args)
Trace = Tracing('Trace', (), {})
@@ -42,4 +42,4 @@ aninstance = MyTracedClass()
aninstance.method1(10)
-print aninstance.method2()
+print(aninstance.method2())
diff --git a/Demo/metaclasses/Synch.py b/Demo/metaclasses/Synch.py
index cd13e86..445ce83 100644
--- a/Demo/metaclasses/Synch.py
+++ b/Demo/metaclasses/Synch.py
@@ -106,13 +106,13 @@ def _testLock():
def f2(lock, done=done):
lock.acquire()
- print "f2 running in thread %d\n" % thread.get_ident(),
+ print("f2 running in thread %d\n" % thread.get_ident(), end=' ')
lock.release()
done.append(1)
def f1(lock, f2=f2, done=done):
lock.acquire()
- print "f1 running in thread %d\n" % thread.get_ident(),
+ print("f1 running in thread %d\n" % thread.get_ident(), end=' ')
try:
f2(lock)
finally:
@@ -134,9 +134,9 @@ def _testLock():
lock.release()
import time
while len(done) < 9:
- print len(done)
+ print(len(done))
time.sleep(0.001)
- print len(done)
+ print(len(done))
# Now, the Locking metaclass is a piece of cake.
@@ -183,22 +183,22 @@ def _test():
return
# Double the buffer size
# First normalize it so that first==0 and last==size-1
- print "buffer =", self.buffer
- print "first = %d, last = %d, size = %d" % (
- self.first, self.last, self.size)
+ print("buffer =", self.buffer)
+ print("first = %d, last = %d, size = %d" % (
+ self.first, self.last, self.size))
if self.first <= self.last:
temp = self.buffer[self.first:self.last]
else:
temp = self.buffer[self.first:] + self.buffer[:self.last]
- print "temp =", temp
+ print("temp =", temp)
self.buffer = temp + [None]*(self.size+1)
self.first = 0
self.last = self.size-1
self.size = self.size*2
- print "Buffer size doubled to", self.size
- print "new buffer =", self.buffer
- print "first = %d, last = %d, size = %d" % (
- self.first, self.last, self.size)
+ print("Buffer size doubled to", self.size)
+ print("new buffer =", self.buffer)
+ print("first = %d, last = %d, size = %d" % (
+ self.first, self.last, self.size))
self.put(item) # Recursive call to test the locking
def get(self):
# Is the buffer empty?
@@ -212,10 +212,10 @@ def _test():
import time
i = 0
while i < n:
- print "put", i
+ print("put", i)
buffer.put(i)
i = i+1
- print "Producer: done producing", n, "items"
+ print("Producer: done producing", n, "items")
wait.release()
def consumer(buffer, wait, n=1000):
@@ -226,15 +226,14 @@ def _test():
try:
x = buffer.get()
if x != i:
- raise AssertionError, \
- "get() returned %s, expected %s" % (x, i)
- print "got", i
+ raise AssertionError("get() returned %s, expected %s" % (x, i))
+ print("got", i)
i = i+1
tout = 0.001
except EOFError:
time.sleep(tout)
tout = tout*2
- print "Consumer: done consuming", n, "items"
+ print("Consumer: done consuming", n, "items")
wait.release()
pwait = thread.allocate_lock()
@@ -246,10 +245,10 @@ def _test():
thread.start_new_thread(consumer, (buffer, cwait, n))
thread.start_new_thread(producer, (buffer, pwait, n))
pwait.acquire()
- print "Producer done"
+ print("Producer done")
cwait.acquire()
- print "All done"
- print "buffer size ==", len(buffer.buffer)
+ print("All done")
+ print("buffer size ==", len(buffer.buffer))
if __name__ == '__main__':
_testLock()
diff --git a/Demo/metaclasses/Trace.py b/Demo/metaclasses/Trace.py
index 97fda56..d211d17 100644
--- a/Demo/metaclasses/Trace.py
+++ b/Demo/metaclasses/Trace.py
@@ -35,7 +35,7 @@ class TraceMetaClass:
return base.__getattr__(name)
except AttributeError:
pass
- raise AttributeError, name
+ raise AttributeError(name)
def __setattr__(self, name, value):
if not self.__inited:
@@ -69,7 +69,7 @@ class TracingInstance:
try:
raw = self.__class.__getattr__(name)
except AttributeError:
- raise AttributeError, name
+ raise AttributeError(name)
if type(raw) != types.FunctionType:
return raw
# It's a function
@@ -99,7 +99,7 @@ class TracingWrapper(NotTracingWrapper):
self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with exception %s: %s",
self.__name__, t, v)
- raise t, v, tb
+ raise t(v).with_traceback(tb)
else:
self.inst.__trace_call__(self.inst.__trace_output__,
"returning from %s with value %s",
@@ -117,28 +117,28 @@ def _test():
def m2(self, y): return self.x + y
__trace_output__ = sys.stdout
class D(C):
- def m2(self, y): print "D.m2(%r)" % (y,); return C.m2(self, y)
+ def m2(self, y): print("D.m2(%r)" % (y,)); return C.m2(self, y)
__trace_output__ = None
x = C(4321)
- print x
- print x.x
- print x.m1(100)
- print x.m1(10)
- print x.m2(33)
- print x.m1(5)
- print x.m2(4000)
- print x.x
-
- print C.__init__
- print C.m2
- print D.__init__
- print D.m2
+ print(x)
+ print(x.x)
+ print(x.m1(100))
+ print(x.m1(10))
+ print(x.m2(33))
+ print(x.m1(5))
+ print(x.m2(4000))
+ print(x.x)
+
+ print(C.__init__)
+ print(C.m2)
+ print(D.__init__)
+ print(D.m2)
y = D()
- print y
- print y.m1(10)
- print y.m2(100)
- print y.x
+ print(y)
+ print(y.m1(10))
+ print(y.m2(100))
+ print(y.x)
if __name__ == '__main__':
_test()
diff --git a/Demo/newmetaclasses/Eiffel.py b/Demo/newmetaclasses/Eiffel.py
index 04f9915..ef7f0c6 100644
--- a/Demo/newmetaclasses/Eiffel.py
+++ b/Demo/newmetaclasses/Eiffel.py
@@ -20,7 +20,7 @@ class EiffelBaseMetaClass(type):
"""
# find methods with pre or post conditions
methods = []
- for k, v in dict.iteritems():
+ for k, v in dict.items():
if k.endswith('_pre') or k.endswith('_post'):
assert isinstance(v, function)
elif isinstance(v, function):
diff --git a/Demo/newmetaclasses/Enum.py b/Demo/newmetaclasses/Enum.py
index 2a5823b..0f7f913 100644
--- a/Demo/newmetaclasses/Enum.py
+++ b/Demo/newmetaclasses/Enum.py
@@ -20,7 +20,7 @@ class EnumMetaclass(type):
def __init__(cls, name, bases, dict):
super(EnumMetaclass, cls).__init__(name, bases, dict)
cls._members = []
- for attr in dict.keys():
+ for attr in list(dict.keys()):
if not (attr.startswith('__') and attr.endswith('__')):
enumval = EnumInstance(name, attr, dict[attr])
setattr(cls, attr, enumval)
@@ -29,7 +29,7 @@ class EnumMetaclass(type):
def __getattr__(cls, name):
if name == "__members__":
return cls._members
- raise AttributeError, name
+ raise AttributeError(name)
def __repr__(cls):
s1 = s2 = ""
@@ -95,13 +95,13 @@ def _test():
green = 2
blue = 3
- print Color.red
+ print(Color.red)
- print repr(Color.red)
- print Color.red == Color.red
- print Color.red == Color.blue
- print Color.red == 1
- print Color.red == 2
+ print(repr(Color.red))
+ print(Color.red == Color.red)
+ print(Color.red == Color.blue)
+ print(Color.red == 1)
+ print(Color.red == 2)
class ExtendedColor(Color):
white = 0
@@ -110,10 +110,10 @@ def _test():
purple = 6
black = 7
- print ExtendedColor.orange
- print ExtendedColor.red
+ print(ExtendedColor.orange)
+ print(ExtendedColor.red)
- print Color.red == ExtendedColor.red
+ print(Color.red == ExtendedColor.red)
class OtherColor(Enum):
white = 4
@@ -122,13 +122,13 @@ def _test():
class MergedColor(Color, OtherColor):
pass
- print MergedColor.red
- print MergedColor.white
+ print(MergedColor.red)
+ print(MergedColor.white)
- print Color
- print ExtendedColor
- print OtherColor
- print MergedColor
+ print(Color)
+ print(ExtendedColor)
+ print(OtherColor)
+ print(MergedColor)
def _test2():
@@ -137,13 +137,13 @@ def _test2():
green = 2
blue = 3
- print Color.red
+ print(Color.red)
- print repr(Color.red)
- print Color.red == Color.red
- print Color.red == Color.blue
- print Color.red == 1
- print Color.red == 2
+ print(repr(Color.red))
+ print(Color.red == Color.red)
+ print(Color.red == Color.blue)
+ print(Color.red == 1)
+ print(Color.red == 2)
class ExtendedColor(Color):
white = 0
@@ -152,10 +152,10 @@ def _test2():
purple = 6
black = 7
- print ExtendedColor.orange
- print ExtendedColor.red
+ print(ExtendedColor.orange)
+ print(ExtendedColor.red)
- print Color.red == ExtendedColor.red
+ print(Color.red == ExtendedColor.red)
class OtherColor(FullEnum):
white = 4
@@ -164,13 +164,13 @@ def _test2():
class MergedColor(Color, OtherColor):
pass
- print MergedColor.red
- print MergedColor.white
+ print(MergedColor.red)
+ print(MergedColor.white)
- print Color
- print ExtendedColor
- print OtherColor
- print MergedColor
+ print(Color)
+ print(ExtendedColor)
+ print(OtherColor)
+ print(MergedColor)
if __name__ == '__main__':
_test()
diff --git a/Demo/parser/example.py b/Demo/parser/example.py
index 2aa9ec2..c2f0883 100644
--- a/Demo/parser/example.py
+++ b/Demo/parser/example.py
@@ -63,7 +63,7 @@ class SuiteInfoBase:
return self._name
def get_class_names(self):
- return self._class_info.keys()
+ return list(self._class_info.keys())
def get_class_info(self, name):
return self._class_info[name]
@@ -79,7 +79,7 @@ class SuiteFuncInfo:
# Mixin class providing access to function names and info.
def get_function_names(self):
- return self._function_info.keys()
+ return list(self._function_info.keys())
def get_function_info(self, name):
return self._function_info[name]
@@ -97,7 +97,7 @@ class ClassInfo(SuiteInfoBase):
SuiteInfoBase.__init__(self, tree and tree[-1] or None)
def get_method_names(self):
- return self._function_info.keys()
+ return list(self._function_info.keys())
def get_method_info(self, name):
return self._function_info[name]
diff --git a/Demo/parser/test_parser.py b/Demo/parser/test_parser.py
index 1589f3b..e4d5571 100755
--- a/Demo/parser/test_parser.py
+++ b/Demo/parser/test_parser.py
@@ -9,7 +9,7 @@ _numFailed = 0
def testChunk(t, fileName):
global _numFailed
- print '----', fileName,
+ print('----', fileName, end=' ')
try:
ast = parser.suite(t)
tup = parser.ast2tuple(ast)
@@ -18,17 +18,17 @@ def testChunk(t, fileName):
ast = None
new = parser.tuple2ast(tup)
except parser.ParserError as err:
- print
- print 'parser module raised exception on input file', fileName + ':'
+ print()
+ print('parser module raised exception on input file', fileName + ':')
traceback.print_exc()
_numFailed = _numFailed + 1
else:
if tup != parser.ast2tuple(new):
- print
- print 'parser module failed on input file', fileName
+ print()
+ print('parser module failed on input file', fileName)
_numFailed = _numFailed + 1
else:
- print 'o.k.'
+ print('o.k.')
def testFile(fileName):
t = open(fileName).read()
@@ -41,7 +41,7 @@ def test():
import glob
args = glob.glob("*.py")
args.sort()
- map(testFile, args)
+ list(map(testFile, args))
sys.exit(_numFailed != 0)
if __name__ == '__main__':
diff --git a/Demo/parser/unparse.py b/Demo/parser/unparse.py
index 751ea6f..6582487 100644
--- a/Demo/parser/unparse.py
+++ b/Demo/parser/unparse.py
@@ -1,7 +1,7 @@
"Usage: unparse.py <path to source file>"
import sys
import _ast
-import cStringIO
+import io
import os
def interleave(inter, f, seq):
@@ -9,7 +9,7 @@ def interleave(inter, f, seq):
"""
seq = iter(seq)
try:
- f(seq.next())
+ f(next(seq))
except StopIteration:
pass
else:
@@ -28,7 +28,7 @@ class Unparser:
self.f = file
self._indent = 0
self.dispatch(tree)
- print >>self.f,""
+ print("", file=self.f)
self.f.flush()
def fill(self, text = ""):
@@ -326,7 +326,8 @@ class Unparser:
def _Dict(self, t):
self.write("{")
- def writem((k, v)):
+ def writem(xxx_todo_changeme):
+ (k, v) = xxx_todo_changeme
self.dispatch(k)
self.write(": ")
self.dispatch(v)
@@ -482,17 +483,17 @@ def testdir(a):
try:
names = [n for n in os.listdir(a) if n.endswith('.py')]
except OSError:
- print >> sys.stderr, "Directory not readable: %s" % a
+ print("Directory not readable: %s" % a, file=sys.stderr)
else:
for n in names:
fullname = os.path.join(a, n)
if os.path.isfile(fullname):
- output = cStringIO.StringIO()
- print 'Testing %s' % fullname
+ output = io.StringIO()
+ print('Testing %s' % fullname)
try:
roundtrip(fullname, output)
except Exception as e:
- print ' Failed to compile, exception is %s' % repr(e)
+ print(' Failed to compile, exception is %s' % repr(e))
elif os.path.isdir(fullname):
testdir(fullname)
diff --git a/Demo/pdist/FSProxy.py b/Demo/pdist/FSProxy.py
index dad4015..510ac76 100755
--- a/Demo/pdist/FSProxy.py
+++ b/Demo/pdist/FSProxy.py
@@ -88,7 +88,7 @@ class FSProxyLocal:
c, t = fs.GetCreatorType()
if t != 'TEXT': return 0
except macfs.error as msg:
- print "***", name, msg
+ print("***", name, msg)
return 0
else:
if os.path.islink(name): return 0
@@ -99,12 +99,12 @@ class FSProxyLocal:
def check(self, name):
if not self.visible(name):
- raise os.error, "protected name %s" % repr(name)
+ raise os.error("protected name %s" % repr(name))
def checkfile(self, name):
self.check(name)
if not os.path.isfile(name):
- raise os.error, "not a plain file %s" % repr(name)
+ raise os.error("not a plain file %s" % repr(name))
def pwd(self):
return os.getcwd()
@@ -118,7 +118,7 @@ class FSProxyLocal:
def back(self):
if not self._dirstack:
- raise os.error, "empty directory stack"
+ raise os.error("empty directory stack")
dir, ignore = self._dirstack[-1]
os.chdir(dir)
del self._dirstack[-1]
@@ -128,8 +128,8 @@ class FSProxyLocal:
if pat:
def keep(name, pat = pat):
return fnmatch.fnmatch(name, pat)
- files = filter(keep, files)
- files = filter(self.visible, files)
+ files = list(filter(keep, files))
+ files = list(filter(self.visible, files))
files.sort()
return files
@@ -139,12 +139,12 @@ class FSProxyLocal:
def listfiles(self, pat = None):
files = os.listdir(os.curdir)
- files = filter(os.path.isfile, files)
+ files = list(filter(os.path.isfile, files))
return self._filter(files, pat)
def listsubdirs(self, pat = None):
files = os.listdir(os.curdir)
- files = filter(os.path.isdir, files)
+ files = list(filter(os.path.isdir, files))
return self._filter(files, pat)
def exists(self, name):
@@ -278,7 +278,7 @@ class FSProxyLocal:
def mkdir(self, name):
self.check(name)
- os.mkdir(name, 0777)
+ os.mkdir(name, 0o777)
def rmdir(self, name):
self.check(name)
diff --git a/Demo/pdist/RCSProxy.py b/Demo/pdist/RCSProxy.py
index 6732308..7c3b24f 100755
--- a/Demo/pdist/RCSProxy.py
+++ b/Demo/pdist/RCSProxy.py
@@ -50,21 +50,21 @@ class DirSupport:
def back(self):
if not self._dirstack:
- raise os.error, "empty directory stack"
+ raise os.error("empty directory stack")
dir = self._dirstack[-1]
os.chdir(dir)
del self._dirstack[-1]
def listsubdirs(self, pat = None):
files = os.listdir(os.curdir)
- files = filter(os.path.isdir, files)
+ files = list(filter(os.path.isdir, files))
return self._filter(files, pat)
def isdir(self, name):
return os.path.isdir(name)
def mkdir(self, name):
- os.mkdir(name, 0777)
+ os.mkdir(name, 0o777)
def rmdir(self, name):
os.rmdir(name)
@@ -186,11 +186,11 @@ def test():
if hasattr(proxy, what):
attr = getattr(proxy, what)
if hasattr(attr, '__call__'):
- print attr(*sys.argv[2:])
+ print(attr(*sys.argv[2:]))
else:
- print repr(attr)
+ print(repr(attr))
else:
- print "%s: no such attribute" % what
+ print("%s: no such attribute" % what)
sys.exit(2)
diff --git a/Demo/pdist/client.py b/Demo/pdist/client.py
index 664c41b..13158f2 100755
--- a/Demo/pdist/client.py
+++ b/Demo/pdist/client.py
@@ -24,10 +24,10 @@ class Client:
address = ('', address)
self._address = address
self._verbose = verbose
- if self._verbose: print "Connecting to %s ..." % repr(address)
+ if self._verbose: print("Connecting to %s ..." % repr(address))
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.connect(address)
- if self._verbose: print "Connected."
+ if self._verbose: print("Connected.")
self._lastid = 0 # Last id for which a reply has been received
self._nextid = 1 # Id of next request
self._replies = {} # Unprocessed replies
@@ -53,7 +53,7 @@ class Client:
method = _stub(self, name)
setattr(self, name, method) # XXX circular reference
return method
- raise AttributeError, name
+ raise AttributeError(name)
def _setverbose(self, verbose):
self._verbose = verbose
@@ -78,7 +78,7 @@ class Client:
self._nextid = id+1
if not wantreply: id = -id
request = (name, args, id)
- if self._verbose > 1: print "sending request: %s" % repr(request)
+ if self._verbose > 1: print("sending request: %s" % repr(request))
wp = pickle.Pickler(self._wf)
wp.dump(request)
return id
@@ -86,7 +86,7 @@ class Client:
def _recv(self, id):
exception, value, rid = self._vrecv(id)
if rid != id:
- raise RuntimeError, "request/reply id mismatch: %d/%d" % (id, rid)
+ raise RuntimeError("request/reply id mismatch: %d/%d" % (id, rid))
if exception is None:
return value
x = exception
@@ -96,30 +96,30 @@ class Client:
x = os.error
if x == exception:
exception = x
- raise exception, value
+ raise exception(value)
def _vrecv(self, id):
self._flush()
- if self._replies.has_key(id):
- if self._verbose > 1: print "retrieving previous reply, id = %d" % id
+ if id in self._replies:
+ if self._verbose > 1: print("retrieving previous reply, id = %d" % id)
reply = self._replies[id]
del self._replies[id]
return reply
aid = abs(id)
while 1:
- if self._verbose > 1: print "waiting for reply, id = %d" % id
+ if self._verbose > 1: print("waiting for reply, id = %d" % id)
rp = pickle.Unpickler(self._rf)
reply = rp.load()
del rp
- if self._verbose > 1: print "got reply: %s" % repr(reply)
+ if self._verbose > 1: print("got reply: %s" % repr(reply))
rid = reply[2]
arid = abs(rid)
if arid == aid:
- if self._verbose > 1: print "got it"
+ if self._verbose > 1: print("got it")
return reply
self._replies[rid] = reply
if arid > aid:
- if self._verbose > 1: print "got higher id, assume all ok"
+ if self._verbose > 1: print("got higher id, assume all ok")
return (None, None, id)
def _flush(self):
@@ -138,7 +138,7 @@ class SecureClient(Client, Security):
line = self._rf.readline()
challenge = int(line.strip())
response = self._encode_challenge(challenge)
- line = repr(long(response))
+ line = repr(int(response))
if line[-1] in 'Ll': line = line[:-1]
self._wf.write(line + '\n')
self._wf.flush()
diff --git a/Demo/pdist/cmdfw.py b/Demo/pdist/cmdfw.py
index 47d13bc..7bcb461 100755
--- a/Demo/pdist/cmdfw.py
+++ b/Demo/pdist/cmdfw.py
@@ -72,11 +72,11 @@ class CommandFrameWork:
"""Process the options retrieved by getopt.
Override this if you have any options."""
if opts:
- print "-"*40
- print "Options:"
+ print("-"*40)
+ print("Options:")
for o, a in opts:
- print 'option', o, 'value', repr(a)
- print "-"*40
+ print('option', o, 'value', repr(a))
+ print("-"*40)
def ready(self):
"""Called just before calling the subcommand."""
@@ -84,14 +84,14 @@ class CommandFrameWork:
def usage(self, msg = None):
"""Print usage message. Return suitable exit code (2)."""
- if msg: print msg
- print self.UsageMessage % {'name': self.__class__.__name__}
+ if msg: print(msg)
+ print(self.UsageMessage % {'name': self.__class__.__name__})
docstrings = {}
c = self.__class__
while 1:
for name in dir(c):
if name[:3] == 'do_':
- if docstrings.has_key(name):
+ if name in docstrings:
continue
try:
doc = getattr(c, name).__doc__
@@ -103,19 +103,19 @@ class CommandFrameWork:
break
c = c.__bases__[0]
if docstrings:
- print "where subcommand can be:"
- names = docstrings.keys()
+ print("where subcommand can be:")
+ names = list(docstrings.keys())
names.sort()
for name in names:
- print docstrings[name]
+ print(docstrings[name])
if self.PostUsageMessage:
- print self.PostUsageMessage
+ print(self.PostUsageMessage)
return 2
def default(self):
"""Default method, called when no subcommand is given.
You should always override this."""
- print "Nobody expects the Spanish Inquisition!"
+ print("Nobody expects the Spanish Inquisition!")
def test():
@@ -124,7 +124,7 @@ def test():
class Hello(CommandFrameWork):
def do_hello(self, opts, args):
"hello -- print 'hello world', needs no arguments"
- print "Hello, world"
+ print("Hello, world")
x = Hello()
tests = [
[],
@@ -135,9 +135,9 @@ def test():
None,
]
for t in tests:
- print '-'*10, t, '-'*10
+ print('-'*10, t, '-'*10)
sts = x.run(t)
- print "Exit status:", repr(sts)
+ print("Exit status:", repr(sts))
if __name__ == '__main__':
diff --git a/Demo/pdist/cmptree.py b/Demo/pdist/cmptree.py
index 5031869..d6962e9 100755
--- a/Demo/pdist/cmptree.py
+++ b/Demo/pdist/cmptree.py
@@ -13,7 +13,7 @@ def raw_input(prompt):
def main():
pwd = os.getcwd()
- s = raw_input("chdir [%s] " % pwd)
+ s = input("chdir [%s] " % pwd)
if s:
os.chdir(s)
pwd = os.getcwd()
@@ -21,14 +21,14 @@ def main():
port = 4127
verbose = 1
mode = ''
- print """\
+ print("""\
Mode should be a string of characters, indicating what to do with differences.
r - read different files to local file system
w - write different files to remote file system
c - create new files, either remote or local
d - delete disappearing files, either remote or local
-"""
- s = raw_input("mode [%s] " % mode)
+""")
+ s = input("mode [%s] " % mode)
if s: mode = s
address = (host, port)
t1 = time.time()
@@ -40,74 +40,74 @@ d - delete disappearing files, either remote or local
t2 = time.time()
dt = t2-t1
mins, secs = divmod(dt, 60)
- print mins, "minutes and", round(secs), "seconds"
- raw_input("[Return to exit] ")
+ print(mins, "minutes and", round(secs), "seconds")
+ input("[Return to exit] ")
def ask(prompt, default):
- s = raw_input("%s [%s] " % (prompt, default))
+ s = input("%s [%s] " % (prompt, default))
return s or default
def askint(prompt, default):
- s = raw_input("%s [%s] " % (prompt, str(default)))
+ s = input("%s [%s] " % (prompt, str(default)))
if s: return string.atoi(s)
return default
def compare(local, remote, mode):
- print
- print "PWD =", repr(os.getcwd())
+ print()
+ print("PWD =", repr(os.getcwd()))
sums_id = remote._send('sumlist')
subdirs_id = remote._send('listsubdirs')
remote._flush()
- print "calculating local sums ..."
+ print("calculating local sums ...")
lsumdict = {}
for name, info in local.sumlist():
lsumdict[name] = info
- print "getting remote sums ..."
+ print("getting remote sums ...")
sums = remote._recv(sums_id)
- print "got", len(sums)
+ print("got", len(sums))
rsumdict = {}
for name, rsum in sums:
rsumdict[name] = rsum
- if not lsumdict.has_key(name):
- print repr(name), "only remote"
+ if name not in lsumdict:
+ print(repr(name), "only remote")
if 'r' in mode and 'c' in mode:
recvfile(local, remote, name)
else:
lsum = lsumdict[name]
if lsum != rsum:
- print repr(name),
+ print(repr(name), end=' ')
rmtime = remote.mtime(name)
lmtime = local.mtime(name)
if rmtime > lmtime:
- print "remote newer",
+ print("remote newer", end=' ')
if 'r' in mode:
recvfile(local, remote, name)
elif lmtime > rmtime:
- print "local newer",
+ print("local newer", end=' ')
if 'w' in mode:
sendfile(local, remote, name)
else:
- print "same mtime but different sum?!?!",
- print
- for name in lsumdict.keys():
- if not rsumdict.keys():
- print repr(name), "only locally",
+ print("same mtime but different sum?!?!", end=' ')
+ print()
+ for name in list(lsumdict.keys()):
+ if not list(rsumdict.keys()):
+ print(repr(name), "only locally", end=' ')
fl()
if 'w' in mode and 'c' in mode:
sendfile(local, remote, name)
elif 'r' in mode and 'd' in mode:
os.unlink(name)
- print "removed."
- print
- print "gettin subdirs ..."
+ print("removed.")
+ print()
+ print("gettin subdirs ...")
subdirs = remote._recv(subdirs_id)
common = []
for name in subdirs:
if local.isdir(name):
- print "Common subdirectory", repr(name)
+ print("Common subdirectory", repr(name))
common.append(name)
else:
- print "Remote subdirectory", repr(name), "not found locally"
+ print("Remote subdirectory", repr(name), "not found locally")
if 'r' in mode and 'c' in mode:
pr = "Create local subdirectory %s? [y] " % \
repr(name)
@@ -117,15 +117,15 @@ def compare(local, remote, mode):
ok = ask(pr, "y")
if ok[:1] in ('y', 'Y'):
local.mkdir(name)
- print "Subdirectory %s made" % \
- repr(name)
+ print("Subdirectory %s made" % \
+ repr(name))
common.append(name)
lsubdirs = local.listsubdirs()
for name in lsubdirs:
if name not in subdirs:
- print "Local subdirectory", repr(name), "not found remotely"
+ print("Local subdirectory", repr(name), "not found remotely")
for name in common:
- print "Entering subdirectory", repr(name)
+ print("Entering subdirectory", repr(name))
local.cd(name)
remote.cd(name)
compare(local, remote, mode)
@@ -136,10 +136,10 @@ def sendfile(local, remote, name):
try:
remote.create(name)
except (IOError, os.error) as msg:
- print "cannot create:", msg
+ print("cannot create:", msg)
return
- print "sending ...",
+ print("sending ...", end=' ')
fl()
data = open(name).read()
@@ -152,10 +152,10 @@ def sendfile(local, remote, name):
t2 = time.time()
dt = t2-t1
- print len(data), "bytes in", round(dt), "seconds",
+ print(len(data), "bytes in", round(dt), "seconds", end=' ')
if dt:
- print "i.e.", round(len(data)/dt), "bytes/sec",
- print
+ print("i.e.", round(len(data)/dt), "bytes/sec", end=' ')
+ print()
def recvfile(local, remote, name):
ok = 0
@@ -165,17 +165,17 @@ def recvfile(local, remote, name):
return rv
finally:
if not ok:
- print "*** recvfile of %r failed, deleting" % (name,)
+ print("*** recvfile of %r failed, deleting" % (name,))
local.delete(name)
def recvfile_real(local, remote, name):
try:
local.create(name)
except (IOError, os.error) as msg:
- print "cannot create:", msg
+ print("cannot create:", msg)
return
- print "receiving ...",
+ print("receiving ...", end=' ')
fl()
f = open(name, 'w')
@@ -200,10 +200,10 @@ def recvfile_real(local, remote, name):
f.close()
dt = t2-t1
- print size, "bytes in", round(dt), "seconds",
+ print(size, "bytes in", round(dt), "seconds", end=' ')
if dt:
- print "i.e.", int(size/dt), "bytes/sec",
- print
+ print("i.e.", int(size/dt), "bytes/sec", end=' ')
+ print()
remote._recv(id) # ignored
def fl():
diff --git a/Demo/pdist/cvslib.py b/Demo/pdist/cvslib.py
index ebcc697..8ccb616 100755
--- a/Demo/pdist/cvslib.py
+++ b/Demo/pdist/cvslib.py
@@ -56,7 +56,7 @@ class File:
def __init__(self, file = None):
if file and '/' in file:
- raise ValueError, "no slash allowed in file"
+ raise ValueError("no slash allowed in file")
self.file = file
self.lseen = self.eseen = self.rseen = 0
self.proxy = None
@@ -76,7 +76,7 @@ class File:
def getentry(self, line):
words = string.splitfields(line, '/')
if self.file and words[1] != self.file:
- raise ValueError, "file name mismatch"
+ raise ValueError("file name mismatch")
self.file = words[1]
self.erev = words[2]
self.edeleted = 0
@@ -146,13 +146,13 @@ class File:
self.extra)
def report(self):
- print '-'*50
+ print('-'*50)
def r(key, repr=repr, self=self):
try:
value = repr(getattr(self, key))
except AttributeError:
value = "?"
- print "%-15s:" % key, value
+ print("%-15s:" % key, value)
r("file")
if self.lseen:
r("lsum", hexify)
@@ -200,7 +200,7 @@ class CVS:
if proxy is self.proxy:
return
self.proxy = proxy
- for e in self.entries.values():
+ for e in list(self.entries.values()):
e.rseen = 0
def getentries(self):
@@ -218,12 +218,12 @@ class CVS:
def putentries(self):
"""Write CVS/Entries back"""
f = self.cvsopen("Entries", 'w')
- for e in self.values():
+ for e in list(self.values()):
f.write(e.putentry())
f.close()
def getlocalfiles(self):
- list = self.entries.keys()
+ list = list(self.entries.keys())
addlist = os.listdir(os.curdir)
for name in addlist:
if name in list:
@@ -242,7 +242,7 @@ class CVS:
if proxy:
self.proxy = proxy
if not self.proxy:
- raise RuntimeError, "no RCS proxy"
+ raise RuntimeError("no RCS proxy")
addlist = self.proxy.listfiles()
for file in addlist:
try:
@@ -252,24 +252,24 @@ class CVS:
e.getremote(self.proxy)
def report(self):
- for e in self.values():
+ for e in list(self.values()):
e.report()
- print '-'*50
+ print('-'*50)
def keys(self):
- keys = self.entries.keys()
+ keys = list(self.entries.keys())
keys.sort()
return keys
def values(self):
def value(key, self=self):
return self.entries[key]
- return map(value, self.keys())
+ return list(map(value, list(self.keys())))
def items(self):
def item(key, self=self):
return (key, self.entries[key])
- return map(item, self.keys())
+ return list(map(item, list(self.keys())))
def cvsexists(self, file):
file = os.path.join("CVS", file)
@@ -328,7 +328,7 @@ def unctime(date):
year = string.atoi(words[4])
month = unctime_monthmap[words[1]]
day = string.atoi(words[2])
- [hh, mm, ss] = map(string.atoi, string.splitfields(words[3], ':'))
+ [hh, mm, ss] = list(map(string.atoi, string.splitfields(words[3], ':')))
ss = ss - time.timezone
return time.mktime((year, month, day, hh, mm, ss, 0, 0, 0))
@@ -340,14 +340,14 @@ def test_unctime():
now = int(time.time())
t = time.gmtime(now)
at = time.asctime(t)
- print 'GMT', now, at
- print 'timezone', time.timezone
- print 'local', time.ctime(now)
+ print('GMT', now, at)
+ print('timezone', time.timezone)
+ print('local', time.ctime(now))
u = unctime(at)
- print 'unctime()', u
+ print('unctime()', u)
gu = time.gmtime(u)
- print '->', gu
- print time.asctime(gu)
+ print('->', gu)
+ print(time.asctime(gu))
def test():
x = CVS()
diff --git a/Demo/pdist/cvslock.py b/Demo/pdist/cvslock.py
index c93c3f6..a48c702 100755
--- a/Demo/pdist/cvslock.py
+++ b/Demo/pdist/cvslock.py
@@ -120,14 +120,14 @@ class Lock:
self.cvswfl = self.join(CVSWFL + pid)
def __del__(self):
- print "__del__"
+ print("__del__")
self.unlock()
def setlockdir(self):
while 1:
try:
self.lockdir = self.cvslck
- os.mkdir(self.cvslck, 0777)
+ os.mkdir(self.cvslck, 0o777)
return
except os.error as msg:
self.lockdir = None
@@ -147,7 +147,7 @@ class Lock:
def unlockfile(self):
if self.lockfile:
- print "unlink", self.lockfile
+ print("unlink", self.lockfile)
try:
os.unlink(self.lockfile)
except os.error:
@@ -156,7 +156,7 @@ class Lock:
def unlockdir(self):
if self.lockdir:
- print "rmdir", self.lockdir
+ print("rmdir", self.lockdir)
try:
os.rmdir(self.lockdir)
except os.error:
@@ -179,8 +179,8 @@ def sleep(st, repository, delay):
user = pwent[0]
except KeyError:
user = "uid %d" % uid
- print "[%s]" % time.ctime(time.time())[11:19],
- print "Waiting for %s's lock in" % user, repository
+ print("[%s]" % time.ctime(time.time())[11:19], end=' ')
+ print("Waiting for %s's lock in" % user, repository)
time.sleep(delay)
@@ -252,27 +252,27 @@ def test():
rl = None
wl = None
try:
- print "attempting write lock ..."
+ print("attempting write lock ...")
wl = WriteLock(repository)
- print "got it."
+ print("got it.")
wl.unlock()
- print "attempting read lock ..."
+ print("attempting read lock ...")
rl = ReadLock(repository)
- print "got it."
+ print("got it.")
rl.unlock()
finally:
- print [1]
- print [2]
+ print([1])
+ print([2])
if rl:
rl.unlock()
- print [3]
+ print([3])
if wl:
wl.unlock()
- print [4]
+ print([4])
rl = None
- print [5]
+ print([5])
wl = None
- print [6]
+ print([6])
if __name__ == '__main__':
diff --git a/Demo/pdist/mac.py b/Demo/pdist/mac.py
index 61cff09..beb77ec 100755
--- a/Demo/pdist/mac.py
+++ b/Demo/pdist/mac.py
@@ -9,7 +9,7 @@ def raw_input(prompt):
def main():
while 1:
try:
- line = raw_input('$ ')
+ line = input('$ ')
except EOFError:
break
words = line.split()
diff --git a/Demo/pdist/makechangelog.py b/Demo/pdist/makechangelog.py
index 1ffa588..db66e8f 100755
--- a/Demo/pdist/makechangelog.py
+++ b/Demo/pdist/makechangelog.py
@@ -50,25 +50,25 @@ def formatrev(rev, prefix):
if parsedateprog.match(dateline) >= 0:
fields = parsedateprog.group(1, 2, 3, 4, 5, 6)
author = parsedateprog.group(7)
- if authormap.has_key(author): author = authormap[author]
- tfields = map(string.atoi, fields) + [0, 0, 0]
+ if author in authormap: author = authormap[author]
+ tfields = list(map(string.atoi, fields)) + [0, 0, 0]
tfields[5] = tfields[5] - time.timezone
t = time.mktime(tuple(tfields))
- print time.ctime(t), '', author
+ print(time.ctime(t), '', author)
words = string.split(log)
words[:0] = ['*', prefix + file + ':']
maxcol = 72-8
col = maxcol
for word in words:
if col > 0 and col + len(word) >= maxcol:
- print
- print '\t' + word,
+ print()
+ print('\t' + word, end=' ')
col = -1
else:
- print word,
+ print(word, end=' ')
col = col + 1 + len(word)
- print
- print
+ print()
+ print()
startprog = re.compile("^Working file: (.*)$")
diff --git a/Demo/pdist/rcslib.py b/Demo/pdist/rcslib.py
index 3e63869..9690f3b 100755
--- a/Demo/pdist/rcslib.py
+++ b/Demo/pdist/rcslib.py
@@ -90,7 +90,7 @@ class RCS:
dict[key] = value
status = self._closepipe(f)
if status:
- raise IOError, status
+ raise IOError(status)
return dict
# --- Methods that change files ---
@@ -160,12 +160,12 @@ class RCS:
def listfiles(self, pat = None):
"""Return a list of all version files matching optional PATTERN."""
files = os.listdir(os.curdir)
- files = filter(self._isrcs, files)
+ files = list(filter(self._isrcs, files))
if os.path.isdir('RCS'):
files2 = os.listdir('RCS')
- files2 = filter(self._isrcs, files2)
+ files2 = list(filter(self._isrcs, files2))
files = files + files2
- files = map(self.realname, files)
+ files = list(map(self.realname, files))
return self._filter(files, pat)
def isvalid(self, name):
@@ -218,7 +218,7 @@ class RCS:
line = f.readline()
status = self._closepipe(f)
if status:
- raise IOError, status
+ raise IOError(status)
if not line: return None
if line[-1] == '\n':
line = line[:-1]
@@ -232,7 +232,7 @@ class RCS:
"""
name, rev = self._unmangle(name_rev)
if not self.isvalid(name):
- raise os.error, 'not an rcs file %r' % (name,)
+ raise os.error('not an rcs file %r' % (name,))
return name, rev
# --- Internal methods ---
@@ -269,7 +269,7 @@ class RCS:
name, rev = name_rev
for c in rev:
if c not in self.okchars:
- raise ValueError, "bad char in rev"
+ raise ValueError("bad char in rev")
return name_rev
def _closepipe(self, f):
@@ -304,7 +304,7 @@ class RCS:
"""
cmd = cmd + " </dev/null"
sts = os.system(cmd)
- if sts: raise IOError, "command exit status %d" % sts
+ if sts: raise IOError("command exit status %d" % sts)
def _filter(self, files, pat = None):
"""INTERNAL: Return a sorted copy of the given list of FILES.
@@ -316,7 +316,7 @@ class RCS:
if pat:
def keep(name, pat = pat):
return fnmatch.fnmatch(name, pat)
- files = filter(keep, files)
+ files = list(filter(keep, files))
else:
files = files[:]
files.sort()
diff --git a/Demo/pdist/rcvs.py b/Demo/pdist/rcvs.py
index ab1fd87..4e2532a 100755
--- a/Demo/pdist/rcvs.py
+++ b/Demo/pdist/rcvs.py
@@ -90,9 +90,9 @@ class MyFile(File):
else: return 'r' # Get rid of entry
else: # not self.edeleted
if self.rsum:
- print "warning:",
- print self.file,
- print "was lost"
+ print("warning:", end=' ')
+ print(self.file, end=' ')
+ print("was lost")
return 'U'
else: return 'r' # Get rid of entry
else: # self.lsum
@@ -120,12 +120,12 @@ class MyFile(File):
def update(self):
code = self.action()
if code == '=': return
- print code, self.file
+ print(code, self.file)
if code in ('U', 'N'):
self.get()
elif code == 'C':
- print "%s: conflict resolution not yet implemented" % \
- self.file
+ print("%s: conflict resolution not yet implemented" % \
+ self.file)
elif code == 'D':
remove(self.file)
self.eseen = 0
@@ -146,11 +146,11 @@ class MyFile(File):
self.put(message)
return 1
elif code == 'R':
- print "%s: committing removes not yet implemented" % \
- self.file
+ print("%s: committing removes not yet implemented" % \
+ self.file)
elif code == 'C':
- print "%s: conflict resolution not yet implemented" % \
- self.file
+ print("%s: conflict resolution not yet implemented" % \
+ self.file)
def diff(self, opts = []):
self.action() # To update lseen, rseen
@@ -174,22 +174,22 @@ class MyFile(File):
tf = tempfile.NamedTemporaryFile()
tf.write(data)
tf.flush()
- print 'diff %s -r%s %s' % (flags, rev, fn)
+ print('diff %s -r%s %s' % (flags, rev, fn))
sts = os.system('diff %s %s %s' % (flags, tf.name, fn))
if sts:
- print '='*70
+ print('='*70)
def commitcheck(self):
return self.action() != 'C'
def put(self, message = ""):
- print "Checking in", self.file, "..."
+ print("Checking in", self.file, "...")
data = open(self.file).read()
if not self.enew:
self.proxy.lock(self.file)
messages = self.proxy.put(self.file, data, message)
if messages:
- print messages
+ print(messages)
self.setentry(self.proxy.head(self.file), self.lsum)
def get(self):
@@ -200,7 +200,7 @@ class MyFile(File):
self.setentry(self.rrev, self.rsum)
def log(self, otherflags):
- print self.proxy.log(self.file, otherflags)
+ print(self.proxy.log(self.file, otherflags))
def add(self):
self.eseen = 0 # While we're hacking...
@@ -256,10 +256,10 @@ class RCVS(CVS):
if not e.commitcheck():
ok = 0
if not ok:
- print "correct above errors first"
+ print("correct above errors first")
return
if not message:
- message = raw_input("One-liner: ")
+ message = input("One-liner: ")
committed = []
for e in list:
if e.commit(message):
@@ -270,20 +270,20 @@ class RCVS(CVS):
towhom = "sjoerd@cwi.nl, jack@cwi.nl" # XXX
mailtext = MAILFORM % (towhom, ' '.join(files),
' '.join(files), message)
- print '-'*70
- print mailtext
- print '-'*70
- ok = raw_input("OK to mail to %s? " % towhom)
+ print('-'*70)
+ print(mailtext)
+ print('-'*70)
+ ok = input("OK to mail to %s? " % towhom)
if ok.lower().strip() in ('y', 'ye', 'yes'):
p = os.popen(SENDMAIL, "w")
p.write(mailtext)
sts = p.close()
if sts:
- print "Sendmail exit status %s" % str(sts)
+ print("Sendmail exit status %s" % str(sts))
else:
- print "Mail sent."
+ print("Mail sent.")
else:
- print "No mail sent."
+ print("No mail sent.")
def report(self, files):
for e in self.whichentries(files):
@@ -295,15 +295,15 @@ class RCVS(CVS):
def add(self, files):
if not files:
- raise RuntimeError, "'cvs add' needs at least one file"
+ raise RuntimeError("'cvs add' needs at least one file")
list = []
for e in self.whichentries(files, 1):
e.add()
def rm(self, files):
if not files:
- raise RuntimeError, "'cvs rm' needs at least one file"
- raise RuntimeError, "'cvs rm' not yet imlemented"
+ raise RuntimeError("'cvs rm' needs at least one file")
+ raise RuntimeError("'cvs rm' not yet imlemented")
def log(self, files, opts):
flags = ''
@@ -316,23 +316,23 @@ class RCVS(CVS):
if files:
list = []
for file in files:
- if self.entries.has_key(file):
+ if file in self.entries:
e = self.entries[file]
else:
e = self.FileClass(file)
self.entries[file] = e
list.append(e)
else:
- list = self.entries.values()
+ list = list(self.entries.values())
for file in self.proxy.listfiles():
- if self.entries.has_key(file):
+ if file in self.entries:
continue
e = self.FileClass(file)
self.entries[file] = e
list.append(e)
if localfilestoo:
for file in os.listdir(os.curdir):
- if not self.entries.has_key(file) \
+ if file not in self.entries \
and not self.ignored(file):
e = self.FileClass(file)
self.entries[file] = e
@@ -376,7 +376,7 @@ class rcvs(CommandFrameWork):
continue
if os.path.islink(name):
continue
- print "--- entering subdirectory", name, "---"
+ print("--- entering subdirectory", name, "---")
os.chdir(name)
try:
if os.path.isdir("CVS"):
@@ -385,7 +385,7 @@ class rcvs(CommandFrameWork):
self.recurse()
finally:
os.chdir(os.pardir)
- print "--- left subdirectory", name, "---"
+ print("--- left subdirectory", name, "---")
def options(self, opts):
self.opts = opts
@@ -437,7 +437,7 @@ class rcvs(CommandFrameWork):
def do_add(self, opts, files):
"""add file ..."""
if not files:
- print "'rcvs add' requires at least one file"
+ print("'rcvs add' requires at least one file")
return
self.cvs.add(files)
self.cvs.putentries()
@@ -445,7 +445,7 @@ class rcvs(CommandFrameWork):
def do_remove(self, opts, files):
"""remove file ..."""
if not files:
- print "'rcvs remove' requires at least one file"
+ print("'rcvs remove' requires at least one file")
return
self.cvs.remove(files)
self.cvs.putentries()
diff --git a/Demo/pdist/rrcs.py b/Demo/pdist/rrcs.py
index 540d296..8d0ef03 100755
--- a/Demo/pdist/rrcs.py
+++ b/Demo/pdist/rrcs.py
@@ -18,22 +18,22 @@ def main():
cmd = 'head'
else:
cmd, rest = rest[0], rest[1:]
- if not commands.has_key(cmd):
- raise getopt.error, "unknown command"
+ if cmd not in commands:
+ raise getopt.error("unknown command")
coptset, func = commands[cmd]
copts, files = getopt.getopt(rest, coptset)
except getopt.error as msg:
- print msg
- print "usage: rrcs [options] command [options] [file] ..."
- print "where command can be:"
- print " ci|put # checkin the given files"
- print " co|get # checkout"
- print " info # print header info"
- print " head # print revision of head branch"
- print " list # list filename if valid"
- print " log # print full log"
- print " diff # diff rcs file and work file"
- print "if no files are given, all remote rcs files are assumed"
+ print(msg)
+ print("usage: rrcs [options] command [options] [file] ...")
+ print("where command can be:")
+ print(" ci|put # checkin the given files")
+ print(" co|get # checkout")
+ print(" info # print header info")
+ print(" head # print revision of head branch")
+ print(" list # list filename if valid")
+ print(" log # print full log")
+ print(" diff # diff rcs file and work file")
+ print("if no files are given, all remote rcs files are assumed")
sys.exit(2)
x = openrcsclient(opts)
if not files:
@@ -42,7 +42,7 @@ def main():
try:
func(x, copts, fn)
except (IOError, os.error) as msg:
- print "%s: %s" % (fn, msg)
+ print("%s: %s" % (fn, msg))
def checkin(x, copts, fn):
f = open(fn)
@@ -50,13 +50,13 @@ def checkin(x, copts, fn):
f.close()
new = not x.isvalid(fn)
if not new and same(x, copts, fn, data):
- print "%s: unchanged since last checkin" % fn
+ print("%s: unchanged since last checkin" % fn)
return
- print "Checking in", fn, "..."
+ print("Checking in", fn, "...")
message = asklogmessage(new)
messages = x.put(fn, data, message)
if messages:
- print messages
+ print(messages)
def checkout(x, copts, fn):
data = x.get(fn)
@@ -72,19 +72,19 @@ def unlock(x, copts, fn):
def info(x, copts, fn):
dict = x.info(fn)
- keys = dict.keys()
+ keys = list(dict.keys())
keys.sort()
for key in keys:
- print key + ':', dict[key]
- print '='*70
+ print(key + ':', dict[key])
+ print('='*70)
def head(x, copts, fn):
head = x.head(fn)
- print fn, head
+ print(fn, head)
def list(x, copts, fn):
if x.isvalid(fn):
- print fn
+ print(fn)
def log(x, copts, fn):
flags = ''
@@ -92,7 +92,7 @@ def log(x, copts, fn):
flags = flags + ' ' + o + a
flags = flags[1:]
messages = x.log(fn, flags)
- print messages
+ print(messages)
def diff(x, copts, fn):
if same(x, copts, fn):
@@ -105,10 +105,10 @@ def diff(x, copts, fn):
tf = tempfile.NamedTemporaryFile()
tf.write(data)
tf.flush()
- print 'diff %s -r%s %s' % (flags, x.head(fn), fn)
+ print('diff %s -r%s %s' % (flags, x.head(fn), fn))
sts = os.system('diff %s %s %s' % (flags, tf.name, fn))
if sts:
- print '='*70
+ print('='*70)
def same(x, copts, fn, data = None):
if data is None:
@@ -121,12 +121,12 @@ def same(x, copts, fn, data = None):
def asklogmessage(new):
if new:
- print "enter description,",
+ print("enter description,", end=' ')
else:
- print "enter log message,",
- print "terminate with single '.' or end of file:"
+ print("enter log message,", end=' ')
+ print("terminate with single '.' or end of file:")
if new:
- print "NOTE: This is NOT the log message!"
+ print("NOTE: This is NOT the log message!")
message = ""
while 1:
sys.stderr.write(">> ")
diff --git a/Demo/pdist/security.py b/Demo/pdist/security.py
index b63081e..ffdbe2d 100755
--- a/Demo/pdist/security.py
+++ b/Demo/pdist/security.py
@@ -3,11 +3,11 @@ class Security:
def __init__(self):
import os
env = os.environ
- if env.has_key('PYTHON_KEYFILE'):
+ if 'PYTHON_KEYFILE' in env:
keyfile = env['PYTHON_KEYFILE']
else:
keyfile = '.python_keyfile'
- if env.has_key('HOME'):
+ if 'HOME' in env:
keyfile = os.path.join(env['HOME'], keyfile)
if not os.path.exists(keyfile):
import sys
@@ -19,7 +19,7 @@ class Security:
try:
self._key = eval(open(keyfile).readline())
except IOError:
- raise IOError, "python keyfile %s: cannot open" % keyfile
+ raise IOError("python keyfile %s: cannot open" % keyfile)
def _generate_challenge(self):
import random
@@ -30,4 +30,4 @@ class Security:
def _encode_challenge(self, challenge):
p, m = self._key
- return pow(long(challenge), p, m)
+ return pow(int(challenge), p, m)
diff --git a/Demo/pdist/server.py b/Demo/pdist/server.py
index 79afa8b..98a4741 100755
--- a/Demo/pdist/server.py
+++ b/Demo/pdist/server.py
@@ -43,11 +43,11 @@ class Server:
self._serve()
def _serve(self):
- if self._verbose: print "Wait for connection ..."
+ if self._verbose: print("Wait for connection ...")
conn, address = self._socket.accept()
- if self._verbose: print "Accepted connection from %s" % repr(address)
+ if self._verbose: print("Accepted connection from %s" % repr(address))
if not self._verify(conn, address):
- print "*** Connection from %s refused" % repr(address)
+ print("*** Connection from %s refused" % repr(address))
conn.close()
return
rf = conn.makefile('r')
@@ -55,7 +55,7 @@ class Server:
ok = 1
while ok:
wf.flush()
- if self._verbose > 1: print "Wait for next request ..."
+ if self._verbose > 1: print("Wait for next request ...")
ok = self._dorequest(rf, wf)
_valid = ['192.16.201.*', '192.16.197.*', '132.151.1.*', '129.6.64.*']
@@ -72,22 +72,22 @@ class Server:
request = rp.load()
except EOFError:
return 0
- if self._verbose > 1: print "Got request: %s" % repr(request)
+ if self._verbose > 1: print("Got request: %s" % repr(request))
try:
methodname, args, id = request
if '.' in methodname:
reply = (None, self._special(methodname, args), id)
elif methodname[0] == '_':
- raise NameError, "illegal method name %s" % repr(methodname)
+ raise NameError("illegal method name %s" % repr(methodname))
else:
method = getattr(self, methodname)
reply = (None, method(*args), id)
except:
reply = (sys.exc_info()[:2], id)
if id < 0 and reply[:2] == (None, None):
- if self._verbose > 1: print "Suppress reply"
+ if self._verbose > 1: print("Suppress reply")
return 1
- if self._verbose > 1: print "Send reply: %s" % repr(reply)
+ if self._verbose > 1: print("Send reply: %s" % repr(reply))
wp = pickle.Pickler(wf)
wp.dump(reply)
return 1
@@ -97,16 +97,16 @@ class Server:
if not hasattr(self, '_methods'):
self._methods = tuple(self._listmethods())
return self._methods
- raise NameError, "unrecognized special method name %s" % repr(methodname)
+ raise NameError("unrecognized special method name %s" % repr(methodname))
def _listmethods(self, cl=None):
if not cl: cl = self.__class__
- names = cl.__dict__.keys()
- names = filter(lambda x: x[0] != '_', names)
+ names = list(cl.__dict__.keys())
+ names = [x for x in names if x[0] != '_']
names.sort()
for base in cl.__bases__:
basenames = self._listmethods(base)
- basenames = filter(lambda x, names=names: x not in names, basenames)
+ basenames = list(filter(lambda x, names=names: x not in names, basenames))
names[len(names):] = basenames
return names
@@ -134,12 +134,12 @@ class SecureServer(Server, Security):
response = string.atol(string.strip(response))
except string.atol_error:
if self._verbose > 0:
- print "Invalid response syntax", repr(response)
+ print("Invalid response syntax", repr(response))
return 0
if not self._compare_challenge_response(challenge, response):
if self._verbose > 0:
- print "Invalid response value", repr(response)
+ print("Invalid response value", repr(response))
return 0
if self._verbose > 1:
- print "Response matches challenge. Go ahead!"
+ print("Response matches challenge. Go ahead!")
return 1
diff --git a/Demo/pdist/sumtree.py b/Demo/pdist/sumtree.py
index 68224df..92e7771 100755
--- a/Demo/pdist/sumtree.py
+++ b/Demo/pdist/sumtree.py
@@ -9,13 +9,13 @@ def main():
sumtree(proxy)
proxy._close()
t2 = time.time()
- print t2-t1, "seconds"
+ print(t2-t1, "seconds")
sys.stdout.write("[Return to exit] ")
sys.stdout.flush()
sys.stdin.readline()
def sumtree(proxy):
- print "PWD =", proxy.pwd()
+ print("PWD =", proxy.pwd())
files = proxy.listfiles()
proxy.infolist(files)
subdirs = proxy.listsubdirs()
diff --git a/Demo/pysvr/pysvr.py b/Demo/pysvr/pysvr.py
index b1b7565..b200fad 100755
--- a/Demo/pysvr/pysvr.py
+++ b/Demo/pysvr/pysvr.py
@@ -20,7 +20,7 @@ def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "")
if len(args) > 1:
- raise getopt.error, "Too many arguments."
+ raise getopt.error("Too many arguments.")
except getopt.error as msg:
usage(msg)
for o, a in opts:
@@ -37,32 +37,32 @@ def main():
def usage(msg=None):
sys.stdout = sys.stderr
if msg:
- print msg
- print "\n", __doc__,
+ print(msg)
+ print("\n", __doc__, end=' ')
sys.exit(2)
def main_thread(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", port))
sock.listen(5)
- print "Listening on port", port, "..."
+ print("Listening on port", port, "...")
while 1:
(conn, addr) = sock.accept()
if addr[0] != conn.getsockname()[0]:
conn.close()
- print "Refusing connection from non-local host", addr[0], "."
+ print("Refusing connection from non-local host", addr[0], ".")
continue
thread.start_new_thread(service_thread, (conn, addr))
del conn, addr
def service_thread(conn, addr):
(caddr, cport) = addr
- print "Thread %s has connection from %s.\n" % (str(thread.get_ident()),
- caddr),
+ print("Thread %s has connection from %s.\n" % (str(thread.get_ident()),
+ caddr), end=' ')
stdin = conn.makefile("r")
stdout = conn.makefile("w", 0)
run_interpreter(stdin, stdout)
- print "Thread %s is done.\n" % str(thread.get_ident()),
+ print("Thread %s is done.\n" % str(thread.get_ident()), end=' ')
def run_interpreter(stdin, stdout):
globals = {}
@@ -110,7 +110,7 @@ def run_command(code, stdin, stdout, globals):
try:
exec(code, globals)
except SystemExit as how:
- raise SystemExit, how, sys.exc_info()[2]
+ raise SystemExit(how).with_traceback(sys.exc_info()[2])
except:
type, value, tb = sys.exc_info()
if tb: tb = tb.tb_next
diff --git a/Demo/rpc/mountclient.py b/Demo/rpc/mountclient.py
index 318a9d9..3bb88b1 100644
--- a/Demo/rpc/mountclient.py
+++ b/Demo/rpc/mountclient.py
@@ -193,10 +193,10 @@ def test():
mcl = C(host)
list = mcl.Export()
for item in list:
- print item
+ print(item)
try:
mcl.Mnt(item[0])
except:
- print 'Sorry'
+ print('Sorry')
continue
mcl.Umnt(item[0])
diff --git a/Demo/rpc/nfsclient.py b/Demo/rpc/nfsclient.py
index 3890aff..aad8cf3 100644
--- a/Demo/rpc/nfsclient.py
+++ b/Demo/rpc/nfsclient.py
@@ -187,14 +187,14 @@ def test():
if filesys == None:
list = mcl.Export()
for item in list:
- print item
+ print(item)
return
sf = mcl.Mnt(filesys)
- print sf
+ print(sf)
fh = sf[1]
if fh:
ncl = NFSClient(host)
- print ncl.Getattr(fh)
+ print(ncl.Getattr(fh))
list = ncl.Listdir(fh)
- for item in list: print item
+ for item in list: print(item)
mcl.Umnt(filesys)
diff --git a/Demo/rpc/rnusersclient.py b/Demo/rpc/rnusersclient.py
index 1f3a882..eaabefe 100644
--- a/Demo/rpc/rnusersclient.py
+++ b/Demo/rpc/rnusersclient.py
@@ -77,19 +77,19 @@ def test():
line = strip0(line)
name = strip0(name)
host = strip0(host)
- print "%r %r %r %s %s" % (name, host, line, time, idle)
+ print("%r %r %r %s %s" % (name, host, line, time, idle))
def testbcast():
c = BroadcastRnusersClient('<broadcast>')
def listit(list, fromaddr):
host, port = fromaddr
- print host + '\t:',
+ print(host + '\t:', end=' ')
for (line, name, host, time), idle in list:
- print strip0(name),
- print
+ print(strip0(name), end=' ')
+ print()
c.set_reply_handler(listit)
all = c.Names()
- print 'Total Count:', len(all)
+ print('Total Count:', len(all))
def strip0(s):
while s and s[-1] == '\0': s = s[:-1]
diff --git a/Demo/rpc/rpc.py b/Demo/rpc/rpc.py
index f7231c1..99115d3 100644
--- a/Demo/rpc/rpc.py
+++ b/Demo/rpc/rpc.py
@@ -95,10 +95,10 @@ class Unpacker(xdr.Unpacker):
xid = self.unpack_uint()
temp = self.unpack_enum()
if temp != CALL:
- raise BadRPCFormat, 'no CALL but %r' % (temp,)
+ raise BadRPCFormat('no CALL but %r' % (temp,))
temp = self.unpack_uint()
if temp != RPCVERSION:
- raise BadRPCVersion, 'bad RPC version %r' % (temp,)
+ raise BadRPCVersion('bad RPC version %r' % (temp,))
prog = self.unpack_uint()
vers = self.unpack_uint()
proc = self.unpack_uint()
@@ -111,38 +111,34 @@ class Unpacker(xdr.Unpacker):
xid = self.unpack_uint()
mtype = self.unpack_enum()
if mtype != REPLY:
- raise RuntimeError, 'no REPLY but %r' % (mtype,)
+ raise RuntimeError('no REPLY but %r' % (mtype,))
stat = self.unpack_enum()
if stat == MSG_DENIED:
stat = self.unpack_enum()
if stat == RPC_MISMATCH:
low = self.unpack_uint()
high = self.unpack_uint()
- raise RuntimeError, \
- 'MSG_DENIED: RPC_MISMATCH: %r' % ((low, high),)
+ raise RuntimeError('MSG_DENIED: RPC_MISMATCH: %r' % ((low, high),))
if stat == AUTH_ERROR:
stat = self.unpack_uint()
- raise RuntimeError, \
- 'MSG_DENIED: AUTH_ERROR: %r' % (stat,)
- raise RuntimeError, 'MSG_DENIED: %r' % (stat,)
+ raise RuntimeError('MSG_DENIED: AUTH_ERROR: %r' % (stat,))
+ raise RuntimeError('MSG_DENIED: %r' % (stat,))
if stat != MSG_ACCEPTED:
- raise RuntimeError, \
- 'Neither MSG_DENIED nor MSG_ACCEPTED: %r' % (stat,)
+ raise RuntimeError('Neither MSG_DENIED nor MSG_ACCEPTED: %r' % (stat,))
verf = self.unpack_auth()
stat = self.unpack_enum()
if stat == PROG_UNAVAIL:
- raise RuntimeError, 'call failed: PROG_UNAVAIL'
+ raise RuntimeError('call failed: PROG_UNAVAIL')
if stat == PROG_MISMATCH:
low = self.unpack_uint()
high = self.unpack_uint()
- raise RuntimeError, \
- 'call failed: PROG_MISMATCH: %r' % ((low, high),)
+ raise RuntimeError('call failed: PROG_MISMATCH: %r' % ((low, high),))
if stat == PROC_UNAVAIL:
- raise RuntimeError, 'call failed: PROC_UNAVAIL'
+ raise RuntimeError('call failed: PROC_UNAVAIL')
if stat == GARBAGE_ARGS:
- raise RuntimeError, 'call failed: GARBAGE_ARGS'
+ raise RuntimeError('call failed: GARBAGE_ARGS')
if stat != SUCCESS:
- raise RuntimeError, 'call failed: %r' % (stat,)
+ raise RuntimeError('call failed: %r' % (stat,))
return xid, verf
# Caller must get procedure-specific part of reply
@@ -193,7 +189,7 @@ def unix_epoch():
offset, hh = divmod(hh + offset, 24)
d = d + offset
_unix_epoch = time.mktime((y, m, d, hh, mm, ss, 0, 0, 0))
- print "Unix epoch:", time.ctime(_unix_epoch)
+ print("Unix epoch:", time.ctime(_unix_epoch))
return _unix_epoch
@@ -219,7 +215,7 @@ class Client:
def makesocket(self):
# This MUST be overridden
- raise RuntimeError, 'makesocket not defined'
+ raise RuntimeError('makesocket not defined')
def connsocket(self):
# Override this if you don't want/need a connection
@@ -237,7 +233,7 @@ class Client:
def make_call(self, proc, args, pack_func, unpack_func):
# Don't normally override this (but see Broadcast)
if pack_func is None and args is not None:
- raise TypeError, 'non-null args with null pack_func'
+ raise TypeError('non-null args with null pack_func')
self.start_call(proc)
if pack_func:
pack_func(args)
@@ -260,7 +256,7 @@ class Client:
def do_call(self):
# This MUST be overridden
- raise RuntimeError, 'do_call not defined'
+ raise RuntimeError('do_call not defined')
def mkcred(self):
# Override this to use more powerful credentials
@@ -282,7 +278,7 @@ class Client:
def sendfrag(sock, last, frag):
x = len(frag)
- if last: x = x | 0x80000000L
+ if last: x = x | 0x80000000
header = (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \
chr(int(x>>8 & 0xff)) + chr(int(x & 0xff)))
sock.send(header + frag)
@@ -294,7 +290,7 @@ def recvfrag(sock):
header = sock.recv(4)
if len(header) < 4:
raise EOFError
- x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \
+ x = int(ord(header[0]))<<24 | ord(header[1])<<16 | \
ord(header[2])<<8 | ord(header[3])
last = ((x & 0x80000000) != 0)
n = int(x & 0x7fffffff)
@@ -333,8 +329,8 @@ def bindresvport(sock, host):
except socket.error as e:
(errno, msg) = e
if errno != 114:
- raise socket.error, (errno, msg)
- raise RuntimeError, 'can\'t assign reserved port'
+ raise socket.error(errno, msg)
+ raise RuntimeError('can\'t assign reserved port')
# Client using TCP to a specific port
@@ -353,8 +349,8 @@ class RawTCPClient(Client):
xid, verf = u.unpack_replyheader()
if xid != self.lastxid:
# Can't really happen since this is TCP...
- raise RuntimeError, 'wrong xid in reply %r instead of %r' % (
- xid, self.lastxid)
+ raise RuntimeError('wrong xid in reply %r instead of %r' % (
+ xid, self.lastxid))
# Client using UDP to a specific port
@@ -370,7 +366,7 @@ class RawUDPClient(Client):
try:
from select import select
except ImportError:
- print 'WARNING: select not found, RPC may hang'
+ print('WARNING: select not found, RPC may hang')
select = None
BUFSIZE = 8192 # Max UDP buffer size
timeout = 1
@@ -381,7 +377,7 @@ class RawUDPClient(Client):
r, w, x = select(r, w, x, timeout)
if self.sock not in r:
count = count - 1
- if count < 0: raise RuntimeError, 'timeout'
+ if count < 0: raise RuntimeError('timeout')
if timeout < 25: timeout = timeout *2
## print 'RESEND', timeout, count
self.sock.send(call)
@@ -417,7 +413,7 @@ class RawBroadcastUDPClient(RawUDPClient):
def make_call(self, proc, args, pack_func, unpack_func):
if pack_func is None and args is not None:
- raise TypeError, 'non-null args with null pack_func'
+ raise TypeError('non-null args with null pack_func')
self.start_call(proc)
if pack_func:
pack_func(args)
@@ -426,7 +422,7 @@ class RawBroadcastUDPClient(RawUDPClient):
try:
from select import select
except ImportError:
- print 'WARNING: select not found, broadcast will hang'
+ print('WARNING: select not found, broadcast will hang')
select = None
BUFSIZE = 8192 # Max UDP buffer size (for reply)
replies = []
@@ -585,7 +581,7 @@ class TCPClient(RawTCPClient):
port = pmap.Getport((prog, vers, IPPROTO_TCP, 0))
pmap.close()
if port == 0:
- raise RuntimeError, 'program not registered'
+ raise RuntimeError('program not registered')
RawTCPClient.__init__(self, host, prog, vers, port)
@@ -596,7 +592,7 @@ class UDPClient(RawUDPClient):
port = pmap.Getport((prog, vers, IPPROTO_UDP, 0))
pmap.close()
if port == 0:
- raise RuntimeError, 'program not registered'
+ raise RuntimeError('program not registered')
RawUDPClient.__init__(self, host, prog, vers, port)
@@ -665,13 +661,13 @@ class Server:
mapping = self.prog, self.vers, self.prot, self.port
p = TCPPortMapperClient(self.host)
if not p.Set(mapping):
- raise RuntimeError, 'register failed'
+ raise RuntimeError('register failed')
def unregister(self):
mapping = self.prog, self.vers, self.prot, self.port
p = TCPPortMapperClient(self.host)
if not p.Unset(mapping):
- raise RuntimeError, 'unregister failed'
+ raise RuntimeError('unregister failed')
def handle(self, call):
# Don't use unpack_header but parse the header piecewise
@@ -736,7 +732,7 @@ class Server:
def makesocket(self):
# This MUST be overridden
- raise RuntimeError, 'makesocket not defined'
+ raise RuntimeError('makesocket not defined')
def bindsocket(self):
# Override this to bind to a different port (e.g. reserved)
@@ -767,7 +763,7 @@ class TCPServer(Server):
except EOFError:
break
except socket.error as msg:
- print 'socket error:', msg
+ print('socket error:', msg)
break
reply = self.handle(call)
if reply is not None:
@@ -826,11 +822,11 @@ def test():
list = pmap.Dump()
list.sort()
for prog, vers, prot, port in list:
- print prog, vers,
- if prot == IPPROTO_TCP: print 'tcp',
- elif prot == IPPROTO_UDP: print 'udp',
- else: print prot,
- print port
+ print(prog, vers, end=' ')
+ if prot == IPPROTO_TCP: print('tcp', end=' ')
+ elif prot == IPPROTO_UDP: print('udp', end=' ')
+ else: print(prot, end=' ')
+ print(port)
# Test program for broadcast operation -- dump everybody's portmapper status
@@ -843,7 +839,7 @@ def testbcast():
bcastaddr = '<broadcast>'
def rh(reply, fromaddr):
host, port = fromaddr
- print host + '\t' + repr(reply)
+ print(host + '\t' + repr(reply))
pmap = BroadcastUDPPortMapperClient(bcastaddr)
pmap.set_reply_handler(rh)
pmap.set_timeout(5)
@@ -861,21 +857,21 @@ def testsvr():
def handle_1(self):
arg = self.unpacker.unpack_string()
self.turn_around()
- print 'RPC function 1 called, arg', repr(arg)
+ print('RPC function 1 called, arg', repr(arg))
self.packer.pack_string(arg + arg)
#
s = S('', 0x20000000, 1, 0)
try:
s.unregister()
except RuntimeError as msg:
- print 'RuntimeError:', msg, '(ignored)'
+ print('RuntimeError:', msg, '(ignored)')
s.register()
- print 'Service started...'
+ print('Service started...')
try:
s.loop()
finally:
s.unregister()
- print 'Service interrupted.'
+ print('Service interrupted.')
def testclt():
@@ -889,6 +885,6 @@ def testclt():
self.packer.pack_string, \
self.unpacker.unpack_string)
c = C(host, 0x20000000, 1)
- print 'making call...'
+ print('making call...')
reply = c.call_1('hello, world, ')
- print 'call returned', repr(reply)
+ print('call returned', repr(reply))
diff --git a/Demo/rpc/xdr.py b/Demo/rpc/xdr.py
index e03b352..fd9efee 100644
--- a/Demo/rpc/xdr.py
+++ b/Demo/rpc/xdr.py
@@ -7,7 +7,7 @@ except ImportError:
struct = None
-Long = type(0L)
+Long = type(0)
class Packer:
@@ -28,8 +28,8 @@ class Packer:
if struct and struct.pack('l', 1) == '\0\0\0\1':
def pack_uint(self, x):
if type(x) == Long:
- x = int((x + 0x80000000L) % 0x100000000L \
- - 0x80000000L)
+ x = int((x + 0x80000000) % 0x100000000 \
+ - 0x80000000)
self.buf = self.buf + struct.pack('l', x)
pack_int = pack_uint
@@ -56,7 +56,7 @@ class Packer:
def pack_fstring(self, n, s):
if n < 0:
- raise ValueError, 'fstring size must be nonnegative'
+ raise ValueError('fstring size must be nonnegative')
n = ((n+3)/4)*4
data = s[:n]
data = data + (n - len(data)) * '\0'
@@ -79,7 +79,7 @@ class Packer:
def pack_farray(self, n, list, pack_item):
if len(list) != n:
- raise ValueError, 'wrong array size'
+ raise ValueError('wrong array size')
for item in list:
pack_item(item)
@@ -100,7 +100,7 @@ class Unpacker:
def done(self):
if self.pos < len(self.buf):
- raise RuntimeError, 'unextracted data remains'
+ raise RuntimeError('unextracted data remains')
def unpack_uint(self):
i = self.pos
@@ -108,11 +108,11 @@ class Unpacker:
data = self.buf[i:j]
if len(data) < 4:
raise EOFError
- x = long(ord(data[0]))<<24 | ord(data[1])<<16 | \
+ x = int(ord(data[0]))<<24 | ord(data[1])<<16 | \
ord(data[2])<<8 | ord(data[3])
# Return a Python long only if the value is not representable
# as a nonnegative Python int
- if x < 0x80000000L: x = int(x)
+ if x < 0x80000000: x = int(x)
return x
if struct and struct.unpack('l', '\0\0\0\1') == 1:
def unpack_uint(self):
@@ -125,7 +125,7 @@ class Unpacker:
def unpack_int(self):
x = self.unpack_uint()
- if x >= 0x80000000L: x = x - 0x100000000L
+ if x >= 0x80000000: x = x - 0x100000000
return int(x)
unpack_enum = unpack_int
@@ -135,11 +135,11 @@ class Unpacker:
def unpack_uhyper(self):
hi = self.unpack_uint()
lo = self.unpack_uint()
- return long(hi)<<32 | lo
+ return int(hi)<<32 | lo
def unpack_hyper(self):
x = self.unpack_uhyper()
- if x >= 0x8000000000000000L: x = x - 0x10000000000000000L
+ if x >= 0x8000000000000000: x = x - 0x10000000000000000
return x
def unpack_float(self):
@@ -162,7 +162,7 @@ class Unpacker:
def unpack_fstring(self, n):
if n < 0:
- raise ValueError, 'fstring size must be nonnegative'
+ raise ValueError('fstring size must be nonnegative')
i = self.pos
j = i + (n+3)/4*4
if j > len(self.buf):
@@ -184,7 +184,7 @@ class Unpacker:
x = self.unpack_uint()
if x == 0: break
if x != 1:
- raise RuntimeError, '0 or 1 expected, got %r' % (x, )
+ raise RuntimeError('0 or 1 expected, got %r' % (x, ))
item = unpack_item()
list.append(item)
return list
diff --git a/Demo/scripts/beer.py b/Demo/scripts/beer.py
index 1b9ac8b..f050572 100644
--- a/Demo/scripts/beer.py
+++ b/Demo/scripts/beer.py
@@ -8,7 +8,7 @@ def bottle(n):
if n == 1: return "one bottle of beer"
return str(n) + " bottles of beer"
for i in range(n):
- print bottle(n-i), "on the wall,"
- print bottle(n-i) + "."
- print "Take one down, pass it around,"
- print bottle(n-i-1), "on the wall."
+ print(bottle(n-i), "on the wall,")
+ print(bottle(n-i) + ".")
+ print("Take one down, pass it around,")
+ print(bottle(n-i-1), "on the wall.")
diff --git a/Demo/scripts/eqfix.py b/Demo/scripts/eqfix.py
index 497ab20..47c00d3 100755
--- a/Demo/scripts/eqfix.py
+++ b/Demo/scripts/eqfix.py
@@ -143,7 +143,7 @@ def fix(filename):
# First copy the file's mode to the temp file
try:
statbuf = os.stat(filename)
- os.chmod(tempname, statbuf[ST_MODE] & 07777)
+ os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
except os.error as msg:
err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
# Then make a backup of the original file as filename~
@@ -176,22 +176,22 @@ def fixline(line):
j = tokenprog.match(line, i)
if j < 0:
# A bad token; forget about the rest of this line
- print '(Syntax error:)'
- print line,
+ print('(Syntax error:)')
+ print(line, end=' ')
return line
a, b = tokenprog.regs[3] # Location of the token proper
token = line[a:b]
i = i+j
if stack and token == stack[-1]:
del stack[-1]
- elif match.has_key(token):
+ elif token in match:
stack.append(match[token])
elif token == '=' and stack:
line = line[:a] + '==' + line[b:]
i, n = a + len('=='), len(line)
elif token == '==' and not stack:
- print '(Warning: \'==\' at top level:)'
- print line,
+ print('(Warning: \'==\' at top level:)')
+ print(line, end=' ')
return line
if __name__ == "__main__":
diff --git a/Demo/scripts/fact.py b/Demo/scripts/fact.py
index 03cab8b..19d28eb 100755
--- a/Demo/scripts/fact.py
+++ b/Demo/scripts/fact.py
@@ -36,12 +36,12 @@ def main():
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
n = eval(arg)
- print n, fact(n)
+ print(n, fact(n))
else:
try:
while 1:
- n = input()
- print n, fact(n)
+ n = eval(input())
+ print(n, fact(n))
except EOFError:
pass
diff --git a/Demo/scripts/find-uname.py b/Demo/scripts/find-uname.py
index b76b9f0..fbf4033 100644
--- a/Demo/scripts/find-uname.py
+++ b/Demo/scripts/find-uname.py
@@ -24,7 +24,7 @@ def main(args):
unicode_names= []
for ix in range(sys.maxunicode+1):
try:
- unicode_names.append( (ix, unicodedata.name(unichr(ix))) )
+ unicode_names.append( (ix, unicodedata.name(chr(ix))) )
except ValueError: # no name for the character
pass
for arg in args:
@@ -32,9 +32,9 @@ def main(args):
matches = [(x,y) for (x,y) in unicode_names
if pat.search(y) is not None]
if matches:
- print "***", arg, "matches", "***"
+ print("***", arg, "matches", "***")
for (x,y) in matches:
- print "%s (%d)" % (y,x)
+ print("%s (%d)" % (y,x))
if __name__ == "__main__":
main(sys.argv[1:])
diff --git a/Demo/scripts/from.py b/Demo/scripts/from.py
index 3c04fcd..323e684 100755
--- a/Demo/scripts/from.py
+++ b/Demo/scripts/from.py
@@ -25,11 +25,11 @@ while 1:
break # EOF
if line.startswith('From '):
# Start of message found
- print line[:-1],
+ print(line[:-1], end=' ')
while 1:
line = mail.readline()
if not line or line == '\n':
break
if line.startswith('Subject: '):
- print repr(line[9:-1]),
- print
+ print(repr(line[9:-1]), end=' ')
+ print()
diff --git a/Demo/scripts/ftpstats.py b/Demo/scripts/ftpstats.py
index c7c0749..d0a0824 100755
--- a/Demo/scripts/ftpstats.py
+++ b/Demo/scripts/ftpstats.py
@@ -26,8 +26,8 @@ def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'm:s:')
except getopt.error as msg:
- print msg
- print 'usage: ftpstats [-m maxitems] [file]'
+ print(msg)
+ print('usage: ftpstats [-m maxitems] [file]')
sys.exit(2)
for o, a in opts:
if o == '-m':
@@ -42,7 +42,7 @@ def main():
try:
f = open(file, 'r')
except IOError as msg:
- print file, ':', msg
+ print(file, ':', msg)
sys.exit(1)
bydate = {}
bytime = {}
@@ -60,7 +60,7 @@ def main():
if search and string.find(line, search) < 0:
continue
if prog.match(line) < 0:
- print 'Bad line', lineno, ':', repr(line)
+ print('Bad line', lineno, ':', repr(line))
continue
items = prog.group(1, 2, 3, 4, 5, 6)
(logtime, loguser, loghost, logfile, logbytes,
@@ -93,7 +93,7 @@ def main():
add(byuser, loguser, items)
add(bytype, direction, items)
except KeyboardInterrupt:
- print 'Interrupted at line', lineno
+ print('Interrupted at line', lineno)
show(bytype, 'by transfer direction', maxitems)
show(bydir, 'by directory', maxitems)
show(byfile, 'by file', maxitems)
@@ -104,9 +104,9 @@ def main():
def showbar(dict, title):
n = len(title)
- print '='*((70-n)/2), title, '='*((71-n)/2)
+ print('='*((70-n)/2), title, '='*((71-n)/2))
list = []
- keys = dict.keys()
+ keys = list(dict.keys())
keys.sort()
for key in keys:
n = len(str(key))
@@ -120,23 +120,23 @@ def showbar(dict, title):
for count, key in list:
barlength = int(round(maxbarlength*float(count)/maxcount))
bar = '*'*barlength
- print '%5d %-*s %s' % (count, maxkeylength, key, bar)
+ print('%5d %-*s %s' % (count, maxkeylength, key, bar))
def show(dict, title, maxitems):
if len(dict) > maxitems:
title = title + ' (first %d)'%maxitems
n = len(title)
- print '='*((70-n)/2), title, '='*((71-n)/2)
+ print('='*((70-n)/2), title, '='*((71-n)/2))
list = []
- keys = dict.keys()
+ keys = list(dict.keys())
for key in keys:
list.append((-len(dict[key]), key))
list.sort()
for count, key in list[:maxitems]:
- print '%5d %s' % (-count, key)
+ print('%5d %s' % (-count, key))
def add(dict, key, item):
- if dict.has_key(key):
+ if key in dict:
dict[key].append(item)
else:
dict[key] = [item]
diff --git a/Demo/scripts/lpwatch.py b/Demo/scripts/lpwatch.py
index c3dcb34..567385c 100755
--- a/Demo/scripts/lpwatch.py
+++ b/Demo/scripts/lpwatch.py
@@ -25,7 +25,7 @@ def main():
if printers[i][:2] == '-P':
printers[i] = printers[i][2:]
else:
- if posix.environ.has_key('PRINTER'):
+ if 'PRINTER' in posix.environ:
printers = [posix.environ['PRINTER']]
else:
printers = [DEF_PRINTER]
@@ -36,7 +36,7 @@ def main():
text = clearhome
for name in printers:
text = text + makestatus(name, thisuser) + '\n'
- print text
+ print(text)
time.sleep(delay)
def makestatus(name, thisuser):
@@ -66,7 +66,7 @@ def makestatus(name, thisuser):
aheadjobs = aheadjobs + 1
totalbytes = totalbytes + bytes
totaljobs = totaljobs + 1
- if users.has_key(user):
+ if user in users:
ujobs, ubytes = users[user]
else:
ujobs, ubytes = 0, 0
@@ -87,7 +87,7 @@ def makestatus(name, thisuser):
if totaljobs != len(users):
line = line + ' (%d jobs)' % totaljobs
if len(users) == 1:
- line = line + ' for %s' % (users.keys()[0],)
+ line = line + ' for %s' % (list(users.keys())[0],)
else:
line = line + ' for %d users' % len(users)
if userseen:
diff --git a/Demo/scripts/makedir.py b/Demo/scripts/makedir.py
index f70facd..7095868 100755
--- a/Demo/scripts/makedir.py
+++ b/Demo/scripts/makedir.py
@@ -15,7 +15,7 @@ def makedirs(p):
if p and not os.path.isdir(p):
head, tail = os.path.split(p)
makedirs(head)
- os.mkdir(p, 0777)
+ os.mkdir(p, 0o777)
if __name__ == "__main__":
main()
diff --git a/Demo/scripts/markov.py b/Demo/scripts/markov.py
index bddec56..a91e359 100755
--- a/Demo/scripts/markov.py
+++ b/Demo/scripts/markov.py
@@ -6,7 +6,7 @@ class Markov:
self.choice = choice
self.trans = {}
def add(self, state, next):
- if not self.trans.has_key(state):
+ if state not in self.trans:
self.trans[state] = [next]
else:
self.trans[state].append(next)
@@ -36,19 +36,19 @@ def test():
try:
opts, args = getopt.getopt(args, '0123456789cdw')
except getopt.error:
- print 'Usage: markov [-#] [-cddqw] [file] ...'
- print 'Options:'
- print '-#: 1-digit history size (default 2)'
- print '-c: characters (default)'
- print '-w: words'
- print '-d: more debugging output'
- print '-q: no debugging output'
- print 'Input files (default stdin) are split in paragraphs'
- print 'separated blank lines and each paragraph is split'
- print 'in words by whitespace, then reconcatenated with'
- print 'exactly one space separating words.'
- print 'Output consists of paragraphs separated by blank'
- print 'lines, where lines are no longer than 72 characters.'
+ print('Usage: markov [-#] [-cddqw] [file] ...')
+ print('Options:')
+ print('-#: 1-digit history size (default 2)')
+ print('-c: characters (default)')
+ print('-w: words')
+ print('-d: more debugging output')
+ print('-q: no debugging output')
+ print('Input files (default stdin) are split in paragraphs')
+ print('separated blank lines and each paragraph is split')
+ print('in words by whitespace, then reconcatenated with')
+ print('exactly one space separating words.')
+ print('Output consists of paragraphs separated by blank')
+ print('lines, where lines are no longer than 72 characters.')
histsize = 2
do_words = 0
debug = 1
@@ -65,33 +65,33 @@ def test():
if filename == '-':
f = sys.stdin
if f.isatty():
- print 'Sorry, need stdin from file'
+ print('Sorry, need stdin from file')
continue
else:
f = open(filename, 'r')
- if debug: print 'processing', filename, '...'
+ if debug: print('processing', filename, '...')
text = f.read()
f.close()
paralist = string.splitfields(text, '\n\n')
for para in paralist:
- if debug > 1: print 'feeding ...'
+ if debug > 1: print('feeding ...')
words = string.split(para)
if words:
if do_words: data = tuple(words)
else: data = string.joinfields(words, ' ')
m.put(data)
except KeyboardInterrupt:
- print 'Interrupted -- continue with data read so far'
+ print('Interrupted -- continue with data read so far')
if not m.trans:
- print 'No valid input files'
+ print('No valid input files')
return
- if debug: print 'done.'
+ if debug: print('done.')
if debug > 1:
- for key in m.trans.keys():
+ for key in list(m.trans.keys()):
if key is None or len(key) < histsize:
- print repr(key), m.trans[key]
- if histsize == 0: print repr(''), m.trans['']
- print
+ print(repr(key), m.trans[key])
+ if histsize == 0: print(repr(''), m.trans[''])
+ print()
while 1:
data = m.get()
if do_words: words = data
@@ -100,12 +100,12 @@ def test():
limit = 72
for w in words:
if n + len(w) > limit:
- print
+ print()
n = 0
- print w,
+ print(w, end=' ')
n = n + len(w) + 1
- print
- print
+ print()
+ print()
def tuple(list):
if len(list) == 0: return ()
diff --git a/Demo/scripts/mboxconvert.py b/Demo/scripts/mboxconvert.py
index 8da37bf..787c760 100755
--- a/Demo/scripts/mboxconvert.py
+++ b/Demo/scripts/mboxconvert.py
@@ -91,19 +91,19 @@ def message(f, delimiter = ''):
sys.stderr.write(
'Unparseable date: %r\n' % (m.getheader('Date'),))
t = os.fstat(f.fileno())[stat.ST_MTIME]
- print 'From', email, time.ctime(t)
+ print('From', email, time.ctime(t))
# Copy RFC822 header
for line in m.headers:
- print line,
+ print(line, end=' ')
# Invent Message-ID header if none is present
- if not m.has_key('message-id'):
+ if 'message-id' not in m:
global counter
counter = counter + 1
msgid = "<%s.%d>" % (hex(t), counter)
sys.stderr.write("Adding Message-ID %s (From %s)\n" %
(msgid, email))
- print "Message-ID:", msgid
- print
+ print("Message-ID:", msgid)
+ print()
# Copy body
while 1:
line = f.readline()
@@ -115,9 +115,9 @@ def message(f, delimiter = ''):
break
if line[:5] == 'From ':
line = '>' + line
- print line,
+ print(line, end=' ')
# Print trailing newline
- print
+ print()
return sts
if __name__ == "__main__":
diff --git a/Demo/scripts/mkrcs.py b/Demo/scripts/mkrcs.py
index cacdda0..317647a 100755
--- a/Demo/scripts/mkrcs.py
+++ b/Demo/scripts/mkrcs.py
@@ -12,13 +12,13 @@ def main():
rcstree = 'RCStree'
rcs = 'RCS'
if os.path.islink(rcs):
- print '%r is a symlink to %r' % (rcs, os.readlink(rcs))
+ print('%r is a symlink to %r' % (rcs, os.readlink(rcs)))
return
if os.path.isdir(rcs):
- print '%r is an ordinary directory' % (rcs,)
+ print('%r is an ordinary directory' % (rcs,))
return
if os.path.exists(rcs):
- print '%r is a file?!?!' % (rcs,)
+ print('%r is a file?!?!' % (rcs,))
return
#
p = os.getcwd()
@@ -34,7 +34,7 @@ def main():
head, tail = os.path.split(p)
#print 'head = %r; tail = %r' % (head, tail)
if not tail:
- print 'Sorry, no ancestor dir contains %r' % (rcstree,)
+ print('Sorry, no ancestor dir contains %r' % (rcstree,))
return
p = head
up = os.path.join(os.pardir, up)
@@ -44,18 +44,18 @@ def main():
there = os.path.join(there, down)
there = os.path.join(there, rcs)
if os.path.isdir(there):
- print '%r already exists' % (there, )
+ print('%r already exists' % (there, ))
else:
- print 'making %r' % (there,)
+ print('making %r' % (there,))
makedirs(there)
- print 'making symlink %r -> %r' % (rcs, there)
+ print('making symlink %r -> %r' % (rcs, there))
os.symlink(there, rcs)
def makedirs(p):
if not os.path.isdir(p):
head, tail = os.path.split(p)
makedirs(head)
- os.mkdir(p, 0777)
+ os.mkdir(p, 0o777)
if __name__ == "__main__":
main()
diff --git a/Demo/scripts/newslist.py b/Demo/scripts/newslist.py
index 0111ace..4635f1d 100755
--- a/Demo/scripts/newslist.py
+++ b/Demo/scripts/newslist.py
@@ -98,7 +98,7 @@ sublistsize = 4
for dir in os.curdir, os.environ['HOME']:
rcfile = os.path.join(dir, '.newslistrc.py')
if os.path.exists(rcfile):
- print rcfile
+ print(rcfile)
execfile(rcfile)
break
@@ -106,7 +106,7 @@ from nntplib import NNTP
from stat import *
rcsrev = '$Revision$'
-rcsrev = string.join(filter(lambda s: '$' not in s, string.split(rcsrev)))
+rcsrev = string.join([s for s in string.split(rcsrev) if '$' not in s])
desc = {}
# Make (possibly) relative filenames into absolute ones
@@ -118,7 +118,7 @@ page = os.path.join(topdir,pagedir)
# Addtotree creates/augments a tree from a list of group names
def addtotree(tree, groups):
- print 'Updating tree...'
+ print('Updating tree...')
for i in groups:
parts = string.splitfields(i,'.')
makeleaf(tree, parts)
@@ -128,7 +128,7 @@ def makeleaf(tree,path):
j = path[0]
l = len(path)
- if not tree.has_key(j):
+ if j not in tree:
tree[j] = {}
if l == 1:
tree[j]['.'] = '.'
@@ -172,7 +172,7 @@ def printtree(f, tree, indent, p):
createpage(p[1:], tree, p)
return
- kl = tree.keys()
+ kl = list(tree.keys())
if l > 1:
kl.sort()
@@ -188,7 +188,7 @@ def printtree(f, tree, indent, p):
if i == '.':
# Output a newsgroup
f.write('<LI><A HREF="news:' + p[1:] + '">'+ p[1:] + '</A> ')
- if desc.has_key(p[1:]):
+ if p[1:] in desc:
f.write(' <I>'+desc[p[1:]]+'</I>\n')
else:
f.write('\n')
@@ -213,9 +213,9 @@ def readdesc(descfile):
try:
d = open(descfile, 'r')
- print 'Reading descriptions...'
+ print('Reading descriptions...')
except (IOError):
- print 'Failed to open description file ' + descfile
+ print('Failed to open description file ' + descfile)
return
l = d.readline()
while l != '':
@@ -234,29 +234,29 @@ def readdesc(descfile):
def checkopdir(pagedir):
if not os.path.isdir(pagedir):
- print 'Directory '+pagedir+' does not exist.'
- print 'Shall I create it for you? (y/n)'
+ print('Directory '+pagedir+' does not exist.')
+ print('Shall I create it for you? (y/n)')
if sys.stdin.readline()[0] == 'y':
try:
- os.mkdir(pagedir,0777)
+ os.mkdir(pagedir,0o777)
except:
- print 'Sorry - failed!'
+ print('Sorry - failed!')
sys.exit(1)
else:
- print 'OK. Exiting.'
+ print('OK. Exiting.')
sys.exit(1)
# Read and write current local tree ----------------------------------
def readlocallist(treefile):
- print 'Reading current local group list...'
+ print('Reading current local group list...')
tree = {}
try:
treetime = time.localtime(os.stat(treefile)[ST_MTIME])
except:
- print '\n*** Failed to open local group cache '+treefile
- print 'If this is the first time you have run newslist, then'
- print 'use the -a option to create it.'
+ print('\n*** Failed to open local group cache '+treefile)
+ print('If this is the first time you have run newslist, then')
+ print('use the -a option to create it.')
sys.exit(1)
treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2])
try:
@@ -264,7 +264,7 @@ def readlocallist(treefile):
tree = marshal.load(dump)
dump.close()
except (IOError):
- print 'Cannot open local group list ' + treefile
+ print('Cannot open local group list ' + treefile)
return (tree, treedate)
def writelocallist(treefile, tree):
@@ -272,45 +272,45 @@ def writelocallist(treefile, tree):
dump = open(treefile,'w')
groups = marshal.dump(tree,dump)
dump.close()
- print 'Saved list to '+treefile+'\n'
+ print('Saved list to '+treefile+'\n')
except:
- print 'Sorry - failed to write to local group cache '+treefile
- print 'Does it (or its directory) have the correct permissions?'
+ print('Sorry - failed to write to local group cache '+treefile)
+ print('Does it (or its directory) have the correct permissions?')
sys.exit(1)
# Return list of all groups on server -----------------------------
def getallgroups(server):
- print 'Getting list of all groups...'
+ print('Getting list of all groups...')
treedate='010101'
info = server.list()[1]
groups = []
- print 'Processing...'
+ print('Processing...')
if skipempty:
- print '\nIgnoring following empty groups:'
+ print('\nIgnoring following empty groups:')
for i in info:
grpname = string.split(i[0])[0]
if skipempty and string.atoi(i[1]) < string.atoi(i[2]):
- print grpname+' ',
+ print(grpname+' ', end=' ')
else:
groups.append(grpname)
- print '\n'
+ print('\n')
if skipempty:
- print '(End of empty groups)'
+ print('(End of empty groups)')
return groups
# Return list of new groups on server -----------------------------
def getnewgroups(server, treedate):
- print 'Getting list of new groups since start of '+treedate+'...',
+ print('Getting list of new groups since start of '+treedate+'...', end=' ')
info = server.newgroups(treedate,'000001')[1]
- print 'got %d.' % len(info)
- print 'Processing...',
+ print('got %d.' % len(info))
+ print('Processing...', end=' ')
groups = []
for i in info:
grpname = string.split(i)[0]
groups.append(grpname)
- print 'Done'
+ print('Done')
return groups
# Now the main program --------------------------------------------
@@ -324,15 +324,15 @@ def main():
checkopdir(pagedir);
try:
- print 'Connecting to '+newshost+'...'
+ print('Connecting to '+newshost+'...')
if sys.version[0] == '0':
s = NNTP.init(newshost)
else:
s = NNTP(newshost)
connected = 1
except (nntplib.error_temp, nntplib.error_perm) as x:
- print 'Error connecting to host:', x
- print 'I\'ll try to use just the local list.'
+ print('Error connecting to host:', x)
+ print('I\'ll try to use just the local list.')
connected = 0
# If -a is specified, read the full list of groups from server
@@ -355,9 +355,9 @@ def main():
# Read group descriptions
readdesc(descfile)
- print 'Creating pages...'
+ print('Creating pages...')
createpage(rootpage, tree, '')
- print 'Done'
+ print('Done')
if __name__ == "__main__":
main()
diff --git a/Demo/scripts/pi.py b/Demo/scripts/pi.py
index 9b24245..a360e40 100755
--- a/Demo/scripts/pi.py
+++ b/Demo/scripts/pi.py
@@ -11,16 +11,16 @@
import sys
def main():
- k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
+ k, a, b, a1, b1 = 2, 4, 1, 12, 4
while 1:
# Next approximation
- p, q, k = k*k, 2L*k+1L, k+1L
+ p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
- a, a1 = 10L*(a%b), 10L*(a1%b1)
+ a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
diff --git a/Demo/scripts/pp.py b/Demo/scripts/pp.py
index 2530ea3..486986a 100755
--- a/Demo/scripts/pp.py
+++ b/Demo/scripts/pp.py
@@ -58,7 +58,7 @@ for option, optarg in optlist:
NFLAG = 1
PFLAG = 1
else:
- print option, 'not recognized???'
+ print(option, 'not recognized???')
if not ARGS: ARGS.append('-')
diff --git a/Demo/scripts/primes.py b/Demo/scripts/primes.py
index 8762fe2..0924aab 100755
--- a/Demo/scripts/primes.py
+++ b/Demo/scripts/primes.py
@@ -12,7 +12,7 @@ def main():
primes(min, max)
def primes(min, max):
- if 2 >= min: print 2
+ if 2 >= min: print(2)
primes = [2]
i = 3
while i <= max:
@@ -20,7 +20,7 @@ def primes(min, max):
if i%p == 0 or p*p > i: break
if i%p != 0:
primes.append(i)
- if i >= min: print i
+ if i >= min: print(i)
i = i+2
if __name__ == "__main__":
diff --git a/Demo/scripts/queens.py b/Demo/scripts/queens.py
index 74756be..820c9ad 100755
--- a/Demo/scripts/queens.py
+++ b/Demo/scripts/queens.py
@@ -56,16 +56,16 @@ class Queens:
self.nfound = self.nfound + 1
if self.silent:
return
- print '+-' + '--'*self.n + '+'
+ print('+-' + '--'*self.n + '+')
for y in range(self.n-1, -1, -1):
- print '|',
+ print('|', end=' ')
for x in range(self.n):
if self.y[x] == y:
- print "Q",
+ print("Q", end=' ')
else:
- print ".",
- print '|'
- print '+-' + '--'*self.n + '+'
+ print(".", end=' ')
+ print('|')
+ print('+-' + '--'*self.n + '+')
def main():
import sys
@@ -79,7 +79,7 @@ def main():
q = Queens(n)
q.silent = silent
q.solve()
- print "Found", q.nfound, "solutions."
+ print("Found", q.nfound, "solutions.")
if __name__ == "__main__":
main()
diff --git a/Demo/scripts/script.py b/Demo/scripts/script.py
index 6eaa7ae..174c13e 100755
--- a/Demo/scripts/script.py
+++ b/Demo/scripts/script.py
@@ -17,7 +17,7 @@ def read(fd):
shell = 'sh'
filename = 'typescript'
mode = 'w'
-if os.environ.has_key('SHELL'):
+if 'SHELL' in os.environ:
shell = os.environ['SHELL']
if '-a' in sys.argv:
mode = 'a'
diff --git a/Demo/scripts/unbirthday.py b/Demo/scripts/unbirthday.py
index 94ad448..5c39092 100755
--- a/Demo/scripts/unbirthday.py
+++ b/Demo/scripts/unbirthday.py
@@ -21,69 +21,70 @@ def main():
if sys.argv[1:]:
year = int(sys.argv[1])
else:
- year = int(raw_input('In which year were you born? '))
+ year = int(input('In which year were you born? '))
if 0<=year<100:
- print "I'll assume that by", year,
+ print("I'll assume that by", year, end=' ')
year = year + 1900
- print 'you mean', year, 'and not the early Christian era'
+ print('you mean', year, 'and not the early Christian era')
elif not (1850<=year<=2002):
- print "It's hard to believe you were born in", year
+ print("It's hard to believe you were born in", year)
return
#
if sys.argv[2:]:
month = int(sys.argv[2])
else:
- month = int(raw_input('And in which month? (1-12) '))
+ month = int(input('And in which month? (1-12) '))
if not (1<=month<=12):
- print 'There is no month numbered', month
+ print('There is no month numbered', month)
return
#
if sys.argv[3:]:
day = int(sys.argv[3])
else:
- day = int(raw_input('And on what day of that month? (1-31) '))
+ day = int(input('And on what day of that month? (1-31) '))
if month == 2 and calendar.isleap(year):
maxday = 29
else:
maxday = calendar.mdays[month]
if not (1<=day<=maxday):
- print 'There are no', day, 'days in that month!'
+ print('There are no', day, 'days in that month!')
return
#
bdaytuple = (year, month, day)
bdaydate = mkdate(bdaytuple)
- print 'You were born on', format(bdaytuple)
+ print('You were born on', format(bdaytuple))
#
todaytuple = time.localtime()[:3]
todaydate = mkdate(todaytuple)
- print 'Today is', format(todaytuple)
+ print('Today is', format(todaytuple))
#
if bdaytuple > todaytuple:
- print 'You are a time traveler. Go back to the future!'
+ print('You are a time traveler. Go back to the future!')
return
#
if bdaytuple == todaytuple:
- print 'You were born today. Have a nice life!'
+ print('You were born today. Have a nice life!')
return
#
days = todaydate - bdaydate
- print 'You have lived', days, 'days'
+ print('You have lived', days, 'days')
#
age = 0
for y in range(year, todaytuple[0] + 1):
if bdaytuple < (y, month, day) <= todaytuple:
age = age + 1
#
- print 'You are', age, 'years old'
+ print('You are', age, 'years old')
#
if todaytuple[1:] == bdaytuple[1:]:
- print 'Congratulations! Today is your', nth(age), 'birthday'
- print 'Yesterday was your',
+ print('Congratulations! Today is your', nth(age), 'birthday')
+ print('Yesterday was your', end=' ')
else:
- print 'Today is your',
- print nth(days - age), 'unbirthday'
+ print('Today is your', end=' ')
+ print(nth(days - age), 'unbirthday')
-def format((year, month, day)):
+def format(xxx_todo_changeme):
+ (year, month, day) = xxx_todo_changeme
return '%d %s %d' % (day, calendar.month_name[month], year)
def nth(n):
@@ -92,10 +93,11 @@ def nth(n):
if n == 3: return '3rd'
return '%dth' % n
-def mkdate((year, month, day)):
+def mkdate(xxx_todo_changeme1):
# Januari 1st, in 0 A.D. is arbitrarily defined to be day 1,
# even though that day never actually existed and the calendar
# was different then...
+ (year, month, day) = xxx_todo_changeme1
days = year*365 # years, roughly
days = days + (year+3)/4 # plus leap years, roughly
days = days - (year+99)/100 # minus non-leap years every century
diff --git a/Demo/scripts/update.py b/Demo/scripts/update.py
index a965e4a..d49e4b3 100755
--- a/Demo/scripts/update.py
+++ b/Demo/scripts/update.py
@@ -20,22 +20,22 @@ class FileObj:
try:
self.lines = open(filename, 'r').readlines()
except IOError as msg:
- print '*** Can\'t open "%s":' % filename, msg
+ print('*** Can\'t open "%s":' % filename, msg)
self.lines = None
return
- print 'diffing', self.filename
+ print('diffing', self.filename)
def finish(self):
if not self.changed:
- print 'no changes to', self.filename
+ print('no changes to', self.filename)
return
try:
os.rename(self.filename, self.filename + '~')
fp = open(self.filename, 'w')
except (os.error, IOError) as msg:
- print '*** Can\'t rewrite "%s":' % self.filename, msg
+ print('*** Can\'t rewrite "%s":' % self.filename, msg)
return
- print 'writing', self.filename
+ print('writing', self.filename)
for line in self.lines:
fp.write(line)
fp.close()
@@ -43,32 +43,32 @@ class FileObj:
def process(self, lineno, rest):
if self.lines is None:
- print '(not processed): %s:%s:%s' % (
- self.filename, lineno, rest),
+ print('(not processed): %s:%s:%s' % (
+ self.filename, lineno, rest), end=' ')
return
i = eval(lineno) - 1
if not 0 <= i < len(self.lines):
- print '*** Line number out of range: %s:%s:%s' % (
- self.filename, lineno, rest),
+ print('*** Line number out of range: %s:%s:%s' % (
+ self.filename, lineno, rest), end=' ')
return
if self.lines[i] == rest:
- print '(no change): %s:%s:%s' % (
- self.filename, lineno, rest),
+ print('(no change): %s:%s:%s' % (
+ self.filename, lineno, rest), end=' ')
return
if not self.changed:
self.changed = 1
- print '%sc%s' % (lineno, lineno)
- print '<', self.lines[i],
- print '---'
+ print('%sc%s' % (lineno, lineno))
+ print('<', self.lines[i], end=' ')
+ print('---')
self.lines[i] = rest
- print '>', self.lines[i],
+ print('>', self.lines[i], end=' ')
def main():
if sys.argv[1:]:
try:
fp = open(sys.argv[1], 'r')
except IOError as msg:
- print 'Can\'t open "%s":' % sys.argv[1], msg
+ print('Can\'t open "%s":' % sys.argv[1], msg)
sys.exit(1)
else:
fp = sys.stdin
@@ -80,7 +80,7 @@ def main():
break
n = prog.match(line)
if n < 0:
- print 'Funny line:', line,
+ print('Funny line:', line, end=' ')
continue
filename, lineno = prog.group(1, 2)
if not curfile or filename != curfile.filename:
diff --git a/Demo/sockets/echosvr.py b/Demo/sockets/echosvr.py
index f8a9623..7de6391 100755
--- a/Demo/sockets/echosvr.py
+++ b/Demo/sockets/echosvr.py
@@ -21,7 +21,7 @@ def main():
s.bind(('', port))
s.listen(1)
conn, (remotehost, remoteport) = s.accept()
- print 'connected by', remotehost, remoteport
+ print('connected by', remotehost, remoteport)
while 1:
data = conn.recv(BUFSIZE)
if not data:
diff --git a/Demo/sockets/ftp.py b/Demo/sockets/ftp.py
index eed45be..9f9f1dc 100755
--- a/Demo/sockets/ftp.py
+++ b/Demo/sockets/ftp.py
@@ -107,13 +107,13 @@ def sendportcmd(s, f, port):
def getreply(f):
line = f.readline()
if not line: return 'EOF'
- print line,
+ print(line, end=' ')
code = line[:3]
if line[3:4] == '-':
while 1:
line = f.readline()
if not line: break # Really an error
- print line,
+ print(line, end=' ')
if line[:3] == code and line[3:4] != '-': break
return code
@@ -121,14 +121,14 @@ def getreply(f):
# Get the data from the data connection.
#
def getdata(r):
- print '(accepting data connection)'
+ print('(accepting data connection)')
conn, host = r.accept()
- print '(data connection accepted)'
+ print('(data connection accepted)')
while 1:
data = conn.recv(BUFSIZE)
if not data: break
sys.stdout.write(data)
- print '(end of data connection)'
+ print('(end of data connection)')
def raw_input(prompt):
sys.stdout.write(prompt)
@@ -140,7 +140,7 @@ def raw_input(prompt):
def getcommand():
try:
while 1:
- line = raw_input('ftp.py> ')
+ line = input('ftp.py> ')
if line: return line
except EOFError:
return ''
diff --git a/Demo/sockets/gopher.py b/Demo/sockets/gopher.py
index 0635ac1..c287319 100755
--- a/Demo/sockets/gopher.py
+++ b/Demo/sockets/gopher.py
@@ -60,7 +60,7 @@ def get_menu(selector, host, port):
while 1:
line = f.readline()
if not line:
- print '(Unexpected EOF from server)'
+ print('(Unexpected EOF from server)')
break
if line[-2:] == CRLF:
line = line[:-2]
@@ -69,15 +69,15 @@ def get_menu(selector, host, port):
if line == '.':
break
if not line:
- print '(Empty line from server)'
+ print('(Empty line from server)')
continue
typechar = line[0]
parts = line[1:].split(TAB)
if len(parts) < 4:
- print '(Bad line from server: %r)' % (line,)
+ print('(Bad line from server: %r)' % (line,))
continue
if len(parts) > 4:
- print '(Extra info from server: %r)' % (parts[4:],)
+ print('(Extra info from server: %r)' % (parts[4:],))
parts.insert(0, typechar)
list.append(parts)
f.close()
@@ -95,7 +95,7 @@ def get_alt_textfile(selector, host, port, func):
while 1:
line = f.readline()
if not line:
- print '(Unexpected EOF from server)'
+ print('(Unexpected EOF from server)')
break
if line[-2:] == CRLF:
line = line[:-2]
@@ -139,61 +139,61 @@ def browser(*args):
if n > 2 and args[2]:
port = args[2]
if n > 3:
- raise RuntimeError, 'too many args'
+ raise RuntimeError('too many args')
try:
browse_menu(selector, host, port)
except socket.error as msg:
- print 'Socket error:', msg
+ print('Socket error:', msg)
sys.exit(1)
except KeyboardInterrupt:
- print '\n[Goodbye]'
+ print('\n[Goodbye]')
# Browse a menu
def browse_menu(selector, host, port):
list = get_menu(selector, host, port)
while 1:
- print '----- MENU -----'
- print 'Selector:', repr(selector)
- print 'Host:', host, ' Port:', port
- print
+ print('----- MENU -----')
+ print('Selector:', repr(selector))
+ print('Host:', host, ' Port:', port)
+ print()
for i in range(len(list)):
item = list[i]
typechar, description = item[0], item[1]
- print repr(i+1).rjust(3) + ':', description,
- if typename.has_key(typechar):
- print typename[typechar]
+ print(repr(i+1).rjust(3) + ':', description, end=' ')
+ if typechar in typename:
+ print(typename[typechar])
else:
- print '<TYPE=' + repr(typechar) + '>'
- print
+ print('<TYPE=' + repr(typechar) + '>')
+ print()
while 1:
try:
- str = raw_input('Choice [CR == up a level]: ')
+ str = input('Choice [CR == up a level]: ')
except EOFError:
- print
+ print()
return
if not str:
return
try:
choice = int(str)
except ValueError:
- print 'Choice must be a number; try again:'
+ print('Choice must be a number; try again:')
continue
if not 0 < choice <= len(list):
- print 'Choice out of range; try again:'
+ print('Choice out of range; try again:')
continue
break
item = list[choice-1]
typechar = item[0]
[i_selector, i_host, i_port] = item[2:5]
- if typebrowser.has_key(typechar):
+ if typechar in typebrowser:
browserfunc = typebrowser[typechar]
try:
browserfunc(i_selector, i_host, i_port)
except (IOError, socket.error):
t, v, tb = sys.exc_info()
- print '***', t, ':', v
+ print('***', t, ':', v)
else:
- print 'Unsupported object type'
+ print('Unsupported object type')
# Browse a text file
def browse_textfile(selector, host, port):
@@ -203,7 +203,7 @@ def browse_textfile(selector, host, port):
x = SaveLines(p)
get_alt_textfile(selector, host, port, x.writeln)
except IOError as msg:
- print 'IOError:', msg
+ print('IOError:', msg)
if x:
x.close()
f = open_savefile()
@@ -212,9 +212,9 @@ def browse_textfile(selector, host, port):
x = SaveLines(f)
try:
get_alt_textfile(selector, host, port, x.writeln)
- print 'Done.'
+ print('Done.')
except IOError as msg:
- print 'IOError:', msg
+ print('IOError:', msg)
x.close()
def raw_input(prompt):
@@ -225,32 +225,32 @@ def raw_input(prompt):
# Browse a search index
def browse_search(selector, host, port):
while 1:
- print '----- SEARCH -----'
- print 'Selector:', repr(selector)
- print 'Host:', host, ' Port:', port
- print
+ print('----- SEARCH -----')
+ print('Selector:', repr(selector))
+ print('Host:', host, ' Port:', port)
+ print()
try:
- query = raw_input('Query [CR == up a level]: ')
+ query = input('Query [CR == up a level]: ')
except EOFError:
- print
+ print()
break
query = query.strip()
if not query:
break
if '\t' in query:
- print 'Sorry, queries cannot contain tabs'
+ print('Sorry, queries cannot contain tabs')
continue
browse_menu(selector + TAB + query, host, port)
# "Browse" telnet-based information, i.e. open a telnet session
def browse_telnet(selector, host, port):
if selector:
- print 'Log in as', repr(selector)
+ print('Log in as', repr(selector))
if type(port) != type(''):
port = repr(port)
sts = os.system('set -x; exec telnet ' + host + ' ' + port)
if sts:
- print 'Exit status:', sts
+ print('Exit status:', sts)
# "Browse" a binary file, i.e. save it to a file
def browse_binary(selector, host, port):
@@ -280,7 +280,7 @@ class SaveLines:
def close(self):
sts = self.f.close()
if sts:
- print 'Exit status:', sts
+ print('Exit status:', sts)
# Class used to save data while showing progress
class SaveWithProgress:
@@ -291,18 +291,18 @@ class SaveWithProgress:
sys.stdout.flush()
self.f.write(data)
def close(self):
- print
+ print()
sts = self.f.close()
if sts:
- print 'Exit status:', sts
+ print('Exit status:', sts)
# Ask for and open a save file, or return None if not to save
def open_savefile():
try:
- savefile = raw_input( \
+ savefile = input( \
'Save as file [CR == don\'t save; |pipeline or ~user/... OK]: ')
except EOFError:
- print
+ print()
return None
savefile = savefile.strip()
if not savefile:
@@ -312,24 +312,24 @@ def open_savefile():
try:
p = os.popen(cmd, 'w')
except IOError as msg:
- print repr(cmd), ':', msg
+ print(repr(cmd), ':', msg)
return None
- print 'Piping through', repr(cmd), '...'
+ print('Piping through', repr(cmd), '...')
return p
if savefile[0] == '~':
savefile = os.path.expanduser(savefile)
try:
f = open(savefile, 'w')
except IOError as msg:
- print repr(savefile), ':', msg
+ print(repr(savefile), ':', msg)
return None
- print 'Saving to', repr(savefile), '...'
+ print('Saving to', repr(savefile), '...')
return f
# Test program
def test():
if sys.argv[4:]:
- print 'usage: gopher [ [selector] host [port] ]'
+ print('usage: gopher [ [selector] host [port] ]')
sys.exit(2)
elif sys.argv[3:]:
browser(sys.argv[1], sys.argv[2], sys.argv[3])
diff --git a/Demo/sockets/mcast.py b/Demo/sockets/mcast.py
index 1abd305..c1902d6 100755
--- a/Demo/sockets/mcast.py
+++ b/Demo/sockets/mcast.py
@@ -52,7 +52,7 @@ def receiver():
while 1:
data, sender = s.recvfrom(1500)
while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
- print sender, ':', repr(data)
+ print(sender, ':', repr(data))
# Open a UDP socket, bind it to a port and select a multicast group
@@ -76,7 +76,7 @@ def openmcastsock(group, port):
group = gethostbyname(group)
#
# Construct binary group address
- bytes = map(int, string.split(group, "."))
+ bytes = list(map(int, string.split(group, ".")))
grpaddr = 0
for byte in bytes: grpaddr = (grpaddr << 8) | byte
#
diff --git a/Demo/sockets/rpython.py b/Demo/sockets/rpython.py
index 8333d39..b654dc2 100755
--- a/Demo/sockets/rpython.py
+++ b/Demo/sockets/rpython.py
@@ -12,7 +12,7 @@ BUFSIZE = 1024
def main():
if len(sys.argv) < 3:
- print "usage: rpython host command"
+ print("usage: rpython host command")
sys.exit(2)
host = sys.argv[1]
port = PORT
@@ -30,6 +30,6 @@ def main():
data = s.recv(BUFSIZE)
if not data: break
reply = reply + data
- print reply,
+ print(reply, end=' ')
main()
diff --git a/Demo/sockets/rpythond.py b/Demo/sockets/rpythond.py
index 34de982..d745cc7 100755
--- a/Demo/sockets/rpythond.py
+++ b/Demo/sockets/rpythond.py
@@ -7,7 +7,7 @@
import sys
from socket import *
-import StringIO
+import io
import traceback
PORT = 4127
@@ -23,7 +23,7 @@ def main():
s.listen(1)
while 1:
conn, (remotehost, remoteport) = s.accept()
- print 'connected by', remotehost, remoteport
+ print('connected by', remotehost, remoteport)
request = ''
while 1:
data = conn.recv(BUFSIZE)
@@ -37,12 +37,12 @@ def main():
def execute(request):
stdout = sys.stdout
stderr = sys.stderr
- sys.stdout = sys.stderr = fakefile = StringIO.StringIO()
+ sys.stdout = sys.stderr = fakefile = io.StringIO()
try:
try:
exec(request, {}, {})
except:
- print
+ print()
traceback.print_exc(100)
finally:
sys.stderr = stderr
diff --git a/Demo/sockets/telnet.py b/Demo/sockets/telnet.py
index 6bc9bcc..038036ff 100755
--- a/Demo/sockets/telnet.py
+++ b/Demo/sockets/telnet.py
@@ -77,7 +77,7 @@ def main():
cleandata = ''
for c in data:
if opt:
- print ord(c)
+ print(ord(c))
s.send(opt + c)
opt = ''
elif iac:
@@ -85,18 +85,18 @@ def main():
if c == IAC:
cleandata = cleandata + c
elif c in (DO, DONT):
- if c == DO: print '(DO)',
- else: print '(DONT)',
+ if c == DO: print('(DO)', end=' ')
+ else: print('(DONT)', end=' ')
opt = IAC + WONT
elif c in (WILL, WONT):
- if c == WILL: print '(WILL)',
- else: print '(WONT)',
+ if c == WILL: print('(WILL)', end=' ')
+ else: print('(WONT)', end=' ')
opt = IAC + DONT
else:
- print '(command)', ord(c)
+ print('(command)', ord(c))
elif c == IAC:
iac = 1
- print '(IAC)',
+ print('(IAC)', end=' ')
else:
cleandata = cleandata + c
sys.stdout.write(cleandata)
diff --git a/Demo/sockets/throughput.py b/Demo/sockets/throughput.py
index b8df1f3..64244aa 100755
--- a/Demo/sockets/throughput.py
+++ b/Demo/sockets/throughput.py
@@ -33,8 +33,8 @@ def main():
def usage():
sys.stdout = sys.stderr
- print 'Usage: (on host_A) throughput -s [port]'
- print 'and then: (on host_B) throughput -c count host_A [port]'
+ print('Usage: (on host_A) throughput -s [port]')
+ print('and then: (on host_B) throughput -c count host_A [port]')
sys.exit(2)
@@ -46,7 +46,7 @@ def server():
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', port))
s.listen(1)
- print 'Server ready...'
+ print('Server ready...')
while 1:
conn, (host, remoteport) = s.accept()
while 1:
@@ -56,7 +56,7 @@ def server():
del data
conn.send('OK\n')
conn.close()
- print 'Done with', host, 'port', remoteport
+ print('Done with', host, 'port', remoteport)
def client():
@@ -82,12 +82,12 @@ def client():
t4 = time.time()
data = s.recv(BUFSIZE)
t5 = time.time()
- print data
- print 'Raw timers:', t1, t2, t3, t4, t5
- print 'Intervals:', t2-t1, t3-t2, t4-t3, t5-t4
- print 'Total:', t5-t1
- print 'Throughput:', round((BUFSIZE*count*0.001) / (t5-t1), 3),
- print 'K/sec.'
+ print(data)
+ print('Raw timers:', t1, t2, t3, t4, t5)
+ print('Intervals:', t2-t1, t3-t2, t4-t3, t5-t4)
+ print('Total:', t5-t1)
+ print('Throughput:', round((BUFSIZE*count*0.001) / (t5-t1), 3), end=' ')
+ print('K/sec.')
main()
diff --git a/Demo/sockets/udpecho.py b/Demo/sockets/udpecho.py
index 5181c82..8a6bd21 100755
--- a/Demo/sockets/udpecho.py
+++ b/Demo/sockets/udpecho.py
@@ -23,8 +23,8 @@ def main():
def usage():
sys.stdout = sys.stderr
- print 'Usage: udpecho -s [port] (server)'
- print 'or: udpecho -c host [port] <file (client)'
+ print('Usage: udpecho -s [port] (server)')
+ print('or: udpecho -c host [port] <file (client)')
sys.exit(2)
def server():
@@ -34,10 +34,10 @@ def server():
port = ECHO_PORT
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', port))
- print 'udp echo server ready'
+ print('udp echo server ready')
while 1:
data, addr = s.recvfrom(BUFSIZE)
- print 'server received %r from %r' % (data, addr)
+ print('server received %r from %r' % (data, addr))
s.sendto(data, addr)
def client():
@@ -51,13 +51,13 @@ def client():
addr = host, port
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', 0))
- print 'udp echo client ready, reading stdin'
+ print('udp echo client ready, reading stdin')
while 1:
line = sys.stdin.readline()
if not line:
break
s.sendto(line, addr)
data, fromaddr = s.recvfrom(BUFSIZE)
- print 'client received %r from %r' % (data, fromaddr)
+ print('client received %r from %r' % (data, fromaddr))
main()
diff --git a/Demo/sockets/unixclient.py b/Demo/sockets/unixclient.py
index fdbcc7a..cdccb84 100644
--- a/Demo/sockets/unixclient.py
+++ b/Demo/sockets/unixclient.py
@@ -9,4 +9,4 @@ s.connect(FILE)
s.send('Hello, world')
data = s.recv(1024)
s.close()
-print 'Received', repr(data)
+print('Received', repr(data))
diff --git a/Demo/sockets/unixserver.py b/Demo/sockets/unixserver.py
index b73f857..c3c9c4f 100644
--- a/Demo/sockets/unixserver.py
+++ b/Demo/sockets/unixserver.py
@@ -8,7 +8,7 @@ FILE = 'unix-socket'
s = socket(AF_UNIX, SOCK_STREAM)
s.bind(FILE)
-print 'Sock name is: ['+s.getsockname()+']'
+print('Sock name is: ['+s.getsockname()+']')
# Wait for a connection
s.listen(1)
diff --git a/Demo/threads/Coroutine.py b/Demo/threads/Coroutine.py
index 10fa303..6bf788b 100644
--- a/Demo/threads/Coroutine.py
+++ b/Demo/threads/Coroutine.py
@@ -78,7 +78,7 @@ class _CoEvent:
if self.f is None:
return 'main coroutine'
else:
- return 'coroutine for func ' + self.f.func_name
+ return 'coroutine for func ' + self.f.__name__
def __hash__(self):
return id(self)
@@ -125,9 +125,9 @@ class Coroutine:
def kill(self):
if self.killed:
- raise TypeError, 'kill() called on dead coroutines'
+ raise TypeError('kill() called on dead coroutines')
self.killed = 1
- for coroutine in self.invokedby.keys():
+ for coroutine in list(self.invokedby.keys()):
coroutine.resume()
def back(self, data=None):
@@ -137,10 +137,10 @@ class Coroutine:
return self.tran( self.main, data )
def tran(self, target, data=None):
- if not self.invokedby.has_key(target):
- raise TypeError, '.tran target %r is not an active coroutine' % (target,)
+ if target not in self.invokedby:
+ raise TypeError('.tran target %r is not an active coroutine' % (target,))
if self.killed:
- raise TypeError, '.tran target %r is killed' % (target,)
+ raise TypeError('.tran target %r is killed' % (target,))
self.value = data
me = self.active
self.invokedby[target] = me
@@ -152,7 +152,7 @@ class Coroutine:
if self.main is not me:
raise Killed
if self.terminated_by is not None:
- raise EarlyExit, '%r terminated early' % (self.terminated_by,)
+ raise EarlyExit('%r terminated early' % (self.terminated_by,))
return self.value
diff --git a/Demo/threads/Generator.py b/Demo/threads/Generator.py
index 63bed9b..0cc1bda 100644
--- a/Demo/threads/Generator.py
+++ b/Demo/threads/Generator.py
@@ -32,7 +32,7 @@ class Generator:
# Called by producer for each value; raise Killed if no more needed
def put(self, value):
if self.killed:
- raise TypeError, 'put() called on killed generator'
+ raise TypeError('put() called on killed generator')
self.value = value
self.getlock.release() # Resume consumer thread
self.putlock.acquire() # Wait for next get() call
@@ -41,7 +41,7 @@ class Generator:
# Called by producer to get next value; raise EOFError if no more
def get(self):
if self.killed:
- raise TypeError, 'get() called on killed generator'
+ raise TypeError('get() called on killed generator')
self.putlock.release() # Resume producer thread
self.getlock.acquire() # Wait for value to appear
if self.done:
@@ -50,7 +50,7 @@ class Generator:
# Called by consumer if no more values wanted
def kill(self):
if self.killed:
- raise TypeError, 'kill() called on killed generator'
+ raise TypeError('kill() called on killed generator')
self.killed = 1
self.putlock.release()
# Clone constructor
@@ -58,27 +58,27 @@ class Generator:
return Generator(self.func, self.args)
def pi(g):
- k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
+ k, a, b, a1, b1 = 2, 4, 1, 12, 4
while 1:
# Next approximation
- p, q, k = k*k, 2L*k+1L, k+1L
+ p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
g.put(int(d))
- a, a1 = 10L*(a%b), 10L*(a1%b1)
+ a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
def test():
g = Generator(pi, ())
g.kill()
g = Generator(pi, ())
- for i in range(10): print g.get(),
- print
+ for i in range(10): print(g.get(), end=' ')
+ print()
h = g.clone()
g.kill()
while 1:
- print h.get(),
+ print(h.get(), end=' ')
test()
diff --git a/Demo/threads/fcmp.py b/Demo/threads/fcmp.py
index 27af76d..bc2e3ed 100644
--- a/Demo/threads/fcmp.py
+++ b/Demo/threads/fcmp.py
@@ -16,10 +16,10 @@ def printinorder(list):
f = co.create(fringe, co, list)
try:
while 1:
- print co.tran(f),
+ print(co.tran(f), end=' ')
except EarlyExit:
pass
- print
+ print()
printinorder([1,2,3]) # 1 2 3
printinorder([[[[1,[2]]],3]]) # ditto
@@ -49,16 +49,16 @@ def fcmp(l1, l2):
co1.kill(); co2.kill()
return cmp(v1,v2)
-print fcmp(range(7), x) # 0; fringes are equal
-print fcmp(range(6), x) # -1; 1st list ends early
-print fcmp(x, range(6)) # 1; 2nd list ends early
-print fcmp(range(8), x) # 1; 2nd list ends early
-print fcmp(x, range(8)) # -1; 1st list ends early
-print fcmp([1,[[2],8]],
- [[[1],2],8]) # 0
-print fcmp([1,[[3],8]],
- [[[1],2],8]) # 1
-print fcmp([1,[[2],8]],
- [[[1],2],9]) # -1
+print(fcmp(range(7), x)) # 0; fringes are equal
+print(fcmp(range(6), x)) # -1; 1st list ends early
+print(fcmp(x, range(6))) # 1; 2nd list ends early
+print(fcmp(range(8), x)) # 1; 2nd list ends early
+print(fcmp(x, range(8))) # -1; 1st list ends early
+print(fcmp([1,[[2],8]],
+ [[[1],2],8])) # 0
+print(fcmp([1,[[3],8]],
+ [[[1],2],8])) # 1
+print(fcmp([1,[[2],8]],
+ [[[1],2],9])) # -1
# end of example
diff --git a/Demo/threads/find.py b/Demo/threads/find.py
index 68ca155..57fe81e 100644
--- a/Demo/threads/find.py
+++ b/Demo/threads/find.py
@@ -123,7 +123,7 @@ def main():
def selector(dir, name, fullname, stat):
# Look for world writable files that are not symlinks
- return (stat[ST_MODE] & 0002) != 0 and not S_ISLNK(stat[ST_MODE])
+ return (stat[ST_MODE] & 0o002) != 0 and not S_ISLNK(stat[ST_MODE])
# The find procedure -- calls wq.addwork() for subdirectories
@@ -132,7 +132,7 @@ def find(dir, pred, wq):
try:
names = os.listdir(dir)
except os.error as msg:
- print repr(dir), ':', msg
+ print(repr(dir), ':', msg)
return
for name in names:
if name not in (os.curdir, os.pardir):
@@ -140,10 +140,10 @@ def find(dir, pred, wq):
try:
stat = os.lstat(fullname)
except os.error as msg:
- print repr(fullname), ':', msg
+ print(repr(fullname), ':', msg)
continue
if pred(dir, name, fullname, stat):
- print fullname
+ print(fullname)
if S_ISDIR(stat[ST_MODE]):
if not os.path.ismount(fullname):
wq.addwork(find, (fullname, pred, wq))
diff --git a/Demo/threads/squasher.py b/Demo/threads/squasher.py
index 0d59cb8..35b1b1d 100644
--- a/Demo/threads/squasher.py
+++ b/Demo/threads/squasher.py
@@ -89,7 +89,7 @@ def assembler():
def putline():
while 1:
line = co.tran(coassembler)
- print line
+ print(line)
import string
co = Coroutine()
@@ -100,6 +100,6 @@ codisassembler = co.create(disassembler)
cosquasher = co.create(squasher)
co.tran(coputline)
-print 'done'
+print('done')
# end of example
diff --git a/Demo/threads/sync.py b/Demo/threads/sync.py
index 843767a..61e1628 100644
--- a/Demo/threads/sync.py
+++ b/Demo/threads/sync.py
@@ -280,8 +280,8 @@ class condition:
hasattr(lock, 'release'):
self.mutex = lock
else:
- raise TypeError, 'condition constructor requires ' \
- 'a lock argument'
+ raise TypeError('condition constructor requires ' \
+ 'a lock argument')
# lock used to block threads until a signal
self.checkout = thread.allocate_lock()
@@ -304,8 +304,7 @@ class condition:
def wait(self):
mutex, checkout, idlock = self.mutex, self.checkout, self.idlock
if not mutex.locked():
- raise ValueError, \
- "condition must be .acquire'd when .wait() invoked"
+ raise ValueError("condition must be .acquire'd when .wait() invoked")
idlock.acquire()
myid = self.id
@@ -336,7 +335,7 @@ class condition:
def broadcast(self, num = -1):
if num < -1:
- raise ValueError, '.broadcast called with num %r' % (num,)
+ raise ValueError('.broadcast called with num %r' % (num,))
if num == 0:
return
self.idlock.acquire()
@@ -402,7 +401,7 @@ class event:
class semaphore:
def __init__(self, count=1):
if count <= 0:
- raise ValueError, 'semaphore count %d; must be >= 1' % count
+ raise ValueError('semaphore count %d; must be >= 1' % count)
self.count = count
self.maxcount = count
self.nonzero = condition()
@@ -417,8 +416,8 @@ class semaphore:
def v(self):
self.nonzero.acquire()
if self.count == self.maxcount:
- raise ValueError, '.v() tried to raise semaphore count above ' \
- 'initial value %r' % self.maxcount
+ raise ValueError('.v() tried to raise semaphore count above ' \
+ 'initial value %r' % self.maxcount)
self.count = self.count + 1
self.nonzero.signal()
self.nonzero.release()
@@ -445,8 +444,7 @@ class mrsw:
def read_out(self):
self.rwOK.acquire()
if self.nr <= 0:
- raise ValueError, \
- '.read_out() invoked without an active reader'
+ raise ValueError('.read_out() invoked without an active reader')
self.nr = self.nr - 1
if self.nr == 0:
self.writeOK.signal()
@@ -463,8 +461,7 @@ class mrsw:
def write_out(self):
self.rwOK.acquire()
if not self.writing:
- raise ValueError, \
- '.write_out() invoked without an active writer'
+ raise ValueError('.write_out() invoked without an active writer')
self.writing = 0
self.nw = self.nw - 1
if self.nw:
@@ -476,8 +473,7 @@ class mrsw:
def write_to_read(self):
self.rwOK.acquire()
if not self.writing:
- raise ValueError, \
- '.write_to_read() invoked without an active writer'
+ raise ValueError('.write_to_read() invoked without an active writer')
self.writing = 0
self.nw = self.nw - 1
self.nr = self.nr + 1
@@ -496,13 +492,13 @@ def _new_thread(func, *args):
global TID
tid.acquire(); id = TID = TID+1; tid.release()
io.acquire(); alive.append(id); \
- print 'starting thread', id, '--', len(alive), 'alive'; \
+ print('starting thread', id, '--', len(alive), 'alive'); \
io.release()
thread.start_new_thread( func, (id,) + args )
def _qsort(tid, a, l, r, finished):
# sort a[l:r]; post finished when done
- io.acquire(); print 'thread', tid, 'qsort', l, r; io.release()
+ io.acquire(); print('thread', tid, 'qsort', l, r); io.release()
if r-l > 1:
pivot = a[l]
j = l+1 # make a[l:j] <= pivot, and a[j:r] > pivot
@@ -519,44 +515,44 @@ def _qsort(tid, a, l, r, finished):
l_subarray_sorted.wait()
r_subarray_sorted.wait()
- io.acquire(); print 'thread', tid, 'qsort done'; \
+ io.acquire(); print('thread', tid, 'qsort done'); \
alive.remove(tid); io.release()
finished.post()
def _randarray(tid, a, finished):
- io.acquire(); print 'thread', tid, 'randomizing array'; \
+ io.acquire(); print('thread', tid, 'randomizing array'); \
io.release()
for i in range(1, len(a)):
wh.acquire(); j = randint(0,i); wh.release()
a[i], a[j] = a[j], a[i]
- io.acquire(); print 'thread', tid, 'randomizing done'; \
+ io.acquire(); print('thread', tid, 'randomizing done'); \
alive.remove(tid); io.release()
finished.post()
def _check_sort(a):
if a != range(len(a)):
- raise ValueError, ('a not sorted', a)
+ raise ValueError('a not sorted', a)
def _run_one_sort(tid, a, bar, done):
# randomize a, and quicksort it
# for variety, all the threads running this enter a barrier
# at the end, and post `done' after the barrier exits
- io.acquire(); print 'thread', tid, 'randomizing', a; \
+ io.acquire(); print('thread', tid, 'randomizing', a); \
io.release()
finished = event()
_new_thread(_randarray, a, finished)
finished.wait()
- io.acquire(); print 'thread', tid, 'sorting', a; io.release()
+ io.acquire(); print('thread', tid, 'sorting', a); io.release()
finished.clear()
_new_thread(_qsort, a, 0, len(a), finished)
finished.wait()
_check_sort(a)
- io.acquire(); print 'thread', tid, 'entering barrier'; \
+ io.acquire(); print('thread', tid, 'entering barrier'); \
io.release()
bar.enter()
- io.acquire(); print 'thread', tid, 'leaving barrier'; \
+ io.acquire(); print('thread', tid, 'leaving barrier'); \
io.release()
io.acquire(); alive.remove(tid); io.release()
bar.enter() # make sure they've all removed themselves from alive
@@ -586,16 +582,16 @@ def test():
_new_thread(_run_one_sort, arrays[i], bar, finished)
finished.wait()
- print 'all threads done, and checking results ...'
+ print('all threads done, and checking results ...')
if alive:
- raise ValueError, ('threads still alive at end', alive)
+ raise ValueError('threads still alive at end', alive)
for i in range(NSORTS):
a = arrays[i]
if len(a) != (i+1)*10:
- raise ValueError, ('length of array', i, 'screwed up')
+ raise ValueError('length of array', i, 'screwed up')
_check_sort(a)
- print 'test passed!', TID, 'threads created in all'
+ print('test passed!', TID, 'threads created in all')
if __name__ == '__main__':
test()
diff --git a/Demo/threads/telnet.py b/Demo/threads/telnet.py
index 09f3bd9..7366341 100644
--- a/Demo/threads/telnet.py
+++ b/Demo/threads/telnet.py
@@ -76,7 +76,7 @@ def parent(s):
cleandata = ''
for c in data:
if opt:
- print ord(c)
+ print(ord(c))
## print '(replying: %r)' % (opt+c,)
s.send(opt + c)
opt = ''
@@ -85,18 +85,18 @@ def parent(s):
if c == IAC:
cleandata = cleandata + c
elif c in (DO, DONT):
- if c == DO: print '(DO)',
- else: print '(DONT)',
+ if c == DO: print('(DO)', end=' ')
+ else: print('(DONT)', end=' ')
opt = IAC + WONT
elif c in (WILL, WONT):
- if c == WILL: print '(WILL)',
- else: print '(WONT)',
+ if c == WILL: print('(WILL)', end=' ')
+ else: print('(WONT)', end=' ')
opt = IAC + DONT
else:
- print '(command)', ord(c)
+ print('(command)', ord(c))
elif c == IAC:
iac = 1
- print '(IAC)',
+ print('(IAC)', end=' ')
else:
cleandata = cleandata + c
sys.stdout.write(cleandata)
diff --git a/Demo/tix/samples/OptMenu.py b/Demo/tix/samples/OptMenu.py
index 1d39420..2cf625a 100755
--- a/Demo/tix/samples/OptMenu.py
+++ b/Demo/tix/samples/OptMenu.py
@@ -40,7 +40,7 @@ def RunSample(w):
# global variables "demo_opt_from" and "demo_opt_to". Otherwise
# the OptionMenu widget will complain about "unknown options"!
#
- for opt in options.keys():
+ for opt in list(options.keys()):
from_file.add_command(opt, label=options[opt])
to_file.add_command(opt, label=options[opt])
diff --git a/Demo/tix/tixwidgets.py b/Demo/tix/tixwidgets.py
index bf7102a..49d1e7f 100644
--- a/Demo/tix/tixwidgets.py
+++ b/Demo/tix/tixwidgets.py
@@ -166,7 +166,7 @@ class Demo:
try: tkMessageBox.showerror ('Error', text)
except: pass
self.exit = 1
- raise SystemExit, 1
+ raise SystemExit(1)
def destroy (self):
self.root.destroy()
diff --git a/Demo/tkinter/guido/AttrDialog.py b/Demo/tkinter/guido/AttrDialog.py
index d8b2571..98bdd14 100755
--- a/Demo/tkinter/guido/AttrDialog.py
+++ b/Demo/tkinter/guido/AttrDialog.py
@@ -112,7 +112,7 @@ class Dialog:
def addchoices(self):
self.choices = {}
list = []
- for k, dc in self.options.items():
+ for k, dc in list(self.options.items()):
list.append((k, dc))
list.sort()
for k, (d, c) in list:
@@ -157,7 +157,7 @@ class PackDialog(Dialog):
try:
self.dialog.widget.pack(**{self.option: self.current})
except TclError as msg:
- print msg
+ print(msg)
self.refresh()
class booleanoption(packoption, BooleanOption): pass
@@ -213,7 +213,7 @@ class RemotePackDialog(PackDialog):
'info',
self.widget))
except TclError as msg:
- print msg
+ print(msg)
return
dict = {}
for i in range(0, len(words), 2):
@@ -240,7 +240,7 @@ class RemotePackDialog(PackDialog):
self.dialog.master.tk.merge(
self.current))
except TclError as msg:
- print msg
+ print(msg)
self.refresh()
class booleanoption(remotepackoption, BooleanOption): pass
@@ -256,11 +256,11 @@ class WidgetDialog(Dialog):
Dialog.__init__(self, widget)
def fixclasses(self):
- if self.addclasses.has_key(self.klass):
+ if self.klass in self.addclasses:
classes = {}
for c in (self.classes,
self.addclasses[self.klass]):
- for k in c.keys():
+ for k in list(c.keys()):
classes[k] = c[k]
self.classes = classes
@@ -273,7 +273,7 @@ class WidgetDialog(Dialog):
def update(self):
self.current = {}
self.options = {}
- for k, v in self.configuration.items():
+ for k, v in list(self.configuration.items()):
if len(v) > 4:
self.current[k] = v[4]
self.options[k] = v[3], v[2] # default, klass
@@ -286,7 +286,7 @@ class WidgetDialog(Dialog):
try:
self.dialog.widget[self.option] = self.current
except TclError as msg:
- print msg
+ print(msg)
self.refresh()
class booleanoption(widgetoption, BooleanOption): pass
@@ -375,7 +375,7 @@ class RemoteWidgetDialog(WidgetDialog):
self.widget,
'config'))
except TclError as msg:
- print msg
+ print(msg)
return
dict = {}
for item in items:
@@ -399,7 +399,7 @@ class RemoteWidgetDialog(WidgetDialog):
'-'+self.option,
self.current)
except TclError as msg:
- print msg
+ print(msg)
self.refresh()
class booleanoption(remotewidgetoption, BooleanOption): pass
@@ -446,6 +446,6 @@ def opendialogs(e):
try:
RemotePackDialog(list, list.app, widget)
except TclError as msg:
- print msg
+ print(msg)
test()
diff --git a/Demo/tkinter/guido/ManPage.py b/Demo/tkinter/guido/ManPage.py
index b189b64..1266f1c 100755
--- a/Demo/tkinter/guido/ManPage.py
+++ b/Demo/tkinter/guido/ManPage.py
@@ -75,7 +75,7 @@ class EditableManPage(ScrolledText):
# Initialize parsing from a particular file -- must not be busy
def _startparser(self, fp):
if self.busy():
- raise RuntimeError, 'startparser: still busy'
+ raise RuntimeError('startparser: still busy')
fp.fileno() # Test for file-ness
self.fp = fp
self.lineno = 0
@@ -90,7 +90,7 @@ class EditableManPage(ScrolledText):
# End parsing -- must be busy, need not be at EOF
def _endparser(self):
if not self.busy():
- raise RuntimeError, 'endparser: not busy'
+ raise RuntimeError('endparser: not busy')
if self.buffer:
self._parseline('')
try:
diff --git a/Demo/tkinter/guido/ShellWindow.py b/Demo/tkinter/guido/ShellWindow.py
index 104e06d..d7e0a0e 100755
--- a/Demo/tkinter/guido/ShellWindow.py
+++ b/Demo/tkinter/guido/ShellWindow.py
@@ -37,7 +37,7 @@ class ShellWindow(ScrolledText):
if not data:
self.tk.deletefilehandler(file)
pid, sts = os.waitpid(self.pid, 0)
- print 'pid', pid, 'status', sts
+ print('pid', pid, 'status', sts)
self.pid = None
detail = sts>>8
cause = sts & 0xff
diff --git a/Demo/tkinter/guido/dialog.py b/Demo/tkinter/guido/dialog.py
index 50d84b9..426eca4 100755
--- a/Demo/tkinter/guido/dialog.py
+++ b/Demo/tkinter/guido/dialog.py
@@ -81,7 +81,7 @@ def go():
'',
-1,
'OK')
- print 'pressed button', i
+ print('pressed button', i)
i = dialog(mainWidget,
'File Modified',
'File "tcl.h" has been modified since '
@@ -92,7 +92,7 @@ def go():
'Save File',
'Discard Changes',
'Return To Editor')
- print 'pressed button', i
+ print('pressed button', i)
def test():
import sys
diff --git a/Demo/tkinter/guido/mbox.py b/Demo/tkinter/guido/mbox.py
index 47c38b9..88b0b89 100755
--- a/Demo/tkinter/guido/mbox.py
+++ b/Demo/tkinter/guido/mbox.py
@@ -28,7 +28,7 @@ def main():
try:
opts, args = getopt.getopt(sys.argv[1:], '')
except getopt.error as msg:
- print msg
+ print(msg)
sys.exit(2)
for arg in args:
if arg[:1] == '+':
@@ -278,8 +278,6 @@ def rescan():
scanbox.insert('end', line)
def scanfolder(folder = 'inbox', sequence = 'all'):
- return map(
- lambda line: line[:-1],
- os.popen('scan +%s %s' % (folder, sequence), 'r').readlines())
+ return [line[:-1] for line in os.popen('scan +%s %s' % (folder, sequence), 'r').readlines()]
main()
diff --git a/Demo/tkinter/guido/rmt.py b/Demo/tkinter/guido/rmt.py
index 440650c..c177c72 100755
--- a/Demo/tkinter/guido/rmt.py
+++ b/Demo/tkinter/guido/rmt.py
@@ -134,7 +134,7 @@ def fillAppsMenu():
file_m_apps.add('command')
file_m_apps.delete(0, 'last')
names = root.winfo_interps()
- names = map(None, names) # convert tuple to list
+ names = list(names) # convert tuple to list
names.sort()
for name in names:
try:
diff --git a/Demo/tkinter/guido/solitaire.py b/Demo/tkinter/guido/solitaire.py
index 50a8b26..68dc284 100755
--- a/Demo/tkinter/guido/solitaire.py
+++ b/Demo/tkinter/guido/solitaire.py
@@ -80,7 +80,7 @@ for s in (HEARTS, DIAMONDS):
for s in (CLUBS, SPADES):
COLOR[s] = BLACK
-ALLSUITS = COLOR.keys()
+ALLSUITS = list(COLOR.keys())
NSUITS = len(ALLSUITS)
@@ -99,7 +99,7 @@ NVALUES = len(ALLVALUES)
# dummy element at index 0 so it can be indexed directly with the card
# value.
-VALNAMES = ["", "A"] + map(str, range(2, 11)) + ["J", "Q", "K"]
+VALNAMES = ["", "A"] + list(map(str, range(2, 11))) + ["J", "Q", "K"]
# Solitaire constants. The only one I can think of is the number of
diff --git a/Demo/tkinter/guido/sortvisu.py b/Demo/tkinter/guido/sortvisu.py
index 3e4454f..c538a2c 100644
--- a/Demo/tkinter/guido/sortvisu.py
+++ b/Demo/tkinter/guido/sortvisu.py
@@ -344,7 +344,7 @@ def steps(here, there):
def interpolate(oldpts, newpts, n):
if len(oldpts) != len(newpts):
- raise ValueError, "can't interpolate arrays of different length"
+ raise ValueError("can't interpolate arrays of different length")
pts = [0]*len(oldpts)
res = [tuple(oldpts)]
for i in range(1, n):
diff --git a/Demo/tkinter/guido/ss1.py b/Demo/tkinter/guido/ss1.py
index 8935475..d957907 100644
--- a/Demo/tkinter/guido/ss1.py
+++ b/Demo/tkinter/guido/ss1.py
@@ -136,13 +136,13 @@ class Sheet:
return maxx, maxy
def reset(self):
- for cell in self.cells.itervalues():
+ for cell in self.cells.values():
if hasattr(cell, 'reset'):
cell.reset()
def recalc(self):
self.reset()
- for cell in self.cells.itervalues():
+ for cell in self.cells.values():
if hasattr(cell, 'recalc'):
cell.recalc(self.rexec)
@@ -160,7 +160,7 @@ class Sheet:
full[0, y] = text, alignment = str(y), RIGHT
colwidth[0] = max(colwidth[0], len(text))
# Add sheet cells in columns with x>0 and y>0
- for (x, y), cell in self.cells.iteritems():
+ for (x, y), cell in self.cells.items():
if x <= 0 or y <= 0:
continue
if hasattr(cell, 'recalc'):
@@ -192,13 +192,13 @@ class Sheet:
if line:
line += '|'
line += text
- print line
+ print(line)
if y == 0:
- print sep
+ print(sep)
def xml(self):
out = ['<spreadsheet>']
- for (x, y), cell in self.cells.iteritems():
+ for (x, y), cell in self.cells.items():
if hasattr(cell, 'xml'):
cellxml = cell.xml()
else:
@@ -236,7 +236,7 @@ class SheetParser:
def startelement(self, tag, attrs):
method = getattr(self, 'start_'+tag, None)
if method:
- for key, value in attrs.iteritems():
+ for key, value in attrs.items():
attrs[key] = str(value) # XXX Convert Unicode to 8-bit
method(attrs)
self.texts = []
@@ -268,7 +268,7 @@ class SheetParser:
def end_long(self, text):
try:
- self.value = long(text)
+ self.value = int(text)
except:
self.value = None
@@ -325,7 +325,7 @@ class BaseCell:
class NumericCell(BaseCell):
def __init__(self, value, fmt="%s", alignment=RIGHT):
- assert isinstance(value, (int, long, float, complex))
+ assert isinstance(value, (int, int, float, complex))
assert alignment in (LEFT, CENTER, RIGHT)
self.value = value
self.fmt = fmt
@@ -366,7 +366,7 @@ class NumericCell(BaseCell):
class StringCell(BaseCell):
def __init__(self, text, fmt="%s", alignment=LEFT):
- assert isinstance(text, (str, unicode))
+ assert isinstance(text, (str, str))
assert alignment in (LEFT, CENTER, RIGHT)
self.text = text
self.fmt = fmt
@@ -699,7 +699,7 @@ class SheetGUI:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
- for (x, y), cell in self.gridcells.iteritems():
+ for (x, y), cell in self.gridcells.items():
if x1 <= x <= x2 and y1 <= y <= y2:
cell['bg'] = 'lightBlue'
gridcell = self.gridcells.get(self.currentxy)
@@ -735,7 +735,7 @@ class SheetGUI:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
- for (x, y), cell in self.gridcells.iteritems():
+ for (x, y), cell in self.gridcells.items():
if x1 <= x <= x2 and y1 <= y <= y2:
cell['bg'] = 'white'
@@ -775,7 +775,7 @@ class SheetGUI:
if text.startswith('='):
cell = FormulaCell(text[1:])
else:
- for cls in int, long, float, complex:
+ for cls in int, int, float, complex:
try:
value = cls(text)
except:
@@ -794,7 +794,7 @@ class SheetGUI:
def sync(self):
"Fill the GUI cells from the sheet cells."
self.sheet.recalc()
- for (x, y), gridcell in self.gridcells.iteritems():
+ for (x, y), gridcell in self.gridcells.items():
if x == 0 or y == 0:
continue
cell = self.sheet.getcell(x, y)
diff --git a/Demo/tkinter/guido/svkill.py b/Demo/tkinter/guido/svkill.py
index 95f61b8..378d58f 100755
--- a/Demo/tkinter/guido/svkill.py
+++ b/Demo/tkinter/guido/svkill.py
@@ -5,7 +5,7 @@
from Tkinter import *
if TkVersion < 4.0:
- raise ImportError, "This version of svkill requires Tk 4.0 or later"
+ raise ImportError("This version of svkill requires Tk 4.0 or later")
from string import splitfields
from string import split
diff --git a/Demo/tkinter/guido/tkman.py b/Demo/tkinter/guido/tkman.py
index 810bdf8..c84d889 100755
--- a/Demo/tkinter/guido/tkman.py
+++ b/Demo/tkinter/guido/tkman.py
@@ -172,8 +172,8 @@ class SelectionBox:
def updatelist(self):
key = self.entry.get()
- ok = filter(lambda name, key=key, n=len(key): name[:n]==key,
- self.choices)
+ ok = list(filter(lambda name, key=key, n=len(key): name[:n]==key,
+ self.choices))
if not ok:
self.frame.bell()
self.listbox.delete(0, AtEnd())
@@ -205,7 +205,7 @@ class SelectionBox:
def search_string(self, search):
if not search:
self.frame.bell()
- print 'Empty search string'
+ print('Empty search string')
return
if not self.casevar.get():
map = re.IGNORECASE
@@ -218,7 +218,7 @@ class SelectionBox:
prog = re.compile(search)
except re.error as msg:
self.frame.bell()
- print 'Regex error:', msg
+ print('Regex error:', msg)
return
here = self.text.index(AtInsert())
lineno = string.atoi(here[:string.find(here, '.')])
diff --git a/Demo/tkinter/guido/wish.py b/Demo/tkinter/guido/wish.py
index 2367e25..bebab1e 100755
--- a/Demo/tkinter/guido/wish.py
+++ b/Demo/tkinter/guido/wish.py
@@ -24,7 +24,7 @@ while 1:
try:
result = tk.call('eval', cmd)
except _tkinter.TclError as msg:
- print 'TclError:', msg
+ print('TclError:', msg)
else:
- if result: print result
+ if result: print(result)
cmd = ''
diff --git a/Demo/tkinter/matt/00-HELLO-WORLD.py b/Demo/tkinter/matt/00-HELLO-WORLD.py
index 1c3151b..20a2050 100644
--- a/Demo/tkinter/matt/00-HELLO-WORLD.py
+++ b/Demo/tkinter/matt/00-HELLO-WORLD.py
@@ -5,7 +5,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
diff --git a/Demo/tkinter/matt/animation-simple.py b/Demo/tkinter/matt/animation-simple.py
index b52e1dc..071bde7 100644
--- a/Demo/tkinter/matt/animation-simple.py
+++ b/Demo/tkinter/matt/animation-simple.py
@@ -4,7 +4,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
diff --git a/Demo/tkinter/matt/animation-w-velocity-ctrl.py b/Demo/tkinter/matt/animation-w-velocity-ctrl.py
index e676338..68eb1d0 100644
--- a/Demo/tkinter/matt/animation-w-velocity-ctrl.py
+++ b/Demo/tkinter/matt/animation-w-velocity-ctrl.py
@@ -8,7 +8,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
diff --git a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py b/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
index f3220da..f744d26 100644
--- a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
+++ b/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
@@ -24,11 +24,11 @@ class App(Frame):
self.entrythingy.bind('<Key-Return>', self.print_something_else, "+")
def print_contents(self, event):
- print "hi. contents of entry is now ---->", self.entrythingy.get()
+ print("hi. contents of entry is now ---->", self.entrythingy.get())
def print_something_else(self, event):
- print "hi. Now doing something completely different"
+ print("hi. Now doing something completely different")
root = App()
diff --git a/Demo/tkinter/matt/canvas-demo-simple.py b/Demo/tkinter/matt/canvas-demo-simple.py
index a01679a..b677ccd 100644
--- a/Demo/tkinter/matt/canvas-demo-simple.py
+++ b/Demo/tkinter/matt/canvas-demo-simple.py
@@ -4,7 +4,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
diff --git a/Demo/tkinter/matt/canvas-gridding.py b/Demo/tkinter/matt/canvas-gridding.py
index 3c52b91..84f4ea0 100644
--- a/Demo/tkinter/matt/canvas-gridding.py
+++ b/Demo/tkinter/matt/canvas-gridding.py
@@ -7,7 +7,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT',
diff --git a/Demo/tkinter/matt/canvas-reading-tag-info.py b/Demo/tkinter/matt/canvas-reading-tag-info.py
index f57ea18..75990c9 100644
--- a/Demo/tkinter/matt/canvas-reading-tag-info.py
+++ b/Demo/tkinter/matt/canvas-reading-tag-info.py
@@ -3,7 +3,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
@@ -28,14 +28,14 @@ class Test(Frame):
# is used for widgets. (remember, this is for ITEMS drawn
# on a canvas widget, not widgets)
option_value = self.drawing.itemconfig(pgon, "stipple")
- print "pgon's current stipple value is -->", option_value[4], "<--"
+ print("pgon's current stipple value is -->", option_value[4], "<--")
option_value = self.drawing.itemconfig(pgon, "fill")
- print "pgon's current fill value is -->", option_value[4], "<--"
- print " when he is usually colored -->", option_value[3], "<--"
+ print("pgon's current fill value is -->", option_value[4], "<--")
+ print(" when he is usually colored -->", option_value[3], "<--")
## here we print out all the tags associated with this object
option_value = self.drawing.itemconfig(pgon, "tags")
- print "pgon's tags are", option_value[4]
+ print("pgon's tags are", option_value[4])
self.drawing.pack(side=LEFT)
diff --git a/Demo/tkinter/matt/canvas-w-widget-draw-el.py b/Demo/tkinter/matt/canvas-w-widget-draw-el.py
index 5b26210..3cbf937 100644
--- a/Demo/tkinter/matt/canvas-w-widget-draw-el.py
+++ b/Demo/tkinter/matt/canvas-w-widget-draw-el.py
@@ -4,7 +4,7 @@ from Tkinter import *
class Test(Frame):
def printhi(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
diff --git a/Demo/tkinter/matt/canvas-with-scrollbars.py b/Demo/tkinter/matt/canvas-with-scrollbars.py
index 81ef25a..b55215d 100644
--- a/Demo/tkinter/matt/canvas-with-scrollbars.py
+++ b/Demo/tkinter/matt/canvas-with-scrollbars.py
@@ -7,7 +7,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.question = Label(self, text="Can Find The BLUE Square??????")
@@ -46,8 +46,8 @@ class Test(Frame):
def scrollCanvasX(self, *args):
- print "scrolling", args
- print self.draw.scrollX.get()
+ print("scrolling", args)
+ print(self.draw.scrollX.get())
def __init__(self, master=None):
diff --git a/Demo/tkinter/matt/dialog-box.py b/Demo/tkinter/matt/dialog-box.py
index dea8f39..0c71c3a 100644
--- a/Demo/tkinter/matt/dialog-box.py
+++ b/Demo/tkinter/matt/dialog-box.py
@@ -6,7 +6,7 @@ from Dialog import Dialog
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def makeWindow(self):
"""Create a top-level dialog with some buttons.
diff --git a/Demo/tkinter/matt/entry-simple.py b/Demo/tkinter/matt/entry-simple.py
index 5146e6f..0bf4cab 100644
--- a/Demo/tkinter/matt/entry-simple.py
+++ b/Demo/tkinter/matt/entry-simple.py
@@ -17,7 +17,7 @@ class App(Frame):
self.entrythingy.bind('<Key-Return>', self.print_contents)
def print_contents(self, event):
- print "hi. contents of entry is now ---->", self.entrythingy.get()
+ print("hi. contents of entry is now ---->", self.entrythingy.get())
root = App()
root.master.title("Foo")
diff --git a/Demo/tkinter/matt/entry-with-shared-variable.py b/Demo/tkinter/matt/entry-with-shared-variable.py
index 2b76162..c7cd259 100644
--- a/Demo/tkinter/matt/entry-with-shared-variable.py
+++ b/Demo/tkinter/matt/entry-with-shared-variable.py
@@ -39,7 +39,7 @@ class App(Frame):
self.contents.set(str)
def print_contents(self, event):
- print "hi. contents of entry is now ---->", self.contents.get()
+ print("hi. contents of entry is now ---->", self.contents.get())
root = App()
root.master.title("Foo")
diff --git a/Demo/tkinter/matt/killing-window-w-wm.py b/Demo/tkinter/matt/killing-window-w-wm.py
index 6a0e2fe..23ac103 100644
--- a/Demo/tkinter/matt/killing-window-w-wm.py
+++ b/Demo/tkinter/matt/killing-window-w-wm.py
@@ -7,11 +7,11 @@ from Tkinter import *
### ******* this isn't really called -- read the comments
def my_delete_callback():
- print "whoops -- tried to delete me!"
+ print("whoops -- tried to delete me!")
class Test(Frame):
def deathHandler(self, event):
- print self, "is now getting nuked. performing some save here...."
+ print(self, "is now getting nuked. performing some save here....")
def createWidgets(self):
# a hello button
diff --git a/Demo/tkinter/matt/menu-all-types-of-entries.py b/Demo/tkinter/matt/menu-all-types-of-entries.py
index f4afe4a..e4e4bfd 100644
--- a/Demo/tkinter/matt/menu-all-types-of-entries.py
+++ b/Demo/tkinter/matt/menu-all-types-of-entries.py
@@ -35,13 +35,13 @@ from Tkinter import *
# some miscellaneous callbacks
def new_file():
- print "opening new file"
+ print("opening new file")
def open_file():
- print "opening OLD file"
+ print("opening OLD file")
def print_something():
- print "picked a menu item"
+ print("picked a menu item")
@@ -50,7 +50,7 @@ anchovies = 0
def print_anchovies():
global anchovies
anchovies = not anchovies
- print "anchovies?", anchovies
+ print("anchovies?", anchovies)
def makeCommandMenu():
# make menu button
diff --git a/Demo/tkinter/matt/menu-simple.py b/Demo/tkinter/matt/menu-simple.py
index 46b5364..2487561 100644
--- a/Demo/tkinter/matt/menu-simple.py
+++ b/Demo/tkinter/matt/menu-simple.py
@@ -34,11 +34,11 @@ from Tkinter import *
def new_file():
- print "opening new file"
+ print("opening new file")
def open_file():
- print "opening OLD file"
+ print("opening OLD file")
def makeFileMenu():
diff --git a/Demo/tkinter/matt/packer-and-placer-together.py b/Demo/tkinter/matt/packer-and-placer-together.py
index 184d56b..84d3ee0 100644
--- a/Demo/tkinter/matt/packer-and-placer-together.py
+++ b/Demo/tkinter/matt/packer-and-placer-together.py
@@ -8,7 +8,7 @@ def do_motion(event):
app.button.place(x=event.x, y=event.y)
def dothis():
- print 'calling me!'
+ print('calling me!')
def createWidgets(top):
# make a frame. Note that the widget is 200 x 200
diff --git a/Demo/tkinter/matt/packer-simple.py b/Demo/tkinter/matt/packer-simple.py
index f55f1be..1a505dd 100644
--- a/Demo/tkinter/matt/packer-simple.py
+++ b/Demo/tkinter/matt/packer-simple.py
@@ -3,7 +3,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print self.hi_there["command"]
+ print(self.hi_there["command"])
def createWidgets(self):
# a hello button
diff --git a/Demo/tkinter/matt/placer-simple.py b/Demo/tkinter/matt/placer-simple.py
index 30d9e9e..992a8fc 100644
--- a/Demo/tkinter/matt/placer-simple.py
+++ b/Demo/tkinter/matt/placer-simple.py
@@ -6,7 +6,7 @@ def do_motion(event):
app.button.place(x=event.x, y=event.y)
def dothis():
- print 'calling me!'
+ print('calling me!')
def createWidgets(top):
# make a frame. Note that the widget is 200 x 200
diff --git a/Demo/tkinter/matt/printing-coords-of-items.py b/Demo/tkinter/matt/printing-coords-of-items.py
index a37733d..c74c1c3 100644
--- a/Demo/tkinter/matt/printing-coords-of-items.py
+++ b/Demo/tkinter/matt/printing-coords-of-items.py
@@ -35,7 +35,7 @@ class Test(Frame):
# the "current" tag is applied to the object the cursor is over.
# this happens automatically.
self.draw.itemconfig(CURRENT, fill="red")
- print self.draw.coords(CURRENT)
+ print(self.draw.coords(CURRENT))
def mouseLeave(self, event):
# the "current" tag is applied to the object the cursor is over.
diff --git a/Demo/tkinter/matt/radiobutton-simple.py b/Demo/tkinter/matt/radiobutton-simple.py
index e9d6afe..eeddb23 100644
--- a/Demo/tkinter/matt/radiobutton-simple.py
+++ b/Demo/tkinter/matt/radiobutton-simple.py
@@ -12,7 +12,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
diff --git a/Demo/tkinter/matt/rubber-band-box-demo-1.py b/Demo/tkinter/matt/rubber-band-box-demo-1.py
index b00518e..66b8f8b 100644
--- a/Demo/tkinter/matt/rubber-band-box-demo-1.py
+++ b/Demo/tkinter/matt/rubber-band-box-demo-1.py
@@ -2,7 +2,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT',
diff --git a/Demo/tkinter/matt/rubber-line-demo-1.py b/Demo/tkinter/matt/rubber-line-demo-1.py
index 59b8bd9..b1c8e78 100644
--- a/Demo/tkinter/matt/rubber-line-demo-1.py
+++ b/Demo/tkinter/matt/rubber-line-demo-1.py
@@ -2,7 +2,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT',
diff --git a/Demo/tkinter/matt/slider-demo-1.py b/Demo/tkinter/matt/slider-demo-1.py
index db6114b..5662db9 100644
--- a/Demo/tkinter/matt/slider-demo-1.py
+++ b/Demo/tkinter/matt/slider-demo-1.py
@@ -5,7 +5,7 @@ from Tkinter import *
class Test(Frame):
def print_value(self, val):
- print "slider now at", val
+ print("slider now at", val)
def reset(self):
self.slider.set(0)
diff --git a/Demo/tkinter/matt/subclass-existing-widgets.py b/Demo/tkinter/matt/subclass-existing-widgets.py
index 0e08f92..fc04859 100644
--- a/Demo/tkinter/matt/subclass-existing-widgets.py
+++ b/Demo/tkinter/matt/subclass-existing-widgets.py
@@ -5,7 +5,7 @@ from Tkinter import *
class New_Button(Button):
def callback(self):
- print self.counter
+ print(self.counter)
self.counter = self.counter + 1
def createWidgets(top):
diff --git a/Demo/tkinter/matt/two-radio-groups.py b/Demo/tkinter/matt/two-radio-groups.py
index 9fd8f4f..52513ba 100644
--- a/Demo/tkinter/matt/two-radio-groups.py
+++ b/Demo/tkinter/matt/two-radio-groups.py
@@ -75,9 +75,9 @@ def makeFlavors(var):
def printStuff():
- print "party is", party.get()
- print "flavor is", flavor.get()
- print
+ print("party is", party.get())
+ print("flavor is", flavor.get())
+ print()
#################################################
#### Main starts here ...
diff --git a/Demo/tkinter/matt/window-creation-more.py b/Demo/tkinter/matt/window-creation-more.py
index eb0eb6f..3a4ce19 100644
--- a/Demo/tkinter/matt/window-creation-more.py
+++ b/Demo/tkinter/matt/window-creation-more.py
@@ -5,7 +5,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def makeWindow(self):
fred = Toplevel()
diff --git a/Demo/tkinter/matt/window-creation-simple.py b/Demo/tkinter/matt/window-creation-simple.py
index c990ed9..fdf1dcc 100644
--- a/Demo/tkinter/matt/window-creation-simple.py
+++ b/Demo/tkinter/matt/window-creation-simple.py
@@ -4,7 +4,7 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def makeWindow(self):
fred = Toplevel()
diff --git a/Demo/tkinter/matt/window-creation-w-location.py b/Demo/tkinter/matt/window-creation-w-location.py
index 9f23bac..af6f876 100644
--- a/Demo/tkinter/matt/window-creation-w-location.py
+++ b/Demo/tkinter/matt/window-creation-w-location.py
@@ -9,9 +9,9 @@ import sys
class QuitButton(Button):
def __init__(self, master, *args, **kwargs):
- if not kwargs.has_key("text"):
+ if "text" not in kwargs:
kwargs["text"] = "QUIT"
- if not kwargs.has_key("command"):
+ if "command" not in kwargs:
kwargs["command"] = master.quit
Button.__init__(self, master, *args, **kwargs)
diff --git a/Demo/xml/elem_count.py b/Demo/xml/elem_count.py
index 7b53189..a2b4647 100644
--- a/Demo/xml/elem_count.py
+++ b/Demo/xml/elem_count.py
@@ -15,20 +15,20 @@ class FancyCounter(handler.ContentHandler):
self._attrs = self._attrs + len(attrs)
self._elem_types[name] = self._elem_types.get(name, 0) + 1
- for name in attrs.keys():
+ for name in list(attrs.keys()):
self._attr_types[name] = self._attr_types.get(name, 0) + 1
def endDocument(self):
- print "There were", self._elems, "elements."
- print "There were", self._attrs, "attributes."
+ print("There were", self._elems, "elements.")
+ print("There were", self._attrs, "attributes.")
- print "---ELEMENT TYPES"
- for pair in self._elem_types.items():
- print "%20s %d" % pair
+ print("---ELEMENT TYPES")
+ for pair in list(self._elem_types.items()):
+ print("%20s %d" % pair)
- print "---ATTRIBUTE TYPES"
- for pair in self._attr_types.items():
- print "%20s %d" % pair
+ print("---ATTRIBUTE TYPES")
+ for pair in list(self._attr_types.items()):
+ print("%20s %d" % pair)
parser = make_parser()
diff --git a/Demo/xml/roundtrip.py b/Demo/xml/roundtrip.py
index 8d7d437..b0e131e 100644
--- a/Demo/xml/roundtrip.py
+++ b/Demo/xml/roundtrip.py
@@ -22,7 +22,7 @@ class ContentGenerator(handler.ContentHandler):
def startElement(self, name, attrs):
self._out.write('<' + name)
- for (name, value) in attrs.items():
+ for (name, value) in list(attrs.items()):
self._out.write(' %s="%s"' % (name, saxutils.escape(value)))
self._out.write('>')
diff --git a/Demo/zlib/minigzip.py b/Demo/zlib/minigzip.py
index 87fed4a..28d8b26 100755
--- a/Demo/zlib/minigzip.py
+++ b/Demo/zlib/minigzip.py
@@ -49,10 +49,10 @@ def compress (filename, input, output):
def decompress (input, output):
magic = input.read(2)
if magic != '\037\213':
- print 'Not a gzipped file'
+ print('Not a gzipped file')
sys.exit(0)
if ord(input.read(1)) != 8:
- print 'Unknown compression method'
+ print('Unknown compression method')
sys.exit(0)
flag = ord(input.read(1))
input.read(4+1+1) # Discard modification time,
@@ -100,14 +100,14 @@ def decompress (input, output):
crc32 = read32(input)
isize = read32(input)
if crc32 != crcval:
- print 'CRC check failed.'
+ print('CRC check failed.')
if isize != length:
- print 'Incorrect length of data produced'
+ print('Incorrect length of data produced')
def main():
if len(sys.argv)!=2:
- print 'Usage: minigzip.py <filename>'
- print ' The file will be compressed or decompressed.'
+ print('Usage: minigzip.py <filename>')
+ print(' The file will be compressed or decompressed.')
sys.exit(0)
filename = sys.argv[1]
diff --git a/Demo/zlib/zlibdemo.py b/Demo/zlib/zlibdemo.py
index b449c19..53463dd 100755
--- a/Demo/zlib/zlibdemo.py
+++ b/Demo/zlib/zlibdemo.py
@@ -11,7 +11,7 @@ def main():
filename = sys.argv[1]
else:
filename = sys.argv[0]
- print 'Reading', filename
+ print('Reading', filename)
f = open(filename, 'rb') # Get the data to compress
s = f.read()
@@ -21,9 +21,9 @@ def main():
comptext = zlib.compress(s, 1)
decomp = zlib.decompress(comptext)
- print '1-step compression: (level 1)'
- print ' Original:', len(s), 'Compressed:', len(comptext),
- print 'Uncompressed:', len(decomp)
+ print('1-step compression: (level 1)')
+ print(' Original:', len(s), 'Compressed:', len(comptext), end=' ')
+ print('Uncompressed:', len(decomp))
# Now, let's compress the string in stages; set chunk to work in smaller steps
@@ -40,9 +40,9 @@ def main():
decomp = decomp + decompressor.decompress(comptext[i:i+chunk])
decomp=decomp+decompressor.flush()
- print 'Progressive compression (level 9):'
- print ' Original:', len(s), 'Compressed:', len(comptext),
- print 'Uncompressed:', len(decomp)
+ print('Progressive compression (level 9):')
+ print(' Original:', len(s), 'Compressed:', len(comptext), end=' ')
+ print('Uncompressed:', len(decomp))
if __name__ == '__main__':
main()