Replace backticks with repr() or "%r"

From SF patch #852334.
This commit is contained in:
Walter Dörwald 2004-02-12 17:35:32 +00:00
parent ecfeb7f095
commit 70a6b49821
246 changed files with 926 additions and 962 deletions

View file

@ -117,15 +117,15 @@ class Complex:
def __repr__(self): def __repr__(self):
if not self.im: if not self.im:
return 'Complex(%s)' % `self.re` return 'Complex(%r)' % (self.re,)
else: else:
return 'Complex(%s, %s)' % (`self.re`, `self.im`) return 'Complex(%r, %r)' % (self.re, self.im)
def __str__(self): def __str__(self):
if not self.im: if not self.im:
return `self.re` return repr(self.re)
else: else:
return 'Complex(%s, %s)' % (`self.re`, `self.im`) return 'Complex(%r, %r)' % (self.re, self.im)
def __neg__(self): def __neg__(self):
return Complex(-self.re, -self.im) return Complex(-self.re, -self.im)

View file

@ -86,7 +86,7 @@ _DI400Y = _days_before_year( 400 ) # number of days in 400 years
def _num2date( n ): # return date with ordinal n def _num2date( n ): # return date with ordinal n
if type(n) not in _INT_TYPES: if type(n) not in _INT_TYPES:
raise TypeError, 'argument must be integer: ' + `type(n)` raise TypeError, 'argument must be integer: %r' % type(n)
ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj
del ans.ord, ans.month, ans.day, ans.year # un-initialize it del ans.ord, ans.month, ans.day, ans.year # un-initialize it
@ -120,10 +120,10 @@ def _num2day( n ): # return weekday name of day with ordinal n
class Date: class Date:
def __init__( self, month, day, year ): def __init__( self, month, day, year ):
if not 1 <= month <= 12: if not 1 <= month <= 12:
raise ValueError, 'month must be in 1..12: ' + `month` raise ValueError, 'month must be in 1..12: %r' % (month,)
dim = _days_in_month( month, year ) dim = _days_in_month( month, year )
if not 1 <= day <= dim: if not 1 <= day <= dim:
raise ValueError, 'day must be in 1..' + `dim` + ': ' + `day` raise ValueError, 'day must be in 1..%r: %r' % (dim, day)
self.month, self.day, self.year = month, day, year self.month, self.day, self.year = month, day, year
self.ord = _date2num( self ) self.ord = _date2num( self )
@ -142,15 +142,16 @@ class Date:
# print as, e.g., Mon 16 Aug 1993 # print as, e.g., Mon 16 Aug 1993
def __repr__( self ): def __repr__( self ):
return '%.3s %2d %.3s ' % ( return '%.3s %2d %.3s %r' % (
self.weekday(), self.weekday(),
self.day, self.day,
_MONTH_NAMES[self.month-1] ) + `self.year` _MONTH_NAMES[self.month-1],
self.year)
# Python 1.1 coerces neither int+date nor date+int # Python 1.1 coerces neither int+date nor date+int
def __add__( self, n ): def __add__( self, n ):
if type(n) not in _INT_TYPES: if type(n) not in _INT_TYPES:
raise TypeError, 'can\'t add ' + `type(n)` + ' to date' raise TypeError, 'can\'t add %r to date' % type(n)
return _num2date( self.ord + n ) return _num2date( self.ord + n )
__radd__ = __add__ # handle int+date __radd__ = __add__ # handle int+date
@ -177,7 +178,7 @@ DateTestError = 'DateTestError'
def test( firstyear, lastyear ): def test( firstyear, lastyear ):
a = Date(9,30,1913) a = Date(9,30,1913)
b = Date(9,30,1914) b = Date(9,30,1914)
if `a` != 'Tue 30 Sep 1913': 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: if (not a < b) or a == b or a > b or b != b:
raise DateTestError, '__cmp__ failure' raise DateTestError, '__cmp__ failure'

View file

@ -13,7 +13,7 @@ class Dbm:
def __repr__(self): def __repr__(self):
s = '' s = ''
for key in self.keys(): for key in self.keys():
t = `key` + ': ' + `self[key]` t = repr(key) + ': ' + repr(self[key])
if s: t = ', ' + t if s: t = ', ' + t
s = s + t s = s + t
return '{' + s + '}' return '{' + s + '}'
@ -22,13 +22,13 @@ class Dbm:
return len(self.db) return len(self.db)
def __getitem__(self, key): def __getitem__(self, key):
return eval(self.db[`key`]) return eval(self.db[repr(key)])
def __setitem__(self, key, value): def __setitem__(self, key, value):
self.db[`key`] = `value` self.db[repr(key)] = repr(value)
def __delitem__(self, key): def __delitem__(self, key):
del self.db[`key`] del self.db[repr(key)]
def keys(self): def keys(self):
res = [] res = []
@ -37,7 +37,7 @@ class Dbm:
return res return res
def has_key(self, key): def has_key(self, key):
return self.db.has_key(`key`) return self.db.has_key(repr(key))
def test(): def test():

View file

@ -34,9 +34,9 @@ class Range:
self.step = step self.step = step
self.len = max(0, int((self.stop - self.start) / self.step)) self.len = max(0, int((self.stop - self.start) / self.step))
# implement `x` and is also used by print x # implement repr(x) and is also used by print x
def __repr__(self): def __repr__(self):
return 'range' + `self.start, self.stop, self.step` return 'range(%r, %r, %r)' % (self.start, self.stop, self.step)
# implement len(x) # implement len(x)
def __len__(self): def __len__(self):

View file

@ -20,7 +20,7 @@ def _compute_len(param):
mant, l = math.frexp(float(param)) mant, l = math.frexp(float(param))
bitmask = 1L << l bitmask = 1L << l
if bitmask <= param: if bitmask <= param:
raise 'FATAL', '(param, l) = ' + `param, l` raise 'FATAL', '(param, l) = %r' % ((param, l),)
while l: while l:
bitmask = bitmask >> 1 bitmask = bitmask >> 1
if param & bitmask: if param & bitmask:
@ -167,10 +167,10 @@ class BitVec:
def __repr__(self): def __repr__(self):
##rprt('<bitvec class instance object>.' + '__repr__()\n') ##rprt('<bitvec class instance object>.' + '__repr__()\n')
return 'bitvec' + `self._data, self._len` return 'bitvec(%r, %r)' % (self._data, self._len)
def __cmp__(self, other, *rest): def __cmp__(self, other, *rest):
#rprt(`self`+'.__cmp__'+`(other, ) + rest`+'\n') #rprt('%r.__cmp__%r\n' % (self, (other,) + rest))
if type(other) != type(self): if type(other) != type(self):
other = apply(bitvec, (other, ) + rest) other = apply(bitvec, (other, ) + rest)
#expensive solution... recursive binary, with slicing #expensive solution... recursive binary, with slicing
@ -193,16 +193,16 @@ class BitVec:
def __len__(self): def __len__(self):
#rprt(`self`+'.__len__()\n') #rprt('%r.__len__()\n' % (self,))
return self._len return self._len
def __getitem__(self, key): def __getitem__(self, key):
#rprt(`self`+'.__getitem__('+`key`+')\n') #rprt('%r.__getitem__(%r)\n' % (self, key))
key = _check_key(self._len, key) key = _check_key(self._len, key)
return self._data & (1L << key) != 0 return self._data & (1L << key) != 0
def __setitem__(self, key, value): def __setitem__(self, key, value):
#rprt(`self`+'.__setitem__'+`key, value`+'\n') #rprt('%r.__setitem__(%r, %r)\n' % (self, key, value))
key = _check_key(self._len, key) key = _check_key(self._len, key)
#_check_value(value) #_check_value(value)
if value: if value:
@ -211,14 +211,14 @@ class BitVec:
self._data = self._data & ~(1L << key) self._data = self._data & ~(1L << key)
def __delitem__(self, key): def __delitem__(self, key):
#rprt(`self`+'.__delitem__('+`key`+')\n') #rprt('%r.__delitem__(%r)\n' % (self, key))
key = _check_key(self._len, key) key = _check_key(self._len, key)
#el cheapo solution... #el cheapo solution...
self._data = self[:key]._data | self[key+1:]._data >> key self._data = self[:key]._data | self[key+1:]._data >> key
self._len = self._len - 1 self._len = self._len - 1
def __getslice__(self, i, j): def __getslice__(self, i, j):
#rprt(`self`+'.__getslice__'+`i, j`+'\n') #rprt('%r.__getslice__(%r, %r)\n' % (self, i, j))
i, j = _check_slice(self._len, i, j) i, j = _check_slice(self._len, i, j)
if i >= j: if i >= j:
return BitVec(0L, 0) return BitVec(0L, 0)
@ -234,7 +234,7 @@ class BitVec:
return BitVec(ndata, nlength) return BitVec(ndata, nlength)
def __setslice__(self, i, j, sequence, *rest): def __setslice__(self, i, j, sequence, *rest):
#rprt(`self`+'.__setslice__'+`(i, j, sequence) + rest`+'\n') #rprt('%s.__setslice__%r\n' % (self, (i, j, sequence) + rest))
i, j = _check_slice(self._len, i, j) i, j = _check_slice(self._len, i, j)
if type(sequence) != type(self): if type(sequence) != type(self):
sequence = apply(bitvec, (sequence, ) + rest) sequence = apply(bitvec, (sequence, ) + rest)
@ -247,7 +247,7 @@ class BitVec:
self._len = self._len - j + i + sequence._len self._len = self._len - j + i + sequence._len
def __delslice__(self, i, j): def __delslice__(self, i, j):
#rprt(`self`+'.__delslice__'+`i, j`+'\n') #rprt('%r.__delslice__(%r, %r)\n' % (self, i, j))
i, j = _check_slice(self._len, i, j) i, j = _check_slice(self._len, i, j)
if i == 0 and j == self._len: if i == 0 and j == self._len:
self._data, self._len = 0L, 0 self._data, self._len = 0L, 0
@ -256,13 +256,13 @@ class BitVec:
self._len = self._len - j + i self._len = self._len - j + i
def __add__(self, other): def __add__(self, other):
#rprt(`self`+'.__add__('+`other`+')\n') #rprt('%r.__add__(%r)\n' % (self, other))
retval = self.copy() retval = self.copy()
retval[self._len:self._len] = other retval[self._len:self._len] = other
return retval return retval
def __mul__(self, multiplier): def __mul__(self, multiplier):
#rprt(`self`+'.__mul__('+`multiplier`+')\n') #rprt('%r.__mul__(%r)\n' % (self, multiplier))
if type(multiplier) != type(0): if type(multiplier) != type(0):
raise TypeError, 'sequence subscript not int' raise TypeError, 'sequence subscript not int'
if multiplier <= 0: if multiplier <= 0:
@ -281,7 +281,7 @@ class BitVec:
return retval return retval
def __and__(self, otherseq, *rest): def __and__(self, otherseq, *rest):
#rprt(`self`+'.__and__'+`(otherseq, ) + rest`+'\n') #rprt('%r.__and__%r\n' % (self, (otherseq,) + rest))
if type(otherseq) != type(self): if type(otherseq) != type(self):
otherseq = apply(bitvec, (otherseq, ) + rest) otherseq = apply(bitvec, (otherseq, ) + rest)
#sequence is now of our own type #sequence is now of our own type
@ -290,7 +290,7 @@ class BitVec:
def __xor__(self, otherseq, *rest): def __xor__(self, otherseq, *rest):
#rprt(`self`+'.__xor__'+`(otherseq, ) + rest`+'\n') #rprt('%r.__xor__%r\n' % (self, (otherseq,) + rest))
if type(otherseq) != type(self): if type(otherseq) != type(self):
otherseq = apply(bitvec, (otherseq, ) + rest) otherseq = apply(bitvec, (otherseq, ) + rest)
#sequence is now of our own type #sequence is now of our own type
@ -299,7 +299,7 @@ class BitVec:
def __or__(self, otherseq, *rest): def __or__(self, otherseq, *rest):
#rprt(`self`+'.__or__'+`(otherseq, ) + rest`+'\n') #rprt('%r.__or__%r\n' % (self, (otherseq,) + rest))
if type(otherseq) != type(self): if type(otherseq) != type(self):
otherseq = apply(bitvec, (otherseq, ) + rest) otherseq = apply(bitvec, (otherseq, ) + rest)
#sequence is now of our own type #sequence is now of our own type
@ -308,13 +308,13 @@ class BitVec:
def __invert__(self): def __invert__(self):
#rprt(`self`+'.__invert__()\n') #rprt('%r.__invert__()\n' % (self,))
return BitVec(~self._data & ((1L << self._len) - 1), \ return BitVec(~self._data & ((1L << self._len) - 1), \
self._len) self._len)
def __coerce__(self, otherseq, *rest): def __coerce__(self, otherseq, *rest):
#needed for *some* of the arithmetic operations #needed for *some* of the arithmetic operations
#rprt(`self`+'.__coerce__'+`(otherseq, ) + rest`+'\n') #rprt('%r.__coerce__%r\n' % (self, (otherseq,) + rest))
if type(otherseq) != type(self): if type(otherseq) != type(self):
otherseq = apply(bitvec, (otherseq, ) + rest) otherseq = apply(bitvec, (otherseq, ) + rest)
return self, otherseq return self, otherseq

View file

@ -107,9 +107,9 @@ class EnumInstance:
return self.__value return self.__value
def __repr__(self): def __repr__(self):
return "EnumInstance(%s, %s, %s)" % (`self.__classname`, return "EnumInstance(%r, %r, %r)" % (self.__classname,
`self.__enumname`, self.__enumname,
`self.__value`) self.__value)
def __str__(self): def __str__(self):
return "%s.%s" % (self.__classname, self.__enumname) return "%s.%s" % (self.__classname, self.__enumname)

View file

@ -98,7 +98,7 @@ def _test():
def __init__(self, *args): def __init__(self, *args):
print "__init__, args =", args print "__init__, args =", args
def m1(self, x): def m1(self, x):
print "m1(x=%s)" %`x` print "m1(x=%r)" % (x,)
print C print C
x = C() x = C()
print x print x

View file

@ -117,7 +117,7 @@ def _test():
def m2(self, y): return self.x + y def m2(self, y): return self.x + y
__trace_output__ = sys.stdout __trace_output__ = sys.stdout
class D(C): class D(C):
def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y) def m2(self, y): print "D.m2(%r)" % (y,); return C.m2(self, y)
__trace_output__ = None __trace_output__ = None
x = C(4321) x = C(4321)
print x print x

View file

@ -97,7 +97,7 @@ def _test():
print Color.red print Color.red
print `Color.red` print repr(Color.red)
print Color.red == Color.red print Color.red == Color.red
print Color.red == Color.blue print Color.red == Color.blue
print Color.red == 1 print Color.red == 1
@ -139,7 +139,7 @@ def _test2():
print Color.red print Color.red
print `Color.red` print repr(Color.red)
print Color.red == Color.red print Color.red == Color.red
print Color.red == Color.blue print Color.red == Color.blue
print Color.red == 1 print Color.red == 1

View file

@ -188,7 +188,7 @@ def test():
if callable(attr): if callable(attr):
print apply(attr, tuple(sys.argv[2:])) print apply(attr, tuple(sys.argv[2:]))
else: else:
print `attr` print repr(attr)
else: else:
print "%s: no such attribute" % what print "%s: no such attribute" % what
sys.exit(2) sys.exit(2)

View file

@ -139,7 +139,7 @@ class SecureClient(Client, Security):
line = self._rf.readline() line = self._rf.readline()
challenge = string.atoi(string.strip(line)) challenge = string.atoi(string.strip(line))
response = self._encode_challenge(challenge) response = self._encode_challenge(challenge)
line = `long(response)` line = repr(long(response))
if line[-1] in 'Ll': line = line[:-1] if line[-1] in 'Ll': line = line[:-1]
self._wf.write(line + '\n') self._wf.write(line + '\n')
self._wf.flush() self._wf.flush()

View file

@ -55,7 +55,7 @@ class CommandFrameWork:
try: try:
method = getattr(self, mname) method = getattr(self, mname)
except AttributeError: except AttributeError:
return self.usage("command %s unknown" % `cmd`) return self.usage("command %r unknown" % (cmd,))
try: try:
flags = getattr(self, fname) flags = getattr(self, fname)
except AttributeError: except AttributeError:
@ -75,7 +75,7 @@ class CommandFrameWork:
print "-"*40 print "-"*40
print "Options:" print "Options:"
for o, a in opts: for o, a in opts:
print 'option', o, 'value', `a` print 'option', o, 'value', repr(a)
print "-"*40 print "-"*40
def ready(self): def ready(self):
@ -137,7 +137,7 @@ def test():
for t in tests: for t in tests:
print '-'*10, t, '-'*10 print '-'*10, t, '-'*10
sts = x.run(t) sts = x.run(t)
print "Exit status:", `sts` print "Exit status:", repr(sts)
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -49,7 +49,7 @@ def askint(prompt, default):
def compare(local, remote, mode): def compare(local, remote, mode):
print print
print "PWD =", `os.getcwd()` print "PWD =", repr(os.getcwd())
sums_id = remote._send('sumlist') sums_id = remote._send('sumlist')
subdirs_id = remote._send('listsubdirs') subdirs_id = remote._send('listsubdirs')
remote._flush() remote._flush()
@ -64,13 +64,13 @@ def compare(local, remote, mode):
for name, rsum in sums: for name, rsum in sums:
rsumdict[name] = rsum rsumdict[name] = rsum
if not lsumdict.has_key(name): if not lsumdict.has_key(name):
print `name`, "only remote" print repr(name), "only remote"
if 'r' in mode and 'c' in mode: if 'r' in mode and 'c' in mode:
recvfile(local, remote, name) recvfile(local, remote, name)
else: else:
lsum = lsumdict[name] lsum = lsumdict[name]
if lsum != rsum: if lsum != rsum:
print `name`, print repr(name),
rmtime = remote.mtime(name) rmtime = remote.mtime(name)
lmtime = local.mtime(name) lmtime = local.mtime(name)
if rmtime > lmtime: if rmtime > lmtime:
@ -86,7 +86,7 @@ def compare(local, remote, mode):
print print
for name in lsumdict.keys(): for name in lsumdict.keys():
if not rsumdict.keys(): if not rsumdict.keys():
print `name`, "only locally", print repr(name), "only locally",
fl() fl()
if 'w' in mode and 'c' in mode: if 'w' in mode and 'c' in mode:
sendfile(local, remote, name) sendfile(local, remote, name)
@ -160,7 +160,7 @@ def recvfile(local, remote, name):
return rv return rv
finally: finally:
if not ok: if not ok:
print "*** recvfile of %s failed, deleting" % `name` print "*** recvfile of %r failed, deleting" % (name,)
local.delete(name) local.delete(name)
def recvfile_real(local, remote, name): def recvfile_real(local, remote, name):

View file

@ -114,7 +114,7 @@ class Lock:
self.delay = delay self.delay = delay
self.lockdir = None self.lockdir = None
self.lockfile = None self.lockfile = None
pid = `os.getpid()` pid = repr(os.getpid())
self.cvslck = self.join(CVSLCK) self.cvslck = self.join(CVSLCK)
self.cvsrfl = self.join(CVSRFL + pid) self.cvsrfl = self.join(CVSRFL + pid)
self.cvswfl = self.join(CVSWFL + pid) self.cvswfl = self.join(CVSWFL + pid)

View file

@ -232,7 +232,7 @@ class RCS:
""" """
name, rev = self._unmangle(name_rev) name, rev = self._unmangle(name_rev)
if not self.isvalid(name): if not self.isvalid(name):
raise os.error, 'not an rcs file %s' % `name` raise os.error, 'not an rcs file %r' % (name,)
return name, rev return name, rev
# --- Internal methods --- # --- Internal methods ---
@ -252,7 +252,7 @@ class RCS:
namev = self.rcsname(name) namev = self.rcsname(name)
if rev: if rev:
cmd = cmd + ' ' + rflag + rev cmd = cmd + ' ' + rflag + rev
return os.popen("%s %s" % (cmd, `namev`)) return os.popen("%s %r" % (cmd, namev))
def _unmangle(self, name_rev): def _unmangle(self, name_rev):
"""INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple. """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple.

View file

@ -134,11 +134,11 @@ class SecureServer(Server, Security):
response = string.atol(string.strip(response)) response = string.atol(string.strip(response))
except string.atol_error: except string.atol_error:
if self._verbose > 0: if self._verbose > 0:
print "Invalid response syntax", `response` print "Invalid response syntax", repr(response)
return 0 return 0
if not self._compare_challenge_response(challenge, response): if not self._compare_challenge_response(challenge, response):
if self._verbose > 0: if self._verbose > 0:
print "Invalid response value", `response` print "Invalid response value", repr(response)
return 0 return 0
if self._verbose > 1: if self._verbose > 1:
print "Response matches challenge. Go ahead!" print "Response matches challenge. Go ahead!"

View file

@ -18,5 +18,5 @@ def TSTOP(*label):
[u, s, r] = tt [u, s, r] = tt
msg = '' msg = ''
for x in label: msg = msg + (x + ' ') for x in label: msg = msg + (x + ' ')
msg = msg + `u` + ' user, ' + `s` + ' sys, ' + `r` + ' real\n' msg = msg + '%r user, %r sys, %r real\n' % (u, s, r)
sys.stderr.write(msg) sys.stderr.write(msg)

View file

@ -77,7 +77,7 @@ def test():
line = strip0(line) line = strip0(line)
name = strip0(name) name = strip0(name)
host = strip0(host) host = strip0(host)
print `name`, `host`, `line`, time, idle print "%r %r %r %s %s" % (name, host, line, time, idle)
def testbcast(): def testbcast():
c = BroadcastRnusersClient('<broadcast>') c = BroadcastRnusersClient('<broadcast>')

View file

@ -93,10 +93,10 @@ class Unpacker(xdr.Unpacker):
xid = self.unpack_uint(xid) xid = self.unpack_uint(xid)
temp = self.unpack_enum() temp = self.unpack_enum()
if temp <> CALL: if temp <> CALL:
raise BadRPCFormat, 'no CALL but ' + `temp` raise BadRPCFormat, 'no CALL but %r' % (temp,)
temp = self.unpack_uint() temp = self.unpack_uint()
if temp <> RPCVERSION: if temp <> RPCVERSION:
raise BadRPCVerspion, 'bad RPC version ' + `temp` raise BadRPCVerspion, 'bad RPC version %r' % (temp,)
prog = self.unpack_uint() prog = self.unpack_uint()
vers = self.unpack_uint() vers = self.unpack_uint()
proc = self.unpack_uint() proc = self.unpack_uint()
@ -109,7 +109,7 @@ class Unpacker(xdr.Unpacker):
xid = self.unpack_uint() xid = self.unpack_uint()
mtype = self.unpack_enum() mtype = self.unpack_enum()
if mtype <> REPLY: if mtype <> REPLY:
raise RuntimeError, 'no REPLY but ' + `mtype` raise RuntimeError, 'no REPLY but %r' % (mtype,)
stat = self.unpack_enum() stat = self.unpack_enum()
if stat == MSG_DENIED: if stat == MSG_DENIED:
stat = self.unpack_enum() stat = self.unpack_enum()
@ -117,15 +117,15 @@ class Unpacker(xdr.Unpacker):
low = self.unpack_uint() low = self.unpack_uint()
high = self.unpack_uint() high = self.unpack_uint()
raise RuntimeError, \ raise RuntimeError, \
'MSG_DENIED: RPC_MISMATCH: ' + `low, high` 'MSG_DENIED: RPC_MISMATCH: %r' % ((low, high),)
if stat == AUTH_ERROR: if stat == AUTH_ERROR:
stat = self.unpack_uint() stat = self.unpack_uint()
raise RuntimeError, \ raise RuntimeError, \
'MSG_DENIED: AUTH_ERROR: ' + `stat` 'MSG_DENIED: AUTH_ERROR: %r' % (stat,)
raise RuntimeError, 'MSG_DENIED: ' + `stat` raise RuntimeError, 'MSG_DENIED: %r' % (stat,)
if stat <> MSG_ACCEPTED: if stat <> MSG_ACCEPTED:
raise RuntimeError, \ raise RuntimeError, \
'Neither MSG_DENIED nor MSG_ACCEPTED: ' + `stat` 'Neither MSG_DENIED nor MSG_ACCEPTED: %r' % (stat,)
verf = self.unpack_auth() verf = self.unpack_auth()
stat = self.unpack_enum() stat = self.unpack_enum()
if stat == PROG_UNAVAIL: if stat == PROG_UNAVAIL:
@ -134,13 +134,13 @@ class Unpacker(xdr.Unpacker):
low = self.unpack_uint() low = self.unpack_uint()
high = self.unpack_uint() high = self.unpack_uint()
raise RuntimeError, \ raise RuntimeError, \
'call failed: PROG_MISMATCH: ' + `low, high` 'call failed: PROG_MISMATCH: %r' % ((low, high),)
if stat == PROC_UNAVAIL: if stat == PROC_UNAVAIL:
raise RuntimeError, 'call failed: PROC_UNAVAIL' raise RuntimeError, 'call failed: PROC_UNAVAIL'
if stat == GARBAGE_ARGS: if stat == GARBAGE_ARGS:
raise RuntimeError, 'call failed: GARBAGE_ARGS' raise RuntimeError, 'call failed: GARBAGE_ARGS'
if stat <> SUCCESS: if stat <> SUCCESS:
raise RuntimeError, 'call failed: ' + `stat` raise RuntimeError, 'call failed: %r' % (stat,)
return xid, verf return xid, verf
# Caller must get procedure-specific part of reply # Caller must get procedure-specific part of reply
@ -350,8 +350,8 @@ class RawTCPClient(Client):
xid, verf = u.unpack_replyheader() xid, verf = u.unpack_replyheader()
if xid <> self.lastxid: if xid <> self.lastxid:
# Can't really happen since this is TCP... # Can't really happen since this is TCP...
raise RuntimeError, 'wrong xid in reply ' + `xid` + \ raise RuntimeError, 'wrong xid in reply %r instead of %r' % (
' instead of ' + `self.lastxid` xid, self.lastxid)
# Client using UDP to a specific port # Client using UDP to a specific port
@ -701,7 +701,7 @@ class Server:
self.packer.pack_uint(self.vers) self.packer.pack_uint(self.vers)
return self.packer.get_buf() return self.packer.get_buf()
proc = self.unpacker.unpack_uint() proc = self.unpacker.unpack_uint()
methname = 'handle_' + `proc` methname = 'handle_' + repr(proc)
try: try:
meth = getattr(self, methname) meth = getattr(self, methname)
except AttributeError: except AttributeError:
@ -840,7 +840,7 @@ def testbcast():
bcastaddr = '<broadcast>' bcastaddr = '<broadcast>'
def rh(reply, fromaddr): def rh(reply, fromaddr):
host, port = fromaddr host, port = fromaddr
print host + '\t' + `reply` print host + '\t' + repr(reply)
pmap = BroadcastUDPPortMapperClient(bcastaddr) pmap = BroadcastUDPPortMapperClient(bcastaddr)
pmap.set_reply_handler(rh) pmap.set_reply_handler(rh)
pmap.set_timeout(5) pmap.set_timeout(5)
@ -858,7 +858,7 @@ def testsvr():
def handle_1(self): def handle_1(self):
arg = self.unpacker.unpack_string() arg = self.unpacker.unpack_string()
self.turn_around() self.turn_around()
print 'RPC function 1 called, arg', `arg` print 'RPC function 1 called, arg', repr(arg)
self.packer.pack_string(arg + arg) self.packer.pack_string(arg + arg)
# #
s = S('', 0x20000000, 1, 0) s = S('', 0x20000000, 1, 0)
@ -888,4 +888,4 @@ def testclt():
c = C(host, 0x20000000, 1) c = C(host, 0x20000000, 1)
print 'making call...' print 'making call...'
reply = c.call_1('hello, world, ') reply = c.call_1('hello, world, ')
print 'call returned', `reply` print 'call returned', repr(reply)

View file

@ -184,8 +184,7 @@ class Unpacker:
x = self.unpack_uint() x = self.unpack_uint()
if x == 0: break if x == 0: break
if x <> 1: if x <> 1:
raise RuntimeError, \ raise RuntimeError, '0 or 1 expected, got %r' % (x, )
'0 or 1 expected, got ' + `x`
item = unpack_item() item = unpack_item()
list.append(item) list.append(item)
return list return list

View file

@ -58,12 +58,12 @@ def ispython(name):
return ispythonprog.match(name) >= 0 return ispythonprog.match(name) >= 0
def recursedown(dirname): def recursedown(dirname):
dbg('recursedown(' + `dirname` + ')\n') dbg('recursedown(%r)\n' % (dirname,))
bad = 0 bad = 0
try: try:
names = os.listdir(dirname) names = os.listdir(dirname)
except os.error, msg: except os.error, msg:
err(dirname + ': cannot list directory: ' + `msg` + '\n') err('%s: cannot list directory: %r\n' % (dirname, msg))
return 1 return 1
names.sort() names.sort()
subdirs = [] subdirs = []
@ -80,11 +80,11 @@ def recursedown(dirname):
return bad return bad
def fix(filename): def fix(filename):
## dbg('fix(' + `filename` + ')\n') ## dbg('fix(%r)\n' % (dirname,))
try: try:
f = open(filename, 'r') f = open(filename, 'r')
except IOError, msg: except IOError, msg:
err(filename + ': cannot open: ' + `msg` + '\n') err('%s: cannot open: %r\n' % (filename, msg))
return 1 return 1
head, tail = os.path.split(filename) head, tail = os.path.split(filename)
tempname = os.path.join(head, '@' + tail) tempname = os.path.join(head, '@' + tail)
@ -122,14 +122,13 @@ def fix(filename):
g = open(tempname, 'w') g = open(tempname, 'w')
except IOError, msg: except IOError, msg:
f.close() f.close()
err(tempname+': cannot create: '+\ err('%s: cannot create: %r\n' % (tempname, msg))
`msg`+'\n')
return 1 return 1
f.seek(0) f.seek(0)
lineno = 0 lineno = 0
rep(filename + ':\n') rep(filename + ':\n')
continue # restart from the beginning continue # restart from the beginning
rep(`lineno` + '\n') rep(repr(lineno) + '\n')
rep('< ' + line) rep('< ' + line)
rep('> ' + newline) rep('> ' + newline)
if g is not None: if g is not None:
@ -146,17 +145,17 @@ def fix(filename):
statbuf = os.stat(filename) statbuf = os.stat(filename)
os.chmod(tempname, statbuf[ST_MODE] & 07777) os.chmod(tempname, statbuf[ST_MODE] & 07777)
except os.error, msg: except os.error, msg:
err(tempname + ': warning: chmod failed (' + `msg` + ')\n') err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
# Then make a backup of the original file as filename~ # Then make a backup of the original file as filename~
try: try:
os.rename(filename, filename + '~') os.rename(filename, filename + '~')
except os.error, msg: except os.error, msg:
err(filename + ': warning: backup failed (' + `msg` + ')\n') err('%s: warning: backup failed (%r)\n' % (filename, msg))
# Now move the temp file to the original file # Now move the temp file to the original file
try: try:
os.rename(tempname, filename) os.rename(tempname, filename)
except os.error, msg: except os.error, msg:
err(filename + ': rename failed (' + `msg` + ')\n') err('%s: rename failed (%r)\n' % (filename, msg))
return 1 return 1
# Return succes # Return succes
return 0 return 0

View file

@ -31,5 +31,5 @@ while 1:
if not line or line == '\n': if not line or line == '\n':
break break
if line.startswith('Subject: '): if line.startswith('Subject: '):
print `line[9:-1]`, print repr(line[9:-1]),
print print

View file

@ -60,7 +60,7 @@ def main():
if search and string.find(line, search) < 0: if search and string.find(line, search) < 0:
continue continue
if prog.match(line) < 0: if prog.match(line) < 0:
print 'Bad line', lineno, ':', `line` print 'Bad line', lineno, ':', repr(line)
continue continue
items = prog.group(1, 2, 3, 4, 5, 6) items = prog.group(1, 2, 3, 4, 5, 6)
(logtime, loguser, loghost, logfile, logbytes, (logtime, loguser, loghost, logfile, logbytes,

View file

@ -83,24 +83,24 @@ def makestatus(name, thisuser):
lines.append(line) lines.append(line)
# #
if totaljobs: if totaljobs:
line = `(totalbytes+1023)/1024` + ' K' line = '%d K' % ((totalbytes+1023)/1024)
if totaljobs <> len(users): if totaljobs <> len(users):
line = line + ' (' + `totaljobs` + ' jobs)' line = line + ' (%d jobs)' % totaljobs
if len(users) == 1: if len(users) == 1:
line = line + ' for ' + users.keys()[0] line = line + ' for %s' % (users.keys()[0],)
else: else:
line = line + ' for ' + `len(users)` + ' users' line = line + ' for %d users' % len(users)
if userseen: if userseen:
if aheadjobs == 0: if aheadjobs == 0:
line = line + ' (' + thisuser + ' first)' line = line + ' (%s first)' % thisuser
else: else:
line = line + ' (' + `(aheadbytes+1023)/1024` line = line + ' (%d K before %s)' % (
line = line + ' K before ' + thisuser + ')' (aheadbytes+1023)/1024, thisuser)
lines.append(line) lines.append(line)
# #
sts = pipe.close() sts = pipe.close()
if sts: if sts:
lines.append('lpq exit status ' + `sts`) lines.append('lpq exit status %r' % (sts,))
return string.joinfields(lines, ': ') return string.joinfields(lines, ': ')
try: try:

View file

@ -89,8 +89,8 @@ def test():
if debug > 1: if debug > 1:
for key in m.trans.keys(): for key in m.trans.keys():
if key is None or len(key) < histsize: if key is None or len(key) < histsize:
print `key`, m.trans[key] print repr(key), m.trans[key]
if histsize == 0: print `''`, m.trans[''] if histsize == 0: print repr(''), m.trans['']
print print
while 1: while 1:
data = m.get() data = m.get()

View file

@ -73,7 +73,7 @@ def mmdf(f):
sts = message(f, line) or sts sts = message(f, line) or sts
else: else:
sys.stderr.write( sys.stderr.write(
'Bad line in MMFD mailbox: %s\n' % `line`) 'Bad line in MMFD mailbox: %r\n' % (line,))
return sts return sts
counter = 0 # for generating unique Message-ID headers counter = 0 # for generating unique Message-ID headers
@ -89,7 +89,7 @@ def message(f, delimiter = ''):
t = time.mktime(tt) t = time.mktime(tt)
else: else:
sys.stderr.write( sys.stderr.write(
'Unparseable date: %s\n' % `m.getheader('Date')`) 'Unparseable date: %r\n' % (m.getheader('Date'),))
t = os.fstat(f.fileno())[stat.ST_MTIME] t = os.fstat(f.fileno())[stat.ST_MTIME]
print 'From', email, time.ctime(t) print 'From', email, time.ctime(t)
# Copy RFC822 header # Copy RFC822 header

View file

@ -12,13 +12,13 @@ def main():
rcstree = 'RCStree' rcstree = 'RCStree'
rcs = 'RCS' rcs = 'RCS'
if os.path.islink(rcs): if os.path.islink(rcs):
print `rcs`, 'is a symlink to', `os.readlink(rcs)` print '%r is a symlink to %r' % (rcs, os.readlink(rcs))
return return
if os.path.isdir(rcs): if os.path.isdir(rcs):
print `rcs`, 'is an ordinary directory' print '%r is an ordinary directory' % (rcs,)
return return
if os.path.exists(rcs): if os.path.exists(rcs):
print `rcs`, 'is a file?!?!' print '%r is a file?!?!' % (rcs,)
return return
# #
p = os.getcwd() p = os.getcwd()
@ -29,26 +29,26 @@ def main():
# (2) up is the same directory as p # (2) up is the same directory as p
# Ergo: # Ergo:
# (3) join(up, down) is the current directory # (3) join(up, down) is the current directory
#print 'p =', `p` #print 'p =', repr(p)
while not os.path.isdir(os.path.join(p, rcstree)): while not os.path.isdir(os.path.join(p, rcstree)):
head, tail = os.path.split(p) head, tail = os.path.split(p)
#print 'head =', `head`, '; tail =', `tail` #print 'head = %r; tail = %r' % (head, tail)
if not tail: if not tail:
print 'Sorry, no ancestor dir contains', `rcstree` print 'Sorry, no ancestor dir contains %r' % (rcstree,)
return return
p = head p = head
up = os.path.join(os.pardir, up) up = os.path.join(os.pardir, up)
down = os.path.join(tail, down) down = os.path.join(tail, down)
#print 'p =', `p`, '; up =', `up`, '; down =', `down` #print 'p = %r; up = %r; down = %r' % (p, up, down)
there = os.path.join(up, rcstree) there = os.path.join(up, rcstree)
there = os.path.join(there, down) there = os.path.join(there, down)
there = os.path.join(there, rcs) there = os.path.join(there, rcs)
if os.path.isdir(there): if os.path.isdir(there):
print `there`, 'already exists' print '%r already exists' % (there, )
else: else:
print 'making', `there` print 'making %r' % (there,)
makedirs(there) makedirs(there)
print 'making symlink', `rcs`, '->', `there` print 'making symlink %r -> %r' % (rcs, there)
os.symlink(there, rcs) os.symlink(there, rcs)
def makedirs(p): def makedirs(p):

View file

@ -27,7 +27,7 @@ def main():
def output(d): def output(d):
# Use write() to avoid spaces between the digits # Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit # Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`) sys.stdout.write(repr(int(d)))
# Flush so the output is seen immediately # Flush so the output is seen immediately
sys.stdout.flush() sys.stdout.flush()

View file

@ -304,7 +304,7 @@ def getallgroups(server):
def getnewgroups(server, treedate): def getnewgroups(server, treedate):
print 'Getting list of new groups since start of '+treedate+'...', print 'Getting list of new groups since start of '+treedate+'...',
info = server.newgroups(treedate,'000001')[1] info = server.newgroups(treedate,'000001')[1]
print 'got '+`len(info)`+'.' print 'got %d.' % len(info)
print 'Processing...', print 'Processing...',
groups = [] groups = []
for i in info: for i in info:

View file

@ -125,6 +125,6 @@ fp.write(program)
fp.flush() fp.flush()
if DFLAG: if DFLAG:
import pdb import pdb
pdb.run('execfile(' + `tfn` + ')') pdb.run('execfile(%r)' % (tfn,))
else: else:
execfile(tfn) execfile(tfn)

View file

@ -10,7 +10,7 @@ s.bind(('', 0))
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
while 1: while 1:
data = `time.time()` + '\n' data = repr(time.time()) + '\n'
s.sendto(data, ('<broadcast>', MYPORT)) s.sendto(data, ('<broadcast>', MYPORT))
time.sleep(2) time.sleep(2)

View file

@ -91,7 +91,7 @@ def sendportcmd(s, f, port):
hostname = gethostname() hostname = gethostname()
hostaddr = gethostbyname(hostname) hostaddr = gethostbyname(hostname)
hbytes = string.splitfields(hostaddr, '.') hbytes = string.splitfields(hostaddr, '.')
pbytes = [`port/256`, `port%256`] pbytes = [repr(port/256), repr(port%256)]
bytes = hbytes + pbytes bytes = hbytes + pbytes
cmd = 'PORT ' + string.joinfields(bytes, ',') cmd = 'PORT ' + string.joinfields(bytes, ',')
s.send(cmd + '\r\n') s.send(cmd + '\r\n')

View file

@ -75,10 +75,10 @@ def get_menu(selector, host, port):
typechar = line[0] typechar = line[0]
parts = string.splitfields(line[1:], TAB) parts = string.splitfields(line[1:], TAB)
if len(parts) < 4: if len(parts) < 4:
print '(Bad line from server:', `line`, ')' print '(Bad line from server: %r)' % (line,)
continue continue
if len(parts) > 4: if len(parts) > 4:
print '(Extra info from server:', parts[4:], ')' print '(Extra info from server: %r)' % (parts[4:],)
parts.insert(0, typechar) parts.insert(0, typechar)
list.append(parts) list.append(parts)
f.close() f.close()
@ -154,17 +154,17 @@ def browse_menu(selector, host, port):
list = get_menu(selector, host, port) list = get_menu(selector, host, port)
while 1: while 1:
print '----- MENU -----' print '----- MENU -----'
print 'Selector:', `selector` print 'Selector:', repr(selector)
print 'Host:', host, ' Port:', port print 'Host:', host, ' Port:', port
print print
for i in range(len(list)): for i in range(len(list)):
item = list[i] item = list[i]
typechar, description = item[0], item[1] typechar, description = item[0], item[1]
print string.rjust(`i+1`, 3) + ':', description, print string.rjust(repr(i+1), 3) + ':', description,
if typename.has_key(typechar): if typename.has_key(typechar):
print typename[typechar] print typename[typechar]
else: else:
print '<TYPE=' + `typechar` + '>' print '<TYPE=' + repr(typechar) + '>'
print print
while 1: while 1:
try: try:
@ -221,7 +221,7 @@ def browse_textfile(selector, host, port):
def browse_search(selector, host, port): def browse_search(selector, host, port):
while 1: while 1:
print '----- SEARCH -----' print '----- SEARCH -----'
print 'Selector:', `selector` print 'Selector:', repr(selector)
print 'Host:', host, ' Port:', port print 'Host:', host, ' Port:', port
print print
try: try:
@ -240,9 +240,9 @@ def browse_search(selector, host, port):
# "Browse" telnet-based information, i.e. open a telnet session # "Browse" telnet-based information, i.e. open a telnet session
def browse_telnet(selector, host, port): def browse_telnet(selector, host, port):
if selector: if selector:
print 'Log in as', `selector` print 'Log in as', repr(selector)
if type(port) <> type(''): if type(port) <> type(''):
port = `port` port = repr(port)
sts = os.system('set -x; exec telnet ' + host + ' ' + port) sts = os.system('set -x; exec telnet ' + host + ' ' + port)
if sts: if sts:
print 'Exit status:', sts print 'Exit status:', sts
@ -307,18 +307,18 @@ def open_savefile():
try: try:
p = os.popen(cmd, 'w') p = os.popen(cmd, 'w')
except IOError, msg: except IOError, msg:
print `cmd`, ':', msg print repr(cmd), ':', msg
return None return None
print 'Piping through', `cmd`, '...' print 'Piping through', repr(cmd), '...'
return p return p
if savefile[0] == '~': if savefile[0] == '~':
savefile = os.path.expanduser(savefile) savefile = os.path.expanduser(savefile)
try: try:
f = open(savefile, 'w') f = open(savefile, 'w')
except IOError, msg: except IOError, msg:
print `savefile`, ':', msg print repr(savefile), ':', msg
return None return None
print 'Saving to', `savefile`, '...' print 'Saving to', repr(savefile), '...'
return f return f
# Test program # Test program

View file

@ -38,7 +38,7 @@ def sender(flag):
ttl = struct.pack('b', 1) # Time-to-live ttl = struct.pack('b', 1) # Time-to-live
s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl) s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
while 1: while 1:
data = `time.time()` data = repr(time.time())
## data = data + (1400 - len(data)) * '\0' ## data = data + (1400 - len(data)) * '\0'
s.sendto(data, (mygroup, MYPORT)) s.sendto(data, (mygroup, MYPORT))
time.sleep(1) time.sleep(1)
@ -53,7 +53,7 @@ def receiver():
while 1: while 1:
data, sender = s.recvfrom(1500) data, sender = s.recvfrom(1500)
while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
print sender, ':', `data` print sender, ':', repr(data)
# Open a UDP socket, bind it to a port and select a multicast group # Open a UDP socket, bind it to a port and select a multicast group

View file

@ -10,5 +10,5 @@ s.bind(('', MYPORT))
while 1: while 1:
data, wherefrom = s.recvfrom(1500, 0) data, wherefrom = s.recvfrom(1500, 0)
sys.stderr.write(`wherefrom` + '\n') sys.stderr.write(repr(wherefrom) + '\n')
sys.stdout.write(data) sys.stdout.write(data)

View file

@ -53,7 +53,7 @@ def main():
try: try:
s.connect((host, port)) s.connect((host, port))
except error, msg: except error, msg:
sys.stderr.write('connect failed: ' + `msg` + '\n') sys.stderr.write('connect failed: ' + repr(msg) + '\n')
sys.exit(1) sys.exit(1)
# #
pid = posix.fork() pid = posix.fork()

View file

@ -37,7 +37,7 @@ def server():
print 'udp echo server ready' print 'udp echo server ready'
while 1: while 1:
data, addr = s.recvfrom(BUFSIZE) data, addr = s.recvfrom(BUFSIZE)
print 'server received', `data`, 'from', `addr` print 'server received %r from %r' % (data, addr)
s.sendto(data, addr) s.sendto(data, addr)
def client(): def client():
@ -58,6 +58,6 @@ def client():
break break
s.sendto(line, addr) s.sendto(line, addr)
data, fromaddr = s.recvfrom(BUFSIZE) data, fromaddr = s.recvfrom(BUFSIZE)
print 'client received', `data`, 'from', `fromaddr` print 'client received %r from %r' % (data, fromaddr)
main() main()

View file

@ -9,7 +9,7 @@ s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', 0)) s.bind(('', 0))
while 1: while 1:
data = `time.time()` + '\n' data = repr(time.time()) + '\n'
s.sendto(data, ('', MYPORT)) s.sendto(data, ('', MYPORT))
time.sleep(2) time.sleep(2)

View file

@ -7,4 +7,4 @@ s.connect(FILE)
s.send('Hello, world') s.send('Hello, world')
data = s.recv(1024) data = s.recv(1024)
s.close() s.close()
print 'Received', `data` print 'Received', repr(data)

View file

@ -138,10 +138,9 @@ class Coroutine:
def tran(self, target, data=None): def tran(self, target, data=None):
if not self.invokedby.has_key(target): if not self.invokedby.has_key(target):
raise TypeError, '.tran target ' + `target` + \ raise TypeError, '.tran target %r is not an active coroutine' % (target,)
' is not an active coroutine'
if self.killed: if self.killed:
raise TypeError, '.tran target ' + `target` + ' is killed' raise TypeError, '.tran target %r is killed' % (target,)
self.value = data self.value = data
me = self.active me = self.active
self.invokedby[target] = me self.invokedby[target] = me
@ -153,7 +152,7 @@ class Coroutine:
if self.main is not me: if self.main is not me:
raise Killed raise Killed
if self.terminated_by is not None: if self.terminated_by is not None:
raise EarlyExit, `self.terminated_by` + ' terminated early' raise EarlyExit, '%r terminated early' % (self.terminated_by,)
return self.value return self.value

View file

@ -116,7 +116,7 @@ def main():
wq.run(nworkers) wq.run(nworkers)
t2 = time.time() t2 = time.time()
sys.stderr.write('Total time ' + `t2-t1` + ' sec.\n') sys.stderr.write('Total time %r sec.\n' % (t2-t1))
# The predicate -- defines what files we look for. # The predicate -- defines what files we look for.
@ -133,7 +133,7 @@ def find(dir, pred, wq):
try: try:
names = os.listdir(dir) names = os.listdir(dir)
except os.error, msg: except os.error, msg:
print `dir`, ':', msg print repr(dir), ':', msg
return return
for name in names: for name in names:
if name not in (os.curdir, os.pardir): if name not in (os.curdir, os.pardir):
@ -141,7 +141,7 @@ def find(dir, pred, wq):
try: try:
stat = os.lstat(fullname) stat = os.lstat(fullname)
except os.error, msg: except os.error, msg:
print `fullname`, ':', msg print repr(fullname), ':', msg
continue continue
if pred(dir, name, fullname, stat): if pred(dir, name, fullname, stat):
print fullname print fullname

View file

@ -336,7 +336,7 @@ class condition:
def broadcast(self, num = -1): def broadcast(self, num = -1):
if num < -1: if num < -1:
raise ValueError, '.broadcast called with num ' + `num` raise ValueError, '.broadcast called with num %r' % (num,)
if num == 0: if num == 0:
return return
self.idlock.acquire() self.idlock.acquire()
@ -418,7 +418,7 @@ class semaphore:
self.nonzero.acquire() self.nonzero.acquire()
if self.count == self.maxcount: if self.count == self.maxcount:
raise ValueError, '.v() tried to raise semaphore count above ' \ raise ValueError, '.v() tried to raise semaphore count above ' \
'initial value ' + `maxcount` 'initial value %r' % (maxcount,))
self.count = self.count + 1 self.count = self.count + 1
self.nonzero.signal() self.nonzero.signal()
self.nonzero.release() self.nonzero.release()

View file

@ -57,7 +57,7 @@ def main():
try: try:
s.connect((host, port)) s.connect((host, port))
except error, msg: except error, msg:
sys.stderr.write('connect failed: ' + `msg` + '\n') sys.stderr.write('connect failed: %r\n' % (msg,))
sys.exit(1) sys.exit(1)
# #
thread.start_new(child, (s,)) thread.start_new(child, (s,))
@ -77,7 +77,7 @@ def parent(s):
for c in data: for c in data:
if opt: if opt:
print ord(c) print ord(c)
## print '(replying: ' + `opt+c` + ')' ## print '(replying: %r)' % (opt+c,)
s.send(opt + c) s.send(opt + c)
opt = '' opt = ''
elif iac: elif iac:
@ -101,13 +101,13 @@ def parent(s):
cleandata = cleandata + c cleandata = cleandata + c
sys.stdout.write(cleandata) sys.stdout.write(cleandata)
sys.stdout.flush() sys.stdout.flush()
## print 'Out:', `cleandata` ## print 'Out:', repr(cleandata)
def child(s): def child(s):
# read stdin, write socket # read stdin, write socket
while 1: while 1:
line = sys.stdin.readline() line = sys.stdin.readline()
## print 'Got:', `line` ## print 'Got:', repr(line)
if not line: break if not line: break
s.send(line) s.send(line)

View file

@ -75,7 +75,7 @@ class DemoDirList:
top.btn['command'] = lambda dir=top.dir, ent=top.ent, self=self: \ top.btn['command'] = lambda dir=top.dir, ent=top.ent, self=self: \
self.copy_name(dir,ent) self.copy_name(dir,ent)
# top.ent.entry.insert(0,'tix'+`self`) # top.ent.entry.insert(0,'tix'+repr(self))
top.ent.entry.bind('<Return>', lambda self=self: self.okcmd () ) top.ent.entry.bind('<Return>', lambda self=self: self.okcmd () )
top.pack( expand='yes', fill='both', side=TOP) top.pack( expand='yes', fill='both', side=TOP)

View file

@ -253,7 +253,7 @@ def refile_message(e=None):
def fixfocus(near, itop): def fixfocus(near, itop):
n = scanbox.size() n = scanbox.size()
for i in range(n): for i in range(n):
line = scanbox.get(`i`) line = scanbox.get(repr(i))
if scanparser.match(line) >= 0: if scanparser.match(line) >= 0:
num = string.atoi(scanparser.group(1)) num = string.atoi(scanparser.group(1))
if num >= near: if num >= near:

View file

@ -183,7 +183,7 @@ class Card:
def __repr__(self): def __repr__(self):
"""Return a string for debug print statements.""" """Return a string for debug print statements."""
return "Card(%s, %s)" % (`self.suit`, `self.value`) return "Card(%r, %r)" % (self.suit, self.value)
def moveto(self, x, y): def moveto(self, x, y):
"""Move the card to absolute position (x, y).""" """Move the card to absolute position (x, y)."""

View file

@ -28,7 +28,7 @@ class Test(Frame):
def moveThing(self, *args): def moveThing(self, *args):
velocity = self.speed.get() velocity = self.speed.get()
str = float(velocity) / 1000.0 str = float(velocity) / 1000.0
str = `str` + "i" str = "%ri" % (str,)
self.draw.move("thing", str, str) self.draw.move("thing", str, str)
self.after(10, self.moveThing) self.after(10, self.moveThing)

View file

@ -39,7 +39,7 @@ class Pong(Frame):
self.x = self.x + deltax self.x = self.x + deltax
self.y = self.y + deltay self.y = self.y + deltay
self.draw.move(self.ball, `deltax` + "i", `deltay` + "i") self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay)
self.after(10, self.moveBall) self.after(10, self.moveBall)
def __init__(self, master=None): def __init__(self, master=None):

View file

@ -47,10 +47,10 @@ if __name__ == "__main__":
print "not ok: no conflict between -h and -H" print "not ok: no conflict between -h and -H"
parser.add_option("-f", "--file", dest="file") parser.add_option("-f", "--file", dest="file")
#print `parser.get_option("-f")` #print repr(parser.get_option("-f"))
#print `parser.get_option("-F")` #print repr(parser.get_option("-F"))
#print `parser.get_option("--file")` #print repr(parser.get_option("--file"))
#print `parser.get_option("--fIlE")` #print repr(parser.get_option("--fIlE"))
(options, args) = parser.parse_args(["--FiLe", "foo"]) (options, args) = parser.parse_args(["--FiLe", "foo"])
assert options.file == "foo", options.file assert options.file == "foo", options.file
print "ok: case insensitive long options work" print "ok: case insensitive long options work"

View file

@ -78,4 +78,4 @@ class RepositoryInfo:
return fn[len(self.cvsroot_path)+1:] return fn[len(self.cvsroot_path)+1:]
def __repr__(self): def __repr__(self):
return "<RepositoryInfo for %s>" % `self.get_cvsroot()` return "<RepositoryInfo for %r>" % self.get_cvsroot()

View file

@ -32,7 +32,7 @@ def loadfile(fp):
continue continue
parts = line.split(":", 4) parts = line.split(":", 4)
if len(parts) != 5: if len(parts) != 5:
raise ValueError("Not enough fields in " + `line`) raise ValueError("Not enough fields in %r" % line)
function, type, arg, refcount, comment = parts function, type, arg, refcount, comment = parts
if refcount == "null": if refcount == "null":
refcount = None refcount = None

View file

@ -29,7 +29,7 @@ def decode(s):
n, s = s.split(";", 1) n, s = s.split(";", 1)
r = r + unichr(int(n)) r = r + unichr(int(n))
else: else:
raise ValueError, "can't handle " + `s` raise ValueError, "can't handle %r" % s
return r return r
@ -220,8 +220,8 @@ class ESISReader(xml.sax.xmlreader.XMLReader):
return self._decl_handler return self._decl_handler
else: else:
raise xml.sax.SAXNotRecognizedException("unknown property %s" raise xml.sax.SAXNotRecognizedException("unknown property %r"
% `property`) % (property, ))
def setProperty(self, property, value): def setProperty(self, property, value):
if property == xml.sax.handler.property_lexical_handler: if property == xml.sax.handler.property_lexical_handler:

View file

@ -73,8 +73,8 @@ def popping(name, point, depth):
class _Stack(list): class _Stack(list):
def append(self, entry): def append(self, entry):
if not isinstance(entry, str): if not isinstance(entry, str):
raise LaTeXFormatError("cannot push non-string on stack: " raise LaTeXFormatError("cannot push non-string on stack: %r"
+ `entry`) % (entry, ))
#dbgmsg("%s<%s>" % (" "*len(self.data), entry)) #dbgmsg("%s<%s>" % (" "*len(self.data), entry))
list.append(self, entry) list.append(self, entry)
@ -208,8 +208,8 @@ class Conversion:
m = _parameter_rx.match(line) m = _parameter_rx.match(line)
if not m: if not m:
raise LaTeXFormatError( raise LaTeXFormatError(
"could not extract parameter %s for %s: %s" "could not extract parameter %s for %s: %r"
% (pentry.name, macroname, `line[:100]`)) % (pentry.name, macroname, line[:100]))
if entry.outputname: if entry.outputname:
self.dump_attr(pentry, m.group(1)) self.dump_attr(pentry, m.group(1))
line = line[m.end():] line = line[m.end():]
@ -259,7 +259,7 @@ class Conversion:
opened = 1 opened = 1
stack.append(entry.name) stack.append(entry.name)
self.write("(%s\n" % entry.outputname) self.write("(%s\n" % entry.outputname)
#dbgmsg("--- text: %s" % `pentry.text`) #dbgmsg("--- text: %r" % pentry.text)
self.write("-%s\n" % encode(pentry.text)) self.write("-%s\n" % encode(pentry.text))
elif pentry.type == "entityref": elif pentry.type == "entityref":
self.write("&%s\n" % pentry.name) self.write("&%s\n" % pentry.name)
@ -326,8 +326,8 @@ class Conversion:
extra = "" extra = ""
if len(line) > 100: if len(line) > 100:
extra = "..." extra = "..."
raise LaTeXFormatError("could not identify markup: %s%s" raise LaTeXFormatError("could not identify markup: %r%s"
% (`line[:100]`, extra)) % (line[:100], extra))
while stack: while stack:
entry = self.get_entry(stack[-1]) entry = self.get_entry(stack[-1])
if entry.closes: if entry.closes:
@ -361,7 +361,7 @@ class Conversion:
def get_entry(self, name): def get_entry(self, name):
entry = self.table.get(name) entry = self.table.get(name)
if entry is None: if entry is None:
dbgmsg("get_entry(%s) failing; building default entry!" % `name`) dbgmsg("get_entry(%r) failing; building default entry!" % (name, ))
# not defined; build a default entry: # not defined; build a default entry:
entry = TableEntry(name) entry = TableEntry(name)
entry.has_content = 1 entry.has_content = 1
@ -486,7 +486,7 @@ class TableHandler(xml.sax.handler.ContentHandler):
def end_macro(self): def end_macro(self):
name = self.__current.name name = self.__current.name
if self.__table.has_key(name): if self.__table.has_key(name):
raise ValueError("name %s already in use" % `name`) raise ValueError("name %r already in use" % (name,))
self.__table[name] = self.__current self.__table[name] = self.__current
self.__current = None self.__current = None

View file

@ -238,7 +238,7 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
if len(words) == 3: if len(words) == 3:
[command, path, version] = words [command, path, version] = words
if version[:5] != 'HTTP/': if version[:5] != 'HTTP/':
self.send_error(400, "Bad request version (%s)" % `version`) self.send_error(400, "Bad request version (%r)" % version)
return False return False
try: try:
base_version_number = version.split('/', 1)[1] base_version_number = version.split('/', 1)[1]
@ -253,7 +253,7 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
raise ValueError raise ValueError
version_number = int(version_number[0]), int(version_number[1]) version_number = int(version_number[0]), int(version_number[1])
except (ValueError, IndexError): except (ValueError, IndexError):
self.send_error(400, "Bad request version (%s)" % `version`) self.send_error(400, "Bad request version (%r)" % version)
return False return False
if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1": if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
self.close_connection = 0 self.close_connection = 0
@ -266,12 +266,12 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
self.close_connection = 1 self.close_connection = 1
if command != 'GET': if command != 'GET':
self.send_error(400, self.send_error(400,
"Bad HTTP/0.9 request type (%s)" % `command`) "Bad HTTP/0.9 request type (%r)" % command)
return False return False
elif not words: elif not words:
return False return False
else: else:
self.send_error(400, "Bad request syntax (%s)" % `requestline`) self.send_error(400, "Bad request syntax (%r)" % requestline)
return False return False
self.command, self.path, self.request_version = command, path, version self.command, self.path, self.request_version = command, path, version
@ -302,7 +302,7 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
return return
mname = 'do_' + self.command mname = 'do_' + self.command
if not hasattr(self, mname): if not hasattr(self, mname):
self.send_error(501, "Unsupported method (%s)" % `self.command`) self.send_error(501, "Unsupported method (%r)" % self.command)
return return
method = getattr(self, mname) method = getattr(self, mname)
method() method()

View file

@ -124,7 +124,7 @@ def Bastion(object, filter = lambda name: name[:1] != '_',
return get1(name) return get1(name)
if name is None: if name is None:
name = `object` name = repr(object)
return bastionclass(get2, name) return bastionclass(get2, name)

View file

@ -117,21 +117,21 @@ class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
scriptname = dir + '/' + script scriptname = dir + '/' + script
scriptfile = self.translate_path(scriptname) scriptfile = self.translate_path(scriptname)
if not os.path.exists(scriptfile): if not os.path.exists(scriptfile):
self.send_error(404, "No such CGI script (%s)" % `scriptname`) self.send_error(404, "No such CGI script (%r)" % scriptname)
return return
if not os.path.isfile(scriptfile): if not os.path.isfile(scriptfile):
self.send_error(403, "CGI script is not a plain file (%s)" % self.send_error(403, "CGI script is not a plain file (%r)" %
`scriptname`) scriptname)
return return
ispy = self.is_python(scriptname) ispy = self.is_python(scriptname)
if not ispy: if not ispy:
if not (self.have_fork or self.have_popen2 or self.have_popen3): if not (self.have_fork or self.have_popen2 or self.have_popen3):
self.send_error(403, "CGI script is not a Python script (%s)" % self.send_error(403, "CGI script is not a Python script (%r)" %
`scriptname`) scriptname)
return return
if not self.is_executable(scriptfile): if not self.is_executable(scriptfile):
self.send_error(403, "CGI script is not executable (%s)" % self.send_error(403, "CGI script is not executable (%r)" %
`scriptname`) scriptname)
return return
# Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html

View file

@ -118,7 +118,7 @@ class NoSectionError(Error):
"""Raised when no section matches a requested option.""" """Raised when no section matches a requested option."""
def __init__(self, section): def __init__(self, section):
Error.__init__(self, 'No section: ' + `section`) Error.__init__(self, 'No section: %r' % (section,))
self.section = section self.section = section
class DuplicateSectionError(Error): class DuplicateSectionError(Error):
@ -191,7 +191,7 @@ class MissingSectionHeaderError(ParsingError):
def __init__(self, filename, lineno, line): def __init__(self, filename, lineno, line):
Error.__init__( Error.__init__(
self, self,
'File contains no section headers.\nfile: %s, line: %d\n%s' % 'File contains no section headers.\nfile: %s, line: %d\n%r' %
(filename, lineno, line)) (filename, lineno, line))
self.filename = filename self.filename = filename
self.lineno = lineno self.lineno = lineno
@ -453,7 +453,7 @@ class RawConfigParser:
optname = None optname = None
# no section header in the file? # no section header in the file?
elif cursect is None: elif cursect is None:
raise MissingSectionHeaderError(fpname, lineno, `line`) raise MissingSectionHeaderError(fpname, lineno, line)
# an option line? # an option line?
else: else:
mo = self.OPTCRE.match(line) mo = self.OPTCRE.match(line)
@ -478,7 +478,7 @@ class RawConfigParser:
# list of all bogus lines # list of all bogus lines
if not e: if not e:
e = ParsingError(fpname) e = ParsingError(fpname)
e.append(lineno, `line`) e.append(lineno, repr(line))
# if any parsing errors occurred, raise an exception # if any parsing errors occurred, raise an exception
if e: if e:
raise e raise e
@ -613,4 +613,4 @@ class SafeConfigParser(ConfigParser):
else: else:
raise InterpolationSyntaxError( raise InterpolationSyntaxError(
option, section, option, section,
"'%' must be followed by '%' or '(', found: " + `rest`) "'%%' must be followed by '%%' or '(', found: %r" % (rest,))

View file

@ -272,8 +272,8 @@ class HTMLParser(markupbase.ParserBase):
- self.__starttag_text.rfind("\n") - self.__starttag_text.rfind("\n")
else: else:
offset = offset + len(self.__starttag_text) offset = offset + len(self.__starttag_text)
self.error("junk characters in start tag: %s" self.error("junk characters in start tag: %r"
% `rawdata[k:endpos][:20]`) % (rawdata[k:endpos][:20],))
if end.endswith('/>'): if end.endswith('/>'):
# XHTML-style empty tag: <span attr="value" /> # XHTML-style empty tag: <span attr="value" />
self.handle_startendtag(tag, attrs) self.handle_startendtag(tag, attrs)
@ -324,7 +324,7 @@ class HTMLParser(markupbase.ParserBase):
j = match.end() j = match.end()
match = endtagfind.match(rawdata, i) # </ + tag + > match = endtagfind.match(rawdata, i) # </ + tag + >
if not match: if not match:
self.error("bad end tag: %s" % `rawdata[i:j]`) self.error("bad end tag: %r" % (rawdata[i:j],))
tag = match.group(1) tag = match.group(1)
self.handle_endtag(tag.lower()) self.handle_endtag(tag.lower())
self.clear_cdata_mode() self.clear_cdata_mode()
@ -368,7 +368,7 @@ class HTMLParser(markupbase.ParserBase):
pass pass
def unknown_decl(self, data): def unknown_decl(self, data):
self.error("unknown declaration: " + `data`) self.error("unknown declaration: %r" % (data,))
# Internal -- helper to remove special character quoting # Internal -- helper to remove special character quoting
def unescape(self, s): def unescape(self, s):

View file

@ -222,10 +222,10 @@ def test():
f.seek(len(lines[0])) f.seek(len(lines[0]))
f.write(lines[1]) f.write(lines[1])
f.seek(0) f.seek(0)
print 'First line =', `f.readline()` print 'First line =', repr(f.readline())
print 'Position =', f.tell() print 'Position =', f.tell()
line = f.readline() line = f.readline()
print 'Second line =', `line` print 'Second line =', repr(line)
f.seek(-len(line), 1) f.seek(-len(line), 1)
line2 = f.read(len(line)) line2 = f.read(len(line))
if line != line2: if line != line2:

View file

@ -392,7 +392,7 @@ class Aifc_read:
for marker in self._markers: for marker in self._markers:
if id == marker[0]: if id == marker[0]:
return marker return marker
raise Error, 'marker ' + `id` + ' does not exist' raise Error, 'marker %r does not exist' % (id,)
def setpos(self, pos): def setpos(self, pos):
if pos < 0 or pos > self._nframes: if pos < 0 or pos > self._nframes:
@ -697,7 +697,7 @@ class Aifc_write:
for marker in self._markers: for marker in self._markers:
if id == marker[0]: if id == marker[0]:
return marker return marker
raise Error, 'marker ' + `id` + ' does not exist' raise Error, 'marker %r does not exist' % (id,)
def getmarkers(self): def getmarkers(self):
if len(self._markers) == 0: if len(self._markers) == 0:

View file

@ -40,9 +40,9 @@ if __name__ == "__main__":
def x1(): def x1():
print "running x1" print "running x1"
def x2(n): def x2(n):
print "running x2(%s)" % `n` print "running x2(%r)" % (n,)
def x3(n, kwd=None): def x3(n, kwd=None):
print "running x3(%s, kwd=%s)" % (`n`, `kwd`) print "running x3(%r, kwd=%r)" % (n, kwd)
register(x1) register(x1)
register(x2, 12) register(x2, 12)

View file

@ -348,7 +348,7 @@ def test1():
s0 = "Aladdin:open sesame" s0 = "Aladdin:open sesame"
s1 = encodestring(s0) s1 = encodestring(s0)
s2 = decodestring(s1) s2 = decodestring(s1)
print s0, `s1`, s2 print s0, repr(s1), s2
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -52,7 +52,7 @@ class Bdb:
return self.dispatch_return(frame, arg) return self.dispatch_return(frame, arg)
if event == 'exception': if event == 'exception':
return self.dispatch_exception(frame, arg) return self.dispatch_exception(frame, arg)
print 'bdb.Bdb.dispatch: unknown debugging event:', `event` print 'bdb.Bdb.dispatch: unknown debugging event:', repr(event)
return self.trace_dispatch return self.trace_dispatch
def dispatch_line(self, frame): def dispatch_line(self, frame):
@ -311,7 +311,7 @@ class Bdb:
import linecache, repr import linecache, repr
frame, lineno = frame_lineno frame, lineno = frame_lineno
filename = self.canonic(frame.f_code.co_filename) filename = self.canonic(frame.f_code.co_filename)
s = filename + '(' + `lineno` + ')' s = '%s(%r)' % (filename, lineno)
if frame.f_code.co_name: if frame.f_code.co_name:
s = s + frame.f_code.co_name s = s + frame.f_code.co_name
else: else:

View file

@ -229,7 +229,7 @@ class BinHex:
def close_data(self): def close_data(self):
if self.dlen != 0: if self.dlen != 0:
raise Error, 'Incorrect data size, diff='+`self.rlen` raise Error, 'Incorrect data size, diff=%r' % (self.rlen,)
self._writecrc() self._writecrc()
self.state = _DID_DATA self.state = _DID_DATA
@ -248,7 +248,7 @@ class BinHex:
raise Error, 'Close at the wrong time' raise Error, 'Close at the wrong time'
if self.rlen != 0: if self.rlen != 0:
raise Error, \ raise Error, \
"Incorrect resource-datasize, diff="+`self.rlen` "Incorrect resource-datasize, diff=%r" % (self.rlen,)
self._writecrc() self._writecrc()
self.ofp.close() self.ofp.close()
self.state = None self.state = None

View file

@ -164,10 +164,10 @@ def _test():
f.seek(len(lines[0])) f.seek(len(lines[0]))
f.write(lines[1]) f.write(lines[1])
f.seek(0) f.seek(0)
print 'First line =', `f.readline()` print 'First line =', repr(f.readline())
here = f.tell() here = f.tell()
line = f.readline() line = f.readline()
print 'Second line =', `line` print 'Second line =', repr(line)
f.seek(-len(line), 1) f.seek(-len(line), 1)
line2 = f.read(len(line)) line2 = f.read(len(line))
if line != line2: if line != line2:

View file

@ -206,7 +206,7 @@ class bsdTableDB :
try: try:
key, data = cur.first() key, data = cur.first()
while 1: while 1:
print `{key: data}` print repr({key: data})
next = cur.next() next = cur.next()
if next: if next:
key, data = next key, data = next
@ -341,9 +341,9 @@ class bsdTableDB :
try: try:
tcolpickles = self.db.get(_columns_key(table)) tcolpickles = self.db.get(_columns_key(table))
except DBNotFoundError: except DBNotFoundError:
raise TableDBError, "unknown table: " + `table` raise TableDBError, "unknown table: %r" % (table,)
if not tcolpickles: if not tcolpickles:
raise TableDBError, "unknown table: " + `table` raise TableDBError, "unknown table: %r" % (table,)
self.__tablecolumns[table] = pickle.loads(tcolpickles) self.__tablecolumns[table] = pickle.loads(tcolpickles)
def __new_rowid(self, table, txn) : def __new_rowid(self, table, txn) :
@ -384,7 +384,7 @@ class bsdTableDB :
self.__load_column_info(table) self.__load_column_info(table)
for column in rowdict.keys() : for column in rowdict.keys() :
if not self.__tablecolumns[table].count(column): if not self.__tablecolumns[table].count(column):
raise TableDBError, "unknown column: "+`column` raise TableDBError, "unknown column: %r" % (column,)
# get a unique row identifier for this row # get a unique row identifier for this row
txn = self.env.txn_begin() txn = self.env.txn_begin()
@ -535,7 +535,7 @@ class bsdTableDB :
columns = self.tablecolumns[table] columns = self.tablecolumns[table]
for column in (columns + conditions.keys()): for column in (columns + conditions.keys()):
if not self.__tablecolumns[table].count(column): if not self.__tablecolumns[table].count(column):
raise TableDBError, "unknown column: "+`column` raise TableDBError, "unknown column: %r" % (column,)
# keyed on rows that match so far, containings dicts keyed on # keyed on rows that match so far, containings dicts keyed on
# column names containing the data for that row and column. # column names containing the data for that row and column.

View file

@ -200,7 +200,7 @@ class AssociateTestCase(unittest.TestCase):
def getGenre(self, priKey, priData): def getGenre(self, priKey, priData):
assert type(priData) == type("") assert type(priData) == type("")
if verbose: if verbose:
print 'getGenre key:', `priKey`, 'data:', `priData` print 'getGenre key: %r data: %r' % (priKey, priData)
genre = string.split(priData, '|')[2] genre = string.split(priData, '|')[2]
if genre == 'Blues': if genre == 'Blues':
return db.DB_DONOTINDEX return db.DB_DONOTINDEX
@ -242,7 +242,7 @@ class ShelveAssociateTestCase(AssociateTestCase):
def getGenre(self, priKey, priData): def getGenre(self, priKey, priData):
assert type(priData) == type(()) assert type(priData) == type(())
if verbose: if verbose:
print 'getGenre key:', `priKey`, 'data:', `priData` print 'getGenre key: %r data: %r' % (priKey, priData)
genre = priData[2] genre = priData[2]
if genre == 'Blues': if genre == 'Blues':
return db.DB_DONOTINDEX return db.DB_DONOTINDEX

View file

@ -361,7 +361,7 @@ class BasicTestCase(unittest.TestCase):
if set_raises_error: if set_raises_error:
self.fail("expected exception") self.fail("expected exception")
if n != None: if n != None:
self.fail("expected None: "+`n`) self.fail("expected None: %r" % (n,))
rec = c.get_both('0404', self.makeData('0404')) rec = c.get_both('0404', self.makeData('0404'))
assert rec == ('0404', self.makeData('0404')) assert rec == ('0404', self.makeData('0404'))
@ -375,7 +375,7 @@ class BasicTestCase(unittest.TestCase):
if get_raises_error: if get_raises_error:
self.fail("expected exception") self.fail("expected exception")
if n != None: if n != None:
self.fail("expected None: "+`n`) self.fail("expected None: %r" % (n,))
if self.d.get_type() == db.DB_BTREE: if self.d.get_type() == db.DB_BTREE:
rec = c.set_range('011') rec = c.set_range('011')
@ -548,7 +548,7 @@ class BasicTestCase(unittest.TestCase):
num = d.truncate() num = d.truncate()
assert num >= 1, "truncate returned <= 0 on non-empty database" assert num >= 1, "truncate returned <= 0 on non-empty database"
num = d.truncate() num = d.truncate()
assert num == 0, "truncate on empty DB returned nonzero (%s)" % `num` assert num == 0, "truncate on empty DB returned nonzero (%r)" % (num,)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@ -674,7 +674,7 @@ class BasicTransactionTestCase(BasicTestCase):
num = d.truncate(txn) num = d.truncate(txn)
assert num >= 1, "truncate returned <= 0 on non-empty database" assert num >= 1, "truncate returned <= 0 on non-empty database"
num = d.truncate(txn) num = d.truncate(txn)
assert num == 0, "truncate on empty DB returned nonzero (%s)" % `num` assert num == 0, "truncate on empty DB returned nonzero (%r)" % (num,)
txn.commit() txn.commit()
#---------------------------------------- #----------------------------------------

View file

@ -109,7 +109,7 @@ class TableDBTestCase(unittest.TestCase):
assert values[1]['Species'] == 'Penguin' assert values[1]['Species'] == 'Penguin'
else : else :
if verbose: if verbose:
print "values=", `values` print "values= %r" % (values,)
raise "Wrong values returned!" raise "Wrong values returned!"
def test03(self): def test03(self):

View file

@ -151,9 +151,9 @@ def month(theyear, themonth, w=0, l=0):
"""Return a month's calendar string (multi-line).""" """Return a month's calendar string (multi-line)."""
w = max(2, w) w = max(2, w)
l = max(1, l) l = max(1, l)
s = ((month_name[themonth] + ' ' + `theyear`).center( s = ("%s %r" % (month_name[themonth], theyear)).center(
7 * (w + 1) - 1).rstrip() + 7 * (w + 1) - 1).rstrip() + \
'\n' * l + weekheader(w).rstrip() + '\n' * l) '\n' * l + weekheader(w).rstrip() + '\n' * l
for aweek in monthcalendar(theyear, themonth): for aweek in monthcalendar(theyear, themonth):
s = s + week(aweek, w).rstrip() + '\n' * l s = s + week(aweek, w).rstrip() + '\n' * l
return s[:-l] + '\n' return s[:-l] + '\n'
@ -181,7 +181,7 @@ def calendar(year, w=0, l=0, c=_spacing):
l = max(1, l) l = max(1, l)
c = max(2, c) c = max(2, c)
colwidth = (w + 1) * 7 - 1 colwidth = (w + 1) * 7 - 1
s = `year`.center(colwidth * 3 + c * 2).rstrip() + '\n' * l s = repr(year).center(colwidth * 3 + c * 2).rstrip() + '\n' * l
header = weekheader(w) header = weekheader(w)
header = format3cstring(header, header, header, colwidth, c).rstrip() header = format3cstring(header, header, header, colwidth, c).rstrip()
for q in range(January, January+12, 3): for q in range(January, January+12, 3):

View file

@ -212,7 +212,7 @@ def parse_qsl(qs, keep_blank_values=0, strict_parsing=0):
nv = name_value.split('=', 1) nv = name_value.split('=', 1)
if len(nv) != 2: if len(nv) != 2:
if strict_parsing: if strict_parsing:
raise ValueError, "bad query field: %s" % `name_value` raise ValueError, "bad query field: %r" % (name_value,)
continue continue
if len(nv[1]) or keep_blank_values: if len(nv[1]) or keep_blank_values:
name = urllib.unquote(nv[0].replace('+', ' ')) name = urllib.unquote(nv[0].replace('+', ' '))
@ -247,8 +247,8 @@ def parse_multipart(fp, pdict):
if 'boundary' in pdict: if 'boundary' in pdict:
boundary = pdict['boundary'] boundary = pdict['boundary']
if not valid_boundary(boundary): if not valid_boundary(boundary):
raise ValueError, ('Invalid boundary in multipart form: %s' raise ValueError, ('Invalid boundary in multipart form: %r'
% `boundary`) % (boundary,))
nextpart = "--" + boundary nextpart = "--" + boundary
lastpart = "--" + boundary + "--" lastpart = "--" + boundary + "--"
@ -361,7 +361,7 @@ class MiniFieldStorage:
def __repr__(self): def __repr__(self):
"""Return printable representation.""" """Return printable representation."""
return "MiniFieldStorage(%s, %s)" % (`self.name`, `self.value`) return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
class FieldStorage: class FieldStorage:
@ -522,8 +522,8 @@ class FieldStorage:
def __repr__(self): def __repr__(self):
"""Return a printable representation.""" """Return a printable representation."""
return "FieldStorage(%s, %s, %s)" % ( return "FieldStorage(%r, %r, %r)" % (
`self.name`, `self.filename`, `self.value`) self.name, self.filename, self.value)
def __iter__(self): def __iter__(self):
return iter(self.keys()) return iter(self.keys())
@ -632,8 +632,7 @@ class FieldStorage:
"""Internal: read a part that is itself multipart.""" """Internal: read a part that is itself multipart."""
ib = self.innerboundary ib = self.innerboundary
if not valid_boundary(ib): if not valid_boundary(ib):
raise ValueError, ('Invalid boundary in multipart form: %s' raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,)
% `ib`)
self.list = [] self.list = []
klass = self.FieldStorageClass or self.__class__ klass = self.FieldStorageClass or self.__class__
part = klass(self.fp, {}, ib, part = klass(self.fp, {}, ib,
@ -957,8 +956,8 @@ def print_form(form):
for key in keys: for key in keys:
print "<DT>" + escape(key) + ":", print "<DT>" + escape(key) + ":",
value = form[key] value = form[key]
print "<i>" + escape(`type(value)`) + "</i>" print "<i>" + escape(repr(type(value))) + "</i>"
print "<DD>" + escape(`value`) print "<DD>" + escape(repr(value))
print "</DL>" print "</DL>"
print print

View file

@ -689,9 +689,9 @@ def get_close_matches(word, possibilities, n=3, cutoff=0.6):
""" """
if not n > 0: if not n > 0:
raise ValueError("n must be > 0: " + `n`) raise ValueError("n must be > 0: %r" % (n,))
if not 0.0 <= cutoff <= 1.0: if not 0.0 <= cutoff <= 1.0:
raise ValueError("cutoff must be in [0.0, 1.0]: " + `cutoff`) raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
result = [] result = []
s = SequenceMatcher() s = SequenceMatcher()
s.set_seq2(word) s.set_seq2(word)
@ -876,7 +876,7 @@ class Differ:
elif tag == 'equal': elif tag == 'equal':
g = self._dump(' ', a, alo, ahi) g = self._dump(' ', a, alo, ahi)
else: else:
raise ValueError, 'unknown tag ' + `tag` raise ValueError, 'unknown tag %r' % (tag,)
for line in g: for line in g:
yield line yield line
@ -988,7 +988,7 @@ class Differ:
atags += ' ' * la atags += ' ' * la
btags += ' ' * lb btags += ' ' * lb
else: else:
raise ValueError, 'unknown tag ' + `tag` raise ValueError, 'unknown tag %r' % (tag,)
for line in self._qformat(aelt, belt, atags, btags): for line in self._qformat(aelt, belt, atags, btags):
yield line yield line
else: else:

View file

@ -80,7 +80,7 @@ def disassemble(co, lasti=-1):
else: print ' ', else: print ' ',
if i in labels: print '>>', if i in labels: print '>>',
else: print ' ', else: print ' ',
print `i`.rjust(4), print repr(i).rjust(4),
print opname[op].ljust(20), print opname[op].ljust(20),
i = i+1 i = i+1
if op >= HAVE_ARGUMENT: if op >= HAVE_ARGUMENT:
@ -89,13 +89,13 @@ def disassemble(co, lasti=-1):
i = i+2 i = i+2
if op == EXTENDED_ARG: if op == EXTENDED_ARG:
extended_arg = oparg*65536L extended_arg = oparg*65536L
print `oparg`.rjust(5), print repr(oparg).rjust(5),
if op in hasconst: if op in hasconst:
print '(' + `co.co_consts[oparg]` + ')', print '(' + repr(co.co_consts[oparg]) + ')',
elif op in hasname: elif op in hasname:
print '(' + co.co_names[oparg] + ')', print '(' + co.co_names[oparg] + ')',
elif op in hasjrel: elif op in hasjrel:
print '(to ' + `i + oparg` + ')', print '(to ' + repr(i + oparg) + ')',
elif op in haslocal: elif op in haslocal:
print '(' + co.co_varnames[oparg] + ')', print '(' + co.co_varnames[oparg] + ')',
elif op in hascompare: elif op in hascompare:
@ -118,16 +118,16 @@ def disassemble_string(code, lasti=-1, varnames=None, names=None,
else: print ' ', else: print ' ',
if i in labels: print '>>', if i in labels: print '>>',
else: print ' ', else: print ' ',
print `i`.rjust(4), print repr(i).rjust(4),
print opname[op].ljust(15), print opname[op].ljust(15),
i = i+1 i = i+1
if op >= HAVE_ARGUMENT: if op >= HAVE_ARGUMENT:
oparg = ord(code[i]) + ord(code[i+1])*256 oparg = ord(code[i]) + ord(code[i+1])*256
i = i+2 i = i+2
print `oparg`.rjust(5), print repr(oparg).rjust(5),
if op in hasconst: if op in hasconst:
if constants: if constants:
print '(' + `constants[oparg]` + ')', print '(' + repr(constants[oparg]) + ')',
else: else:
print '(%d)'%oparg, print '(%d)'%oparg,
elif op in hasname: elif op in hasname:
@ -136,7 +136,7 @@ def disassemble_string(code, lasti=-1, varnames=None, names=None,
else: else:
print '(%d)'%oparg, print '(%d)'%oparg,
elif op in hasjrel: elif op in hasjrel:
print '(to ' + `i + oparg` + ')', print '(to ' + repr(i + oparg) + ')',
elif op in haslocal: elif op in haslocal:
if varnames: if varnames:
print '(' + varnames[oparg] + ')', print '(' + varnames[oparg] + ')',

View file

@ -253,8 +253,8 @@ class Command:
if not ok: if not ok:
raise DistutilsOptionError, \ raise DistutilsOptionError, \
"'%s' must be a list of strings (got %s)" % \ "'%s' must be a list of strings (got %r)" % \
(option, `val`) (option, val)
def _ensure_tested_string (self, option, tester, def _ensure_tested_string (self, option, tester,
what, error_fmt, default=None): what, error_fmt, default=None):

View file

@ -202,7 +202,7 @@ def run_setup (script_name, script_args=None, stop_after="run"):
used to drive the Distutils. used to drive the Distutils.
""" """
if stop_after not in ('init', 'config', 'commandline', 'run'): if stop_after not in ('init', 'config', 'commandline', 'run'):
raise ValueError, "invalid value for 'stop_after': %s" % `stop_after` raise ValueError, "invalid value for 'stop_after': %r" % (stop_after,)
global _setup_stop_after, _setup_distribution global _setup_stop_after, _setup_distribution
_setup_stop_after = stop_after _setup_stop_after = stop_after

View file

@ -33,7 +33,7 @@ def mkpath (name, mode=0777, verbose=0, dry_run=0):
# Detect a common bug -- name is None # Detect a common bug -- name is None
if type(name) is not StringType: if type(name) is not StringType:
raise DistutilsInternalError, \ raise DistutilsInternalError, \
"mkpath: 'name' must be a string (got %s)" % `name` "mkpath: 'name' must be a string (got %r)" % (name,)
# XXX what's the better way to handle verbosity? print as we create # XXX what's the better way to handle verbosity? print as we create
# each directory in the path (the current behaviour), or only announce # each directory in the path (the current behaviour), or only announce

View file

@ -525,9 +525,9 @@ class Distribution:
func() func()
else: else:
raise DistutilsClassError( raise DistutilsClassError(
"invalid help function %s for help option '%s': " "invalid help function %r for help option '%s': "
"must be a callable object (function, etc.)" "must be a callable object (function, etc.)"
% (`func`, help_option)) % (func, help_option))
if help_option_found: if help_option_found:
return return

View file

@ -162,7 +162,7 @@ class FancyGetopt:
else: else:
# the option table is part of the code, so simply # the option table is part of the code, so simply
# assert that it is correct # assert that it is correct
assert "invalid option tuple: %s" % `option` assert "invalid option tuple: %r" % (option,)
# Type- and value-check the option names # Type- and value-check the option names
if type(long) is not StringType or len(long) < 2: if type(long) is not StringType or len(long) < 2:

View file

@ -285,7 +285,7 @@ def execute (func, args, msg=None, verbose=0, dry_run=0):
print. print.
""" """
if msg is None: if msg is None:
msg = "%s%s" % (func.__name__, `args`) msg = "%s%r" % (func.__name__, args)
if msg[-2:] == ',)': # correct for singleton tuple if msg[-2:] == ',)': # correct for singleton tuple
msg = msg[0:-2] + ')' msg = msg[0:-2] + ')'
@ -307,7 +307,7 @@ def strtobool (val):
elif val in ('n', 'no', 'f', 'false', 'off', '0'): elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0 return 0
else: else:
raise ValueError, "invalid truth value %s" % `val` raise ValueError, "invalid truth value %r" % (val,)
def byte_compile (py_files, def byte_compile (py_files,
@ -394,11 +394,11 @@ files = [
script.write(string.join(map(repr, py_files), ",\n") + "]\n") script.write(string.join(map(repr, py_files), ",\n") + "]\n")
script.write(""" script.write("""
byte_compile(files, optimize=%s, force=%s, byte_compile(files, optimize=%r, force=%r,
prefix=%s, base_dir=%s, prefix=%r, base_dir=%r,
verbose=%s, dry_run=0, verbose=%r, dry_run=0,
direct=1) direct=1)
""" % (`optimize`, `force`, `prefix`, `base_dir`, `verbose`)) """ % (optimize, force, prefix, base_dir, verbose))
script.close() script.close()
@ -432,8 +432,8 @@ byte_compile(files, optimize=%s, force=%s,
if prefix: if prefix:
if file[:len(prefix)] != prefix: if file[:len(prefix)] != prefix:
raise ValueError, \ raise ValueError, \
("invalid prefix: filename %s doesn't start with %s" ("invalid prefix: filename %r doesn't start with %r"
% (`file`, `prefix`)) % (file, prefix))
dfile = dfile[len(prefix):] dfile = dfile[len(prefix):]
if base_dir: if base_dir:
dfile = os.path.join(base_dir, dfile) dfile = os.path.join(base_dir, dfile)

View file

@ -334,8 +334,8 @@ def _extract_examples(s):
continue continue
lineno = i - 1 lineno = i - 1
if line[j] != " ": if line[j] != " ":
raise ValueError("line " + `lineno` + " of docstring lacks " raise ValueError("line %r of docstring lacks blank after %s: %s" %
"blank after " + PS1 + ": " + line) (lineno, PS1, line))
j = j + 1 j = j + 1
blanks = m.group(1) blanks = m.group(1)
nblanks = len(blanks) nblanks = len(blanks)
@ -348,7 +348,7 @@ def _extract_examples(s):
if m: if m:
if m.group(1) != blanks: if m.group(1) != blanks:
raise ValueError("inconsistent leading whitespace " raise ValueError("inconsistent leading whitespace "
"in line " + `i` + " of docstring: " + line) "in line %r of docstring: %s" % (i, line))
i = i + 1 i = i + 1
else: else:
break break
@ -367,7 +367,7 @@ def _extract_examples(s):
while 1: while 1:
if line[:nblanks] != blanks: if line[:nblanks] != blanks:
raise ValueError("inconsistent leading whitespace " raise ValueError("inconsistent leading whitespace "
"in line " + `i` + " of docstring: " + line) "in line %r of docstring: %s" % (i, line))
expect.append(line[nblanks:]) expect.append(line[nblanks:])
i = i + 1 i = i + 1
line = lines[i] line = lines[i]
@ -475,7 +475,7 @@ def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
failures = failures + 1 failures = failures + 1
out("*" * 65 + "\n") out("*" * 65 + "\n")
_tag_out(out, ("Failure in example", source)) _tag_out(out, ("Failure in example", source))
out("from line #" + `lineno` + " of " + name + "\n") out("from line #%r of %s\n" % (lineno, name))
if state == FAIL: if state == FAIL:
_tag_out(out, ("Expected", want or NADA), ("Got", got)) _tag_out(out, ("Expected", want or NADA), ("Got", got))
else: else:
@ -686,8 +686,7 @@ See doctest.testmod docs for the meaning of optionflags.
if mod is None and globs is None: if mod is None and globs is None:
raise TypeError("Tester.__init__: must specify mod or globs") raise TypeError("Tester.__init__: must specify mod or globs")
if mod is not None and not _ismodule(mod): if mod is not None and not _ismodule(mod):
raise TypeError("Tester.__init__: mod must be a module; " + raise TypeError("Tester.__init__: mod must be a module; %r" % (mod,))
`mod`)
if globs is None: if globs is None:
globs = mod.__dict__ globs = mod.__dict__
self.globs = globs self.globs = globs
@ -775,7 +774,7 @@ See doctest.testmod docs for the meaning of optionflags.
name = object.__name__ name = object.__name__
except AttributeError: except AttributeError:
raise ValueError("Tester.rundoc: name must be given " raise ValueError("Tester.rundoc: name must be given "
"when object.__name__ doesn't exist; " + `object`) "when object.__name__ doesn't exist; %r" % (object,))
if self.verbose: if self.verbose:
print "Running", name + ".__doc__" print "Running", name + ".__doc__"
f, t = run_docstring_examples(object, self.globs, self.verbose, name, f, t = run_docstring_examples(object, self.globs, self.verbose, name,
@ -893,8 +892,7 @@ See doctest.testmod docs for the meaning of optionflags.
""" """
if not hasattr(d, "items"): if not hasattr(d, "items"):
raise TypeError("Tester.rundict: d must support .items(); " + raise TypeError("Tester.rundict: d must support .items(); %r" % (d,))
`d`)
f = t = 0 f = t = 0
# Run the tests by alpha order of names, for consistency in # Run the tests by alpha order of names, for consistency in
# verbose-mode output. # verbose-mode output.
@ -936,7 +934,7 @@ See doctest.testmod docs for the meaning of optionflags.
else: else:
raise TypeError("Tester.run__test__: values in " raise TypeError("Tester.run__test__: values in "
"dict must be strings, functions, methods, " "dict must be strings, functions, methods, "
"or classes; " + `v`) "or classes; %r" % (v,))
failures = failures + f failures = failures + f
tries = tries + t tries = tries + t
finally: finally:
@ -1139,7 +1137,7 @@ def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
m = sys.modules.get('__main__') m = sys.modules.get('__main__')
if not _ismodule(m): if not _ismodule(m):
raise TypeError("testmod: module required; " + `m`) raise TypeError("testmod: module required; %r" % (m,))
if name is None: if name is None:
name = m.__name__ name = m.__name__
tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate, tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
@ -1153,7 +1151,7 @@ def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
if testdict: if testdict:
if not hasattr(testdict, "items"): if not hasattr(testdict, "items"):
raise TypeError("testmod: module.__test__ must support " raise TypeError("testmod: module.__test__ must support "
".items(); " + `testdict`) ".items(); %r" % (testdict,))
f, t = tester.run__test__(testdict, name + ".__test__") f, t = tester.run__test__(testdict, name + ".__test__")
failures += f failures += f
tries += t tries += t

View file

@ -325,22 +325,22 @@ class AbstractWriter(NullWriter):
""" """
def new_alignment(self, align): def new_alignment(self, align):
print "new_alignment(%s)" % `align` print "new_alignment(%r)" % (align,)
def new_font(self, font): def new_font(self, font):
print "new_font(%s)" % `font` print "new_font(%r)" % (font,)
def new_margin(self, margin, level): def new_margin(self, margin, level):
print "new_margin(%s, %d)" % (`margin`, level) print "new_margin(%r, %d)" % (margin, level)
def new_spacing(self, spacing): def new_spacing(self, spacing):
print "new_spacing(%s)" % `spacing` print "new_spacing(%r)" % (spacing,)
def new_styles(self, styles): def new_styles(self, styles):
print "new_styles(%s)" % `styles` print "new_styles(%r)" % (styles,)
def send_paragraph(self, blankline): def send_paragraph(self, blankline):
print "send_paragraph(%s)" % `blankline` print "send_paragraph(%r)" % (blankline,)
def send_line_break(self): def send_line_break(self):
print "send_line_break()" print "send_line_break()"
@ -349,13 +349,13 @@ class AbstractWriter(NullWriter):
print "send_hor_rule()" print "send_hor_rule()"
def send_label_data(self, data): def send_label_data(self, data):
print "send_label_data(%s)" % `data` print "send_label_data(%r)" % (data,)
def send_flowing_data(self, data): def send_flowing_data(self, data):
print "send_flowing_data(%s)" % `data` print "send_flowing_data(%r)" % (data,)
def send_literal_data(self, data): def send_literal_data(self, data):
print "send_literal_data(%s)" % `data` print "send_literal_data(%r)" % (data,)
class DumbWriter(NullWriter): class DumbWriter(NullWriter):

View file

@ -88,7 +88,7 @@ def fix(x, digs):
"""Format x as [-]ddd.ddd with 'digs' digits after the point """Format x as [-]ddd.ddd with 'digs' digits after the point
and at least one digit before. and at least one digit before.
If digs <= 0, the point is suppressed.""" If digs <= 0, the point is suppressed."""
if type(x) != type(''): x = `x` if type(x) != type(''): x = repr(x)
try: try:
sign, intpart, fraction, expo = extract(x) sign, intpart, fraction, expo = extract(x)
except NotANumber: except NotANumber:
@ -104,7 +104,7 @@ def sci(x, digs):
"""Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point """Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point
and exactly one digit before. and exactly one digit before.
If digs is <= 0, one digit is kept and the point is suppressed.""" If digs is <= 0, one digit is kept and the point is suppressed."""
if type(x) != type(''): x = `x` if type(x) != type(''): x = repr(x)
sign, intpart, fraction, expo = extract(x) sign, intpart, fraction, expo = extract(x)
if not intpart: if not intpart:
while fraction and fraction[0] == '0': while fraction and fraction[0] == '0':
@ -126,7 +126,7 @@ def sci(x, digs):
expo + len(intpart) - 1 expo + len(intpart) - 1
s = sign + intpart s = sign + intpart
if digs > 0: s = s + '.' + fraction if digs > 0: s = s + '.' + fraction
e = `abs(expo)` e = repr(abs(expo))
e = '0'*(3-len(e)) + e e = '0'*(3-len(e)) + e
if expo < 0: e = '-' + e if expo < 0: e = '-' + e
else: e = '+' + e else: e = '+' + e

View file

@ -161,7 +161,7 @@ class FTP:
while i > 5 and s[i-1] in '\r\n': while i > 5 and s[i-1] in '\r\n':
i = i-1 i = i-1
s = s[:5] + '*'*(i-5) + s[i:] s = s[:5] + '*'*(i-5) + s[i:]
return `s` return repr(s)
# Internal: send one line to the server, appending CRLF # Internal: send one line to the server, appending CRLF
def putline(self, line): def putline(self, line):
@ -250,7 +250,7 @@ class FTP:
port number. port number.
''' '''
hbytes = host.split('.') hbytes = host.split('.')
pbytes = [`port/256`, `port%256`] pbytes = [repr(port/256), repr(port%256)]
bytes = hbytes + pbytes bytes = hbytes + pbytes
cmd = 'PORT ' + ','.join(bytes) cmd = 'PORT ' + ','.join(bytes)
return self.voidcmd(cmd) return self.voidcmd(cmd)
@ -264,7 +264,7 @@ class FTP:
af = 2 af = 2
if af == 0: if af == 0:
raise error_proto, 'unsupported address family' raise error_proto, 'unsupported address family'
fields = ['', `af`, host, `port`, ''] fields = ['', repr(af), host, repr(port), '']
cmd = 'EPRT ' + '|'.join(fields) cmd = 'EPRT ' + '|'.join(fields)
return self.voidcmd(cmd) return self.voidcmd(cmd)
@ -397,7 +397,7 @@ class FTP:
fp = conn.makefile('rb') fp = conn.makefile('rb')
while 1: while 1:
line = fp.readline() line = fp.readline()
if self.debugging > 2: print '*retr*', `line` if self.debugging > 2: print '*retr*', repr(line)
if not line: if not line:
break break
if line[-2:] == CRLF: if line[-2:] == CRLF:

View file

@ -47,7 +47,7 @@ def type_to_name(gtype):
_type_to_name_map[eval(name)] = name[2:] _type_to_name_map[eval(name)] = name[2:]
if gtype in _type_to_name_map: if gtype in _type_to_name_map:
return _type_to_name_map[gtype] return _type_to_name_map[gtype]
return 'TYPE=' + `gtype` return 'TYPE=%r' % (gtype,)
# Names for characters and strings # Names for characters and strings
CRLF = '\r\n' CRLF = '\r\n'
@ -113,7 +113,7 @@ def get_directory(f):
gtype = line[0] gtype = line[0]
parts = line[1:].split(TAB) parts = line[1:].split(TAB)
if len(parts) < 4: if len(parts) < 4:
print '(Bad line from server:', `line`, ')' print '(Bad line from server: %r)' % (line,)
continue continue
if len(parts) > 4: if len(parts) > 4:
if parts[4:] != ['+']: if parts[4:] != ['+']:
@ -198,7 +198,7 @@ def test():
for item in entries: print item for item in entries: print item
else: else:
data = get_binary(f) data = get_binary(f)
print 'binary data:', len(data), 'bytes:', `data[:100]`[:40] print 'binary data:', len(data), 'bytes:', repr(data[:100])[:40]
# Run the test when run as script # Run the test when run as script
if __name__ == '__main__': if __name__ == '__main__':

View file

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

View file

@ -182,7 +182,7 @@ class ColorDelegator(Delegator):
lines_to_get = min(lines_to_get * 2, 100) lines_to_get = min(lines_to_get * 2, 100)
ok = "SYNC" in self.tag_names(next + "-1c") ok = "SYNC" in self.tag_names(next + "-1c")
line = self.get(mark, next) line = self.get(mark, next)
##print head, "get", mark, next, "->", `line` ##print head, "get", mark, next, "->", repr(line)
if not line: if not line:
return return
for tag in self.tagdefs.keys(): for tag in self.tagdefs.keys():

View file

@ -761,7 +761,7 @@ class EditorWindow:
try: try:
self.load_extension(name) self.load_extension(name)
except: except:
print "Failed to load extension", `name` print "Failed to load extension", repr(name)
import traceback import traceback
traceback.print_exc() traceback.print_exc()
@ -937,7 +937,7 @@ class EditorWindow:
elif key == 'context_use_ps1': elif key == 'context_use_ps1':
self.context_use_ps1 = value self.context_use_ps1 = value
else: else:
raise KeyError, "bad option name: %s" % `key` raise KeyError, "bad option name: %r" % (key,)
# If ispythonsource and guess are true, guess a good value for # If ispythonsource and guess are true, guess a good value for
# indentwidth based on file content (if possible), and if # indentwidth based on file content (if possible), and if
@ -1071,7 +1071,7 @@ class EditorWindow:
y = PyParse.Parser(self.indentwidth, self.tabwidth) y = PyParse.Parser(self.indentwidth, self.tabwidth)
for context in self.num_context_lines: for context in self.num_context_lines:
startat = max(lno - context, 1) startat = max(lno - context, 1)
startatindex = `startat` + ".0" startatindex = repr(startat) + ".0"
rawtext = text.get(startatindex, "insert") rawtext = text.get(startatindex, "insert")
y.set_str(rawtext) y.set_str(rawtext)
bod = y.find_good_parse_start( bod = y.find_good_parse_start(
@ -1103,7 +1103,7 @@ class EditorWindow:
else: else:
self.reindent_to(y.compute_backslash_indent()) self.reindent_to(y.compute_backslash_indent())
else: else:
assert 0, "bogus continuation type " + `c` assert 0, "bogus continuation type %r" % (c,)
return "break" return "break"
# This line starts a brand new stmt; indent relative to # This line starts a brand new stmt; indent relative to
@ -1333,7 +1333,7 @@ class IndentSearcher:
if self.finished: if self.finished:
return "" return ""
i = self.i = self.i + 1 i = self.i = self.i + 1
mark = `i` + ".0" mark = repr(i) + ".0"
if self.text.compare(mark, ">=", "end"): if self.text.compare(mark, ">=", "end"):
return "" return ""
return self.text.get(mark, mark + " lineend+1c") return self.text.get(mark, mark + " lineend+1c")

View file

@ -35,7 +35,7 @@ class FileList:
if os.path.isdir(filename): if os.path.isdir(filename):
tkMessageBox.showerror( tkMessageBox.showerror(
"Is A Directory", "Is A Directory",
"The path %s is a directory." % `filename`, "The path %r is a directory." % (filename,),
master=self.root) master=self.root)
return None return None
key = os.path.normcase(filename) key = os.path.normcase(filename)
@ -46,7 +46,7 @@ class FileList:
if not os.path.exists(filename): if not os.path.exists(filename):
tkMessageBox.showinfo( tkMessageBox.showinfo(
"New File", "New File",
"Opening non-existent file %s" % `filename`, "Opening non-existent file %r" % (filename,),
master=self.root) master=self.root)
if action is None: if action is None:
return self.EditorWindow(self, filename, key) return self.EditorWindow(self, filename, key)
@ -102,7 +102,7 @@ class FileList:
self.inversedict[conflict] = None self.inversedict[conflict] = None
tkMessageBox.showerror( tkMessageBox.showerror(
"Name Conflict", "Name Conflict",
"You now have multiple edit windows open for %s" % `filename`, "You now have multiple edit windows open for %r" % (filename,),
master=self.root) master=self.root)
self.dict[newkey] = edit self.dict[newkey] = edit
self.inversedict[edit] = newkey self.inversedict[edit] = newkey

View file

@ -77,7 +77,7 @@ class GrepDialog(SearchDialogBase):
list.sort() list.sort()
self.close() self.close()
pat = self.engine.getpat() pat = self.engine.getpat()
print "Searching %s in %s ..." % (`pat`, path) print "Searching %r in %s ..." % (pat, path)
hits = 0 hits = 0
for fn in list: for fn in list:
try: try:

View file

@ -97,7 +97,7 @@ class SequenceTreeItem(ObjectTreeItem):
continue continue
def setfunction(value, key=key, object=self.object): def setfunction(value, key=key, object=self.object):
object[key] = value object[key] = value
item = make_objecttreeitem(`key` + ":", value, setfunction) item = make_objecttreeitem("%r:" % (key,), value, setfunction)
sublist.append(item) sublist.append(item)
return sublist return sublist

View file

@ -142,7 +142,7 @@ class LastOpenBracketFinder:
y = PyParse.Parser(self.indentwidth, self.tabwidth) y = PyParse.Parser(self.indentwidth, self.tabwidth)
for context in self.num_context_lines: for context in self.num_context_lines:
startat = max(lno - context, 1) startat = max(lno - context, 1)
startatindex = `startat` + ".0" startatindex = repr(startat) + ".0"
# rawtext needs to contain everything up to the last # rawtext needs to contain everything up to the last
# character, which was the close paren. the parser also # character, which was the close paren. the parser also
# requires that the last line ends with "\n" # requires that the last line ends with "\n"

View file

@ -335,9 +335,9 @@ class ModifiedInterpreter(InteractiveInterpreter):
del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc', del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc',
default=False, type='bool') default=False, type='bool')
if __name__ == 'idlelib.PyShell': if __name__ == 'idlelib.PyShell':
command = "__import__('idlelib.run').run.main(" + `del_exitf` +")" command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,)
else: else:
command = "__import__('run').main(" + `del_exitf` + ")" command = "__import__('run').main(%r)" % (del_exitf,)
if sys.platform[:3] == 'win' and ' ' in sys.executable: if sys.platform[:3] == 'win' and ' ' in sys.executable:
# handle embedded space in path by quoting the argument # handle embedded space in path by quoting the argument
decorated_exec = '"%s"' % sys.executable decorated_exec = '"%s"' % sys.executable
@ -454,12 +454,12 @@ class ModifiedInterpreter(InteractiveInterpreter):
def transfer_path(self): def transfer_path(self):
self.runcommand("""if 1: self.runcommand("""if 1:
import sys as _sys import sys as _sys
_sys.path = %s _sys.path = %r
del _sys del _sys
_msg = 'Use File/Exit or your end-of-file key to quit IDLE' _msg = 'Use File/Exit or your end-of-file key to quit IDLE'
__builtins__.quit = __builtins__.exit = _msg __builtins__.quit = __builtins__.exit = _msg
del _msg del _msg
\n""" % `sys.path`) \n""" % (sys.path,))
active_seq = None active_seq = None
@ -483,7 +483,7 @@ class ModifiedInterpreter(InteractiveInterpreter):
console = self.tkconsole.console console = self.tkconsole.console
if how == "OK": if how == "OK":
if what is not None: if what is not None:
print >>console, `what` print >>console, repr(what)
elif how == "EXCEPTION": elif how == "EXCEPTION":
if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"): if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
self.remote_stack_viewer() self.remote_stack_viewer()
@ -589,14 +589,14 @@ class ModifiedInterpreter(InteractiveInterpreter):
def prepend_syspath(self, filename): def prepend_syspath(self, filename):
"Prepend sys.path with file's directory if not already included" "Prepend sys.path with file's directory if not already included"
self.runcommand("""if 1: self.runcommand("""if 1:
_filename = %s _filename = %r
import sys as _sys import sys as _sys
from os.path import dirname as _dirname from os.path import dirname as _dirname
_dir = _dirname(_filename) _dir = _dirname(_filename)
if not _dir in _sys.path: if not _dir in _sys.path:
_sys.path.insert(0, _dir) _sys.path.insert(0, _dir)
del _filename, _sys, _dirname, _dir del _filename, _sys, _dirname, _dir
\n""" % `filename`) \n""" % (filename,))
def showsyntaxerror(self, filename=None): def showsyntaxerror(self, filename=None):
"""Extend base class method: Add Colorizing """Extend base class method: Add Colorizing
@ -1333,9 +1333,9 @@ def main():
if shell and cmd or script: if shell and cmd or script:
shell.interp.runcommand("""if 1: shell.interp.runcommand("""if 1:
import sys as _sys import sys as _sys
_sys.argv = %s _sys.argv = %r
del _sys del _sys
\n""" % `sys.argv`) \n""" % (sys.argv,))
if cmd: if cmd:
shell.interp.execsource(cmd) shell.interp.execsource(cmd)
elif script: elif script:

View file

@ -94,7 +94,7 @@ class IdbAdapter:
self.idb.set_return(frame) self.idb.set_return(frame)
def get_stack(self, fid, tbid): def get_stack(self, fid, tbid):
##print >>sys.__stderr__, "get_stack(%s, %s)" % (`fid`, `tbid`) ##print >>sys.__stderr__, "get_stack(%r, %r)" % (fid, tbid)
frame = frametable[fid] frame = frametable[fid]
if tbid is None: if tbid is None:
tb = None tb = None
@ -295,7 +295,7 @@ class IdbProxy:
def call(self, methodname, *args, **kwargs): def call(self, methodname, *args, **kwargs):
##print "**IdbProxy.call %s %s %s" % (methodname, args, kwargs) ##print "**IdbProxy.call %s %s %s" % (methodname, args, kwargs)
value = self.conn.remotecall(self.oid, methodname, args, kwargs) value = self.conn.remotecall(self.oid, methodname, args, kwargs)
##print "**IdbProxy.call %s returns %s" % (methodname, `value`) ##print "**IdbProxy.call %s returns %r" % (methodname, value)
return value return value
def run(self, cmd, locals): def run(self, cmd, locals):

View file

@ -145,16 +145,16 @@ class ScriptBinding:
dirname = os.path.dirname(filename) dirname = os.path.dirname(filename)
# XXX Too often this discards arguments the user just set... # XXX Too often this discards arguments the user just set...
interp.runcommand("""if 1: interp.runcommand("""if 1:
_filename = %s _filename = %r
import sys as _sys import sys as _sys
from os.path import basename as _basename from os.path import basename as _basename
if (not _sys.argv or if (not _sys.argv or
_basename(_sys.argv[0]) != _basename(_filename)): _basename(_sys.argv[0]) != _basename(_filename)):
_sys.argv = [_filename] _sys.argv = [_filename]
import os as _os import os as _os
_os.chdir(%s) _os.chdir(%r)
del _filename, _sys, _basename, _os del _filename, _sys, _basename, _os
\n""" % (`filename`, `dirname`)) \n""" % (filename, dirname))
interp.prepend_syspath(filename) interp.prepend_syspath(filename)
interp.runcode(code) interp.runcode(code)

View file

@ -31,7 +31,7 @@ except NameError:
if os.path.isdir(_icondir): if os.path.isdir(_icondir):
ICONDIR = _icondir ICONDIR = _icondir
elif not os.path.isdir(ICONDIR): elif not os.path.isdir(ICONDIR):
raise RuntimeError, "can't find icon directory (%s)" % `ICONDIR` raise RuntimeError, "can't find icon directory (%r)" % (ICONDIR,)
def listicons(icondir=ICONDIR): def listicons(icondir=ICONDIR):
"""Utility to display the available icons.""" """Utility to display the available icons."""

View file

@ -177,7 +177,7 @@ class Command:
t = (self.index1, self.index2, self.chars, self.tags) t = (self.index1, self.index2, self.chars, self.tags)
if self.tags is None: if self.tags is None:
t = t[:-1] t = t[:-1]
return s + `t` return s + repr(t)
def do(self, text): def do(self, text):
pass pass
@ -310,7 +310,7 @@ class CommandSequence(Command):
s = self.__class__.__name__ s = self.__class__.__name__
strs = [] strs = []
for cmd in self.cmds: for cmd in self.cmds:
strs.append(" " + `cmd`) strs.append(" %r" % (cmd,))
return s + "(\n" + ",\n".join(strs) + "\n)" return s + "(\n" + ",\n".join(strs) + "\n)"
def __len__(self): def __len__(self):

View file

@ -69,7 +69,7 @@ class OriginalCommand:
self.orig_and_name = (self.orig, self.name) self.orig_and_name = (self.orig, self.name)
def __repr__(self): def __repr__(self):
return "OriginalCommand(%s, %s)" % (`self.redir`, `self.name`) return "OriginalCommand(%r, %r)" % (self.redir, self.name)
def __call__(self, *args): def __call__(self, *args):
return self.tk_call(self.orig_and_name + args) return self.tk_call(self.orig_and_name + args)

View file

@ -66,7 +66,7 @@ class AboutDialog(Toplevel):
sys.version.split()[0], fg=self.fg, bg=self.bg) sys.version.split()[0], fg=self.fg, bg=self.bg)
labelPythonVer.grid(row=9, column=0, sticky=W, padx=10, pady=0) labelPythonVer.grid(row=9, column=0, sticky=W, padx=10, pady=0)
# handle weird tk version num in windoze python >= 1.6 (?!?) # handle weird tk version num in windoze python >= 1.6 (?!?)
tkVer = `TkVersion`.split('.') tkVer = repr(TkVersion).split('.')
tkVer[len(tkVer)-1] = str('%.3g' % (float('.'+tkVer[len(tkVer)-1])))[2:] tkVer[len(tkVer)-1] = str('%.3g' % (float('.'+tkVer[len(tkVer)-1])))[2:]
if tkVer[len(tkVer)-1] == '': if tkVer[len(tkVer)-1] == '':
tkVer[len(tkVer)-1] = '0' tkVer[len(tkVer)-1] = '0'
@ -141,8 +141,7 @@ class AboutDialog(Toplevel):
except IOError: except IOError:
import tkMessageBox import tkMessageBox
tkMessageBox.showerror(title='File Load Error', tkMessageBox.showerror(title='File Load Error',
message='Unable to load file '+ message='Unable to load file %r .' % (fn,),
`fn`+' .',
parent=self) parent=self)
return return
else: else:

View file

@ -718,7 +718,7 @@ class ConfigDialog(Toplevel):
def DeleteCustomKeys(self): def DeleteCustomKeys(self):
keySetName=self.customKeys.get() keySetName=self.customKeys.get()
if not tkMessageBox.askyesno('Delete Key Set','Are you sure you wish '+ if not tkMessageBox.askyesno('Delete Key Set','Are you sure you wish '+
'to delete the key set '+`keySetName`+' ?', 'to delete the key set %r ?' % (keySetName),
parent=self): parent=self):
return return
#remove key set from config #remove key set from config
@ -745,7 +745,7 @@ class ConfigDialog(Toplevel):
def DeleteCustomTheme(self): def DeleteCustomTheme(self):
themeName=self.customTheme.get() themeName=self.customTheme.get()
if not tkMessageBox.askyesno('Delete Theme','Are you sure you wish '+ if not tkMessageBox.askyesno('Delete Theme','Are you sure you wish '+
'to delete the theme '+`themeName`+' ?', 'to delete the theme %r ?' % (themeName,),
parent=self): parent=self):
return return
#remove theme from config #remove theme from config

View file

@ -231,10 +231,11 @@ class IdleConf:
elif self.defaultCfg[configType].has_option(section,option): elif self.defaultCfg[configType].has_option(section,option):
return self.defaultCfg[configType].Get(section, option, type=type) return self.defaultCfg[configType].Get(section, option, type=type)
else: #returning default, print warning else: #returning default, print warning
warning=('\n Warning: configHandler.py - IdleConf.GetOption -\n'+ warning=('\n Warning: configHandler.py - IdleConf.GetOption -\n'
' problem retrieving configration option '+`option`+'\n'+ ' problem retrieving configration option %r\n'
' from section '+`section`+'.\n'+ ' from section %r.\n'
' returning default value: '+`default`+'\n') ' returning default value: %r\n' %
(option, section, default))
sys.stderr.write(warning) sys.stderr.write(warning)
return default return default
@ -331,10 +332,11 @@ class IdleConf:
for element in theme.keys(): for element in theme.keys():
if not cfgParser.has_option(themeName,element): if not cfgParser.has_option(themeName,element):
#we are going to return a default, print warning #we are going to return a default, print warning
warning=('\n Warning: configHandler.py - IdleConf.GetThemeDict'+ warning=('\n Warning: configHandler.py - IdleConf.GetThemeDict'
' -\n problem retrieving theme element '+`element`+ ' -\n problem retrieving theme element %r'
'\n from theme '+`themeName`+'.\n'+ '\n from theme %r.\n'
' returning default value: '+`theme[element]`+'\n') ' returning default value: %r\n' %
(element, themeName, theme[element]))
sys.stderr.write(warning) sys.stderr.write(warning)
colour=cfgParser.Get(themeName,element,default=theme[element]) colour=cfgParser.Get(themeName,element,default=theme[element])
theme[element]=colour theme[element]=colour
@ -561,10 +563,11 @@ class IdleConf:
if binding: if binding:
keyBindings[event]=binding keyBindings[event]=binding
else: #we are going to return a default, print warning else: #we are going to return a default, print warning
warning=('\n Warning: configHandler.py - IdleConf.GetCoreKeys'+ warning=('\n Warning: configHandler.py - IdleConf.GetCoreKeys'
' -\n problem retrieving key binding for event '+ ' -\n problem retrieving key binding for event %r'
`event`+'\n from key set '+`keySetName`+'.\n'+ '\n from key set %r.\n'
' returning default value: '+`keyBindings[event]`+'\n') ' returning default value: %r\n' %
(event, keySetName, keyBindings[event]))
sys.stderr.write(warning) sys.stderr.write(warning)
return keyBindings return keyBindings

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