# 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")
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()
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)
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 = []
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")
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:
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):
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)
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)
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() ),
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': [
],
}
for expr in sorted(testsuite):
- print expr + ':'
+ print(expr + ':')
t = (expr,)
for item in testsuite[expr]:
checkop(*(t+item))
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
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
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
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):
# 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
# 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)
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
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
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
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()
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():
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
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__':
def __init__(self, num, den = 1):
if den == 0:
- raise ZeroDivisionError, 'rat(x, 0)'
+ raise ZeroDivisionError('rat(x, 0)')
# normalize
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
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
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
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
try:
div = int(div)
except OverflowError:
- div = long(div)
+ div = int(div)
return a - b * div
def __rmod__(b, a):
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
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):
# long(a)
def __long__(a):
- return long(a.__num) / long(a.__den)
+ return int(a.__num) / int(a.__den)
# float(a)
def __float__(a):
(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__':
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)
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()
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:
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):
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)
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):
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
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):
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)
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):
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))
#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:
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):
#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
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
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):
return int(self._data)
def __long__(self):
- return long(self._data)
+ return int(self._data)
def __float__(self):
return float(self._data)
import re
def main():
- pats = map(chomp, sys.stdin.readlines())
+ pats = list(map(chomp, sys.stdin.readlines()))
bigpat = '(' + '|'.join(pats) + ')'
prog = re.compile(bigpat)
try:
fp = open(file, 'r')
except IOError as msg:
- print "%s: %s" % (file, msg)
+ print("%s: %s" % (file, msg))
continue
lineno = 0
while 1:
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')
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()
# 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]
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:
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 + '/')
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:
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, ' ')
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:
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:
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()
_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."
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."
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.
Return None if the subfile was not found.
"""
- raise RuntimeError, "get_subfile not implemented"
+ raise RuntimeError("get_subfile not implemented")
class PackageArchive(PackageArchiveImporter):
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
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
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):
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:
outstr = (outstr
+ string.hexdigits[(o >> 4) & 0xF]
+ string.hexdigits[o & 0xF])
- print outstr,
+ print(outstr, end=' ')
from time import time
# start timer
- print 'MD5 time trial. Processing', TEST_BYTES, 'characters...'
+ print('MD5 time trial. Processing', TEST_BYTES, 'characters...')
t1 = time()
mdContext = md5.new()
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):
mdContext.update(data)
MDPrint(mdContext.digest())
- print filename
+ print(filename)
import sys
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')
"""
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):
"""
if name == '__members__':
- return self.__dict.keys()
+ return list(self.__dict.keys())
try:
return self.__dict[name]
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
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
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
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()
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
return base.__getattr__(name)
except AttributeError:
pass
- raise AttributeError, name
+ raise AttributeError(name)
def __setattr__(self, name, value):
if not self.__inited:
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__
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)
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', (), {})
aninstance.method1(10)
-print aninstance.method2()
+print(aninstance.method2())
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:
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.
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?
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):
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()
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()
return base.__getattr__(name)
except AttributeError:
pass
- raise AttributeError, name
+ raise AttributeError(name)
def __setattr__(self, name, value):
if not self.__inited:
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
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",
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()
"""
# 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):
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)
def __getattr__(cls, name):
if name == "__members__":
return cls._members
- raise AttributeError, name
+ raise AttributeError(name)
def __repr__(cls):
s1 = s2 = ""
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
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
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():
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
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
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()
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]
# 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]
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]
def testChunk(t, fileName):
global _numFailed
- print '----', fileName,
+ print('----', fileName, end=' ')
try:
ast = parser.suite(t)
tup = parser.ast2tuple(ast)
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()
import glob
args = glob.glob("*.py")
args.sort()
- map(testFile, args)
+ list(map(testFile, args))
sys.exit(_numFailed != 0)
if __name__ == '__main__':
"Usage: unparse.py <path to source file>"
import sys
import _ast
-import cStringIO
+import io
import os
def interleave(inter, f, seq):
"""
seq = iter(seq)
try:
- f(seq.next())
+ f(next(seq))
except StopIteration:
pass
else:
self.f = file
self._indent = 0
self.dispatch(tree)
- print >>self.f,""
+ print("", file=self.f)
self.f.flush()
def fill(self, text = ""):
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)
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)
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
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()
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]
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
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):
def mkdir(self, name):
self.check(name)
- os.mkdir(name, 0777)
+ os.mkdir(name, 0o777)
def rmdir(self, name):
self.check(name)
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)
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)
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
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
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
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
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):
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()
"""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."""
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__
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():
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 = [
[],
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__':
def main():
pwd = os.getcwd()
- s = raw_input("chdir [%s] " % pwd)
+ s = input("chdir [%s] " % pwd)
if s:
os.chdir(s)
pwd = os.getcwd()
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()
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)
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)
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()
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
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')
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():
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
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
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)
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):
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:
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:
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)
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))
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()
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
def unlockfile(self):
if self.lockfile:
- print "unlink", self.lockfile
+ print("unlink", self.lockfile)
try:
os.unlink(self.lockfile)
except os.error:
def unlockdir(self):
if self.lockdir:
- print "rmdir", self.lockdir
+ print("rmdir", self.lockdir)
try:
os.rmdir(self.lockdir)
except os.error:
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)
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__':
def main():
while 1:
try:
- line = raw_input('$ ')
+ line = input('$ ')
except EOFError:
break
words = line.split()
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: (.*)$")
dict[key] = value
status = self._closepipe(f)
if status:
- raise IOError, status
+ raise IOError(status)
return dict
# --- Methods that change files ---
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):
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]
"""
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 ---
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):
"""
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.
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()
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
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
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
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):
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...
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):
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):
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 = ''
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
continue
if os.path.islink(name):
continue
- print "--- entering subdirectory", name, "---"
+ print("--- entering subdirectory", name, "---")
os.chdir(name)
try:
if os.path.isdir("CVS"):
self.recurse()
finally:
os.chdir(os.pardir)
- print "--- left subdirectory", name, "---"
+ print("--- left subdirectory", name, "---")
def options(self, opts):
self.opts = opts
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()
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()
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:
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)
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)
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 = ''
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):
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:
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(">> ")
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
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
def _encode_challenge(self, challenge):
p, m = self._key
- return pow(long(challenge), p, m)
+ return pow(int(challenge), p, m)
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')
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.*']
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
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
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
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()
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:
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 = {}
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
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])
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)
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]
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()
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
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
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
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)
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
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)
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)
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
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
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
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)
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)
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 = []
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)
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)
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
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)
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:
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
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)
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():
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))
struct = None
-Long = type(0L)
+Long = type(0)
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
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'
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)
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
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):
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
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):
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):
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
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.")
# 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~
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__":
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
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:
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:])
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()
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':
try:
f = open(file, 'r')
except IOError as msg:
- print file, ':', msg
+ print(file, ':', msg)
sys.exit(1)
bydate = {}
bytime = {}
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,
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)
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))
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]
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]
text = clearhome
for name in printers:
text = text + makestatus(name, thisuser) + '\n'
- print text
+ print(text)
time.sleep(delay)
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
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:
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()
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)
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
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
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 ()
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()
break
if line[:5] == 'From ':
line = '>' + line
- print line,
+ print(line, end=' ')
# Print trailing newline
- print
+ print()
return sts
if __name__ == "__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()
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)
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()
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
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
# 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)
j = path[0]
l = len(path)
- if not tree.has_key(j):
+ if j not in tree:
tree[j] = {}
if l == 1:
tree[j]['.'] = '.'
createpage(p[1:], tree, p)
return
- kl = tree.keys()
+ kl = list(tree.keys())
if l > 1:
kl.sort()
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')
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 != '':
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:
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):
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 --------------------------------------------
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
# Read group descriptions
readdesc(descfile)
- print 'Creating pages...'
+ print('Creating pages...')
createpage(rootpage, tree, '')
- print 'Done'
+ print('Done')
if __name__ == "__main__":
main()
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):
NFLAG = 1
PFLAG = 1
else:
- print option, 'not recognized???'
+ print(option, 'not recognized???')
if not ARGS: ARGS.append('-')
primes(min, max)
def primes(min, max):
- if 2 >= min: print 2
+ if 2 >= min: print(2)
primes = [2]
i = 3
while i <= 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__":
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
q = Queens(n)
q.silent = silent
q.solve()
- print "Found", q.nfound, "solutions."
+ print("Found", q.nfound, "solutions.")
if __name__ == "__main__":
main()
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'
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):
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
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()
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
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:
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:
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
# 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)
def getcommand():
try:
while 1:
- line = raw_input('ftp.py> ')
+ line = input('ftp.py> ')
if line: return line
except EOFError:
return ''
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]
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()
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]
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):
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()
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):
# 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):
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:
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:
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])
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
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
#
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
data = s.recv(BUFSIZE)
if not data: break
reply = reply + data
- print reply,
+ print(reply, end=' ')
main()
import sys
from socket import *
-import StringIO
+import io
import traceback
PORT = 4127
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)
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
cleandata = ''
for c in data:
if opt:
- print ord(c)
+ print(ord(c))
s.send(opt + c)
opt = ''
elif iac:
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)
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)
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:
del data
conn.send('OK\n')
conn.close()
- print 'Done with', host, 'port', remoteport
+ print('Done with', host, 'port', remoteport)
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()
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():
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():
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()
s.send('Hello, world')
data = s.recv(1024)
s.close()
-print 'Received', repr(data)
+print('Received', repr(data))
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)
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)
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):
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
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
# 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
# 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:
# 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
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()
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
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
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
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):
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))
def putline():
while 1:
line = co.tran(coassembler)
- print line
+ print(line)
import string
co = Coroutine()
cosquasher = co.create(squasher)
co.tran(coputline)
-print 'done'
+print('done')
# end of example
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()
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
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()
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()
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()
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()
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:
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
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
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
_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()
cleandata = ''
for c in data:
if opt:
- print ord(c)
+ print(ord(c))
## print '(replying: %r)' % (opt+c,)
s.send(opt + c)
opt = ''
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)
# 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])
try: tkMessageBox.showerror ('Error', text)
except: pass
self.exit = 1
- raise SystemExit, 1
+ raise SystemExit(1)
def destroy (self):
self.root.destroy()
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:
try:
self.dialog.widget.pack(**{self.option: self.current})
except TclError as msg:
- print msg
+ print(msg)
self.refresh()
class booleanoption(packoption, BooleanOption): pass
'info',
self.widget))
except TclError as msg:
- print msg
+ print(msg)
return
dict = {}
for i in range(0, len(words), 2):
self.dialog.master.tk.merge(
self.current))
except TclError as msg:
- print msg
+ print(msg)
self.refresh()
class booleanoption(remotepackoption, BooleanOption): pass
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
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
try:
self.dialog.widget[self.option] = self.current
except TclError as msg:
- print msg
+ print(msg)
self.refresh()
class booleanoption(widgetoption, BooleanOption): pass
self.widget,
'config'))
except TclError as msg:
- print msg
+ print(msg)
return
dict = {}
for item in items:
'-'+self.option,
self.current)
except TclError as msg:
- print msg
+ print(msg)
self.refresh()
class booleanoption(remotewidgetoption, BooleanOption): pass
try:
RemotePackDialog(list, list.app, widget)
except TclError as msg:
- print msg
+ print(msg)
test()
# 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
# 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:
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
'',
-1,
'OK')
- print 'pressed button', i
+ print('pressed button', i)
i = dialog(mainWidget,
'File Modified',
'File "tcl.h" has been modified since '
'Save File',
'Discard Changes',
'Return To Editor')
- print 'pressed button', i
+ print('pressed button', i)
def test():
import sys
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] == '+':
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()
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:
for s in (CLUBS, SPADES):
COLOR[s] = BLACK
-ALLSUITS = COLOR.keys()
+ALLSUITS = list(COLOR.keys())
NSUITS = len(ALLSUITS)
# 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
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):
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)
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'):
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:
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 = []
def end_long(self, text):
try:
- self.value = long(text)
+ self.value = int(text)
except:
self.value = None
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
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
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)
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'
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:
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)
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
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())
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
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, '.')])
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 = ''
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
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()
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT',
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
# 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)
class Test(Frame):
def printhi(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT', foreground='red',
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.question = Label(self, text="Can Find The BLUE Square??????")
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):
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def makeWindow(self):
"""Create a top-level dialog with some buttons.
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")
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")
### ******* 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
# 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")
def print_anchovies():
global anchovies
anchovies = not anchovies
- print "anchovies?", anchovies
+ print("anchovies?", anchovies)
def makeCommandMenu():
# make menu button
def new_file():
- print "opening new file"
+ print("opening new file")
def open_file():
- print "opening OLD file"
+ print("opening OLD file")
def makeFileMenu():
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
class Test(Frame):
def printit(self):
- print self.hi_there["command"]
+ print(self.hi_there["command"])
def createWidgets(self):
# a hello button
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
# 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.
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT',
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def createWidgets(self):
self.QUIT = Button(self, text='QUIT',
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)
class New_Button(Button):
def callback(self):
- print self.counter
+ print(self.counter)
self.counter = self.counter + 1
def createWidgets(top):
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 ...
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def makeWindow(self):
fred = Toplevel()
class Test(Frame):
def printit(self):
- print "hi"
+ print("hi")
def makeWindow(self):
fred = Toplevel()
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)
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()
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('>')
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,
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]
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()
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
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()