mirror of
https://github.com/python/cpython.git
synced 2025-09-10 02:36:56 +00:00
Raise statement normalization in Lib/.
This commit is contained in:
parent
8b3febef2f
commit
ce36ad8a46
80 changed files with 502 additions and 530 deletions
|
@ -344,7 +344,7 @@ class RawConfigParser:
|
||||||
def getboolean(self, section, option):
|
def getboolean(self, section, option):
|
||||||
v = self.get(section, option)
|
v = self.get(section, option)
|
||||||
if v.lower() not in self._boolean_states:
|
if v.lower() not in self._boolean_states:
|
||||||
raise ValueError, 'Not a boolean: %s' % v
|
raise ValueError('Not a boolean: %s' % v)
|
||||||
return self._boolean_states[v.lower()]
|
return self._boolean_states[v.lower()]
|
||||||
|
|
||||||
def optionxform(self, optionstr):
|
def optionxform(self, optionstr):
|
||||||
|
|
|
@ -127,8 +127,8 @@ class DictMixin:
|
||||||
return default
|
return default
|
||||||
def pop(self, key, *args):
|
def pop(self, key, *args):
|
||||||
if len(args) > 1:
|
if len(args) > 1:
|
||||||
raise TypeError, "pop expected at most 2 arguments, got "\
|
raise TypeError("pop expected at most 2 arguments, got "
|
||||||
+ repr(1 + len(args))
|
+ repr(1 + len(args)))
|
||||||
try:
|
try:
|
||||||
value = self[key]
|
value = self[key]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
|
@ -141,7 +141,7 @@ class DictMixin:
|
||||||
try:
|
try:
|
||||||
k, v = next(self.iteritems())
|
k, v = next(self.iteritems())
|
||||||
except StopIteration:
|
except StopIteration:
|
||||||
raise KeyError, 'container is empty'
|
raise KeyError('container is empty')
|
||||||
del self[k]
|
del self[k]
|
||||||
return (k, v)
|
return (k, v)
|
||||||
def update(self, other=None, **kwargs):
|
def update(self, other=None, **kwargs):
|
||||||
|
|
|
@ -183,7 +183,7 @@ class MutableString(UserString):
|
||||||
def __init__(self, string=""):
|
def __init__(self, string=""):
|
||||||
self.data = string
|
self.data = string
|
||||||
def __hash__(self):
|
def __hash__(self):
|
||||||
raise TypeError, "unhashable type (it is mutable)"
|
raise TypeError("unhashable type (it is mutable)")
|
||||||
def __setitem__(self, index, sub):
|
def __setitem__(self, index, sub):
|
||||||
if isinstance(index, slice):
|
if isinstance(index, slice):
|
||||||
if isinstance(sub, UserString):
|
if isinstance(sub, UserString):
|
||||||
|
|
78
Lib/aifc.py
78
Lib/aifc.py
|
@ -287,14 +287,14 @@ class Aifc_read:
|
||||||
self._soundpos = 0
|
self._soundpos = 0
|
||||||
self._file = Chunk(file)
|
self._file = Chunk(file)
|
||||||
if self._file.getname() != 'FORM':
|
if self._file.getname() != 'FORM':
|
||||||
raise Error, 'file does not start with FORM id'
|
raise Error('file does not start with FORM id')
|
||||||
formdata = self._file.read(4)
|
formdata = self._file.read(4)
|
||||||
if formdata == 'AIFF':
|
if formdata == 'AIFF':
|
||||||
self._aifc = 0
|
self._aifc = 0
|
||||||
elif formdata == 'AIFC':
|
elif formdata == 'AIFC':
|
||||||
self._aifc = 1
|
self._aifc = 1
|
||||||
else:
|
else:
|
||||||
raise Error, 'not an AIFF or AIFF-C file'
|
raise Error('not an AIFF or AIFF-C file')
|
||||||
self._comm_chunk_read = 0
|
self._comm_chunk_read = 0
|
||||||
while 1:
|
while 1:
|
||||||
self._ssnd_seek_needed = 1
|
self._ssnd_seek_needed = 1
|
||||||
|
@ -317,10 +317,10 @@ class Aifc_read:
|
||||||
elif chunkname in _skiplist:
|
elif chunkname in _skiplist:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
raise Error, 'unrecognized chunk type '+chunk.chunkname
|
raise Error('unrecognized chunk type '+chunk.chunkname)
|
||||||
chunk.skip()
|
chunk.skip()
|
||||||
if not self._comm_chunk_read or not self._ssnd_chunk:
|
if not self._comm_chunk_read or not self._ssnd_chunk:
|
||||||
raise Error, 'COMM chunk and/or SSND chunk missing'
|
raise Error('COMM chunk and/or SSND chunk missing')
|
||||||
if self._aifc and self._decomp:
|
if self._aifc and self._decomp:
|
||||||
import cl
|
import cl
|
||||||
params = [cl.ORIGINAL_FORMAT, 0,
|
params = [cl.ORIGINAL_FORMAT, 0,
|
||||||
|
@ -331,7 +331,7 @@ class Aifc_read:
|
||||||
elif self._nchannels == 2:
|
elif self._nchannels == 2:
|
||||||
params[1] = cl.STEREO_INTERLEAVED
|
params[1] = cl.STEREO_INTERLEAVED
|
||||||
else:
|
else:
|
||||||
raise Error, 'cannot compress more than 2 channels'
|
raise Error('cannot compress more than 2 channels')
|
||||||
self._decomp.SetParams(params)
|
self._decomp.SetParams(params)
|
||||||
|
|
||||||
def __init__(self, f):
|
def __init__(self, f):
|
||||||
|
@ -394,11 +394,11 @@ 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 %r does not exist' % (id,)
|
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:
|
||||||
raise Error, 'position not in range'
|
raise Error('position not in range')
|
||||||
self._soundpos = pos
|
self._soundpos = pos
|
||||||
self._ssnd_seek_needed = 1
|
self._ssnd_seek_needed = 1
|
||||||
|
|
||||||
|
@ -488,7 +488,7 @@ class Aifc_read:
|
||||||
return
|
return
|
||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
raise Error, 'cannot read compressed AIFF-C files'
|
raise Error('cannot read compressed AIFF-C files')
|
||||||
if self._comptype == 'ULAW':
|
if self._comptype == 'ULAW':
|
||||||
scheme = cl.G711_ULAW
|
scheme = cl.G711_ULAW
|
||||||
self._framesize = self._framesize / 2
|
self._framesize = self._framesize / 2
|
||||||
|
@ -496,7 +496,7 @@ class Aifc_read:
|
||||||
scheme = cl.G711_ALAW
|
scheme = cl.G711_ALAW
|
||||||
self._framesize = self._framesize / 2
|
self._framesize = self._framesize / 2
|
||||||
else:
|
else:
|
||||||
raise Error, 'unsupported compression type'
|
raise Error('unsupported compression type')
|
||||||
self._decomp = cl.OpenDecompressor(scheme)
|
self._decomp = cl.OpenDecompressor(scheme)
|
||||||
self._convert = self._decomp_data
|
self._convert = self._decomp_data
|
||||||
else:
|
else:
|
||||||
|
@ -594,53 +594,53 @@ class Aifc_write:
|
||||||
#
|
#
|
||||||
def aiff(self):
|
def aiff(self):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
self._aifc = 0
|
self._aifc = 0
|
||||||
|
|
||||||
def aifc(self):
|
def aifc(self):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
self._aifc = 1
|
self._aifc = 1
|
||||||
|
|
||||||
def setnchannels(self, nchannels):
|
def setnchannels(self, nchannels):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if nchannels < 1:
|
if nchannels < 1:
|
||||||
raise Error, 'bad # of channels'
|
raise Error('bad # of channels')
|
||||||
self._nchannels = nchannels
|
self._nchannels = nchannels
|
||||||
|
|
||||||
def getnchannels(self):
|
def getnchannels(self):
|
||||||
if not self._nchannels:
|
if not self._nchannels:
|
||||||
raise Error, 'number of channels not set'
|
raise Error('number of channels not set')
|
||||||
return self._nchannels
|
return self._nchannels
|
||||||
|
|
||||||
def setsampwidth(self, sampwidth):
|
def setsampwidth(self, sampwidth):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if sampwidth < 1 or sampwidth > 4:
|
if sampwidth < 1 or sampwidth > 4:
|
||||||
raise Error, 'bad sample width'
|
raise Error('bad sample width')
|
||||||
self._sampwidth = sampwidth
|
self._sampwidth = sampwidth
|
||||||
|
|
||||||
def getsampwidth(self):
|
def getsampwidth(self):
|
||||||
if not self._sampwidth:
|
if not self._sampwidth:
|
||||||
raise Error, 'sample width not set'
|
raise Error('sample width not set')
|
||||||
return self._sampwidth
|
return self._sampwidth
|
||||||
|
|
||||||
def setframerate(self, framerate):
|
def setframerate(self, framerate):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if framerate <= 0:
|
if framerate <= 0:
|
||||||
raise Error, 'bad frame rate'
|
raise Error('bad frame rate')
|
||||||
self._framerate = framerate
|
self._framerate = framerate
|
||||||
|
|
||||||
def getframerate(self):
|
def getframerate(self):
|
||||||
if not self._framerate:
|
if not self._framerate:
|
||||||
raise Error, 'frame rate not set'
|
raise Error('frame rate not set')
|
||||||
return self._framerate
|
return self._framerate
|
||||||
|
|
||||||
def setnframes(self, nframes):
|
def setnframes(self, nframes):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
self._nframes = nframes
|
self._nframes = nframes
|
||||||
|
|
||||||
def getnframes(self):
|
def getnframes(self):
|
||||||
|
@ -648,9 +648,9 @@ class Aifc_write:
|
||||||
|
|
||||||
def setcomptype(self, comptype, compname):
|
def setcomptype(self, comptype, compname):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
|
if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
|
||||||
raise Error, 'unsupported compression type'
|
raise Error('unsupported compression type')
|
||||||
self._comptype = comptype
|
self._comptype = comptype
|
||||||
self._compname = compname
|
self._compname = compname
|
||||||
|
|
||||||
|
@ -668,9 +668,9 @@ class Aifc_write:
|
||||||
def setparams(self, params):
|
def setparams(self, params):
|
||||||
nchannels, sampwidth, framerate, nframes, comptype, compname = params
|
nchannels, sampwidth, framerate, nframes, comptype, compname = params
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
|
if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):
|
||||||
raise Error, 'unsupported compression type'
|
raise Error('unsupported compression type')
|
||||||
self.setnchannels(nchannels)
|
self.setnchannels(nchannels)
|
||||||
self.setsampwidth(sampwidth)
|
self.setsampwidth(sampwidth)
|
||||||
self.setframerate(framerate)
|
self.setframerate(framerate)
|
||||||
|
@ -679,17 +679,17 @@ class Aifc_write:
|
||||||
|
|
||||||
def getparams(self):
|
def getparams(self):
|
||||||
if not self._nchannels or not self._sampwidth or not self._framerate:
|
if not self._nchannels or not self._sampwidth or not self._framerate:
|
||||||
raise Error, 'not all parameters set'
|
raise Error('not all parameters set')
|
||||||
return self._nchannels, self._sampwidth, self._framerate, \
|
return self._nchannels, self._sampwidth, self._framerate, \
|
||||||
self._nframes, self._comptype, self._compname
|
self._nframes, self._comptype, self._compname
|
||||||
|
|
||||||
def setmark(self, id, pos, name):
|
def setmark(self, id, pos, name):
|
||||||
if id <= 0:
|
if id <= 0:
|
||||||
raise Error, 'marker ID must be > 0'
|
raise Error('marker ID must be > 0')
|
||||||
if pos < 0:
|
if pos < 0:
|
||||||
raise Error, 'marker position must be >= 0'
|
raise Error('marker position must be >= 0')
|
||||||
if type(name) != type(''):
|
if type(name) != type(''):
|
||||||
raise Error, 'marker name must be a string'
|
raise Error('marker name must be a string')
|
||||||
for i in range(len(self._markers)):
|
for i in range(len(self._markers)):
|
||||||
if id == self._markers[i][0]:
|
if id == self._markers[i][0]:
|
||||||
self._markers[i] = id, pos, name
|
self._markers[i] = id, pos, name
|
||||||
|
@ -700,7 +700,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 %r does not exist' % (id,)
|
raise Error('marker %r does not exist' % (id,))
|
||||||
|
|
||||||
def getmarkers(self):
|
def getmarkers(self):
|
||||||
if len(self._markers) == 0:
|
if len(self._markers) == 0:
|
||||||
|
@ -770,18 +770,18 @@ class Aifc_write:
|
||||||
if not self._sampwidth:
|
if not self._sampwidth:
|
||||||
self._sampwidth = 2
|
self._sampwidth = 2
|
||||||
if self._sampwidth != 2:
|
if self._sampwidth != 2:
|
||||||
raise Error, 'sample width must be 2 when compressing with ULAW or ALAW'
|
raise Error('sample width must be 2 when compressing with ULAW or ALAW')
|
||||||
if self._comptype == 'G722':
|
if self._comptype == 'G722':
|
||||||
if not self._sampwidth:
|
if not self._sampwidth:
|
||||||
self._sampwidth = 2
|
self._sampwidth = 2
|
||||||
if self._sampwidth != 2:
|
if self._sampwidth != 2:
|
||||||
raise Error, 'sample width must be 2 when compressing with G7.22 (ADPCM)'
|
raise Error('sample width must be 2 when compressing with G7.22 (ADPCM)')
|
||||||
if not self._nchannels:
|
if not self._nchannels:
|
||||||
raise Error, '# channels not specified'
|
raise Error('# channels not specified')
|
||||||
if not self._sampwidth:
|
if not self._sampwidth:
|
||||||
raise Error, 'sample width not specified'
|
raise Error('sample width not specified')
|
||||||
if not self._framerate:
|
if not self._framerate:
|
||||||
raise Error, 'sampling rate not specified'
|
raise Error('sampling rate not specified')
|
||||||
self._write_header(datasize)
|
self._write_header(datasize)
|
||||||
|
|
||||||
def _init_compression(self):
|
def _init_compression(self):
|
||||||
|
@ -798,13 +798,13 @@ class Aifc_write:
|
||||||
return
|
return
|
||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
raise Error, 'cannot write compressed AIFF-C files'
|
raise Error('cannot write compressed AIFF-C files')
|
||||||
if self._comptype == 'ULAW':
|
if self._comptype == 'ULAW':
|
||||||
scheme = cl.G711_ULAW
|
scheme = cl.G711_ULAW
|
||||||
elif self._comptype == 'ALAW':
|
elif self._comptype == 'ALAW':
|
||||||
scheme = cl.G711_ALAW
|
scheme = cl.G711_ALAW
|
||||||
else:
|
else:
|
||||||
raise Error, 'unsupported compression type'
|
raise Error('unsupported compression type')
|
||||||
self._comp = cl.OpenCompressor(scheme)
|
self._comp = cl.OpenCompressor(scheme)
|
||||||
params = [cl.ORIGINAL_FORMAT, 0,
|
params = [cl.ORIGINAL_FORMAT, 0,
|
||||||
cl.BITS_PER_COMPONENT, self._sampwidth * 8,
|
cl.BITS_PER_COMPONENT, self._sampwidth * 8,
|
||||||
|
@ -816,7 +816,7 @@ class Aifc_write:
|
||||||
elif self._nchannels == 2:
|
elif self._nchannels == 2:
|
||||||
params[1] = cl.STEREO_INTERLEAVED
|
params[1] = cl.STEREO_INTERLEAVED
|
||||||
else:
|
else:
|
||||||
raise Error, 'cannot compress more than 2 channels'
|
raise Error('cannot compress more than 2 channels')
|
||||||
self._comp.SetParams(params)
|
self._comp.SetParams(params)
|
||||||
# the compressor produces a header which we ignore
|
# the compressor produces a header which we ignore
|
||||||
dummy = self._comp.Compress(0, '')
|
dummy = self._comp.Compress(0, '')
|
||||||
|
@ -930,7 +930,7 @@ def open(f, mode=None):
|
||||||
elif mode in ('w', 'wb'):
|
elif mode in ('w', 'wb'):
|
||||||
return Aifc_write(f)
|
return Aifc_write(f)
|
||||||
else:
|
else:
|
||||||
raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
|
raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
|
||||||
|
|
||||||
openfp = open # B/W compatibility
|
openfp = open # B/W compatibility
|
||||||
|
|
||||||
|
|
|
@ -59,7 +59,7 @@ for _name in _names:
|
||||||
_errors.append(_mod.error)
|
_errors.append(_mod.error)
|
||||||
|
|
||||||
if not _defaultmod:
|
if not _defaultmod:
|
||||||
raise ImportError, "no dbm clone found; tried %s" % _names
|
raise ImportError("no dbm clone found; tried %s" % _names)
|
||||||
|
|
||||||
error = tuple(_errors)
|
error = tuple(_errors)
|
||||||
|
|
||||||
|
@ -74,10 +74,10 @@ def open(file, flag = 'r', mode = 0o666):
|
||||||
# flag was used so use default type
|
# flag was used so use default type
|
||||||
mod = _defaultmod
|
mod = _defaultmod
|
||||||
else:
|
else:
|
||||||
raise error, "need 'c' or 'n' flag to open new db"
|
raise error("need 'c' or 'n' flag to open new db")
|
||||||
elif result == "":
|
elif result == "":
|
||||||
# db type cannot be determined
|
# db type cannot be determined
|
||||||
raise error, "db type could not be determined"
|
raise error("db type could not be determined")
|
||||||
else:
|
else:
|
||||||
mod = __import__(result)
|
mod = __import__(result)
|
||||||
return mod.open(file, flag, mode)
|
return mod.open(file, flag, mode)
|
||||||
|
|
|
@ -66,10 +66,10 @@ class async_chat (asyncore.dispatcher):
|
||||||
asyncore.dispatcher.__init__ (self, conn)
|
asyncore.dispatcher.__init__ (self, conn)
|
||||||
|
|
||||||
def collect_incoming_data(self, data):
|
def collect_incoming_data(self, data):
|
||||||
raise NotImplementedError, "must be implemented in subclass"
|
raise NotImplementedError("must be implemented in subclass")
|
||||||
|
|
||||||
def found_terminator(self):
|
def found_terminator(self):
|
||||||
raise NotImplementedError, "must be implemented in subclass"
|
raise NotImplementedError("must be implemented in subclass")
|
||||||
|
|
||||||
def set_terminator (self, term):
|
def set_terminator (self, term):
|
||||||
"Set the input delimiter. Can be a fixed string of any length, an integer, or None"
|
"Set the input delimiter. Can be a fixed string of any length, an integer, or None"
|
||||||
|
|
|
@ -313,7 +313,7 @@ class dispatcher:
|
||||||
self.connected = True
|
self.connected = True
|
||||||
self.handle_connect()
|
self.handle_connect()
|
||||||
else:
|
else:
|
||||||
raise socket.error, (err, errorcode[err])
|
raise socket.error(err, errorcode[err])
|
||||||
|
|
||||||
def accept(self):
|
def accept(self):
|
||||||
# XXX can return either an address pair or None
|
# XXX can return either an address pair or None
|
||||||
|
|
|
@ -130,7 +130,7 @@ class Bdb:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def do_clear(self, arg):
|
def do_clear(self, arg):
|
||||||
raise NotImplementedError, "subclass of bdb must implement do_clear()"
|
raise NotImplementedError("subclass of bdb must implement do_clear()")
|
||||||
|
|
||||||
def break_anywhere(self, frame):
|
def break_anywhere(self, frame):
|
||||||
return self.canonic(frame.f_code.co_filename) in self.breaks
|
return self.canonic(frame.f_code.co_filename) in self.breaks
|
||||||
|
|
24
Lib/cgi.py
24
Lib/cgi.py
|
@ -140,7 +140,7 @@ def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
|
||||||
elif ctype == 'application/x-www-form-urlencoded':
|
elif ctype == 'application/x-www-form-urlencoded':
|
||||||
clength = int(environ['CONTENT_LENGTH'])
|
clength = int(environ['CONTENT_LENGTH'])
|
||||||
if maxlen and clength > maxlen:
|
if maxlen and clength > maxlen:
|
||||||
raise ValueError, 'Maximum content length exceeded'
|
raise ValueError('Maximum content length exceeded')
|
||||||
qs = fp.read(clength)
|
qs = fp.read(clength)
|
||||||
else:
|
else:
|
||||||
qs = '' # Unknown content-type
|
qs = '' # Unknown content-type
|
||||||
|
@ -215,7 +215,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: %r" % (name_value,)
|
raise ValueError("bad query field: %r" % (name_value,))
|
||||||
# Handle case of a control-name with no equal sign
|
# Handle case of a control-name with no equal sign
|
||||||
if keep_blank_values:
|
if keep_blank_values:
|
||||||
nv.append('')
|
nv.append('')
|
||||||
|
@ -258,7 +258,7 @@ 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: %r'
|
raise ValueError('Invalid boundary in multipart form: %r'
|
||||||
% (boundary,))
|
% (boundary,))
|
||||||
|
|
||||||
nextpart = "--" + boundary
|
nextpart = "--" + boundary
|
||||||
|
@ -280,7 +280,7 @@ def parse_multipart(fp, pdict):
|
||||||
pass
|
pass
|
||||||
if bytes > 0:
|
if bytes > 0:
|
||||||
if maxlen and bytes > maxlen:
|
if maxlen and bytes > maxlen:
|
||||||
raise ValueError, 'Maximum content length exceeded'
|
raise ValueError('Maximum content length exceeded')
|
||||||
data = fp.read(bytes)
|
data = fp.read(bytes)
|
||||||
else:
|
else:
|
||||||
data = ""
|
data = ""
|
||||||
|
@ -520,7 +520,7 @@ class FieldStorage:
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
if maxlen and clen > maxlen:
|
if maxlen and clen > maxlen:
|
||||||
raise ValueError, 'Maximum content length exceeded'
|
raise ValueError('Maximum content length exceeded')
|
||||||
self.length = clen
|
self.length = clen
|
||||||
|
|
||||||
self.list = self.file = None
|
self.list = self.file = None
|
||||||
|
@ -542,7 +542,7 @@ class FieldStorage:
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name):
|
||||||
if name != 'value':
|
if name != 'value':
|
||||||
raise AttributeError, name
|
raise AttributeError(name)
|
||||||
if self.file:
|
if self.file:
|
||||||
self.file.seek(0)
|
self.file.seek(0)
|
||||||
value = self.file.read()
|
value = self.file.read()
|
||||||
|
@ -556,12 +556,12 @@ class FieldStorage:
|
||||||
def __getitem__(self, key):
|
def __getitem__(self, key):
|
||||||
"""Dictionary style indexing."""
|
"""Dictionary style indexing."""
|
||||||
if self.list is None:
|
if self.list is None:
|
||||||
raise TypeError, "not indexable"
|
raise TypeError("not indexable")
|
||||||
found = []
|
found = []
|
||||||
for item in self.list:
|
for item in self.list:
|
||||||
if item.name == key: found.append(item)
|
if item.name == key: found.append(item)
|
||||||
if not found:
|
if not found:
|
||||||
raise KeyError, key
|
raise KeyError(key)
|
||||||
if len(found) == 1:
|
if len(found) == 1:
|
||||||
return found[0]
|
return found[0]
|
||||||
else:
|
else:
|
||||||
|
@ -603,7 +603,7 @@ class FieldStorage:
|
||||||
def keys(self):
|
def keys(self):
|
||||||
"""Dictionary style keys() method."""
|
"""Dictionary style keys() method."""
|
||||||
if self.list is None:
|
if self.list is None:
|
||||||
raise TypeError, "not indexable"
|
raise TypeError("not indexable")
|
||||||
keys = []
|
keys = []
|
||||||
for item in self.list:
|
for item in self.list:
|
||||||
if item.name not in keys: keys.append(item.name)
|
if item.name not in keys: keys.append(item.name)
|
||||||
|
@ -612,7 +612,7 @@ class FieldStorage:
|
||||||
def __contains__(self, key):
|
def __contains__(self, key):
|
||||||
"""Dictionary style __contains__ method."""
|
"""Dictionary style __contains__ method."""
|
||||||
if self.list is None:
|
if self.list is None:
|
||||||
raise TypeError, "not indexable"
|
raise TypeError("not indexable")
|
||||||
for item in self.list:
|
for item in self.list:
|
||||||
if item.name == key: return True
|
if item.name == key: return True
|
||||||
return False
|
return False
|
||||||
|
@ -636,7 +636,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: %r' % (ib,)
|
raise ValueError('Invalid boundary in multipart form: %r' % (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,
|
||||||
|
@ -817,7 +817,7 @@ class SvFormContentDict(FormContentDict):
|
||||||
"""
|
"""
|
||||||
def __getitem__(self, key):
|
def __getitem__(self, key):
|
||||||
if len(self.dict[key]) > 1:
|
if len(self.dict[key]) > 1:
|
||||||
raise IndexError, 'expecting a single value'
|
raise IndexError('expecting a single value')
|
||||||
return self.dict[key][0]
|
return self.dict[key][0]
|
||||||
def getlist(self, key):
|
def getlist(self, key):
|
||||||
return self.dict[key]
|
return self.dict[key]
|
||||||
|
|
12
Lib/chunk.py
12
Lib/chunk.py
|
@ -90,7 +90,7 @@ class Chunk:
|
||||||
|
|
||||||
def isatty(self):
|
def isatty(self):
|
||||||
if self.closed:
|
if self.closed:
|
||||||
raise ValueError, "I/O operation on closed file"
|
raise ValueError("I/O operation on closed file")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def seek(self, pos, whence=0):
|
def seek(self, pos, whence=0):
|
||||||
|
@ -100,9 +100,9 @@ class Chunk:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if self.closed:
|
if self.closed:
|
||||||
raise ValueError, "I/O operation on closed file"
|
raise ValueError("I/O operation on closed file")
|
||||||
if not self.seekable:
|
if not self.seekable:
|
||||||
raise IOError, "cannot seek"
|
raise IOError("cannot seek")
|
||||||
if whence == 1:
|
if whence == 1:
|
||||||
pos = pos + self.size_read
|
pos = pos + self.size_read
|
||||||
elif whence == 2:
|
elif whence == 2:
|
||||||
|
@ -114,7 +114,7 @@ class Chunk:
|
||||||
|
|
||||||
def tell(self):
|
def tell(self):
|
||||||
if self.closed:
|
if self.closed:
|
||||||
raise ValueError, "I/O operation on closed file"
|
raise ValueError("I/O operation on closed file")
|
||||||
return self.size_read
|
return self.size_read
|
||||||
|
|
||||||
def read(self, size=-1):
|
def read(self, size=-1):
|
||||||
|
@ -124,7 +124,7 @@ class Chunk:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if self.closed:
|
if self.closed:
|
||||||
raise ValueError, "I/O operation on closed file"
|
raise ValueError("I/O operation on closed file")
|
||||||
if self.size_read >= self.chunksize:
|
if self.size_read >= self.chunksize:
|
||||||
return ''
|
return ''
|
||||||
if size < 0:
|
if size < 0:
|
||||||
|
@ -148,7 +148,7 @@ class Chunk:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if self.closed:
|
if self.closed:
|
||||||
raise ValueError, "I/O operation on closed file"
|
raise ValueError("I/O operation on closed file")
|
||||||
if self.seekable:
|
if self.seekable:
|
||||||
try:
|
try:
|
||||||
n = self.chunksize - self.size_read
|
n = self.chunksize - self.size_read
|
||||||
|
|
|
@ -358,8 +358,8 @@ class Cmd:
|
||||||
nonstrings = [i for i in range(len(list))
|
nonstrings = [i for i in range(len(list))
|
||||||
if not isinstance(list[i], basestring)]
|
if not isinstance(list[i], basestring)]
|
||||||
if nonstrings:
|
if nonstrings:
|
||||||
raise TypeError, ("list[i] not a string for i in %s" %
|
raise TypeError("list[i] not a string for i in %s"
|
||||||
", ".join(map(str, nonstrings)))
|
% ", ".join(map(str, nonstrings)))
|
||||||
size = len(list)
|
size = len(list)
|
||||||
if size == 1:
|
if size == 1:
|
||||||
self.stdout.write('%s\n'%str(list[0]))
|
self.stdout.write('%s\n'%str(list[0]))
|
||||||
|
|
|
@ -96,7 +96,7 @@ def _maybe_compile(compiler, source, filename, symbol):
|
||||||
if code:
|
if code:
|
||||||
return code
|
return code
|
||||||
if not code1 and repr(err1) == repr(err2):
|
if not code1 and repr(err1) == repr(err2):
|
||||||
raise SyntaxError, err1
|
raise SyntaxError(err1)
|
||||||
|
|
||||||
def _compile(source, filename, symbol):
|
def _compile(source, filename, symbol):
|
||||||
return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT)
|
return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT)
|
||||||
|
|
|
@ -62,7 +62,7 @@ def _reduce_ex(self, proto):
|
||||||
state = None
|
state = None
|
||||||
else:
|
else:
|
||||||
if base is self.__class__:
|
if base is self.__class__:
|
||||||
raise TypeError, "can't pickle %s objects" % base.__name__
|
raise TypeError("can't pickle %s objects" % base.__name__)
|
||||||
state = base(self)
|
state = base(self)
|
||||||
args = (self.__class__, base, state)
|
args = (self.__class__, base, state)
|
||||||
try:
|
try:
|
||||||
|
@ -153,7 +153,7 @@ def add_extension(module, name, code):
|
||||||
"""Register an extension code."""
|
"""Register an extension code."""
|
||||||
code = int(code)
|
code = int(code)
|
||||||
if not 1 <= code <= 0x7fffffff:
|
if not 1 <= code <= 0x7fffffff:
|
||||||
raise ValueError, "code out of range"
|
raise ValueError("code out of range")
|
||||||
key = (module, name)
|
key = (module, name)
|
||||||
if (_extension_registry.get(key) == code and
|
if (_extension_registry.get(key) == code and
|
||||||
_inverted_registry.get(code) == key):
|
_inverted_registry.get(code) == key):
|
||||||
|
|
11
Lib/csv.py
11
Lib/csv.py
|
@ -104,9 +104,8 @@ class DictWriter:
|
||||||
self.fieldnames = fieldnames # list of keys for the dict
|
self.fieldnames = fieldnames # list of keys for the dict
|
||||||
self.restval = restval # for writing short dicts
|
self.restval = restval # for writing short dicts
|
||||||
if extrasaction.lower() not in ("raise", "ignore"):
|
if extrasaction.lower() not in ("raise", "ignore"):
|
||||||
raise ValueError, \
|
raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'"
|
||||||
("extrasaction (%s) must be 'raise' or 'ignore'" %
|
% extrasaction)
|
||||||
extrasaction)
|
|
||||||
self.extrasaction = extrasaction
|
self.extrasaction = extrasaction
|
||||||
self.writer = writer(f, dialect, *args, **kwds)
|
self.writer = writer(f, dialect, *args, **kwds)
|
||||||
|
|
||||||
|
@ -114,8 +113,8 @@ class DictWriter:
|
||||||
if self.extrasaction == "raise":
|
if self.extrasaction == "raise":
|
||||||
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
|
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
|
||||||
if wrong_fields:
|
if wrong_fields:
|
||||||
raise ValueError("dict contains fields not in fieldnames: " +
|
raise ValueError("dict contains fields not in fieldnames: "
|
||||||
", ".join(wrong_fields))
|
+ ", ".join(wrong_fields))
|
||||||
return [rowdict.get(key, self.restval) for key in self.fieldnames]
|
return [rowdict.get(key, self.restval) for key in self.fieldnames]
|
||||||
|
|
||||||
def writerow(self, rowdict):
|
def writerow(self, rowdict):
|
||||||
|
@ -155,7 +154,7 @@ class Sniffer:
|
||||||
delimiters)
|
delimiters)
|
||||||
|
|
||||||
if not delimiter:
|
if not delimiter:
|
||||||
raise Error, "Could not determine delimiter"
|
raise Error("Could not determine delimiter")
|
||||||
|
|
||||||
class dialect(Dialect):
|
class dialect(Dialect):
|
||||||
_name = "sniffed"
|
_name = "sniffed"
|
||||||
|
|
|
@ -2350,7 +2350,7 @@ class Context(object):
|
||||||
|
|
||||||
# Errors should only be risked on copies of the context
|
# Errors should only be risked on copies of the context
|
||||||
# self._ignored_flags = []
|
# self._ignored_flags = []
|
||||||
raise error, explanation
|
raise error(explanation)
|
||||||
|
|
||||||
def _ignore_all_flags(self):
|
def _ignore_all_flags(self):
|
||||||
"""Ignore all flags, if they are raised"""
|
"""Ignore all flags, if they are raised"""
|
||||||
|
|
|
@ -914,7 +914,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 %r' % (tag,)
|
raise ValueError('unknown tag %r' % (tag,))
|
||||||
|
|
||||||
for line in g:
|
for line in g:
|
||||||
yield line
|
yield line
|
||||||
|
@ -1026,7 +1026,7 @@ class Differ:
|
||||||
atags += ' ' * la
|
atags += ' ' * la
|
||||||
btags += ' ' * lb
|
btags += ' ' * lb
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'unknown tag %r' % (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:
|
||||||
|
@ -2005,7 +2005,7 @@ def restore(delta, which):
|
||||||
try:
|
try:
|
||||||
tag = {1: "- ", 2: "+ "}[int(which)]
|
tag = {1: "- ", 2: "+ "}[int(which)]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise ValueError, ('unknown delta choice (must be 1 or 2): %r'
|
raise ValueError('unknown delta choice (must be 1 or 2): %r'
|
||||||
% which)
|
% which)
|
||||||
prefixes = (" ", tag)
|
prefixes = (" ", tag)
|
||||||
for line in delta:
|
for line in delta:
|
||||||
|
|
|
@ -47,7 +47,7 @@ def distb(tb=None):
|
||||||
try:
|
try:
|
||||||
tb = sys.last_traceback
|
tb = sys.last_traceback
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
raise RuntimeError, "no last traceback to disassemble"
|
raise RuntimeError("no last traceback to disassemble")
|
||||||
while tb.tb_next: tb = tb.tb_next
|
while tb.tb_next: tb = tb.tb_next
|
||||||
disassemble(tb.tb_frame.f_code, tb.tb_lasti)
|
disassemble(tb.tb_frame.f_code, tb.tb_lasti)
|
||||||
|
|
||||||
|
|
|
@ -326,9 +326,9 @@ class _OutputRedirectingPdb(pdb.Pdb):
|
||||||
# [XX] Normalize with respect to os.path.pardir?
|
# [XX] Normalize with respect to os.path.pardir?
|
||||||
def _module_relative_path(module, path):
|
def _module_relative_path(module, path):
|
||||||
if not inspect.ismodule(module):
|
if not inspect.ismodule(module):
|
||||||
raise TypeError, 'Expected a module: %r' % module
|
raise TypeError('Expected a module: %r' % module)
|
||||||
if path.startswith('/'):
|
if path.startswith('/'):
|
||||||
raise ValueError, 'Module-relative files may not have absolute paths'
|
raise ValueError('Module-relative files may not have absolute paths')
|
||||||
|
|
||||||
# Find the base directory for the path.
|
# Find the base directory for the path.
|
||||||
if hasattr(module, '__file__'):
|
if hasattr(module, '__file__'):
|
||||||
|
|
|
@ -116,18 +116,16 @@ def search_function(encoding):
|
||||||
entry = getregentry()
|
entry = getregentry()
|
||||||
if not isinstance(entry, codecs.CodecInfo):
|
if not isinstance(entry, codecs.CodecInfo):
|
||||||
if not 4 <= len(entry) <= 7:
|
if not 4 <= len(entry) <= 7:
|
||||||
raise CodecRegistryError,\
|
raise CodecRegistryError('module "%s" (%s) failed to register'
|
||||||
'module "%s" (%s) failed to register' % \
|
% (mod.__name__, mod.__file__))
|
||||||
(mod.__name__, mod.__file__)
|
|
||||||
if not hasattr(entry[0], '__call__') or \
|
if not hasattr(entry[0], '__call__') or \
|
||||||
not hasattr(entry[1], '__call__') or \
|
not hasattr(entry[1], '__call__') or \
|
||||||
(entry[2] is not None and not hasattr(entry[2], '__call__')) or \
|
(entry[2] is not None and not hasattr(entry[2], '__call__')) or \
|
||||||
(entry[3] is not None and not hasattr(entry[3], '__call__')) or \
|
(entry[3] is not None and not hasattr(entry[3], '__call__')) or \
|
||||||
(len(entry) > 4 and entry[4] is not None and not hasattr(entry[4], '__call__')) or \
|
(len(entry) > 4 and entry[4] is not None and not hasattr(entry[4], '__call__')) or \
|
||||||
(len(entry) > 5 and entry[5] is not None and not hasattr(entry[5], '__call__')):
|
(len(entry) > 5 and entry[5] is not None and not hasattr(entry[5], '__call__')):
|
||||||
raise CodecRegistryError,\
|
raise CodecRegistryError('incompatible codecs in module "%s" (%s)'
|
||||||
'incompatible codecs in module "%s" (%s)' % \
|
% (mod.__name__, mod.__file__))
|
||||||
(mod.__name__, mod.__file__)
|
|
||||||
if len(entry)<7 or entry[6] is None:
|
if len(entry)<7 or entry[6] is None:
|
||||||
entry += (None,)*(6-len(entry)) + (mod.__name__.split(".", 1)[1],)
|
entry += (None,)*(6-len(entry)) + (mod.__name__.split(".", 1)[1],)
|
||||||
entry = codecs.CodecInfo(*entry)
|
entry = codecs.CodecInfo(*entry)
|
||||||
|
|
|
@ -135,7 +135,7 @@ def decode_generalized_number(extended, extpos, bias, errors):
|
||||||
char = ord(extended[extpos])
|
char = ord(extended[extpos])
|
||||||
except IndexError:
|
except IndexError:
|
||||||
if errors == "strict":
|
if errors == "strict":
|
||||||
raise UnicodeError, "incomplete punicode string"
|
raise UnicodeError("incomplete punicode string")
|
||||||
return extpos + 1, None
|
return extpos + 1, None
|
||||||
extpos += 1
|
extpos += 1
|
||||||
if 0x41 <= char <= 0x5A: # A-Z
|
if 0x41 <= char <= 0x5A: # A-Z
|
||||||
|
@ -172,7 +172,7 @@ def insertion_sort(base, extended, errors):
|
||||||
char += pos // (len(base) + 1)
|
char += pos // (len(base) + 1)
|
||||||
if char > 0x10FFFF:
|
if char > 0x10FFFF:
|
||||||
if errors == "strict":
|
if errors == "strict":
|
||||||
raise UnicodeError, ("Invalid character U+%x" % char)
|
raise UnicodeError("Invalid character U+%x" % char)
|
||||||
char = ord('?')
|
char = ord('?')
|
||||||
pos = pos % (len(base) + 1)
|
pos = pos % (len(base) + 1)
|
||||||
base = base[:pos] + chr(char) + base[pos:]
|
base = base[:pos] + chr(char) + base[pos:]
|
||||||
|
@ -202,7 +202,7 @@ class Codec(codecs.Codec):
|
||||||
|
|
||||||
def decode(self, input, errors='strict'):
|
def decode(self, input, errors='strict'):
|
||||||
if errors not in ('strict', 'replace', 'ignore'):
|
if errors not in ('strict', 'replace', 'ignore'):
|
||||||
raise UnicodeError, "Unsupported error handling "+errors
|
raise UnicodeError("Unsupported error handling "+errors)
|
||||||
res = punycode_decode(input, errors)
|
res = punycode_decode(input, errors)
|
||||||
return res, len(input)
|
return res, len(input)
|
||||||
|
|
||||||
|
@ -213,7 +213,7 @@ class IncrementalEncoder(codecs.IncrementalEncoder):
|
||||||
class IncrementalDecoder(codecs.IncrementalDecoder):
|
class IncrementalDecoder(codecs.IncrementalDecoder):
|
||||||
def decode(self, input, final=False):
|
def decode(self, input, final=False):
|
||||||
if self.errors not in ('strict', 'replace', 'ignore'):
|
if self.errors not in ('strict', 'replace', 'ignore'):
|
||||||
raise UnicodeError, "Unsupported error handling "+self.errors
|
raise UnicodeError("Unsupported error handling "+self.errors)
|
||||||
return punycode_decode(input, self.errors)
|
return punycode_decode(input, self.errors)
|
||||||
|
|
||||||
class StreamWriter(Codec,codecs.StreamWriter):
|
class StreamWriter(Codec,codecs.StreamWriter):
|
||||||
|
|
|
@ -132,7 +132,7 @@ class StreamReader(codecs.StreamReader):
|
||||||
elif byteorder == 1:
|
elif byteorder == 1:
|
||||||
self.decode = codecs.utf_16_be_decode
|
self.decode = codecs.utf_16_be_decode
|
||||||
elif consumed>=2:
|
elif consumed>=2:
|
||||||
raise UnicodeError,"UTF-16 stream does not start with BOM"
|
raise UnicodeError("UTF-16 stream does not start with BOM")
|
||||||
return (object, consumed)
|
return (object, consumed)
|
||||||
|
|
||||||
### encodings module API
|
### encodings module API
|
||||||
|
|
|
@ -235,7 +235,7 @@ class dircmp:
|
||||||
|
|
||||||
def __getattr__(self, attr):
|
def __getattr__(self, attr):
|
||||||
if attr not in self.methodmap:
|
if attr not in self.methodmap:
|
||||||
raise AttributeError, attr
|
raise AttributeError(attr)
|
||||||
self.methodmap[attr](self)
|
self.methodmap[attr](self)
|
||||||
return getattr(self, attr)
|
return getattr(self, attr)
|
||||||
|
|
||||||
|
|
|
@ -99,7 +99,7 @@ def input(files=None, inplace=0, backup="", bufsize=0,
|
||||||
"""
|
"""
|
||||||
global _state
|
global _state
|
||||||
if _state and _state._file:
|
if _state and _state._file:
|
||||||
raise RuntimeError, "input() already active"
|
raise RuntimeError("input() already active")
|
||||||
_state = FileInput(files, inplace, backup, bufsize, mode, openhook)
|
_state = FileInput(files, inplace, backup, bufsize, mode, openhook)
|
||||||
return _state
|
return _state
|
||||||
|
|
||||||
|
@ -122,7 +122,7 @@ def nextfile():
|
||||||
last file has been read, this function has no effect.
|
last file has been read, this function has no effect.
|
||||||
"""
|
"""
|
||||||
if not _state:
|
if not _state:
|
||||||
raise RuntimeError, "no active input()"
|
raise RuntimeError("no active input()")
|
||||||
return _state.nextfile()
|
return _state.nextfile()
|
||||||
|
|
||||||
def filename():
|
def filename():
|
||||||
|
@ -131,7 +131,7 @@ def filename():
|
||||||
Before the first line has been read, returns None.
|
Before the first line has been read, returns None.
|
||||||
"""
|
"""
|
||||||
if not _state:
|
if not _state:
|
||||||
raise RuntimeError, "no active input()"
|
raise RuntimeError("no active input()")
|
||||||
return _state.filename()
|
return _state.filename()
|
||||||
|
|
||||||
def lineno():
|
def lineno():
|
||||||
|
@ -141,7 +141,7 @@ def lineno():
|
||||||
of the last file has been read, returns the line number of that line.
|
of the last file has been read, returns the line number of that line.
|
||||||
"""
|
"""
|
||||||
if not _state:
|
if not _state:
|
||||||
raise RuntimeError, "no active input()"
|
raise RuntimeError("no active input()")
|
||||||
return _state.lineno()
|
return _state.lineno()
|
||||||
|
|
||||||
def filelineno():
|
def filelineno():
|
||||||
|
@ -151,7 +151,7 @@ def filelineno():
|
||||||
been read, returns the line number of that line within the file.
|
been read, returns the line number of that line within the file.
|
||||||
"""
|
"""
|
||||||
if not _state:
|
if not _state:
|
||||||
raise RuntimeError, "no active input()"
|
raise RuntimeError("no active input()")
|
||||||
return _state.filelineno()
|
return _state.filelineno()
|
||||||
|
|
||||||
def fileno():
|
def fileno():
|
||||||
|
@ -160,7 +160,7 @@ def fileno():
|
||||||
opened, returns -1.
|
opened, returns -1.
|
||||||
"""
|
"""
|
||||||
if not _state:
|
if not _state:
|
||||||
raise RuntimeError, "no active input()"
|
raise RuntimeError("no active input()")
|
||||||
return _state.fileno()
|
return _state.fileno()
|
||||||
|
|
||||||
def isfirstline():
|
def isfirstline():
|
||||||
|
@ -169,7 +169,7 @@ def isfirstline():
|
||||||
otherwise returns false.
|
otherwise returns false.
|
||||||
"""
|
"""
|
||||||
if not _state:
|
if not _state:
|
||||||
raise RuntimeError, "no active input()"
|
raise RuntimeError("no active input()")
|
||||||
return _state.isfirstline()
|
return _state.isfirstline()
|
||||||
|
|
||||||
def isstdin():
|
def isstdin():
|
||||||
|
@ -178,7 +178,7 @@ def isstdin():
|
||||||
otherwise returns false.
|
otherwise returns false.
|
||||||
"""
|
"""
|
||||||
if not _state:
|
if not _state:
|
||||||
raise RuntimeError, "no active input()"
|
raise RuntimeError("no active input()")
|
||||||
return _state.isstdin()
|
return _state.isstdin()
|
||||||
|
|
||||||
class FileInput:
|
class FileInput:
|
||||||
|
@ -257,11 +257,11 @@ class FileInput:
|
||||||
|
|
||||||
def __getitem__(self, i):
|
def __getitem__(self, i):
|
||||||
if i != self._lineno:
|
if i != self._lineno:
|
||||||
raise RuntimeError, "accessing lines out of order"
|
raise RuntimeError("accessing lines out of order")
|
||||||
try:
|
try:
|
||||||
return self.__next__()
|
return self.__next__()
|
||||||
except StopIteration:
|
except StopIteration:
|
||||||
raise IndexError, "end of input reached"
|
raise IndexError("end of input reached")
|
||||||
|
|
||||||
def nextfile(self):
|
def nextfile(self):
|
||||||
savestdout = self._savestdout
|
savestdout = self._savestdout
|
||||||
|
|
|
@ -36,7 +36,7 @@ def extract(s):
|
||||||
fraction is 0 or more digits
|
fraction is 0 or more digits
|
||||||
expo is an integer"""
|
expo is an integer"""
|
||||||
res = decoder.match(s)
|
res = decoder.match(s)
|
||||||
if res is None: raise NotANumber, s
|
if res is None: raise NotANumber(s)
|
||||||
sign, intpart, fraction, exppart = res.group(1,2,3,4)
|
sign, intpart, fraction, exppart = res.group(1,2,3,4)
|
||||||
if sign == '+': sign = ''
|
if sign == '+': sign = ''
|
||||||
if fraction: fraction = fraction[1:]
|
if fraction: fraction = fraction[1:]
|
||||||
|
|
|
@ -212,16 +212,16 @@ class FTP:
|
||||||
if c in ('1', '2', '3'):
|
if c in ('1', '2', '3'):
|
||||||
return resp
|
return resp
|
||||||
if c == '4':
|
if c == '4':
|
||||||
raise error_temp, resp
|
raise error_temp(resp)
|
||||||
if c == '5':
|
if c == '5':
|
||||||
raise error_perm, resp
|
raise error_perm(resp)
|
||||||
raise error_proto, resp
|
raise error_proto(resp)
|
||||||
|
|
||||||
def voidresp(self):
|
def voidresp(self):
|
||||||
"""Expect a response beginning with '2'."""
|
"""Expect a response beginning with '2'."""
|
||||||
resp = self.getresp()
|
resp = self.getresp()
|
||||||
if resp[0] != '2':
|
if resp[0] != '2':
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
def abort(self):
|
def abort(self):
|
||||||
|
@ -234,7 +234,7 @@ class FTP:
|
||||||
self.sock.sendall(line, MSG_OOB)
|
self.sock.sendall(line, MSG_OOB)
|
||||||
resp = self.getmultiline()
|
resp = self.getmultiline()
|
||||||
if resp[:3] not in ('426', '226'):
|
if resp[:3] not in ('426', '226'):
|
||||||
raise error_proto, resp
|
raise error_proto(resp)
|
||||||
|
|
||||||
def sendcmd(self, cmd):
|
def sendcmd(self, cmd):
|
||||||
'''Send a command and return the response.'''
|
'''Send a command and return the response.'''
|
||||||
|
@ -264,7 +264,7 @@ class FTP:
|
||||||
if self.af == socket.AF_INET6:
|
if self.af == socket.AF_INET6:
|
||||||
af = 2
|
af = 2
|
||||||
if af == 0:
|
if af == 0:
|
||||||
raise error_proto, 'unsupported address family'
|
raise error_proto('unsupported address family')
|
||||||
fields = ['', repr(af), host, repr(port), '']
|
fields = ['', repr(af), host, repr(port), '']
|
||||||
cmd = 'EPRT ' + '|'.join(fields)
|
cmd = 'EPRT ' + '|'.join(fields)
|
||||||
return self.voidcmd(cmd)
|
return self.voidcmd(cmd)
|
||||||
|
@ -285,7 +285,7 @@ class FTP:
|
||||||
continue
|
continue
|
||||||
break
|
break
|
||||||
if not sock:
|
if not sock:
|
||||||
raise socket.error, msg
|
raise socket.error(msg)
|
||||||
sock.listen(1)
|
sock.listen(1)
|
||||||
port = sock.getsockname()[1] # Get proper port
|
port = sock.getsockname()[1] # Get proper port
|
||||||
host = self.sock.getsockname()[0] # Get proper host
|
host = self.sock.getsockname()[0] # Get proper host
|
||||||
|
@ -333,7 +333,7 @@ class FTP:
|
||||||
if resp[0] == '2':
|
if resp[0] == '2':
|
||||||
resp = self.getresp()
|
resp = self.getresp()
|
||||||
if resp[0] != '1':
|
if resp[0] != '1':
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
else:
|
else:
|
||||||
sock = self.makeport()
|
sock = self.makeport()
|
||||||
if rest is not None:
|
if rest is not None:
|
||||||
|
@ -343,7 +343,7 @@ class FTP:
|
||||||
if resp[0] == '2':
|
if resp[0] == '2':
|
||||||
resp = self.getresp()
|
resp = self.getresp()
|
||||||
if resp[0] != '1':
|
if resp[0] != '1':
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
conn, sockaddr = sock.accept()
|
conn, sockaddr = sock.accept()
|
||||||
if resp[:3] == '150':
|
if resp[:3] == '150':
|
||||||
# this is conditional in case we received a 125
|
# this is conditional in case we received a 125
|
||||||
|
@ -372,7 +372,7 @@ class FTP:
|
||||||
if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
|
if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
|
||||||
if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
|
if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
|
||||||
if resp[0] != '2':
|
if resp[0] != '2':
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
|
def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
|
||||||
|
@ -477,7 +477,7 @@ class FTP:
|
||||||
'''Rename a file.'''
|
'''Rename a file.'''
|
||||||
resp = self.sendcmd('RNFR ' + fromname)
|
resp = self.sendcmd('RNFR ' + fromname)
|
||||||
if resp[0] != '3':
|
if resp[0] != '3':
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
return self.voidcmd('RNTO ' + toname)
|
return self.voidcmd('RNTO ' + toname)
|
||||||
|
|
||||||
def delete(self, filename):
|
def delete(self, filename):
|
||||||
|
@ -486,9 +486,9 @@ class FTP:
|
||||||
if resp[:3] in ('250', '200'):
|
if resp[:3] in ('250', '200'):
|
||||||
return resp
|
return resp
|
||||||
elif resp[:1] == '5':
|
elif resp[:1] == '5':
|
||||||
raise error_perm, resp
|
raise error_perm(resp)
|
||||||
else:
|
else:
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
|
|
||||||
def cwd(self, dirname):
|
def cwd(self, dirname):
|
||||||
'''Change to a directory.'''
|
'''Change to a directory.'''
|
||||||
|
@ -550,7 +550,7 @@ def parse150(resp):
|
||||||
be present in the 150 message.
|
be present in the 150 message.
|
||||||
'''
|
'''
|
||||||
if resp[:3] != '150':
|
if resp[:3] != '150':
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
global _150_re
|
global _150_re
|
||||||
if _150_re is None:
|
if _150_re is None:
|
||||||
import re
|
import re
|
||||||
|
@ -573,14 +573,14 @@ def parse227(resp):
|
||||||
Return ('host.addr.as.numbers', port#) tuple.'''
|
Return ('host.addr.as.numbers', port#) tuple.'''
|
||||||
|
|
||||||
if resp[:3] != '227':
|
if resp[:3] != '227':
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
global _227_re
|
global _227_re
|
||||||
if _227_re is None:
|
if _227_re is None:
|
||||||
import re
|
import re
|
||||||
_227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)')
|
_227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)')
|
||||||
m = _227_re.search(resp)
|
m = _227_re.search(resp)
|
||||||
if not m:
|
if not m:
|
||||||
raise error_proto, resp
|
raise error_proto(resp)
|
||||||
numbers = m.groups()
|
numbers = m.groups()
|
||||||
host = '.'.join(numbers[:4])
|
host = '.'.join(numbers[:4])
|
||||||
port = (int(numbers[4]) << 8) + int(numbers[5])
|
port = (int(numbers[4]) << 8) + int(numbers[5])
|
||||||
|
@ -593,17 +593,17 @@ def parse229(resp, peer):
|
||||||
Return ('host.addr.as.numbers', port#) tuple.'''
|
Return ('host.addr.as.numbers', port#) tuple.'''
|
||||||
|
|
||||||
if resp[:3] != '229':
|
if resp[:3] != '229':
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
left = resp.find('(')
|
left = resp.find('(')
|
||||||
if left < 0: raise error_proto, resp
|
if left < 0: raise error_proto(resp)
|
||||||
right = resp.find(')', left + 1)
|
right = resp.find(')', left + 1)
|
||||||
if right < 0:
|
if right < 0:
|
||||||
raise error_proto, resp # should contain '(|||port|)'
|
raise error_proto(resp) # should contain '(|||port|)'
|
||||||
if resp[left + 1] != resp[right - 1]:
|
if resp[left + 1] != resp[right - 1]:
|
||||||
raise error_proto, resp
|
raise error_proto(resp)
|
||||||
parts = resp[left + 1:right].split(resp[left+1])
|
parts = resp[left + 1:right].split(resp[left+1])
|
||||||
if len(parts) != 5:
|
if len(parts) != 5:
|
||||||
raise error_proto, resp
|
raise error_proto(resp)
|
||||||
host = peer[0]
|
host = peer[0]
|
||||||
port = int(parts[3])
|
port = int(parts[3])
|
||||||
return host, port
|
return host, port
|
||||||
|
@ -615,7 +615,7 @@ def parse257(resp):
|
||||||
Returns the directoryname in the 257 reply.'''
|
Returns the directoryname in the 257 reply.'''
|
||||||
|
|
||||||
if resp[:3] != '257':
|
if resp[:3] != '257':
|
||||||
raise error_reply, resp
|
raise error_reply(resp)
|
||||||
if resp[3:5] != ' "':
|
if resp[3:5] != ' "':
|
||||||
return '' # Not compliant to RFC 959, but UNIX ftpd does this
|
return '' # Not compliant to RFC 959, but UNIX ftpd does this
|
||||||
dirname = ''
|
dirname = ''
|
||||||
|
@ -674,8 +674,7 @@ class Netrc:
|
||||||
filename = os.path.join(os.environ["HOME"],
|
filename = os.path.join(os.environ["HOME"],
|
||||||
".netrc")
|
".netrc")
|
||||||
else:
|
else:
|
||||||
raise IOError, \
|
raise IOError("specify file to load or set $HOME")
|
||||||
"specify file to load or set $HOME"
|
|
||||||
self.__hosts = {}
|
self.__hosts = {}
|
||||||
self.__macros = {}
|
self.__macros = {}
|
||||||
fp = open(filename, "r")
|
fp = open(filename, "r")
|
||||||
|
|
|
@ -83,11 +83,10 @@ def c2py(plural):
|
||||||
try:
|
try:
|
||||||
danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
|
danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
|
||||||
except tokenize.TokenError:
|
except tokenize.TokenError:
|
||||||
raise ValueError, \
|
raise ValueError('plural forms expression error, maybe unbalanced parenthesis')
|
||||||
'plural forms expression error, maybe unbalanced parenthesis'
|
|
||||||
else:
|
else:
|
||||||
if danger:
|
if danger:
|
||||||
raise ValueError, 'plural forms expression could be dangerous'
|
raise ValueError('plural forms expression could be dangerous')
|
||||||
|
|
||||||
# Replace some C operators by their Python equivalents
|
# Replace some C operators by their Python equivalents
|
||||||
plural = plural.replace('&&', ' and ')
|
plural = plural.replace('&&', ' and ')
|
||||||
|
@ -113,7 +112,7 @@ def c2py(plural):
|
||||||
# Actually, we never reach this code, because unbalanced
|
# Actually, we never reach this code, because unbalanced
|
||||||
# parentheses get caught in the security check at the
|
# parentheses get caught in the security check at the
|
||||||
# beginning.
|
# beginning.
|
||||||
raise ValueError, 'unbalanced parenthesis in plural form'
|
raise ValueError('unbalanced parenthesis in plural form')
|
||||||
s = expr.sub(repl, stack.pop())
|
s = expr.sub(repl, stack.pop())
|
||||||
stack[-1] += '(%s)' % s
|
stack[-1] += '(%s)' % s
|
||||||
else:
|
else:
|
||||||
|
|
18
Lib/gzip.py
18
Lib/gzip.py
|
@ -119,7 +119,7 @@ class GzipFile:
|
||||||
zlib.DEF_MEM_LEVEL,
|
zlib.DEF_MEM_LEVEL,
|
||||||
0)
|
0)
|
||||||
else:
|
else:
|
||||||
raise IOError, "Mode " + mode + " not supported"
|
raise IOError("Mode " + mode + " not supported")
|
||||||
|
|
||||||
self.fileobj = fileobj
|
self.fileobj = fileobj
|
||||||
self.offset = 0
|
self.offset = 0
|
||||||
|
@ -174,10 +174,10 @@ class GzipFile:
|
||||||
def _read_gzip_header(self):
|
def _read_gzip_header(self):
|
||||||
magic = self.fileobj.read(2)
|
magic = self.fileobj.read(2)
|
||||||
if magic != b'\037\213':
|
if magic != b'\037\213':
|
||||||
raise IOError, 'Not a gzipped file'
|
raise IOError('Not a gzipped file')
|
||||||
method = ord( self.fileobj.read(1) )
|
method = ord( self.fileobj.read(1) )
|
||||||
if method != 8:
|
if method != 8:
|
||||||
raise IOError, 'Unknown compression method'
|
raise IOError('Unknown compression method')
|
||||||
flag = ord( self.fileobj.read(1) )
|
flag = ord( self.fileobj.read(1) )
|
||||||
# modtime = self.fileobj.read(4)
|
# modtime = self.fileobj.read(4)
|
||||||
# extraflag = self.fileobj.read(1)
|
# extraflag = self.fileobj.read(1)
|
||||||
|
@ -211,7 +211,7 @@ class GzipFile:
|
||||||
raise IOError(errno.EBADF, "write() on read-only GzipFile object")
|
raise IOError(errno.EBADF, "write() on read-only GzipFile object")
|
||||||
|
|
||||||
if self.fileobj is None:
|
if self.fileobj is None:
|
||||||
raise ValueError, "write() on closed GzipFile object"
|
raise ValueError("write() on closed GzipFile object")
|
||||||
if len(data) > 0:
|
if len(data) > 0:
|
||||||
self.size = self.size + len(data)
|
self.size = self.size + len(data)
|
||||||
self.crc = zlib.crc32(data, self.crc)
|
self.crc = zlib.crc32(data, self.crc)
|
||||||
|
@ -257,7 +257,7 @@ class GzipFile:
|
||||||
|
|
||||||
def _read(self, size=1024):
|
def _read(self, size=1024):
|
||||||
if self.fileobj is None:
|
if self.fileobj is None:
|
||||||
raise EOFError, "Reached EOF"
|
raise EOFError("Reached EOF")
|
||||||
|
|
||||||
if self._new_member:
|
if self._new_member:
|
||||||
# If the _new_member flag is set, we have to
|
# If the _new_member flag is set, we have to
|
||||||
|
@ -268,7 +268,7 @@ class GzipFile:
|
||||||
pos = self.fileobj.tell() # Save current position
|
pos = self.fileobj.tell() # Save current position
|
||||||
self.fileobj.seek(0, 2) # Seek to end of file
|
self.fileobj.seek(0, 2) # Seek to end of file
|
||||||
if pos == self.fileobj.tell():
|
if pos == self.fileobj.tell():
|
||||||
raise EOFError, "Reached EOF"
|
raise EOFError("Reached EOF")
|
||||||
else:
|
else:
|
||||||
self.fileobj.seek( pos ) # Return to original position
|
self.fileobj.seek( pos ) # Return to original position
|
||||||
|
|
||||||
|
@ -287,7 +287,7 @@ class GzipFile:
|
||||||
uncompress = self.decompress.flush()
|
uncompress = self.decompress.flush()
|
||||||
self._read_eof()
|
self._read_eof()
|
||||||
self._add_read_data( uncompress )
|
self._add_read_data( uncompress )
|
||||||
raise EOFError, 'Reached EOF'
|
raise EOFError('Reached EOF')
|
||||||
|
|
||||||
uncompress = self.decompress.decompress(buf)
|
uncompress = self.decompress.decompress(buf)
|
||||||
self._add_read_data( uncompress )
|
self._add_read_data( uncompress )
|
||||||
|
@ -321,9 +321,9 @@ class GzipFile:
|
||||||
crc32 = read32(self.fileobj)
|
crc32 = read32(self.fileobj)
|
||||||
isize = U32(read32(self.fileobj)) # may exceed 2GB
|
isize = U32(read32(self.fileobj)) # may exceed 2GB
|
||||||
if U32(crc32) != U32(self.crc):
|
if U32(crc32) != U32(self.crc):
|
||||||
raise IOError, "CRC check failed"
|
raise IOError("CRC check failed")
|
||||||
elif isize != LOWU32(self.size):
|
elif isize != LOWU32(self.size):
|
||||||
raise IOError, "Incorrect length of data produced"
|
raise IOError("Incorrect length of data produced")
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
if self.mode == WRITE:
|
if self.mode == WRITE:
|
||||||
|
|
|
@ -74,7 +74,7 @@ def __get_builtin_constructor(name):
|
||||||
elif bs == '384':
|
elif bs == '384':
|
||||||
return _sha512.sha384
|
return _sha512.sha384
|
||||||
|
|
||||||
raise ValueError, "unsupported hash type"
|
raise ValueError("unsupported hash type")
|
||||||
|
|
||||||
|
|
||||||
def __py_new(name, data=b''):
|
def __py_new(name, data=b''):
|
||||||
|
|
|
@ -271,8 +271,8 @@ class ModuleLoader(BasicModuleLoader):
|
||||||
elif type == PKG_DIRECTORY:
|
elif type == PKG_DIRECTORY:
|
||||||
m = self.hooks.load_package(name, filename, file)
|
m = self.hooks.load_package(name, filename, file)
|
||||||
else:
|
else:
|
||||||
raise ImportError, "Unrecognized module type (%r) for %s" % \
|
raise ImportError("Unrecognized module type (%r) for %s"
|
||||||
(type, name)
|
% (type, name))
|
||||||
finally:
|
finally:
|
||||||
if file: file.close()
|
if file: file.close()
|
||||||
m.__file__ = filename
|
m.__file__ = filename
|
||||||
|
@ -291,14 +291,13 @@ class FancyModuleLoader(ModuleLoader):
|
||||||
if type == PKG_DIRECTORY:
|
if type == PKG_DIRECTORY:
|
||||||
initstuff = self.find_module_in_dir("__init__", filename, 0)
|
initstuff = self.find_module_in_dir("__init__", filename, 0)
|
||||||
if not initstuff:
|
if not initstuff:
|
||||||
raise ImportError, "No __init__ module in package %s" % name
|
raise ImportError("No __init__ module in package %s" % name)
|
||||||
initfile, initfilename, initinfo = initstuff
|
initfile, initfilename, initinfo = initstuff
|
||||||
initsuff, initmode, inittype = initinfo
|
initsuff, initmode, inittype = initinfo
|
||||||
if inittype not in (PY_COMPILED, PY_SOURCE):
|
if inittype not in (PY_COMPILED, PY_SOURCE):
|
||||||
if initfile: initfile.close()
|
if initfile: initfile.close()
|
||||||
raise ImportError, \
|
raise ImportError("Bad type (%r) for __init__ module"
|
||||||
"Bad type (%r) for __init__ module in package %s" % (
|
" in package %s" % (inittype, name))
|
||||||
inittype, name)
|
|
||||||
path = [filename]
|
path = [filename]
|
||||||
file = initfile
|
file = initfile
|
||||||
realfilename = initfilename
|
realfilename = initfilename
|
||||||
|
@ -361,14 +360,14 @@ class BasicModuleImporter(_Verbose):
|
||||||
return self.modules[name] # Fast path
|
return self.modules[name] # Fast path
|
||||||
stuff = self.loader.find_module(name)
|
stuff = self.loader.find_module(name)
|
||||||
if not stuff:
|
if not stuff:
|
||||||
raise ImportError, "No module named %s" % name
|
raise ImportError("No module named %s" % name)
|
||||||
return self.loader.load_module(name, stuff)
|
return self.loader.load_module(name, stuff)
|
||||||
|
|
||||||
def reload(self, module, path = None):
|
def reload(self, module, path = None):
|
||||||
name = str(module.__name__)
|
name = str(module.__name__)
|
||||||
stuff = self.loader.find_module(name, path)
|
stuff = self.loader.find_module(name, path)
|
||||||
if not stuff:
|
if not stuff:
|
||||||
raise ImportError, "Module %s not found for reload" % name
|
raise ImportError("Module %s not found for reload" % name)
|
||||||
return self.loader.load_module(name, stuff)
|
return self.loader.load_module(name, stuff)
|
||||||
|
|
||||||
def unload(self, module):
|
def unload(self, module):
|
||||||
|
@ -439,7 +438,7 @@ class ModuleImporter(BasicModuleImporter):
|
||||||
parent = None
|
parent = None
|
||||||
q = self.import_it(head, qname, parent)
|
q = self.import_it(head, qname, parent)
|
||||||
if q: return q, tail
|
if q: return q, tail
|
||||||
raise ImportError, "No module named " + qname
|
raise ImportError("No module named " + qname)
|
||||||
|
|
||||||
def load_tail(self, q, tail):
|
def load_tail(self, q, tail):
|
||||||
m = q
|
m = q
|
||||||
|
@ -450,7 +449,7 @@ class ModuleImporter(BasicModuleImporter):
|
||||||
mname = "%s.%s" % (m.__name__, head)
|
mname = "%s.%s" % (m.__name__, head)
|
||||||
m = self.import_it(head, mname, m)
|
m = self.import_it(head, mname, m)
|
||||||
if not m:
|
if not m:
|
||||||
raise ImportError, "No module named " + mname
|
raise ImportError("No module named " + mname)
|
||||||
return m
|
return m
|
||||||
|
|
||||||
def ensure_fromlist(self, m, fromlist, recursive=0):
|
def ensure_fromlist(self, m, fromlist, recursive=0):
|
||||||
|
@ -468,11 +467,11 @@ class ModuleImporter(BasicModuleImporter):
|
||||||
subname = "%s.%s" % (m.__name__, sub)
|
subname = "%s.%s" % (m.__name__, sub)
|
||||||
submod = self.import_it(sub, subname, m)
|
submod = self.import_it(sub, subname, m)
|
||||||
if not submod:
|
if not submod:
|
||||||
raise ImportError, "No module named " + subname
|
raise ImportError("No module named " + subname)
|
||||||
|
|
||||||
def import_it(self, partname, fqname, parent, force_load=0):
|
def import_it(self, partname, fqname, parent, force_load=0):
|
||||||
if not partname:
|
if not partname:
|
||||||
raise ValueError, "Empty module name"
|
raise ValueError("Empty module name")
|
||||||
if not force_load:
|
if not force_load:
|
||||||
try:
|
try:
|
||||||
return self.modules[fqname]
|
return self.modules[fqname]
|
||||||
|
|
|
@ -99,7 +99,7 @@ class ImportManager:
|
||||||
top_module = self._import_top_module(parts[0])
|
top_module = self._import_top_module(parts[0])
|
||||||
if not top_module:
|
if not top_module:
|
||||||
# the topmost module wasn't found at all.
|
# the topmost module wasn't found at all.
|
||||||
raise ImportError, 'No module named ' + fqname
|
raise ImportError('No module named ' + fqname)
|
||||||
|
|
||||||
# fast-path simple imports
|
# fast-path simple imports
|
||||||
if len(parts) == 1:
|
if len(parts) == 1:
|
||||||
|
@ -137,7 +137,7 @@ class ImportManager:
|
||||||
# If the importer does not exist, then we have to bail. A missing
|
# If the importer does not exist, then we have to bail. A missing
|
||||||
# importer means that something else imported the module, and we have
|
# importer means that something else imported the module, and we have
|
||||||
# no knowledge of how to get sub-modules out of the thing.
|
# no knowledge of how to get sub-modules out of the thing.
|
||||||
raise ImportError, 'No module named ' + fqname
|
raise ImportError('No module named ' + fqname)
|
||||||
|
|
||||||
def _determine_import_context(self, globals):
|
def _determine_import_context(self, globals):
|
||||||
"""Returns the context in which a module should be imported.
|
"""Returns the context in which a module should be imported.
|
||||||
|
@ -306,7 +306,7 @@ class Importer:
|
||||||
fqname = "%s.%s" % (m.__name__, part)
|
fqname = "%s.%s" % (m.__name__, part)
|
||||||
m = self._import_one(m, part, fqname)
|
m = self._import_one(m, part, fqname)
|
||||||
if not m:
|
if not m:
|
||||||
raise ImportError, "No module named " + fqname
|
raise ImportError("No module named " + fqname)
|
||||||
return m
|
return m
|
||||||
|
|
||||||
def _import_fromlist(self, package, fromlist):
|
def _import_fromlist(self, package, fromlist):
|
||||||
|
@ -325,7 +325,7 @@ class Importer:
|
||||||
subname = "%s.%s" % (package.__name__, sub)
|
subname = "%s.%s" % (package.__name__, sub)
|
||||||
submod = self._import_one(package, sub, subname)
|
submod = self._import_one(package, sub, subname)
|
||||||
if not submod:
|
if not submod:
|
||||||
raise ImportError, "cannot import name " + subname
|
raise ImportError("cannot import name " + subname)
|
||||||
|
|
||||||
def _do_import(self, parent, parts, fromlist):
|
def _do_import(self, parent, parts, fromlist):
|
||||||
"""Attempt to import the module relative to parent.
|
"""Attempt to import the module relative to parent.
|
||||||
|
@ -377,7 +377,7 @@ class Importer:
|
||||||
object, then these names/values will be inserted *after* the module
|
object, then these names/values will be inserted *after* the module
|
||||||
has been loaded/initialized.
|
has been loaded/initialized.
|
||||||
"""
|
"""
|
||||||
raise RuntimeError, "get_code not implemented"
|
raise RuntimeError("get_code not implemented")
|
||||||
|
|
||||||
|
|
||||||
######################################################################
|
######################################################################
|
||||||
|
@ -452,7 +452,7 @@ def _os_bootstrap():
|
||||||
a = a + ':'
|
a = a + ':'
|
||||||
return a + b
|
return a + b
|
||||||
else:
|
else:
|
||||||
raise ImportError, 'no os specific module found'
|
raise ImportError('no os specific module found')
|
||||||
|
|
||||||
if join is None:
|
if join is None:
|
||||||
def join(a, b, sep=sep):
|
def join(a, b, sep=sep):
|
||||||
|
|
|
@ -724,7 +724,7 @@ def getargspec(func):
|
||||||
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
|
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
|
||||||
getfullargspec(func)
|
getfullargspec(func)
|
||||||
if kwonlyargs or ann:
|
if kwonlyargs or ann:
|
||||||
raise ValueError, ("Function has keyword-only arguments or annotations"
|
raise ValueError("Function has keyword-only arguments or annotations"
|
||||||
", use getfullargspec() API which can support them")
|
", use getfullargspec() API which can support them")
|
||||||
return (args, varargs, varkw, defaults)
|
return (args, varargs, varkw, defaults)
|
||||||
|
|
||||||
|
|
|
@ -31,7 +31,7 @@ from Tkinter import _flatten, _cnfmerge, _default_root
|
||||||
|
|
||||||
# WARNING - TkVersion is a limited precision floating point number
|
# WARNING - TkVersion is a limited precision floating point number
|
||||||
if TkVersion < 3.999:
|
if TkVersion < 3.999:
|
||||||
raise ImportError, "This version of Tix.py requires Tk 4.0 or higher"
|
raise ImportError("This version of Tix.py requires Tk 4.0 or higher")
|
||||||
|
|
||||||
import _tkinter # If this fails your Python may not be configured for Tk
|
import _tkinter # If this fails your Python may not be configured for Tk
|
||||||
|
|
||||||
|
@ -323,7 +323,7 @@ class TixWidget(Tkinter.Widget):
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name):
|
||||||
if name in self.subwidget_list:
|
if name in self.subwidget_list:
|
||||||
return self.subwidget_list[name]
|
return self.subwidget_list[name]
|
||||||
raise AttributeError, name
|
raise AttributeError(name)
|
||||||
|
|
||||||
def set_silent(self, value):
|
def set_silent(self, value):
|
||||||
"""Set a variable without calling its action routine"""
|
"""Set a variable without calling its action routine"""
|
||||||
|
@ -334,7 +334,7 @@ class TixWidget(Tkinter.Widget):
|
||||||
the sub-class)."""
|
the sub-class)."""
|
||||||
n = self._subwidget_name(name)
|
n = self._subwidget_name(name)
|
||||||
if not n:
|
if not n:
|
||||||
raise TclError, "Subwidget " + name + " not child of " + self._name
|
raise TclError("Subwidget " + name + " not child of " + self._name)
|
||||||
# Remove header of name and leading dot
|
# Remove header of name and leading dot
|
||||||
n = n[len(self._w)+1:]
|
n = n[len(self._w)+1:]
|
||||||
return self._nametowidget(n)
|
return self._nametowidget(n)
|
||||||
|
@ -385,7 +385,7 @@ class TixWidget(Tkinter.Widget):
|
||||||
if not master:
|
if not master:
|
||||||
master = Tkinter._default_root
|
master = Tkinter._default_root
|
||||||
if not master:
|
if not master:
|
||||||
raise RuntimeError, 'Too early to create image'
|
raise RuntimeError('Too early to create image')
|
||||||
if kw and cnf: cnf = _cnfmerge((cnf, kw))
|
if kw and cnf: cnf = _cnfmerge((cnf, kw))
|
||||||
elif kw: cnf = kw
|
elif kw: cnf = kw
|
||||||
options = ()
|
options = ()
|
||||||
|
@ -475,7 +475,7 @@ class DisplayStyle:
|
||||||
master = _default_root # global from Tkinter
|
master = _default_root # global from Tkinter
|
||||||
if not master and 'refwindow' in cnf: master=cnf['refwindow']
|
if not master and 'refwindow' in cnf: master=cnf['refwindow']
|
||||||
elif not master and 'refwindow' in kw: master= kw['refwindow']
|
elif not master and 'refwindow' in kw: master= kw['refwindow']
|
||||||
elif not master: raise RuntimeError, "Too early to create display style: no root window"
|
elif not master: raise RuntimeError("Too early to create display style: no root window")
|
||||||
self.tk = master.tk
|
self.tk = master.tk
|
||||||
self.stylename = self.tk.call('tixDisplayStyle', itemtype,
|
self.stylename = self.tk.call('tixDisplayStyle', itemtype,
|
||||||
*self._options(cnf,kw) )
|
*self._options(cnf,kw) )
|
||||||
|
|
|
@ -158,7 +158,7 @@ def _tkerror(err):
|
||||||
|
|
||||||
def _exit(code='0'):
|
def _exit(code='0'):
|
||||||
"""Internal function. Calling it will throw the exception SystemExit."""
|
"""Internal function. Calling it will throw the exception SystemExit."""
|
||||||
raise SystemExit, code
|
raise SystemExit(code)
|
||||||
|
|
||||||
_varnum = 0
|
_varnum = 0
|
||||||
class Variable:
|
class Variable:
|
||||||
|
@ -1401,7 +1401,7 @@ class CallWrapper:
|
||||||
args = self.subst(*args)
|
args = self.subst(*args)
|
||||||
return self.func(*args)
|
return self.func(*args)
|
||||||
except SystemExit as msg:
|
except SystemExit as msg:
|
||||||
raise SystemExit, msg
|
raise SystemExit(msg)
|
||||||
except:
|
except:
|
||||||
self.widget._report_exception()
|
self.widget._report_exception()
|
||||||
|
|
||||||
|
@ -1652,19 +1652,16 @@ class Tk(Misc, Wm):
|
||||||
# Version sanity checks
|
# Version sanity checks
|
||||||
tk_version = self.tk.getvar('tk_version')
|
tk_version = self.tk.getvar('tk_version')
|
||||||
if tk_version != _tkinter.TK_VERSION:
|
if tk_version != _tkinter.TK_VERSION:
|
||||||
raise RuntimeError, \
|
raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
|
||||||
"tk.h version (%s) doesn't match libtk.a version (%s)" \
|
% (_tkinter.TK_VERSION, tk_version))
|
||||||
% (_tkinter.TK_VERSION, tk_version)
|
|
||||||
# Under unknown circumstances, tcl_version gets coerced to float
|
# Under unknown circumstances, tcl_version gets coerced to float
|
||||||
tcl_version = str(self.tk.getvar('tcl_version'))
|
tcl_version = str(self.tk.getvar('tcl_version'))
|
||||||
if tcl_version != _tkinter.TCL_VERSION:
|
if tcl_version != _tkinter.TCL_VERSION:
|
||||||
raise RuntimeError, \
|
raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
|
||||||
"tcl.h version (%s) doesn't match libtcl.a version (%s)" \
|
% (_tkinter.TCL_VERSION, tcl_version))
|
||||||
% (_tkinter.TCL_VERSION, tcl_version)
|
|
||||||
if TkVersion < 4.0:
|
if TkVersion < 4.0:
|
||||||
raise RuntimeError, \
|
raise RuntimeError("Tk 4.0 or higher is required; found Tk %s"
|
||||||
"Tk 4.0 or higher is required; found Tk %s" \
|
% str(TkVersion))
|
||||||
% str(TkVersion)
|
|
||||||
# Create and register the tkerror and exit commands
|
# Create and register the tkerror and exit commands
|
||||||
# We need to inline parts of _register here, _ register
|
# We need to inline parts of _register here, _ register
|
||||||
# would register differently-named commands.
|
# would register differently-named commands.
|
||||||
|
@ -3182,7 +3179,7 @@ class OptionMenu(Menubutton):
|
||||||
if 'command' in kwargs:
|
if 'command' in kwargs:
|
||||||
del kwargs['command']
|
del kwargs['command']
|
||||||
if kwargs:
|
if kwargs:
|
||||||
raise TclError, 'unknown option -'+kwargs.keys()[0]
|
raise TclError('unknown option -'+kwargs.keys()[0])
|
||||||
menu.add_command(label=value,
|
menu.add_command(label=value,
|
||||||
command=_setit(variable, value, callback))
|
command=_setit(variable, value, callback))
|
||||||
for v in values:
|
for v in values:
|
||||||
|
@ -3208,7 +3205,7 @@ class Image:
|
||||||
if not master:
|
if not master:
|
||||||
master = _default_root
|
master = _default_root
|
||||||
if not master:
|
if not master:
|
||||||
raise RuntimeError, 'Too early to create image'
|
raise RuntimeError('Too early to create image')
|
||||||
self.tk = master.tk
|
self.tk = master.tk
|
||||||
if not name:
|
if not name:
|
||||||
Image._last_id += 1
|
Image._last_id += 1
|
||||||
|
|
|
@ -18,7 +18,7 @@ class Dialog:
|
||||||
|
|
||||||
# FIXME: should this be placed on the module level instead?
|
# FIXME: should this be placed on the module level instead?
|
||||||
if TkVersion < 4.2:
|
if TkVersion < 4.2:
|
||||||
raise TclError, "this module requires Tk 4.2 or newer"
|
raise TclError("this module requires Tk 4.2 or newer")
|
||||||
|
|
||||||
self.master = master
|
self.master = master
|
||||||
self.options = options
|
self.options = options
|
||||||
|
|
|
@ -79,7 +79,7 @@ class Font:
|
||||||
self.delete_font = False
|
self.delete_font = False
|
||||||
# confirm font exists
|
# confirm font exists
|
||||||
if self.name not in root.tk.call("font", "names"):
|
if self.name not in root.tk.call("font", "names"):
|
||||||
raise Tkinter._tkinter.TclError, "named font %s does not already exist" % (self.name,)
|
raise Tkinter._tkinter.TclError("named font %s does not already exist" % (self.name,))
|
||||||
# if font config info supplied, apply it
|
# if font config info supplied, apply it
|
||||||
if font:
|
if font:
|
||||||
root.tk.call("font", "configure", self.name, *font)
|
root.tk.call("font", "configure", self.name, *font)
|
||||||
|
|
|
@ -231,7 +231,7 @@ class RawPen:
|
||||||
>>> turtle.color(0, .5, 0)
|
>>> turtle.color(0, .5, 0)
|
||||||
"""
|
"""
|
||||||
if not args:
|
if not args:
|
||||||
raise Error, "no color arguments"
|
raise Error("no color arguments")
|
||||||
if len(args) == 1:
|
if len(args) == 1:
|
||||||
color = args[0]
|
color = args[0]
|
||||||
if type(color) == type(""):
|
if type(color) == type(""):
|
||||||
|
@ -239,18 +239,18 @@ class RawPen:
|
||||||
try:
|
try:
|
||||||
id = self._canvas.create_line(0, 0, 0, 0, fill=color)
|
id = self._canvas.create_line(0, 0, 0, 0, fill=color)
|
||||||
except Tkinter.TclError:
|
except Tkinter.TclError:
|
||||||
raise Error, "bad color string: %r" % (color,)
|
raise Error("bad color string: %r" % (color,))
|
||||||
self._set_color(color)
|
self._set_color(color)
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
r, g, b = color
|
r, g, b = color
|
||||||
except:
|
except:
|
||||||
raise Error, "bad color sequence: %r" % (color,)
|
raise Error("bad color sequence: %r" % (color,))
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
r, g, b = args
|
r, g, b = args
|
||||||
except:
|
except:
|
||||||
raise Error, "bad color arguments: %r" % (args,)
|
raise Error("bad color arguments: %r" % (args,))
|
||||||
assert 0 <= r <= 1
|
assert 0 <= r <= 1
|
||||||
assert 0 <= g <= 1
|
assert 0 <= g <= 1
|
||||||
assert 0 <= b <= 1
|
assert 0 <= b <= 1
|
||||||
|
@ -520,12 +520,12 @@ class RawPen:
|
||||||
try:
|
try:
|
||||||
x, y = args[0]
|
x, y = args[0]
|
||||||
except:
|
except:
|
||||||
raise Error, "bad point argument: %r" % (args[0],)
|
raise Error("bad point argument: %r" % (args[0],))
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
x, y = args
|
x, y = args
|
||||||
except:
|
except:
|
||||||
raise Error, "bad coordinates: %r" % (args[0],)
|
raise Error("bad coordinates: %r" % (args[0],))
|
||||||
x0, y0 = self._origin
|
x0, y0 = self._origin
|
||||||
self._goto(x0+x, y0-y)
|
self._goto(x0+x, y0-y)
|
||||||
|
|
||||||
|
@ -752,25 +752,25 @@ def setup(**geometry):
|
||||||
if width >= 0 or width == None:
|
if width >= 0 or width == None:
|
||||||
_width = width
|
_width = width
|
||||||
else:
|
else:
|
||||||
raise ValueError, "width can not be less than 0"
|
raise ValueError("width can not be less than 0")
|
||||||
|
|
||||||
height = geometry.get('height',_height)
|
height = geometry.get('height',_height)
|
||||||
if height >= 0 or height == None:
|
if height >= 0 or height == None:
|
||||||
_height = height
|
_height = height
|
||||||
else:
|
else:
|
||||||
raise ValueError, "height can not be less than 0"
|
raise ValueError("height can not be less than 0")
|
||||||
|
|
||||||
startx = geometry.get('startx', _startx)
|
startx = geometry.get('startx', _startx)
|
||||||
if startx >= 0 or startx == None:
|
if startx >= 0 or startx == None:
|
||||||
_startx = _startx
|
_startx = _startx
|
||||||
else:
|
else:
|
||||||
raise ValueError, "startx can not be less than 0"
|
raise ValueError("startx can not be less than 0")
|
||||||
|
|
||||||
starty = geometry.get('starty', _starty)
|
starty = geometry.get('starty', _starty)
|
||||||
if starty >= 0 or starty == None:
|
if starty >= 0 or starty == None:
|
||||||
_starty = starty
|
_starty = starty
|
||||||
else:
|
else:
|
||||||
raise ValueError, "startx can not be less than 0"
|
raise ValueError("startx can not be less than 0")
|
||||||
|
|
||||||
|
|
||||||
if _root and _width and _height:
|
if _root and _width and _height:
|
||||||
|
|
|
@ -72,7 +72,7 @@ except ImportError:
|
||||||
Activates/queries locale processing.
|
Activates/queries locale processing.
|
||||||
"""
|
"""
|
||||||
if value not in (None, '', 'C'):
|
if value not in (None, '', 'C'):
|
||||||
raise Error, '_locale emulation only supports "C" locale'
|
raise Error('_locale emulation only supports "C" locale')
|
||||||
return 'C'
|
return 'C'
|
||||||
|
|
||||||
def strcoll(a,b):
|
def strcoll(a,b):
|
||||||
|
@ -372,7 +372,7 @@ def _parse_localename(localename):
|
||||||
return tuple(code.split('.')[:2])
|
return tuple(code.split('.')[:2])
|
||||||
elif code == 'C':
|
elif code == 'C':
|
||||||
return None, None
|
return None, None
|
||||||
raise ValueError, 'unknown locale: %s' % localename
|
raise ValueError('unknown locale: %s' % localename)
|
||||||
|
|
||||||
def _build_localename(localetuple):
|
def _build_localename(localetuple):
|
||||||
|
|
||||||
|
@ -458,7 +458,7 @@ def getlocale(category=LC_CTYPE):
|
||||||
"""
|
"""
|
||||||
localename = _setlocale(category)
|
localename = _setlocale(category)
|
||||||
if category == LC_ALL and ';' in localename:
|
if category == LC_ALL and ';' in localename:
|
||||||
raise TypeError, 'category LC_ALL is not supported'
|
raise TypeError('category LC_ALL is not supported')
|
||||||
return _parse_localename(localename)
|
return _parse_localename(localename)
|
||||||
|
|
||||||
def setlocale(category, locale=None):
|
def setlocale(category, locale=None):
|
||||||
|
|
|
@ -638,8 +638,8 @@ class Handler(Filterer):
|
||||||
This version is intended to be implemented by subclasses and so
|
This version is intended to be implemented by subclasses and so
|
||||||
raises a NotImplementedError.
|
raises a NotImplementedError.
|
||||||
"""
|
"""
|
||||||
raise NotImplementedError, 'emit must be implemented '\
|
raise NotImplementedError('emit must be implemented '
|
||||||
'by Handler subclasses'
|
'by Handler subclasses')
|
||||||
|
|
||||||
def handle(self, record):
|
def handle(self, record):
|
||||||
"""
|
"""
|
||||||
|
@ -834,8 +834,8 @@ def setLoggerClass(klass):
|
||||||
"""
|
"""
|
||||||
if klass != Logger:
|
if klass != Logger:
|
||||||
if not issubclass(klass, Logger):
|
if not issubclass(klass, Logger):
|
||||||
raise TypeError, "logger not derived from logging.Logger: " + \
|
raise TypeError("logger not derived from logging.Logger: "
|
||||||
klass.__name__
|
+ klass.__name__)
|
||||||
global _loggerClass
|
global _loggerClass
|
||||||
_loggerClass = klass
|
_loggerClass = klass
|
||||||
|
|
||||||
|
@ -1047,7 +1047,7 @@ class Logger(Filterer):
|
||||||
"""
|
"""
|
||||||
if not isinstance(level, int):
|
if not isinstance(level, int):
|
||||||
if raiseExceptions:
|
if raiseExceptions:
|
||||||
raise TypeError, "level must be an integer"
|
raise TypeError("level must be an integer")
|
||||||
else:
|
else:
|
||||||
return
|
return
|
||||||
if self.isEnabledFor(level):
|
if self.isEnabledFor(level):
|
||||||
|
|
|
@ -246,7 +246,7 @@ def listen(port=DEFAULT_LOGGING_CONFIG_PORT):
|
||||||
stopListening().
|
stopListening().
|
||||||
"""
|
"""
|
||||||
if not thread:
|
if not thread:
|
||||||
raise NotImplementedError, "listen() needs threading to work"
|
raise NotImplementedError("listen() needs threading to work")
|
||||||
|
|
||||||
class ConfigStreamHandler(StreamRequestHandler):
|
class ConfigStreamHandler(StreamRequestHandler):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -920,7 +920,7 @@ class HTTPHandler(logging.Handler):
|
||||||
logging.Handler.__init__(self)
|
logging.Handler.__init__(self)
|
||||||
method = method.upper()
|
method = method.upper()
|
||||||
if method not in ["GET", "POST"]:
|
if method not in ["GET", "POST"]:
|
||||||
raise ValueError, "method must be GET or POST"
|
raise ValueError("method must be GET or POST")
|
||||||
self.host = host
|
self.host = host
|
||||||
self.url = url
|
self.url = url
|
||||||
self.method = method
|
self.method = method
|
||||||
|
|
|
@ -143,7 +143,7 @@ def normpath(s):
|
||||||
i = i - 1
|
i = i - 1
|
||||||
else:
|
else:
|
||||||
# best way to handle this is to raise an exception
|
# best way to handle this is to raise an exception
|
||||||
raise norm_error, 'Cannot use :: immediately after volume name'
|
raise norm_error('Cannot use :: immediately after volume name')
|
||||||
else:
|
else:
|
||||||
i = i + 1
|
i = i + 1
|
||||||
|
|
||||||
|
|
|
@ -15,12 +15,12 @@ def url2pathname(pathname):
|
||||||
#
|
#
|
||||||
tp = urllib.splittype(pathname)[0]
|
tp = urllib.splittype(pathname)[0]
|
||||||
if tp and tp != 'file':
|
if tp and tp != 'file':
|
||||||
raise RuntimeError, 'Cannot convert non-local URL to pathname'
|
raise RuntimeError('Cannot convert non-local URL to pathname')
|
||||||
# Turn starting /// into /, an empty hostname means current host
|
# Turn starting /// into /, an empty hostname means current host
|
||||||
if pathname[:3] == '///':
|
if pathname[:3] == '///':
|
||||||
pathname = pathname[2:]
|
pathname = pathname[2:]
|
||||||
elif pathname[:2] == '//':
|
elif pathname[:2] == '//':
|
||||||
raise RuntimeError, 'Cannot convert non-local URL to pathname'
|
raise RuntimeError('Cannot convert non-local URL to pathname')
|
||||||
components = pathname.split('/')
|
components = pathname.split('/')
|
||||||
# Remove . and embedded ..
|
# Remove . and embedded ..
|
||||||
i = 0
|
i = 0
|
||||||
|
@ -53,7 +53,7 @@ def pathname2url(pathname):
|
||||||
"""OS-specific conversion from a file system path to a relative URL
|
"""OS-specific conversion from a file system path to a relative URL
|
||||||
of the 'file' scheme; not recommended for general use."""
|
of the 'file' scheme; not recommended for general use."""
|
||||||
if '/' in pathname:
|
if '/' in pathname:
|
||||||
raise RuntimeError, "Cannot convert pathname containing slashes"
|
raise RuntimeError("Cannot convert pathname containing slashes")
|
||||||
components = pathname.split(':')
|
components = pathname.split(':')
|
||||||
# Remove empty first and/or last component
|
# Remove empty first and/or last component
|
||||||
if components[0] == '':
|
if components[0] == '':
|
||||||
|
|
44
Lib/mhlib.py
44
Lib/mhlib.py
|
@ -104,7 +104,7 @@ class MH:
|
||||||
if not os.path.isabs(path) and path[0] != '~':
|
if not os.path.isabs(path) and path[0] != '~':
|
||||||
path = os.path.join('~', path)
|
path = os.path.join('~', path)
|
||||||
path = os.path.expanduser(path)
|
path = os.path.expanduser(path)
|
||||||
if not os.path.isdir(path): raise Error, 'MH() path not found'
|
if not os.path.isdir(path): raise Error('MH() path not found')
|
||||||
self.path = path
|
self.path = path
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
|
@ -243,7 +243,7 @@ class Folder:
|
||||||
self.mh = mh
|
self.mh = mh
|
||||||
self.name = name
|
self.name = name
|
||||||
if not os.path.isdir(self.getfullname()):
|
if not os.path.isdir(self.getfullname()):
|
||||||
raise Error, 'no folder %s' % name
|
raise Error('no folder %s' % name)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
"""String representation."""
|
"""String representation."""
|
||||||
|
@ -332,7 +332,7 @@ class Folder:
|
||||||
try:
|
try:
|
||||||
return max(seqs['cur'])
|
return max(seqs['cur'])
|
||||||
except (ValueError, KeyError):
|
except (ValueError, KeyError):
|
||||||
raise Error, "no cur message"
|
raise Error("no cur message")
|
||||||
|
|
||||||
def setcurrent(self, n):
|
def setcurrent(self, n):
|
||||||
"""Set the current message."""
|
"""Set the current message."""
|
||||||
|
@ -350,7 +350,7 @@ class Folder:
|
||||||
all = self.listmessages()
|
all = self.listmessages()
|
||||||
# Observed behavior: test for empty folder is done first
|
# Observed behavior: test for empty folder is done first
|
||||||
if not all:
|
if not all:
|
||||||
raise Error, "no messages in %s" % self.name
|
raise Error("no messages in %s" % self.name)
|
||||||
# Common case first: all is frequently the default
|
# Common case first: all is frequently the default
|
||||||
if seq == 'all':
|
if seq == 'all':
|
||||||
return all
|
return all
|
||||||
|
@ -361,7 +361,7 @@ class Folder:
|
||||||
if tail[:1] in '-+':
|
if tail[:1] in '-+':
|
||||||
dir, tail = tail[:1], tail[1:]
|
dir, tail = tail[:1], tail[1:]
|
||||||
if not isnumeric(tail):
|
if not isnumeric(tail):
|
||||||
raise Error, "bad message list %s" % seq
|
raise Error("bad message list %s" % seq)
|
||||||
try:
|
try:
|
||||||
count = int(tail)
|
count = int(tail)
|
||||||
except (ValueError, OverflowError):
|
except (ValueError, OverflowError):
|
||||||
|
@ -374,10 +374,10 @@ class Folder:
|
||||||
if not head in seqs:
|
if not head in seqs:
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "bad message list %s" % seq
|
msg = "bad message list %s" % seq
|
||||||
raise Error, msg, sys.exc_info()[2]
|
raise Error(msg).with_traceback(sys.exc_info()[2])
|
||||||
msgs = seqs[head]
|
msgs = seqs[head]
|
||||||
if not msgs:
|
if not msgs:
|
||||||
raise Error, "sequence %s empty" % head
|
raise Error("sequence %s empty" % head)
|
||||||
if dir == '-':
|
if dir == '-':
|
||||||
return msgs[-count:]
|
return msgs[-count:]
|
||||||
else:
|
else:
|
||||||
|
@ -401,7 +401,7 @@ class Folder:
|
||||||
j = bisect(all, end)
|
j = bisect(all, end)
|
||||||
r = all[i:j]
|
r = all[i:j]
|
||||||
if not r:
|
if not r:
|
||||||
raise Error, "bad message list %s" % seq
|
raise Error("bad message list %s" % seq)
|
||||||
return r
|
return r
|
||||||
# Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence
|
# Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence
|
||||||
try:
|
try:
|
||||||
|
@ -411,14 +411,14 @@ class Folder:
|
||||||
if not seq in seqs:
|
if not seq in seqs:
|
||||||
if not msg:
|
if not msg:
|
||||||
msg = "bad message list %s" % seq
|
msg = "bad message list %s" % seq
|
||||||
raise Error, msg
|
raise Error(msg)
|
||||||
return seqs[seq]
|
return seqs[seq]
|
||||||
else:
|
else:
|
||||||
if n not in all:
|
if n not in all:
|
||||||
if isnumeric(seq):
|
if isnumeric(seq):
|
||||||
raise Error, "message %d doesn't exist" % n
|
raise Error("message %d doesn't exist" % n)
|
||||||
else:
|
else:
|
||||||
raise Error, "no %s message" % seq
|
raise Error("no %s message" % seq)
|
||||||
else:
|
else:
|
||||||
return [n]
|
return [n]
|
||||||
|
|
||||||
|
@ -441,17 +441,17 @@ class Folder:
|
||||||
try:
|
try:
|
||||||
return all[i]
|
return all[i]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
raise Error, "no next message"
|
raise Error("no next message")
|
||||||
if seq == 'prev':
|
if seq == 'prev':
|
||||||
n = self.getcurrent()
|
n = self.getcurrent()
|
||||||
i = bisect(all, n-1)
|
i = bisect(all, n-1)
|
||||||
if i == 0:
|
if i == 0:
|
||||||
raise Error, "no prev message"
|
raise Error("no prev message")
|
||||||
try:
|
try:
|
||||||
return all[i-1]
|
return all[i-1]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
raise Error, "no prev message"
|
raise Error("no prev message")
|
||||||
raise Error, None
|
raise Error()
|
||||||
|
|
||||||
def openmessage(self, n):
|
def openmessage(self, n):
|
||||||
"""Open a message -- returns a Message object."""
|
"""Open a message -- returns a Message object."""
|
||||||
|
@ -478,9 +478,9 @@ class Folder:
|
||||||
self.removefromallsequences(deleted)
|
self.removefromallsequences(deleted)
|
||||||
if errors:
|
if errors:
|
||||||
if len(errors) == 1:
|
if len(errors) == 1:
|
||||||
raise os.error, errors[0]
|
raise os.error(errors[0])
|
||||||
else:
|
else:
|
||||||
raise os.error, ('multiple errors:', errors)
|
raise os.error('multiple errors:', errors)
|
||||||
|
|
||||||
def refilemessages(self, list, tofolder, keepsequences=0):
|
def refilemessages(self, list, tofolder, keepsequences=0):
|
||||||
"""Refile one or more messages -- may raise os.error.
|
"""Refile one or more messages -- may raise os.error.
|
||||||
|
@ -513,9 +513,9 @@ class Folder:
|
||||||
self.removefromallsequences(refiled.keys())
|
self.removefromallsequences(refiled.keys())
|
||||||
if errors:
|
if errors:
|
||||||
if len(errors) == 1:
|
if len(errors) == 1:
|
||||||
raise os.error, errors[0]
|
raise os.error(errors[0])
|
||||||
else:
|
else:
|
||||||
raise os.error, ('multiple errors:', errors)
|
raise os.error('multiple errors:', errors)
|
||||||
|
|
||||||
def _copysequences(self, fromfolder, refileditems):
|
def _copysequences(self, fromfolder, refileditems):
|
||||||
"""Helper for refilemessages() to copy sequences."""
|
"""Helper for refilemessages() to copy sequences."""
|
||||||
|
@ -706,10 +706,10 @@ class Message(mimetools.Message):
|
||||||
list of SubMessage objects. Each submessage object behaves
|
list of SubMessage objects. Each submessage object behaves
|
||||||
(almost) as a Message object."""
|
(almost) as a Message object."""
|
||||||
if self.getmaintype() != 'multipart':
|
if self.getmaintype() != 'multipart':
|
||||||
raise Error, 'Content-Type is not multipart/*'
|
raise Error('Content-Type is not multipart/*')
|
||||||
bdry = self.getparam('boundary')
|
bdry = self.getparam('boundary')
|
||||||
if not bdry:
|
if not bdry:
|
||||||
raise Error, 'multipart/* without boundary param'
|
raise Error('multipart/* without boundary param')
|
||||||
self.fp.seek(self.startofbody)
|
self.fp.seek(self.startofbody)
|
||||||
mf = multifile.MultiFile(self.fp)
|
mf = multifile.MultiFile(self.fp)
|
||||||
mf.push(bdry)
|
mf.push(bdry)
|
||||||
|
@ -890,7 +890,7 @@ class IntSet:
|
||||||
elif len(list) == 2 and list[0] <= list[1]:
|
elif len(list) == 2 and list[0] <= list[1]:
|
||||||
new.append((list[0], list[1]))
|
new.append((list[0], list[1]))
|
||||||
else:
|
else:
|
||||||
raise ValueError, 'bad data passed to IntSet'
|
raise ValueError('bad data passed to IntSet')
|
||||||
self.pairs = self.pairs + new
|
self.pairs = self.pairs + new
|
||||||
self.normalize()
|
self.normalize()
|
||||||
|
|
||||||
|
|
|
@ -162,8 +162,7 @@ def decode(input, output, encoding):
|
||||||
if encoding in decodetab:
|
if encoding in decodetab:
|
||||||
pipethrough(input, decodetab[encoding], output)
|
pipethrough(input, decodetab[encoding], output)
|
||||||
else:
|
else:
|
||||||
raise ValueError, \
|
raise ValueError('unknown Content-Transfer-Encoding: %s' % encoding)
|
||||||
'unknown Content-Transfer-Encoding: %s' % encoding
|
|
||||||
|
|
||||||
def encode(input, output, encoding):
|
def encode(input, output, encoding):
|
||||||
"""Encode common content-transfer-encodings (base64, quopri, uuencode)."""
|
"""Encode common content-transfer-encodings (base64, quopri, uuencode)."""
|
||||||
|
@ -181,8 +180,7 @@ def encode(input, output, encoding):
|
||||||
if encoding in encodetab:
|
if encoding in encodetab:
|
||||||
pipethrough(input, encodetab[encoding], output)
|
pipethrough(input, encodetab[encoding], output)
|
||||||
else:
|
else:
|
||||||
raise ValueError, \
|
raise ValueError('unknown Content-Transfer-Encoding: %s' % encoding)
|
||||||
'unknown Content-Transfer-Encoding: %s' % encoding
|
|
||||||
|
|
||||||
# The following is no longer used for standard encodings
|
# The following is no longer used for standard encodings
|
||||||
|
|
||||||
|
|
|
@ -146,7 +146,7 @@ class ModuleFinder:
|
||||||
self.msgout(4, "determine_parent ->", parent)
|
self.msgout(4, "determine_parent ->", parent)
|
||||||
return parent
|
return parent
|
||||||
if pname.count(".") < level:
|
if pname.count(".") < level:
|
||||||
raise ImportError, "relative importpath too deep"
|
raise ImportError("relative importpath too deep")
|
||||||
pname = ".".join(pname.split(".")[:-level])
|
pname = ".".join(pname.split(".")[:-level])
|
||||||
parent = self.modules[pname]
|
parent = self.modules[pname]
|
||||||
self.msgout(4, "determine_parent ->", parent)
|
self.msgout(4, "determine_parent ->", parent)
|
||||||
|
@ -191,7 +191,7 @@ class ModuleFinder:
|
||||||
self.msgout(4, "find_head_package ->", (q, tail))
|
self.msgout(4, "find_head_package ->", (q, tail))
|
||||||
return q, tail
|
return q, tail
|
||||||
self.msgout(4, "raise ImportError: No module named", qname)
|
self.msgout(4, "raise ImportError: No module named", qname)
|
||||||
raise ImportError, "No module named " + qname
|
raise ImportError("No module named " + qname)
|
||||||
|
|
||||||
def load_tail(self, q, tail):
|
def load_tail(self, q, tail):
|
||||||
self.msgin(4, "load_tail", q, tail)
|
self.msgin(4, "load_tail", q, tail)
|
||||||
|
@ -204,7 +204,7 @@ class ModuleFinder:
|
||||||
m = self.import_module(head, mname, m)
|
m = self.import_module(head, mname, m)
|
||||||
if not m:
|
if not m:
|
||||||
self.msgout(4, "raise ImportError: No module named", mname)
|
self.msgout(4, "raise ImportError: No module named", mname)
|
||||||
raise ImportError, "No module named " + mname
|
raise ImportError("No module named " + mname)
|
||||||
self.msgout(4, "load_tail ->", m)
|
self.msgout(4, "load_tail ->", m)
|
||||||
return m
|
return m
|
||||||
|
|
||||||
|
@ -220,7 +220,7 @@ class ModuleFinder:
|
||||||
subname = "%s.%s" % (m.__name__, sub)
|
subname = "%s.%s" % (m.__name__, sub)
|
||||||
submod = self.import_module(sub, subname, m)
|
submod = self.import_module(sub, subname, m)
|
||||||
if not submod:
|
if not submod:
|
||||||
raise ImportError, "No module named " + subname
|
raise ImportError("No module named " + subname)
|
||||||
|
|
||||||
def find_all_submodules(self, m):
|
def find_all_submodules(self, m):
|
||||||
if not m.__path__:
|
if not m.__path__:
|
||||||
|
@ -291,7 +291,7 @@ class ModuleFinder:
|
||||||
elif type == imp.PY_COMPILED:
|
elif type == imp.PY_COMPILED:
|
||||||
if fp.read(4) != imp.get_magic():
|
if fp.read(4) != imp.get_magic():
|
||||||
self.msgout(2, "raise ImportError: Bad magic number", pathname)
|
self.msgout(2, "raise ImportError: Bad magic number", pathname)
|
||||||
raise ImportError, "Bad magic number in %s" % pathname
|
raise ImportError("Bad magic number in %s" % pathname)
|
||||||
fp.read(4)
|
fp.read(4)
|
||||||
co = marshal.load(fp)
|
co = marshal.load(fp)
|
||||||
else:
|
else:
|
||||||
|
@ -470,7 +470,7 @@ class ModuleFinder:
|
||||||
fullname = name
|
fullname = name
|
||||||
if fullname in self.excludes:
|
if fullname in self.excludes:
|
||||||
self.msgout(3, "find_module -> Excluded", fullname)
|
self.msgout(3, "find_module -> Excluded", fullname)
|
||||||
raise ImportError, name
|
raise ImportError(name)
|
||||||
|
|
||||||
if path is None:
|
if path is None:
|
||||||
if name in sys.builtin_module_names:
|
if name in sys.builtin_module_names:
|
||||||
|
|
|
@ -89,7 +89,7 @@ def change_sequence(seq, action, seqno=_Unspecified, cond = _Unspecified):
|
||||||
seqno = seq[i][2]
|
seqno = seq[i][2]
|
||||||
seq[i] = (action, cond, seqno)
|
seq[i] = (action, cond, seqno)
|
||||||
return
|
return
|
||||||
raise ValueError, "Action not found in sequence"
|
raise ValueError("Action not found in sequence")
|
||||||
|
|
||||||
def add_data(db, table, values):
|
def add_data(db, table, values):
|
||||||
v = db.OpenView("SELECT * FROM `%s`" % table)
|
v = db.OpenView("SELECT * FROM `%s`" % table)
|
||||||
|
@ -108,7 +108,7 @@ def add_data(db, table, values):
|
||||||
elif isinstance(field, Binary):
|
elif isinstance(field, Binary):
|
||||||
r.SetStream(i+1, field.name)
|
r.SetStream(i+1, field.name)
|
||||||
else:
|
else:
|
||||||
raise TypeError, "Unsupported type %s" % field.__class__.__name__
|
raise TypeError("Unsupported type %s" % field.__class__.__name__)
|
||||||
try:
|
try:
|
||||||
v.Modify(MSIMODIFY_INSERT, r)
|
v.Modify(MSIMODIFY_INSERT, r)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
@ -60,10 +60,10 @@ class MultiFile:
|
||||||
if self.level > 0:
|
if self.level > 0:
|
||||||
pos = pos + self.lastpos
|
pos = pos + self.lastpos
|
||||||
else:
|
else:
|
||||||
raise Error, "can't use whence=2 yet"
|
raise Error("can't use whence=2 yet")
|
||||||
if not 0 <= pos <= here or \
|
if not 0 <= pos <= here or \
|
||||||
self.level > 0 and pos > self.lastpos:
|
self.level > 0 and pos > self.lastpos:
|
||||||
raise Error, 'bad MultiFile.seek() call'
|
raise Error('bad MultiFile.seek() call')
|
||||||
self.fp.seek(pos + self.start)
|
self.fp.seek(pos + self.start)
|
||||||
self.level = 0
|
self.level = 0
|
||||||
self.last = 0
|
self.last = 0
|
||||||
|
@ -77,7 +77,7 @@ class MultiFile:
|
||||||
self.level = len(self.stack)
|
self.level = len(self.stack)
|
||||||
self.last = (self.level > 0)
|
self.last = (self.level > 0)
|
||||||
if self.last:
|
if self.last:
|
||||||
raise Error, 'sudden EOF in MultiFile.readline()'
|
raise Error('sudden EOF in MultiFile.readline()')
|
||||||
return ''
|
return ''
|
||||||
assert self.level == 0
|
assert self.level == 0
|
||||||
# Fast check to see if this is just data
|
# Fast check to see if this is just data
|
||||||
|
@ -102,7 +102,7 @@ class MultiFile:
|
||||||
self.lastpos = self.tell() - len(line)
|
self.lastpos = self.tell() - len(line)
|
||||||
self.level = i+1
|
self.level = i+1
|
||||||
if self.level > 1:
|
if self.level > 1:
|
||||||
raise Error,'Missing endmarker in MultiFile.readline()'
|
raise Error('Missing endmarker in MultiFile.readline()')
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
def readlines(self):
|
def readlines(self):
|
||||||
|
@ -128,7 +128,7 @@ class MultiFile:
|
||||||
|
|
||||||
def push(self, sep):
|
def push(self, sep):
|
||||||
if self.level > 0:
|
if self.level > 0:
|
||||||
raise Error, 'bad MultiFile.push() call'
|
raise Error('bad MultiFile.push() call')
|
||||||
self.stack.append(sep)
|
self.stack.append(sep)
|
||||||
if self.seekable:
|
if self.seekable:
|
||||||
self.posstack.append(self.start)
|
self.posstack.append(self.start)
|
||||||
|
@ -136,7 +136,7 @@ class MultiFile:
|
||||||
|
|
||||||
def pop(self):
|
def pop(self):
|
||||||
if self.stack == []:
|
if self.stack == []:
|
||||||
raise Error, 'bad MultiFile.pop() call'
|
raise Error('bad MultiFile.pop() call')
|
||||||
if self.level <= 1:
|
if self.level <= 1:
|
||||||
self.last = 0
|
self.last = 0
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -23,7 +23,7 @@ def url2pathname(url):
|
||||||
comp = url.split('|')
|
comp = url.split('|')
|
||||||
if len(comp) != 2 or comp[0][-1] not in string.ascii_letters:
|
if len(comp) != 2 or comp[0][-1] not in string.ascii_letters:
|
||||||
error = 'Bad URL: ' + url
|
error = 'Bad URL: ' + url
|
||||||
raise IOError, error
|
raise IOError(error)
|
||||||
drive = comp[0][-1].upper()
|
drive = comp[0][-1].upper()
|
||||||
components = comp[1].split('/')
|
components = comp[1].split('/')
|
||||||
path = drive + ':'
|
path = drive + ':'
|
||||||
|
@ -52,7 +52,7 @@ def pathname2url(p):
|
||||||
comp = p.split(':')
|
comp = p.split(':')
|
||||||
if len(comp) != 2 or len(comp[0]) > 1:
|
if len(comp) != 2 or len(comp[0]) > 1:
|
||||||
error = 'Bad path: ' + p
|
error = 'Bad path: ' + p
|
||||||
raise IOError, error
|
raise IOError(error)
|
||||||
|
|
||||||
drive = urllib.quote(comp[0].upper())
|
drive = urllib.quote(comp[0].upper())
|
||||||
components = comp[1].split('\\')
|
components = comp[1].split('\\')
|
||||||
|
|
|
@ -239,10 +239,10 @@ class HelpFormatter:
|
||||||
self.level -= 1
|
self.level -= 1
|
||||||
|
|
||||||
def format_usage(self, usage):
|
def format_usage(self, usage):
|
||||||
raise NotImplementedError, "subclasses must implement"
|
raise NotImplementedError("subclasses must implement")
|
||||||
|
|
||||||
def format_heading(self, heading):
|
def format_heading(self, heading):
|
||||||
raise NotImplementedError, "subclasses must implement"
|
raise NotImplementedError("subclasses must implement")
|
||||||
|
|
||||||
def _format_text(self, text):
|
def _format_text(self, text):
|
||||||
"""
|
"""
|
||||||
|
@ -805,7 +805,7 @@ class Option:
|
||||||
parser.print_version()
|
parser.print_version()
|
||||||
parser.exit()
|
parser.exit()
|
||||||
else:
|
else:
|
||||||
raise RuntimeError, "unknown action %r" % self.action
|
raise RuntimeError("unknown action %r" % self.action)
|
||||||
|
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
@ -865,7 +865,7 @@ class Values:
|
||||||
elif mode == "loose":
|
elif mode == "loose":
|
||||||
self._update_loose(dict)
|
self._update_loose(dict)
|
||||||
else:
|
else:
|
||||||
raise ValueError, "invalid update mode: %r" % mode
|
raise ValueError("invalid update mode: %r" % mode)
|
||||||
|
|
||||||
def read_module(self, modname, mode="careful"):
|
def read_module(self, modname, mode="careful"):
|
||||||
__import__(modname)
|
__import__(modname)
|
||||||
|
@ -944,7 +944,7 @@ class OptionContainer:
|
||||||
|
|
||||||
def set_conflict_handler(self, handler):
|
def set_conflict_handler(self, handler):
|
||||||
if handler not in ("error", "resolve"):
|
if handler not in ("error", "resolve"):
|
||||||
raise ValueError, "invalid conflict_resolution value %r" % handler
|
raise ValueError("invalid conflict_resolution value %r" % handler)
|
||||||
self.conflict_handler = handler
|
self.conflict_handler = handler
|
||||||
|
|
||||||
def set_description(self, description):
|
def set_description(self, description):
|
||||||
|
@ -999,9 +999,9 @@ class OptionContainer:
|
||||||
elif len(args) == 1 and not kwargs:
|
elif len(args) == 1 and not kwargs:
|
||||||
option = args[0]
|
option = args[0]
|
||||||
if not isinstance(option, Option):
|
if not isinstance(option, Option):
|
||||||
raise TypeError, "not an Option instance: %r" % option
|
raise TypeError("not an Option instance: %r" % option)
|
||||||
else:
|
else:
|
||||||
raise TypeError, "invalid arguments"
|
raise TypeError("invalid arguments")
|
||||||
|
|
||||||
self._check_conflict(option)
|
self._check_conflict(option)
|
||||||
|
|
||||||
|
@ -1310,11 +1310,11 @@ class OptionParser (OptionContainer):
|
||||||
elif len(args) == 1 and not kwargs:
|
elif len(args) == 1 and not kwargs:
|
||||||
group = args[0]
|
group = args[0]
|
||||||
if not isinstance(group, OptionGroup):
|
if not isinstance(group, OptionGroup):
|
||||||
raise TypeError, "not an OptionGroup instance: %r" % group
|
raise TypeError("not an OptionGroup instance: %r" % group)
|
||||||
if group.parser is not self:
|
if group.parser is not self:
|
||||||
raise ValueError, "invalid OptionGroup (wrong parser)"
|
raise ValueError("invalid OptionGroup (wrong parser)")
|
||||||
else:
|
else:
|
||||||
raise TypeError, "invalid arguments"
|
raise TypeError("invalid arguments")
|
||||||
|
|
||||||
self.option_groups.append(group)
|
self.option_groups.append(group)
|
||||||
return group
|
return group
|
||||||
|
|
46
Lib/pipes.py
46
Lib/pipes.py
|
@ -111,45 +111,33 @@ class Template:
|
||||||
def append(self, cmd, kind):
|
def append(self, cmd, kind):
|
||||||
"""t.append(cmd, kind) adds a new step at the end."""
|
"""t.append(cmd, kind) adds a new step at the end."""
|
||||||
if type(cmd) is not type(''):
|
if type(cmd) is not type(''):
|
||||||
raise TypeError, \
|
raise TypeError('Template.append: cmd must be a string')
|
||||||
'Template.append: cmd must be a string'
|
|
||||||
if kind not in stepkinds:
|
if kind not in stepkinds:
|
||||||
raise ValueError, \
|
raise ValueError('Template.append: bad kind %r' % (kind,))
|
||||||
'Template.append: bad kind %r' % (kind,)
|
|
||||||
if kind == SOURCE:
|
if kind == SOURCE:
|
||||||
raise ValueError, \
|
raise ValueError('Template.append: SOURCE can only be prepended')
|
||||||
'Template.append: SOURCE can only be prepended'
|
|
||||||
if self.steps and self.steps[-1][1] == SINK:
|
if self.steps and self.steps[-1][1] == SINK:
|
||||||
raise ValueError, \
|
raise ValueError('Template.append: already ends with SINK')
|
||||||
'Template.append: already ends with SINK'
|
|
||||||
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
|
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
|
||||||
raise ValueError, \
|
raise ValueError('Template.append: missing $IN in cmd')
|
||||||
'Template.append: missing $IN in cmd'
|
|
||||||
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
|
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
|
||||||
raise ValueError, \
|
raise ValueError('Template.append: missing $OUT in cmd')
|
||||||
'Template.append: missing $OUT in cmd'
|
|
||||||
self.steps.append((cmd, kind))
|
self.steps.append((cmd, kind))
|
||||||
|
|
||||||
def prepend(self, cmd, kind):
|
def prepend(self, cmd, kind):
|
||||||
"""t.prepend(cmd, kind) adds a new step at the front."""
|
"""t.prepend(cmd, kind) adds a new step at the front."""
|
||||||
if type(cmd) is not type(''):
|
if type(cmd) is not type(''):
|
||||||
raise TypeError, \
|
raise TypeError('Template.prepend: cmd must be a string')
|
||||||
'Template.prepend: cmd must be a string'
|
|
||||||
if kind not in stepkinds:
|
if kind not in stepkinds:
|
||||||
raise ValueError, \
|
raise ValueError('Template.prepend: bad kind %r' % (kind,))
|
||||||
'Template.prepend: bad kind %r' % (kind,)
|
|
||||||
if kind == SINK:
|
if kind == SINK:
|
||||||
raise ValueError, \
|
raise ValueError('Template.prepend: SINK can only be appended')
|
||||||
'Template.prepend: SINK can only be appended'
|
|
||||||
if self.steps and self.steps[0][1] == SOURCE:
|
if self.steps and self.steps[0][1] == SOURCE:
|
||||||
raise ValueError, \
|
raise ValueError('Template.prepend: already begins with SOURCE')
|
||||||
'Template.prepend: already begins with SOURCE'
|
|
||||||
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
|
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
|
||||||
raise ValueError, \
|
raise ValueError('Template.prepend: missing $IN in cmd')
|
||||||
'Template.prepend: missing $IN in cmd'
|
|
||||||
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
|
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
|
||||||
raise ValueError, \
|
raise ValueError('Template.prepend: missing $OUT in cmd')
|
||||||
'Template.prepend: missing $OUT in cmd'
|
|
||||||
self.steps.insert(0, (cmd, kind))
|
self.steps.insert(0, (cmd, kind))
|
||||||
|
|
||||||
def open(self, file, rw):
|
def open(self, file, rw):
|
||||||
|
@ -159,8 +147,8 @@ class Template:
|
||||||
return self.open_r(file)
|
return self.open_r(file)
|
||||||
if rw == 'w':
|
if rw == 'w':
|
||||||
return self.open_w(file)
|
return self.open_w(file)
|
||||||
raise ValueError, \
|
raise ValueError('Template.open: rw must be \'r\' or \'w\', not %r'
|
||||||
'Template.open: rw must be \'r\' or \'w\', not %r' % (rw,)
|
% (rw,))
|
||||||
|
|
||||||
def open_r(self, file):
|
def open_r(self, file):
|
||||||
"""t.open_r(file) and t.open_w(file) implement
|
"""t.open_r(file) and t.open_w(file) implement
|
||||||
|
@ -168,8 +156,7 @@ class Template:
|
||||||
if not self.steps:
|
if not self.steps:
|
||||||
return open(file, 'r')
|
return open(file, 'r')
|
||||||
if self.steps[-1][1] == SINK:
|
if self.steps[-1][1] == SINK:
|
||||||
raise ValueError, \
|
raise ValueError('Template.open_r: pipeline ends width SINK')
|
||||||
'Template.open_r: pipeline ends width SINK'
|
|
||||||
cmd = self.makepipeline(file, '')
|
cmd = self.makepipeline(file, '')
|
||||||
return os.popen(cmd, 'r')
|
return os.popen(cmd, 'r')
|
||||||
|
|
||||||
|
@ -177,8 +164,7 @@ class Template:
|
||||||
if not self.steps:
|
if not self.steps:
|
||||||
return open(file, 'w')
|
return open(file, 'w')
|
||||||
if self.steps[0][1] == SOURCE:
|
if self.steps[0][1] == SOURCE:
|
||||||
raise ValueError, \
|
raise ValueError('Template.open_w: pipeline begins with SOURCE')
|
||||||
'Template.open_w: pipeline begins with SOURCE'
|
|
||||||
cmd = self.makepipeline('', file)
|
cmd = self.makepipeline('', file)
|
||||||
return os.popen(cmd, 'w')
|
return os.popen(cmd, 'w')
|
||||||
|
|
||||||
|
|
|
@ -378,7 +378,7 @@ class _popen:
|
||||||
def __init__(self,cmd,mode='r',bufsize=None):
|
def __init__(self,cmd,mode='r',bufsize=None):
|
||||||
|
|
||||||
if mode != 'r':
|
if mode != 'r':
|
||||||
raise ValueError,'popen()-emulation only supports read mode'
|
raise ValueError('popen()-emulation only supports read mode')
|
||||||
import tempfile
|
import tempfile
|
||||||
self.tmpfile = tmpfile = tempfile.mktemp()
|
self.tmpfile = tmpfile = tempfile.mktemp()
|
||||||
os.system(cmd + ' > %s' % tmpfile)
|
os.system(cmd + ' > %s' % tmpfile)
|
||||||
|
@ -490,7 +490,7 @@ def _syscmd_ver(system='', release='', version='',
|
||||||
pipe = popen(cmd)
|
pipe = popen(cmd)
|
||||||
info = pipe.read()
|
info = pipe.read()
|
||||||
if pipe.close():
|
if pipe.close():
|
||||||
raise os.error,'command failed'
|
raise os.error('command failed')
|
||||||
# XXX How can I supress shell errors from being written
|
# XXX How can I supress shell errors from being written
|
||||||
# to stderr ?
|
# to stderr ?
|
||||||
except os.error as why:
|
except os.error as why:
|
||||||
|
|
|
@ -340,7 +340,7 @@ class POP3_SSL(POP3):
|
||||||
continue
|
continue
|
||||||
break
|
break
|
||||||
if not self.sock:
|
if not self.sock:
|
||||||
raise socket.error, msg
|
raise socket.error(msg)
|
||||||
self.file = self.sock.makefile('rb')
|
self.file = self.sock.makefile('rb')
|
||||||
self.sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
|
self.sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
|
||||||
self._debugging = 0
|
self._debugging = 0
|
||||||
|
|
|
@ -83,7 +83,7 @@ class Stats:
|
||||||
keys = kwds.keys()
|
keys = kwds.keys()
|
||||||
keys.sort()
|
keys.sort()
|
||||||
extras = ", ".join(["%s=%s" % (k, kwds[k]) for k in keys])
|
extras = ", ".join(["%s=%s" % (k, kwds[k]) for k in keys])
|
||||||
raise ValueError, "unrecognized keyword args: %s" % extras
|
raise ValueError("unrecognized keyword args: %s" % extras)
|
||||||
if not len(args):
|
if not len(args):
|
||||||
arg = None
|
arg = None
|
||||||
else:
|
else:
|
||||||
|
@ -131,8 +131,8 @@ class Stats:
|
||||||
self.stats = arg.stats
|
self.stats = arg.stats
|
||||||
arg.stats = {}
|
arg.stats = {}
|
||||||
if not self.stats:
|
if not self.stats:
|
||||||
raise TypeError, "Cannot create or construct a %r object from '%r''" % (
|
raise TypeError("Cannot create or construct a %r object from '%r''"
|
||||||
self.__class__, arg)
|
% (self.__class__, arg))
|
||||||
return
|
return
|
||||||
|
|
||||||
def get_top_level_stats(self):
|
def get_top_level_stats(self):
|
||||||
|
|
|
@ -57,7 +57,7 @@ def _open_terminal():
|
||||||
try:
|
try:
|
||||||
tty_name, master_fd = sgi._getpty(os.O_RDWR, 0o666, 0)
|
tty_name, master_fd = sgi._getpty(os.O_RDWR, 0o666, 0)
|
||||||
except IOError as msg:
|
except IOError as msg:
|
||||||
raise os.error, msg
|
raise os.error(msg)
|
||||||
return master_fd, tty_name
|
return master_fd, tty_name
|
||||||
for x in 'pqrstuvwxyzPQRST':
|
for x in 'pqrstuvwxyzPQRST':
|
||||||
for y in '0123456789abcdef':
|
for y in '0123456789abcdef':
|
||||||
|
@ -67,7 +67,7 @@ def _open_terminal():
|
||||||
except os.error:
|
except os.error:
|
||||||
continue
|
continue
|
||||||
return (fd, '/dev/tty' + x + y)
|
return (fd, '/dev/tty' + x + y)
|
||||||
raise os.error, 'out of pty devices'
|
raise os.error('out of pty devices')
|
||||||
|
|
||||||
def slave_open(tty_name):
|
def slave_open(tty_name):
|
||||||
"""slave_open(tty_name) -> slave_fd
|
"""slave_open(tty_name) -> slave_fd
|
||||||
|
|
|
@ -328,7 +328,7 @@ class Doc:
|
||||||
"""Raise an exception for unimplemented types."""
|
"""Raise an exception for unimplemented types."""
|
||||||
message = "don't know how to document object%s of type %s" % (
|
message = "don't know how to document object%s of type %s" % (
|
||||||
name and ' ' + repr(name), type(object).__name__)
|
name and ' ' + repr(name), type(object).__name__)
|
||||||
raise TypeError, message
|
raise TypeError(message)
|
||||||
|
|
||||||
docmodule = docclass = docroutine = docother = docproperty = docdata = fail
|
docmodule = docclass = docroutine = docother = docproperty = docdata = fail
|
||||||
|
|
||||||
|
@ -1463,7 +1463,7 @@ def resolve(thing, forceload=0):
|
||||||
if isinstance(thing, str):
|
if isinstance(thing, str):
|
||||||
object = locate(thing, forceload)
|
object = locate(thing, forceload)
|
||||||
if not object:
|
if not object:
|
||||||
raise ImportError, 'no Python documentation found for %r' % thing
|
raise ImportError('no Python documentation found for %r' % thing)
|
||||||
return object, thing
|
return object, thing
|
||||||
else:
|
else:
|
||||||
return thing, getattr(thing, '__name__', None)
|
return thing, getattr(thing, '__name__', None)
|
||||||
|
|
|
@ -157,18 +157,18 @@ class Random(_random.Random):
|
||||||
# common case while still doing adequate error checking.
|
# common case while still doing adequate error checking.
|
||||||
istart = int(start)
|
istart = int(start)
|
||||||
if istart != start:
|
if istart != start:
|
||||||
raise ValueError, "non-integer arg 1 for randrange()"
|
raise ValueError("non-integer arg 1 for randrange()")
|
||||||
if stop is default:
|
if stop is default:
|
||||||
if istart > 0:
|
if istart > 0:
|
||||||
if istart >= maxwidth:
|
if istart >= maxwidth:
|
||||||
return self._randbelow(istart)
|
return self._randbelow(istart)
|
||||||
return int(self.random() * istart)
|
return int(self.random() * istart)
|
||||||
raise ValueError, "empty range for randrange()"
|
raise ValueError("empty range for randrange()")
|
||||||
|
|
||||||
# stop argument supplied.
|
# stop argument supplied.
|
||||||
istop = int(stop)
|
istop = int(stop)
|
||||||
if istop != stop:
|
if istop != stop:
|
||||||
raise ValueError, "non-integer stop for randrange()"
|
raise ValueError("non-integer stop for randrange()")
|
||||||
width = istop - istart
|
width = istop - istart
|
||||||
if step == 1 and width > 0:
|
if step == 1 and width > 0:
|
||||||
# Note that
|
# Note that
|
||||||
|
@ -188,21 +188,21 @@ class Random(_random.Random):
|
||||||
return int(istart + self._randbelow(width))
|
return int(istart + self._randbelow(width))
|
||||||
return int(istart + int(self.random()*width))
|
return int(istart + int(self.random()*width))
|
||||||
if step == 1:
|
if step == 1:
|
||||||
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
|
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
|
||||||
|
|
||||||
# Non-unit step argument supplied.
|
# Non-unit step argument supplied.
|
||||||
istep = int(step)
|
istep = int(step)
|
||||||
if istep != step:
|
if istep != step:
|
||||||
raise ValueError, "non-integer step for randrange()"
|
raise ValueError("non-integer step for randrange()")
|
||||||
if istep > 0:
|
if istep > 0:
|
||||||
n = (width + istep - 1) // istep
|
n = (width + istep - 1) // istep
|
||||||
elif istep < 0:
|
elif istep < 0:
|
||||||
n = (width + istep + 1) // istep
|
n = (width + istep + 1) // istep
|
||||||
else:
|
else:
|
||||||
raise ValueError, "zero step for randrange()"
|
raise ValueError("zero step for randrange()")
|
||||||
|
|
||||||
if n <= 0:
|
if n <= 0:
|
||||||
raise ValueError, "empty range for randrange()"
|
raise ValueError("empty range for randrange()")
|
||||||
|
|
||||||
if n >= maxwidth:
|
if n >= maxwidth:
|
||||||
return istart + istep*self._randbelow(n)
|
return istart + istep*self._randbelow(n)
|
||||||
|
@ -300,7 +300,7 @@ class Random(_random.Random):
|
||||||
|
|
||||||
n = len(population)
|
n = len(population)
|
||||||
if not 0 <= k <= n:
|
if not 0 <= k <= n:
|
||||||
raise ValueError, "sample larger than population"
|
raise ValueError("sample larger than population")
|
||||||
random = self.random
|
random = self.random
|
||||||
_int = int
|
_int = int
|
||||||
result = [None] * k
|
result = [None] * k
|
||||||
|
@ -459,7 +459,7 @@ class Random(_random.Random):
|
||||||
# Warning: a few older sources define the gamma distribution in terms
|
# Warning: a few older sources define the gamma distribution in terms
|
||||||
# of alpha > -1.0
|
# of alpha > -1.0
|
||||||
if alpha <= 0.0 or beta <= 0.0:
|
if alpha <= 0.0 or beta <= 0.0:
|
||||||
raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
|
raise ValueError('gammavariate: alpha and beta must be > 0.0')
|
||||||
|
|
||||||
random = self.random
|
random = self.random
|
||||||
if alpha > 1.0:
|
if alpha > 1.0:
|
||||||
|
|
|
@ -226,11 +226,8 @@ def _compile(*key):
|
||||||
if isinstance(pattern, _pattern_type):
|
if isinstance(pattern, _pattern_type):
|
||||||
return pattern
|
return pattern
|
||||||
if not sre_compile.isstring(pattern):
|
if not sre_compile.isstring(pattern):
|
||||||
raise TypeError, "first argument must be string or compiled pattern"
|
raise TypeError("first argument must be string or compiled pattern")
|
||||||
try:
|
|
||||||
p = sre_compile.compile(pattern, flags)
|
p = sre_compile.compile(pattern, flags)
|
||||||
except error as v:
|
|
||||||
raise error, v # invalid expression
|
|
||||||
if len(_cache) >= _MAXCACHE:
|
if len(_cache) >= _MAXCACHE:
|
||||||
_cache.clear()
|
_cache.clear()
|
||||||
_cache[cachekey] = p
|
_cache[cachekey] = p
|
||||||
|
@ -242,10 +239,7 @@ def _compile_repl(*key):
|
||||||
if p is not None:
|
if p is not None:
|
||||||
return p
|
return p
|
||||||
repl, pattern = key
|
repl, pattern = key
|
||||||
try:
|
|
||||||
p = sre_parse.parse_template(repl, pattern)
|
p = sre_parse.parse_template(repl, pattern)
|
||||||
except error as v:
|
|
||||||
raise error, v # invalid expression
|
|
||||||
if len(_cache_repl) >= _MAXCACHE:
|
if len(_cache_repl) >= _MAXCACHE:
|
||||||
_cache_repl.clear()
|
_cache_repl.clear()
|
||||||
_cache_repl[key] = p
|
_cache_repl[key] = p
|
||||||
|
|
|
@ -112,7 +112,7 @@ class Message:
|
||||||
def rewindbody(self):
|
def rewindbody(self):
|
||||||
"""Rewind the file to the start of the body (if seekable)."""
|
"""Rewind the file to the start of the body (if seekable)."""
|
||||||
if not self.seekable:
|
if not self.seekable:
|
||||||
raise IOError, "unseekable file"
|
raise IOError("unseekable file")
|
||||||
self.fp.seek(self.startofbody)
|
self.fp.seek(self.startofbody)
|
||||||
|
|
||||||
def readheaders(self):
|
def readheaders(self):
|
||||||
|
|
|
@ -55,7 +55,7 @@ class Completer:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if namespace and not isinstance(namespace, dict):
|
if namespace and not isinstance(namespace, dict):
|
||||||
raise TypeError,'namespace must be a dictionary'
|
raise TypeError('namespace must be a dictionary')
|
||||||
|
|
||||||
# Don't bind to namespace quite yet, but flag whether the user wants a
|
# Don't bind to namespace quite yet, but flag whether the user wants a
|
||||||
# specific namespace or to use __main__.__dict__. This will allow us
|
# specific namespace or to use __main__.__dict__. This will allow us
|
||||||
|
|
|
@ -166,7 +166,7 @@ class shlex:
|
||||||
if self.debug >= 2:
|
if self.debug >= 2:
|
||||||
print("shlex: I see EOF in quotes state")
|
print("shlex: I see EOF in quotes state")
|
||||||
# XXX what error should be raised here?
|
# XXX what error should be raised here?
|
||||||
raise ValueError, "No closing quotation"
|
raise ValueError("No closing quotation")
|
||||||
if nextchar == self.state:
|
if nextchar == self.state:
|
||||||
if not self.posix:
|
if not self.posix:
|
||||||
self.token = self.token + nextchar
|
self.token = self.token + nextchar
|
||||||
|
@ -185,7 +185,7 @@ class shlex:
|
||||||
if self.debug >= 2:
|
if self.debug >= 2:
|
||||||
print("shlex: I see EOF in escape state")
|
print("shlex: I see EOF in escape state")
|
||||||
# XXX what error should be raised here?
|
# XXX what error should be raised here?
|
||||||
raise ValueError, "No escaped character"
|
raise ValueError("No escaped character")
|
||||||
# In posix shells, only the quote itself or the escape
|
# In posix shells, only the quote itself or the escape
|
||||||
# character may be escaped within quotes.
|
# character may be escaped within quotes.
|
||||||
if escapedstate in self.quotes and \
|
if escapedstate in self.quotes and \
|
||||||
|
|
|
@ -38,7 +38,7 @@ def _samefile(src, dst):
|
||||||
def copyfile(src, dst):
|
def copyfile(src, dst):
|
||||||
"""Copy data from src to dst"""
|
"""Copy data from src to dst"""
|
||||||
if _samefile(src, dst):
|
if _samefile(src, dst):
|
||||||
raise Error, "`%s` and `%s` are the same file" % (src, dst)
|
raise Error("`%s` and `%s` are the same file" % (src, dst))
|
||||||
|
|
||||||
fsrc = None
|
fsrc = None
|
||||||
fdst = None
|
fdst = None
|
||||||
|
@ -137,7 +137,7 @@ def copytree(src, dst, symlinks=False):
|
||||||
except OSError as why:
|
except OSError as why:
|
||||||
errors.extend((src, dst, str(why)))
|
errors.extend((src, dst, str(why)))
|
||||||
if errors:
|
if errors:
|
||||||
raise Error, errors
|
raise Error(errors)
|
||||||
|
|
||||||
def rmtree(path, ignore_errors=False, onerror=None):
|
def rmtree(path, ignore_errors=False, onerror=None):
|
||||||
"""Recursively delete a directory tree.
|
"""Recursively delete a directory tree.
|
||||||
|
@ -194,7 +194,7 @@ def move(src, dst):
|
||||||
except OSError:
|
except OSError:
|
||||||
if os.path.isdir(src):
|
if os.path.isdir(src):
|
||||||
if destinsrc(src, dst):
|
if destinsrc(src, dst):
|
||||||
raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
|
raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst))
|
||||||
copytree(src, dst, symlinks=True)
|
copytree(src, dst, symlinks=True)
|
||||||
rmtree(src)
|
rmtree(src)
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -69,7 +69,7 @@ def _compile(code, pattern, flags):
|
||||||
emit(OPCODES[ANY])
|
emit(OPCODES[ANY])
|
||||||
elif op in REPEATING_CODES:
|
elif op in REPEATING_CODES:
|
||||||
if flags & SRE_FLAG_TEMPLATE:
|
if flags & SRE_FLAG_TEMPLATE:
|
||||||
raise error, "internal: unsupported template operator"
|
raise error("internal: unsupported template operator")
|
||||||
emit(OPCODES[REPEAT])
|
emit(OPCODES[REPEAT])
|
||||||
skip = _len(code); emit(0)
|
skip = _len(code); emit(0)
|
||||||
emit(av[0])
|
emit(av[0])
|
||||||
|
@ -118,7 +118,7 @@ def _compile(code, pattern, flags):
|
||||||
else:
|
else:
|
||||||
lo, hi = av[1].getwidth()
|
lo, hi = av[1].getwidth()
|
||||||
if lo != hi:
|
if lo != hi:
|
||||||
raise error, "look-behind requires fixed-width pattern"
|
raise error("look-behind requires fixed-width pattern")
|
||||||
emit(lo) # look behind
|
emit(lo) # look behind
|
||||||
_compile(code, av[1], flags)
|
_compile(code, av[1], flags)
|
||||||
emit(OPCODES[SUCCESS])
|
emit(OPCODES[SUCCESS])
|
||||||
|
@ -179,7 +179,7 @@ def _compile(code, pattern, flags):
|
||||||
else:
|
else:
|
||||||
code[skipyes] = _len(code) - skipyes + 1
|
code[skipyes] = _len(code) - skipyes + 1
|
||||||
else:
|
else:
|
||||||
raise ValueError, ("unsupported operand type", op)
|
raise ValueError("unsupported operand type", op)
|
||||||
|
|
||||||
def _compile_charset(charset, flags, code, fixup=None):
|
def _compile_charset(charset, flags, code, fixup=None):
|
||||||
# compile charset subprogram
|
# compile charset subprogram
|
||||||
|
@ -207,7 +207,7 @@ def _compile_charset(charset, flags, code, fixup=None):
|
||||||
else:
|
else:
|
||||||
emit(CHCODES[av])
|
emit(CHCODES[av])
|
||||||
else:
|
else:
|
||||||
raise error, "internal: unsupported set operator"
|
raise error("internal: unsupported set operator")
|
||||||
emit(OPCODES[FAILURE])
|
emit(OPCODES[FAILURE])
|
||||||
|
|
||||||
def _optimize_charset(charset, fixup):
|
def _optimize_charset(charset, fixup):
|
||||||
|
@ -362,7 +362,7 @@ def _simple(av):
|
||||||
# check if av is a "simple" operator
|
# check if av is a "simple" operator
|
||||||
lo, hi = av[2].getwidth()
|
lo, hi = av[2].getwidth()
|
||||||
if lo == 0 and hi == MAXREPEAT:
|
if lo == 0 and hi == MAXREPEAT:
|
||||||
raise error, "nothing to repeat"
|
raise error("nothing to repeat")
|
||||||
return lo == hi == 1 and av[2][0][0] != SUBPATTERN
|
return lo == hi == 1 and av[2][0][0] != SUBPATTERN
|
||||||
|
|
||||||
def _compile_info(code, pattern, flags):
|
def _compile_info(code, pattern, flags):
|
||||||
|
|
|
@ -81,7 +81,7 @@ class Pattern:
|
||||||
if name is not None:
|
if name is not None:
|
||||||
ogid = self.groupdict.get(name, None)
|
ogid = self.groupdict.get(name, None)
|
||||||
if ogid is not None:
|
if ogid is not None:
|
||||||
raise error, ("redefinition of group name %s as group %d; "
|
raise error("redefinition of group name %s as group %d; "
|
||||||
"was group %d" % (repr(name), gid, ogid))
|
"was group %d" % (repr(name), gid, ogid))
|
||||||
self.groupdict[name] = gid
|
self.groupdict[name] = gid
|
||||||
self.open.append(gid)
|
self.open.append(gid)
|
||||||
|
@ -196,7 +196,7 @@ class Tokenizer:
|
||||||
try:
|
try:
|
||||||
c = self.string[self.index + 1]
|
c = self.string[self.index + 1]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
raise error, "bogus escape (end of line)"
|
raise error("bogus escape (end of line)")
|
||||||
char = char + c
|
char = char + c
|
||||||
self.index = self.index + len(char)
|
self.index = self.index + len(char)
|
||||||
self.next = char
|
self.next = char
|
||||||
|
@ -246,7 +246,7 @@ def _class_escape(source, escape):
|
||||||
escape = escape + source.get()
|
escape = escape + source.get()
|
||||||
escape = escape[2:]
|
escape = escape[2:]
|
||||||
if len(escape) != 2:
|
if len(escape) != 2:
|
||||||
raise error, "bogus escape: %s" % repr("\\" + escape)
|
raise error("bogus escape: %s" % repr("\\" + escape))
|
||||||
return LITERAL, int(escape, 16) & 0xff
|
return LITERAL, int(escape, 16) & 0xff
|
||||||
elif c in OCTDIGITS:
|
elif c in OCTDIGITS:
|
||||||
# octal escape (up to three digits)
|
# octal escape (up to three digits)
|
||||||
|
@ -255,12 +255,12 @@ def _class_escape(source, escape):
|
||||||
escape = escape[1:]
|
escape = escape[1:]
|
||||||
return LITERAL, int(escape, 8) & 0xff
|
return LITERAL, int(escape, 8) & 0xff
|
||||||
elif c in DIGITS:
|
elif c in DIGITS:
|
||||||
raise error, "bogus escape: %s" % repr(escape)
|
raise error("bogus escape: %s" % repr(escape))
|
||||||
if len(escape) == 2:
|
if len(escape) == 2:
|
||||||
return LITERAL, ord(escape[1])
|
return LITERAL, ord(escape[1])
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
raise error, "bogus escape: %s" % repr(escape)
|
raise error("bogus escape: %s" % repr(escape))
|
||||||
|
|
||||||
def _escape(source, escape, state):
|
def _escape(source, escape, state):
|
||||||
# handle escape code in expression
|
# handle escape code in expression
|
||||||
|
@ -297,14 +297,14 @@ def _escape(source, escape, state):
|
||||||
group = int(escape[1:])
|
group = int(escape[1:])
|
||||||
if group < state.groups:
|
if group < state.groups:
|
||||||
if not state.checkgroup(group):
|
if not state.checkgroup(group):
|
||||||
raise error, "cannot refer to open group"
|
raise error("cannot refer to open group")
|
||||||
return GROUPREF, group
|
return GROUPREF, group
|
||||||
raise ValueError
|
raise ValueError
|
||||||
if len(escape) == 2:
|
if len(escape) == 2:
|
||||||
return LITERAL, ord(escape[1])
|
return LITERAL, ord(escape[1])
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
raise error, "bogus escape: %s" % repr(escape)
|
raise error("bogus escape: %s" % repr(escape))
|
||||||
|
|
||||||
def _parse_sub(source, state, nested=1):
|
def _parse_sub(source, state, nested=1):
|
||||||
# parse an alternation: a|b|c
|
# parse an alternation: a|b|c
|
||||||
|
@ -321,7 +321,7 @@ def _parse_sub(source, state, nested=1):
|
||||||
if not source.next or sourcematch(")", 0):
|
if not source.next or sourcematch(")", 0):
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
raise error, "pattern not properly closed"
|
raise error("pattern not properly closed")
|
||||||
|
|
||||||
if len(items) == 1:
|
if len(items) == 1:
|
||||||
return items[0]
|
return items[0]
|
||||||
|
@ -370,11 +370,11 @@ def _parse_sub_cond(source, state, condgroup):
|
||||||
if source.match("|"):
|
if source.match("|"):
|
||||||
item_no = _parse(source, state)
|
item_no = _parse(source, state)
|
||||||
if source.match("|"):
|
if source.match("|"):
|
||||||
raise error, "conditional backref with more than two branches"
|
raise error("conditional backref with more than two branches")
|
||||||
else:
|
else:
|
||||||
item_no = None
|
item_no = None
|
||||||
if source.next and not source.match(")", 0):
|
if source.next and not source.match(")", 0):
|
||||||
raise error, "pattern not properly closed"
|
raise error("pattern not properly closed")
|
||||||
subpattern = SubPattern(state)
|
subpattern = SubPattern(state)
|
||||||
subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
|
subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))
|
||||||
return subpattern
|
return subpattern
|
||||||
|
@ -439,7 +439,7 @@ def _parse(source, state):
|
||||||
elif this:
|
elif this:
|
||||||
code1 = LITERAL, ord(this)
|
code1 = LITERAL, ord(this)
|
||||||
else:
|
else:
|
||||||
raise error, "unexpected end of regular expression"
|
raise error("unexpected end of regular expression")
|
||||||
if sourcematch("-"):
|
if sourcematch("-"):
|
||||||
# potential range
|
# potential range
|
||||||
this = sourceget()
|
this = sourceget()
|
||||||
|
@ -455,14 +455,14 @@ def _parse(source, state):
|
||||||
else:
|
else:
|
||||||
code2 = LITERAL, ord(this)
|
code2 = LITERAL, ord(this)
|
||||||
if code1[0] != LITERAL or code2[0] != LITERAL:
|
if code1[0] != LITERAL or code2[0] != LITERAL:
|
||||||
raise error, "bad character range"
|
raise error("bad character range")
|
||||||
lo = code1[1]
|
lo = code1[1]
|
||||||
hi = code2[1]
|
hi = code2[1]
|
||||||
if hi < lo:
|
if hi < lo:
|
||||||
raise error, "bad character range"
|
raise error("bad character range")
|
||||||
setappend((RANGE, (lo, hi)))
|
setappend((RANGE, (lo, hi)))
|
||||||
else:
|
else:
|
||||||
raise error, "unexpected end of regular expression"
|
raise error("unexpected end of regular expression")
|
||||||
else:
|
else:
|
||||||
if code1[0] is IN:
|
if code1[0] is IN:
|
||||||
code1 = code1[1][0]
|
code1 = code1[1][0]
|
||||||
|
@ -509,18 +509,18 @@ def _parse(source, state):
|
||||||
if hi:
|
if hi:
|
||||||
max = int(hi)
|
max = int(hi)
|
||||||
if max < min:
|
if max < min:
|
||||||
raise error, "bad repeat interval"
|
raise error("bad repeat interval")
|
||||||
else:
|
else:
|
||||||
raise error, "not supported"
|
raise error("not supported")
|
||||||
# figure out which item to repeat
|
# figure out which item to repeat
|
||||||
if subpattern:
|
if subpattern:
|
||||||
item = subpattern[-1:]
|
item = subpattern[-1:]
|
||||||
else:
|
else:
|
||||||
item = None
|
item = None
|
||||||
if not item or (_len(item) == 1 and item[0][0] == AT):
|
if not item or (_len(item) == 1 and item[0][0] == AT):
|
||||||
raise error, "nothing to repeat"
|
raise error("nothing to repeat")
|
||||||
if item[0][0] in REPEATCODES:
|
if item[0][0] in REPEATCODES:
|
||||||
raise error, "multiple repeat"
|
raise error("multiple repeat")
|
||||||
if sourcematch("?"):
|
if sourcematch("?"):
|
||||||
subpattern[-1] = (MIN_REPEAT, (min, max, item))
|
subpattern[-1] = (MIN_REPEAT, (min, max, item))
|
||||||
else:
|
else:
|
||||||
|
@ -544,35 +544,35 @@ def _parse(source, state):
|
||||||
while 1:
|
while 1:
|
||||||
char = sourceget()
|
char = sourceget()
|
||||||
if char is None:
|
if char is None:
|
||||||
raise error, "unterminated name"
|
raise error("unterminated name")
|
||||||
if char == ">":
|
if char == ">":
|
||||||
break
|
break
|
||||||
name = name + char
|
name = name + char
|
||||||
group = 1
|
group = 1
|
||||||
if not isname(name):
|
if not isname(name):
|
||||||
raise error, "bad character in group name"
|
raise error("bad character in group name")
|
||||||
elif sourcematch("="):
|
elif sourcematch("="):
|
||||||
# named backreference
|
# named backreference
|
||||||
name = ""
|
name = ""
|
||||||
while 1:
|
while 1:
|
||||||
char = sourceget()
|
char = sourceget()
|
||||||
if char is None:
|
if char is None:
|
||||||
raise error, "unterminated name"
|
raise error("unterminated name")
|
||||||
if char == ")":
|
if char == ")":
|
||||||
break
|
break
|
||||||
name = name + char
|
name = name + char
|
||||||
if not isname(name):
|
if not isname(name):
|
||||||
raise error, "bad character in group name"
|
raise error("bad character in group name")
|
||||||
gid = state.groupdict.get(name)
|
gid = state.groupdict.get(name)
|
||||||
if gid is None:
|
if gid is None:
|
||||||
raise error, "unknown group name"
|
raise error("unknown group name")
|
||||||
subpatternappend((GROUPREF, gid))
|
subpatternappend((GROUPREF, gid))
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
char = sourceget()
|
char = sourceget()
|
||||||
if char is None:
|
if char is None:
|
||||||
raise error, "unexpected end of pattern"
|
raise error("unexpected end of pattern")
|
||||||
raise error, "unknown specifier: ?P%s" % char
|
raise error("unknown specifier: ?P%s" % char)
|
||||||
elif sourcematch(":"):
|
elif sourcematch(":"):
|
||||||
# non-capturing group
|
# non-capturing group
|
||||||
group = 2
|
group = 2
|
||||||
|
@ -583,7 +583,7 @@ def _parse(source, state):
|
||||||
break
|
break
|
||||||
sourceget()
|
sourceget()
|
||||||
if not sourcematch(")"):
|
if not sourcematch(")"):
|
||||||
raise error, "unbalanced parenthesis"
|
raise error("unbalanced parenthesis")
|
||||||
continue
|
continue
|
||||||
elif source.next in ASSERTCHARS:
|
elif source.next in ASSERTCHARS:
|
||||||
# lookahead assertions
|
# lookahead assertions
|
||||||
|
@ -591,12 +591,12 @@ def _parse(source, state):
|
||||||
dir = 1
|
dir = 1
|
||||||
if char == "<":
|
if char == "<":
|
||||||
if source.next not in LOOKBEHINDASSERTCHARS:
|
if source.next not in LOOKBEHINDASSERTCHARS:
|
||||||
raise error, "syntax error"
|
raise error("syntax error")
|
||||||
dir = -1 # lookbehind
|
dir = -1 # lookbehind
|
||||||
char = sourceget()
|
char = sourceget()
|
||||||
p = _parse_sub(source, state)
|
p = _parse_sub(source, state)
|
||||||
if not sourcematch(")"):
|
if not sourcematch(")"):
|
||||||
raise error, "unbalanced parenthesis"
|
raise error("unbalanced parenthesis")
|
||||||
if char == "=":
|
if char == "=":
|
||||||
subpatternappend((ASSERT, (dir, p)))
|
subpatternappend((ASSERT, (dir, p)))
|
||||||
else:
|
else:
|
||||||
|
@ -608,7 +608,7 @@ def _parse(source, state):
|
||||||
while 1:
|
while 1:
|
||||||
char = sourceget()
|
char = sourceget()
|
||||||
if char is None:
|
if char is None:
|
||||||
raise error, "unterminated name"
|
raise error("unterminated name")
|
||||||
if char == ")":
|
if char == ")":
|
||||||
break
|
break
|
||||||
condname = condname + char
|
condname = condname + char
|
||||||
|
@ -616,16 +616,16 @@ def _parse(source, state):
|
||||||
if isname(condname):
|
if isname(condname):
|
||||||
condgroup = state.groupdict.get(condname)
|
condgroup = state.groupdict.get(condname)
|
||||||
if condgroup is None:
|
if condgroup is None:
|
||||||
raise error, "unknown group name"
|
raise error("unknown group name")
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
condgroup = int(condname)
|
condgroup = int(condname)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise error, "bad character in group name"
|
raise error("bad character in group name")
|
||||||
else:
|
else:
|
||||||
# flags
|
# flags
|
||||||
if not source.next in FLAGS:
|
if not source.next in FLAGS:
|
||||||
raise error, "unexpected end of pattern"
|
raise error("unexpected end of pattern")
|
||||||
while source.next in FLAGS:
|
while source.next in FLAGS:
|
||||||
state.flags = state.flags | FLAGS[sourceget()]
|
state.flags = state.flags | FLAGS[sourceget()]
|
||||||
if group:
|
if group:
|
||||||
|
@ -640,7 +640,7 @@ def _parse(source, state):
|
||||||
else:
|
else:
|
||||||
p = _parse_sub(source, state)
|
p = _parse_sub(source, state)
|
||||||
if not sourcematch(")"):
|
if not sourcematch(")"):
|
||||||
raise error, "unbalanced parenthesis"
|
raise error("unbalanced parenthesis")
|
||||||
if group is not None:
|
if group is not None:
|
||||||
state.closegroup(group)
|
state.closegroup(group)
|
||||||
subpatternappend((SUBPATTERN, (group, p)))
|
subpatternappend((SUBPATTERN, (group, p)))
|
||||||
|
@ -648,10 +648,10 @@ def _parse(source, state):
|
||||||
while 1:
|
while 1:
|
||||||
char = sourceget()
|
char = sourceget()
|
||||||
if char is None:
|
if char is None:
|
||||||
raise error, "unexpected end of pattern"
|
raise error("unexpected end of pattern")
|
||||||
if char == ")":
|
if char == ")":
|
||||||
break
|
break
|
||||||
raise error, "unknown extension"
|
raise error("unknown extension")
|
||||||
|
|
||||||
elif this == "^":
|
elif this == "^":
|
||||||
subpatternappend((AT, AT_BEGINNING))
|
subpatternappend((AT, AT_BEGINNING))
|
||||||
|
@ -664,7 +664,7 @@ def _parse(source, state):
|
||||||
subpatternappend(code)
|
subpatternappend(code)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
raise error, "parser error"
|
raise error("parser error")
|
||||||
|
|
||||||
return subpattern
|
return subpattern
|
||||||
|
|
||||||
|
@ -682,9 +682,9 @@ def parse(str, flags=0, pattern=None):
|
||||||
|
|
||||||
tail = source.get()
|
tail = source.get()
|
||||||
if tail == ")":
|
if tail == ")":
|
||||||
raise error, "unbalanced parenthesis"
|
raise error("unbalanced parenthesis")
|
||||||
elif tail:
|
elif tail:
|
||||||
raise error, "bogus characters at end of regular expression"
|
raise error("bogus characters at end of regular expression")
|
||||||
|
|
||||||
if flags & SRE_FLAG_DEBUG:
|
if flags & SRE_FLAG_DEBUG:
|
||||||
p.dump()
|
p.dump()
|
||||||
|
@ -726,23 +726,23 @@ def parse_template(source, pattern):
|
||||||
while 1:
|
while 1:
|
||||||
char = sget()
|
char = sget()
|
||||||
if char is None:
|
if char is None:
|
||||||
raise error, "unterminated group name"
|
raise error("unterminated group name")
|
||||||
if char == ">":
|
if char == ">":
|
||||||
break
|
break
|
||||||
name = name + char
|
name = name + char
|
||||||
if not name:
|
if not name:
|
||||||
raise error, "bad group name"
|
raise error("bad group name")
|
||||||
try:
|
try:
|
||||||
index = int(name)
|
index = int(name)
|
||||||
if index < 0:
|
if index < 0:
|
||||||
raise error, "negative group number"
|
raise error("negative group number")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
if not isname(name):
|
if not isname(name):
|
||||||
raise error, "bad character in group name"
|
raise error("bad character in group name")
|
||||||
try:
|
try:
|
||||||
index = pattern.groupindex[name]
|
index = pattern.groupindex[name]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise IndexError, "unknown group name"
|
raise IndexError("unknown group name")
|
||||||
a((MARK, index))
|
a((MARK, index))
|
||||||
elif c == "0":
|
elif c == "0":
|
||||||
if s.next in OCTDIGITS:
|
if s.next in OCTDIGITS:
|
||||||
|
@ -792,7 +792,7 @@ def expand_template(template, match):
|
||||||
for index, group in groups:
|
for index, group in groups:
|
||||||
literals[index] = s = g(group)
|
literals[index] = s = g(group)
|
||||||
if s is None:
|
if s is None:
|
||||||
raise error, "unmatched group"
|
raise error("unmatched group")
|
||||||
except IndexError:
|
except IndexError:
|
||||||
raise error, "invalid group reference"
|
raise error("invalid group reference")
|
||||||
return sep.join(literals)
|
return sep.join(literals)
|
||||||
|
|
|
@ -55,7 +55,7 @@ def maketrans(fromstr, tostr):
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if len(fromstr) != len(tostr):
|
if len(fromstr) != len(tostr):
|
||||||
raise ValueError, "maketrans arguments must have same length"
|
raise ValueError("maketrans arguments must have same length")
|
||||||
global _idmapL
|
global _idmapL
|
||||||
if not _idmapL:
|
if not _idmapL:
|
||||||
_idmapL = list(_idmap)
|
_idmapL = list(_idmap)
|
||||||
|
|
48
Lib/sunau.py
48
Lib/sunau.py
|
@ -166,18 +166,18 @@ class Au_read:
|
||||||
self._soundpos = 0
|
self._soundpos = 0
|
||||||
magic = int(_read_u32(file))
|
magic = int(_read_u32(file))
|
||||||
if magic != AUDIO_FILE_MAGIC:
|
if magic != AUDIO_FILE_MAGIC:
|
||||||
raise Error, 'bad magic number'
|
raise Error('bad magic number')
|
||||||
self._hdr_size = int(_read_u32(file))
|
self._hdr_size = int(_read_u32(file))
|
||||||
if self._hdr_size < 24:
|
if self._hdr_size < 24:
|
||||||
raise Error, 'header size too small'
|
raise Error('header size too small')
|
||||||
if self._hdr_size > 100:
|
if self._hdr_size > 100:
|
||||||
raise Error, 'header size ridiculously large'
|
raise Error('header size ridiculously large')
|
||||||
self._data_size = _read_u32(file)
|
self._data_size = _read_u32(file)
|
||||||
if self._data_size != AUDIO_UNKNOWN_SIZE:
|
if self._data_size != AUDIO_UNKNOWN_SIZE:
|
||||||
self._data_size = int(self._data_size)
|
self._data_size = int(self._data_size)
|
||||||
self._encoding = int(_read_u32(file))
|
self._encoding = int(_read_u32(file))
|
||||||
if self._encoding not in _simple_encodings:
|
if self._encoding not in _simple_encodings:
|
||||||
raise Error, 'encoding not (yet) supported'
|
raise Error('encoding not (yet) supported')
|
||||||
if self._encoding in (AUDIO_FILE_ENCODING_MULAW_8,
|
if self._encoding in (AUDIO_FILE_ENCODING_MULAW_8,
|
||||||
AUDIO_FILE_ENCODING_ALAW_8):
|
AUDIO_FILE_ENCODING_ALAW_8):
|
||||||
self._sampwidth = 2
|
self._sampwidth = 2
|
||||||
|
@ -191,7 +191,7 @@ class Au_read:
|
||||||
elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_32:
|
elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_32:
|
||||||
self._framesize = self._sampwidth = 4
|
self._framesize = self._sampwidth = 4
|
||||||
else:
|
else:
|
||||||
raise Error, 'unknown encoding'
|
raise Error('unknown encoding')
|
||||||
self._framerate = int(_read_u32(file))
|
self._framerate = int(_read_u32(file))
|
||||||
self._nchannels = int(_read_u32(file))
|
self._nchannels = int(_read_u32(file))
|
||||||
self._framesize = self._framesize * self._nchannels
|
self._framesize = self._framesize * self._nchannels
|
||||||
|
@ -248,7 +248,7 @@ class Au_read:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def getmark(self, id):
|
def getmark(self, id):
|
||||||
raise Error, 'no marks'
|
raise Error('no marks')
|
||||||
|
|
||||||
def readframes(self, nframes):
|
def readframes(self, nframes):
|
||||||
if self._encoding in _simple_encodings:
|
if self._encoding in _simple_encodings:
|
||||||
|
@ -271,7 +271,7 @@ class Au_read:
|
||||||
|
|
||||||
def setpos(self, pos):
|
def setpos(self, pos):
|
||||||
if pos < 0 or pos > self.getnframes():
|
if pos < 0 or pos > self.getnframes():
|
||||||
raise Error, 'position not in range'
|
raise Error('position not in range')
|
||||||
self._file.seek(pos * self._framesize + self._hdr_size)
|
self._file.seek(pos * self._framesize + self._hdr_size)
|
||||||
self._soundpos = pos
|
self._soundpos = pos
|
||||||
|
|
||||||
|
@ -305,43 +305,43 @@ class Au_write:
|
||||||
|
|
||||||
def setnchannels(self, nchannels):
|
def setnchannels(self, nchannels):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if nchannels not in (1, 2, 4):
|
if nchannels not in (1, 2, 4):
|
||||||
raise Error, 'only 1, 2, or 4 channels supported'
|
raise Error('only 1, 2, or 4 channels supported')
|
||||||
self._nchannels = nchannels
|
self._nchannels = nchannels
|
||||||
|
|
||||||
def getnchannels(self):
|
def getnchannels(self):
|
||||||
if not self._nchannels:
|
if not self._nchannels:
|
||||||
raise Error, 'number of channels not set'
|
raise Error('number of channels not set')
|
||||||
return self._nchannels
|
return self._nchannels
|
||||||
|
|
||||||
def setsampwidth(self, sampwidth):
|
def setsampwidth(self, sampwidth):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if sampwidth not in (1, 2, 4):
|
if sampwidth not in (1, 2, 4):
|
||||||
raise Error, 'bad sample width'
|
raise Error('bad sample width')
|
||||||
self._sampwidth = sampwidth
|
self._sampwidth = sampwidth
|
||||||
|
|
||||||
def getsampwidth(self):
|
def getsampwidth(self):
|
||||||
if not self._framerate:
|
if not self._framerate:
|
||||||
raise Error, 'sample width not specified'
|
raise Error('sample width not specified')
|
||||||
return self._sampwidth
|
return self._sampwidth
|
||||||
|
|
||||||
def setframerate(self, framerate):
|
def setframerate(self, framerate):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
self._framerate = framerate
|
self._framerate = framerate
|
||||||
|
|
||||||
def getframerate(self):
|
def getframerate(self):
|
||||||
if not self._framerate:
|
if not self._framerate:
|
||||||
raise Error, 'frame rate not set'
|
raise Error('frame rate not set')
|
||||||
return self._framerate
|
return self._framerate
|
||||||
|
|
||||||
def setnframes(self, nframes):
|
def setnframes(self, nframes):
|
||||||
if self._nframeswritten:
|
if self._nframeswritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if nframes < 0:
|
if nframes < 0:
|
||||||
raise Error, '# of frames cannot be negative'
|
raise Error('# of frames cannot be negative')
|
||||||
self._nframes = nframes
|
self._nframes = nframes
|
||||||
|
|
||||||
def getnframes(self):
|
def getnframes(self):
|
||||||
|
@ -351,7 +351,7 @@ class Au_write:
|
||||||
if type in ('NONE', 'ULAW'):
|
if type in ('NONE', 'ULAW'):
|
||||||
self._comptype = type
|
self._comptype = type
|
||||||
else:
|
else:
|
||||||
raise Error, 'unknown compression type'
|
raise Error('unknown compression type')
|
||||||
|
|
||||||
def getcomptype(self):
|
def getcomptype(self):
|
||||||
return self._comptype
|
return self._comptype
|
||||||
|
@ -411,11 +411,11 @@ class Au_write:
|
||||||
def _ensure_header_written(self):
|
def _ensure_header_written(self):
|
||||||
if not self._nframeswritten:
|
if not self._nframeswritten:
|
||||||
if not self._nchannels:
|
if not self._nchannels:
|
||||||
raise Error, '# of channels not specified'
|
raise Error('# of channels not specified')
|
||||||
if not self._sampwidth:
|
if not self._sampwidth:
|
||||||
raise Error, 'sample width not specified'
|
raise Error('sample width not specified')
|
||||||
if not self._framerate:
|
if not self._framerate:
|
||||||
raise Error, 'frame rate not specified'
|
raise Error('frame rate not specified')
|
||||||
self._write_header()
|
self._write_header()
|
||||||
|
|
||||||
def _write_header(self):
|
def _write_header(self):
|
||||||
|
@ -430,12 +430,12 @@ class Au_write:
|
||||||
encoding = AUDIO_FILE_ENCODING_LINEAR_32
|
encoding = AUDIO_FILE_ENCODING_LINEAR_32
|
||||||
self._framesize = 4
|
self._framesize = 4
|
||||||
else:
|
else:
|
||||||
raise Error, 'internal error'
|
raise Error('internal error')
|
||||||
elif self._comptype == 'ULAW':
|
elif self._comptype == 'ULAW':
|
||||||
encoding = AUDIO_FILE_ENCODING_MULAW_8
|
encoding = AUDIO_FILE_ENCODING_MULAW_8
|
||||||
self._framesize = 1
|
self._framesize = 1
|
||||||
else:
|
else:
|
||||||
raise Error, 'internal error'
|
raise Error('internal error')
|
||||||
self._framesize = self._framesize * self._nchannels
|
self._framesize = self._framesize * self._nchannels
|
||||||
_write_u32(self._file, AUDIO_FILE_MAGIC)
|
_write_u32(self._file, AUDIO_FILE_MAGIC)
|
||||||
header_size = 25 + len(self._info)
|
header_size = 25 + len(self._info)
|
||||||
|
@ -470,6 +470,6 @@ def open(f, mode=None):
|
||||||
elif mode in ('w', 'wb'):
|
elif mode in ('w', 'wb'):
|
||||||
return Au_write(f)
|
return Au_write(f)
|
||||||
else:
|
else:
|
||||||
raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
|
raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
|
||||||
|
|
||||||
openfp = open
|
openfp = open
|
||||||
|
|
|
@ -14,7 +14,7 @@ def get_long_be(s):
|
||||||
def gethdr(fp):
|
def gethdr(fp):
|
||||||
"""Read a sound header from an open file."""
|
"""Read a sound header from an open file."""
|
||||||
if fp.read(4) != MAGIC:
|
if fp.read(4) != MAGIC:
|
||||||
raise error, 'gethdr: bad magic word'
|
raise error('gethdr: bad magic word')
|
||||||
hdr_size = get_long_be(fp.read(4))
|
hdr_size = get_long_be(fp.read(4))
|
||||||
data_size = get_long_be(fp.read(4))
|
data_size = get_long_be(fp.read(4))
|
||||||
encoding = get_long_be(fp.read(4))
|
encoding = get_long_be(fp.read(4))
|
||||||
|
@ -22,7 +22,7 @@ def gethdr(fp):
|
||||||
channels = get_long_be(fp.read(4))
|
channels = get_long_be(fp.read(4))
|
||||||
excess = hdr_size - 24
|
excess = hdr_size - 24
|
||||||
if excess < 0:
|
if excess < 0:
|
||||||
raise error, 'gethdr: bad hdr_size'
|
raise error('gethdr: bad hdr_size')
|
||||||
if excess > 0:
|
if excess > 0:
|
||||||
info = fp.read(excess)
|
info = fp.read(excess)
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -240,7 +240,7 @@ class Symbol:
|
||||||
Raises ValueError if the name is bound to multiple namespaces.
|
Raises ValueError if the name is bound to multiple namespaces.
|
||||||
"""
|
"""
|
||||||
if len(self.__namespaces) != 1:
|
if len(self.__namespaces) != 1:
|
||||||
raise ValueError, "name is bound to multiple namespaces"
|
raise ValueError("name is bound to multiple namespaces")
|
||||||
return self.__namespaces[0]
|
return self.__namespaces[0]
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -57,7 +57,7 @@ if sys.platform == 'mac':
|
||||||
# handling. In many places it is assumed a simple substitution of / by the
|
# handling. In many places it is assumed a simple substitution of / by the
|
||||||
# local os.path.sep is good enough to convert pathnames, but this does not
|
# local os.path.sep is good enough to convert pathnames, but this does not
|
||||||
# work with the mac rooted:path:name versus :nonrooted:path:name syntax
|
# work with the mac rooted:path:name versus :nonrooted:path:name syntax
|
||||||
raise ImportError, "tarfile does not work for platform==mac"
|
raise ImportError("tarfile does not work for platform==mac")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import grp, pwd
|
import grp, pwd
|
||||||
|
|
|
@ -394,7 +394,7 @@ class Telnet:
|
||||||
buf = self.cookedq
|
buf = self.cookedq
|
||||||
self.cookedq = ''
|
self.cookedq = ''
|
||||||
if not buf and self.eof and not self.rawq:
|
if not buf and self.eof and not self.rawq:
|
||||||
raise EOFError, 'telnet connection closed'
|
raise EOFError('telnet connection closed')
|
||||||
return buf
|
return buf
|
||||||
|
|
||||||
def read_sb_data(self):
|
def read_sb_data(self):
|
||||||
|
|
|
@ -204,8 +204,8 @@ def _get_default_tempdir():
|
||||||
if e[0] != _errno.EEXIST:
|
if e[0] != _errno.EEXIST:
|
||||||
break # no point trying more names in this directory
|
break # no point trying more names in this directory
|
||||||
pass
|
pass
|
||||||
raise IOError, (_errno.ENOENT,
|
raise IOError(_errno.ENOENT,
|
||||||
("No usable temporary directory found in %s" % dirlist))
|
"No usable temporary directory found in %s" % dirlist)
|
||||||
|
|
||||||
_name_sequence = None
|
_name_sequence = None
|
||||||
|
|
||||||
|
@ -240,7 +240,7 @@ def _mkstemp_inner(dir, pre, suf, flags):
|
||||||
continue # try again
|
continue # try again
|
||||||
raise
|
raise
|
||||||
|
|
||||||
raise IOError, (_errno.EEXIST, "No usable temporary file name found")
|
raise IOError(_errno.EEXIST, "No usable temporary file name found")
|
||||||
|
|
||||||
|
|
||||||
# User visible interfaces.
|
# User visible interfaces.
|
||||||
|
@ -331,7 +331,7 @@ def mkdtemp(suffix="", prefix=template, dir=None):
|
||||||
continue # try again
|
continue # try again
|
||||||
raise
|
raise
|
||||||
|
|
||||||
raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
|
raise IOError(_errno.EEXIST, "No usable temporary directory name found")
|
||||||
|
|
||||||
def mktemp(suffix="", prefix=template, dir=None):
|
def mktemp(suffix="", prefix=template, dir=None):
|
||||||
"""mktemp([suffix, [prefix, [dir]]])
|
"""mktemp([suffix, [prefix, [dir]]])
|
||||||
|
@ -361,7 +361,7 @@ def mktemp(suffix="", prefix=template, dir=None):
|
||||||
if not _exists(file):
|
if not _exists(file):
|
||||||
return file
|
return file
|
||||||
|
|
||||||
raise IOError, (_errno.EEXIST, "No usable temporary filename found")
|
raise IOError(_errno.EEXIST, "No usable temporary filename found")
|
||||||
|
|
||||||
class _TemporaryFileWrapper:
|
class _TemporaryFileWrapper:
|
||||||
"""Temporary file wrapper
|
"""Temporary file wrapper
|
||||||
|
|
|
@ -326,7 +326,7 @@ class _BoundedSemaphore(_Semaphore):
|
||||||
|
|
||||||
def release(self):
|
def release(self):
|
||||||
if self._value >= self._initial_value:
|
if self._value >= self._initial_value:
|
||||||
raise ValueError, "Semaphore released too many times"
|
raise ValueError("Semaphore released too many times")
|
||||||
return _Semaphore.release(self)
|
return _Semaphore.release(self)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -269,7 +269,7 @@ def generate_tokens(readline):
|
||||||
|
|
||||||
if contstr: # continued string
|
if contstr: # continued string
|
||||||
if not line:
|
if not line:
|
||||||
raise TokenError, ("EOF in multi-line string", strstart)
|
raise TokenError("EOF in multi-line string", strstart)
|
||||||
endmatch = endprog.match(line)
|
endmatch = endprog.match(line)
|
||||||
if endmatch:
|
if endmatch:
|
||||||
pos = end = endmatch.end(0)
|
pos = end = endmatch.end(0)
|
||||||
|
@ -325,7 +325,7 @@ def generate_tokens(readline):
|
||||||
|
|
||||||
else: # continued statement
|
else: # continued statement
|
||||||
if not line:
|
if not line:
|
||||||
raise TokenError, ("EOF in multi-line statement", (lnum, 0))
|
raise TokenError("EOF in multi-line statement", (lnum, 0))
|
||||||
continued = 0
|
continued = 0
|
||||||
|
|
||||||
while pos < max:
|
while pos < max:
|
||||||
|
|
|
@ -130,7 +130,8 @@ class TestResult:
|
||||||
if exctype is test.failureException:
|
if exctype is test.failureException:
|
||||||
# Skip assert*() traceback levels
|
# Skip assert*() traceback levels
|
||||||
length = self._count_relevant_tb_levels(tb)
|
length = self._count_relevant_tb_levels(tb)
|
||||||
return ''.join(traceback.format_exception(exctype, value, tb, length))
|
return ''.join(traceback.format_exception(exctype, value,
|
||||||
|
tb, length))
|
||||||
return ''.join(traceback.format_exception(exctype, value, tb))
|
return ''.join(traceback.format_exception(exctype, value, tb))
|
||||||
|
|
||||||
def _is_relevant_tb_level(self, tb):
|
def _is_relevant_tb_level(self, tb):
|
||||||
|
@ -186,8 +187,8 @@ class TestCase:
|
||||||
testMethod = getattr(self, methodName)
|
testMethod = getattr(self, methodName)
|
||||||
self._testMethodDoc = testMethod.__doc__
|
self._testMethodDoc = testMethod.__doc__
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
raise ValueError, "no such test method in %s: %s" % \
|
raise ValueError("no such test method in %s: %s"
|
||||||
(self.__class__, methodName)
|
% (self.__class__, methodName))
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
"Hook method for setting up the test fixture before exercising it."
|
"Hook method for setting up the test fixture before exercising it."
|
||||||
|
@ -288,15 +289,15 @@ class TestCase:
|
||||||
|
|
||||||
def fail(self, msg=None):
|
def fail(self, msg=None):
|
||||||
"""Fail immediately, with the given message."""
|
"""Fail immediately, with the given message."""
|
||||||
raise self.failureException, msg
|
raise self.failureException(msg)
|
||||||
|
|
||||||
def failIf(self, expr, msg=None):
|
def failIf(self, expr, msg=None):
|
||||||
"Fail the test if the expression is true."
|
"Fail the test if the expression is true."
|
||||||
if expr: raise self.failureException, msg
|
if expr: raise self.failureException(msg)
|
||||||
|
|
||||||
def failUnless(self, expr, msg=None):
|
def failUnless(self, expr, msg=None):
|
||||||
"""Fail the test unless the expression is true."""
|
"""Fail the test unless the expression is true."""
|
||||||
if not expr: raise self.failureException, msg
|
if not expr: raise self.failureException(msg)
|
||||||
|
|
||||||
def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
|
def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
|
||||||
"""Fail unless an exception of class excClass is thrown
|
"""Fail unless an exception of class excClass is thrown
|
||||||
|
@ -313,24 +314,22 @@ class TestCase:
|
||||||
else:
|
else:
|
||||||
excName = str(getattr(excClass, '__name__', excClass))
|
excName = str(getattr(excClass, '__name__', excClass))
|
||||||
objName = str(getattr(callableObj, '__name__', callableObj))
|
objName = str(getattr(callableObj, '__name__', callableObj))
|
||||||
raise self.failureException, "%s not raised by %s" % (excName,
|
raise self.failureException("%s not raised by %s" % (excName,
|
||||||
objName)
|
objName))
|
||||||
|
|
||||||
def failUnlessEqual(self, first, second, msg=None):
|
def failUnlessEqual(self, first, second, msg=None):
|
||||||
"""Fail if the two objects are unequal as determined by the '=='
|
"""Fail if the two objects are unequal as determined by the '=='
|
||||||
operator.
|
operator.
|
||||||
"""
|
"""
|
||||||
if not first == second:
|
if not first == second:
|
||||||
raise self.failureException, \
|
raise self.failureException(msg or '%r != %r' % (first, second))
|
||||||
(msg or '%r != %r' % (first, second))
|
|
||||||
|
|
||||||
def failIfEqual(self, first, second, msg=None):
|
def failIfEqual(self, first, second, msg=None):
|
||||||
"""Fail if the two objects are equal as determined by the '=='
|
"""Fail if the two objects are equal as determined by the '=='
|
||||||
operator.
|
operator.
|
||||||
"""
|
"""
|
||||||
if first == second:
|
if first == second:
|
||||||
raise self.failureException, \
|
raise self.failureException(msg or '%r == %r' % (first, second))
|
||||||
(msg or '%r == %r' % (first, second))
|
|
||||||
|
|
||||||
def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
|
def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
|
||||||
"""Fail if the two objects are unequal as determined by their
|
"""Fail if the two objects are unequal as determined by their
|
||||||
|
@ -341,8 +340,8 @@ class TestCase:
|
||||||
as significant digits (measured from the most signficant digit).
|
as significant digits (measured from the most signficant digit).
|
||||||
"""
|
"""
|
||||||
if round(second-first, places) != 0:
|
if round(second-first, places) != 0:
|
||||||
raise self.failureException, \
|
raise self.failureException(msg or '%r != %r within %r places'
|
||||||
(msg or '%r != %r within %r places' % (first, second, places))
|
% (first, second, places))
|
||||||
|
|
||||||
def failIfAlmostEqual(self, first, second, places=7, msg=None):
|
def failIfAlmostEqual(self, first, second, places=7, msg=None):
|
||||||
"""Fail if the two objects are equal as determined by their
|
"""Fail if the two objects are equal as determined by their
|
||||||
|
@ -353,8 +352,8 @@ class TestCase:
|
||||||
as significant digits (measured from the most signficant digit).
|
as significant digits (measured from the most signficant digit).
|
||||||
"""
|
"""
|
||||||
if round(second-first, places) == 0:
|
if round(second-first, places) == 0:
|
||||||
raise self.failureException, \
|
raise self.failureException(msg or '%r == %r within %r places'
|
||||||
(msg or '%r == %r within %r places' % (first, second, places))
|
% (first, second, places))
|
||||||
|
|
||||||
# Synonyms for assertion methods
|
# Synonyms for assertion methods
|
||||||
|
|
||||||
|
@ -487,10 +486,12 @@ class FunctionTestCase(TestCase):
|
||||||
self.__testFunc, self.__description))
|
self.__testFunc, self.__description))
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
|
return "%s (%s)" % (_strclass(self.__class__),
|
||||||
|
self.__testFunc.__name__)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
|
return "<%s testFunc=%s>" % (_strclass(self.__class__),
|
||||||
|
self.__testFunc)
|
||||||
|
|
||||||
def shortDescription(self):
|
def shortDescription(self):
|
||||||
if self.__description is not None: return self.__description
|
if self.__description is not None: return self.__description
|
||||||
|
@ -514,7 +515,8 @@ class TestLoader:
|
||||||
def loadTestsFromTestCase(self, testCaseClass):
|
def loadTestsFromTestCase(self, testCaseClass):
|
||||||
"""Return a suite of all tests cases contained in testCaseClass"""
|
"""Return a suite of all tests cases contained in testCaseClass"""
|
||||||
if issubclass(testCaseClass, TestSuite):
|
if issubclass(testCaseClass, TestSuite):
|
||||||
raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
|
raise TypeError("Test cases should not be derived from TestSuite."
|
||||||
|
"Maybe you meant to derive from TestCase?")
|
||||||
testCaseNames = self.getTestCaseNames(testCaseClass)
|
testCaseNames = self.getTestCaseNames(testCaseClass)
|
||||||
if not testCaseNames and hasattr(testCaseClass, 'runTest'):
|
if not testCaseNames and hasattr(testCaseClass, 'runTest'):
|
||||||
testCaseNames = ['runTest']
|
testCaseNames = ['runTest']
|
||||||
|
@ -585,8 +587,10 @@ class TestLoader:
|
||||||
def getTestCaseNames(self, testCaseClass):
|
def getTestCaseNames(self, testCaseClass):
|
||||||
"""Return a sorted sequence of method names found within testCaseClass
|
"""Return a sorted sequence of method names found within testCaseClass
|
||||||
"""
|
"""
|
||||||
def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
|
def isTestMethod(attrname, testCaseClass=testCaseClass,
|
||||||
return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')
|
prefix=self.testMethodPrefix):
|
||||||
|
return attrname.startswith(prefix) \
|
||||||
|
and hasattr(getattr(testCaseClass, attrname), '__call__')
|
||||||
testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
|
testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
|
||||||
if self.sortTestMethodsUsing:
|
if self.sortTestMethodsUsing:
|
||||||
testFnNames.sort(self.sortTestMethodsUsing)
|
testFnNames.sort(self.sortTestMethodsUsing)
|
||||||
|
|
|
@ -196,12 +196,12 @@ class URLopener:
|
||||||
def open_unknown(self, fullurl, data=None):
|
def open_unknown(self, fullurl, data=None):
|
||||||
"""Overridable interface to open unknown URL type."""
|
"""Overridable interface to open unknown URL type."""
|
||||||
type, url = splittype(fullurl)
|
type, url = splittype(fullurl)
|
||||||
raise IOError, ('url error', 'unknown url type', type)
|
raise IOError('url error', 'unknown url type', type)
|
||||||
|
|
||||||
def open_unknown_proxy(self, proxy, fullurl, data=None):
|
def open_unknown_proxy(self, proxy, fullurl, data=None):
|
||||||
"""Overridable interface to open unknown URL type."""
|
"""Overridable interface to open unknown URL type."""
|
||||||
type, url = splittype(fullurl)
|
type, url = splittype(fullurl)
|
||||||
raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
|
raise IOError('url error', 'invalid proxy for %s' % type, proxy)
|
||||||
|
|
||||||
# External interface
|
# External interface
|
||||||
def retrieve(self, url, filename=None, reporthook=None, data=None):
|
def retrieve(self, url, filename=None, reporthook=None, data=None):
|
||||||
|
@ -308,7 +308,7 @@ class URLopener:
|
||||||
host = realhost
|
host = realhost
|
||||||
|
|
||||||
#print "proxy via http:", host, selector
|
#print "proxy via http:", host, selector
|
||||||
if not host: raise IOError, ('http error', 'no host given')
|
if not host: raise IOError('http error', 'no host given')
|
||||||
|
|
||||||
if proxy_passwd:
|
if proxy_passwd:
|
||||||
import base64
|
import base64
|
||||||
|
@ -380,7 +380,7 @@ class URLopener:
|
||||||
"""Default error handler: close the connection and raise IOError."""
|
"""Default error handler: close the connection and raise IOError."""
|
||||||
void = fp.read()
|
void = fp.read()
|
||||||
fp.close()
|
fp.close()
|
||||||
raise IOError, ('http error', errcode, errmsg, headers)
|
raise IOError('http error', errcode, errmsg, headers)
|
||||||
|
|
||||||
if hasattr(socket, "ssl"):
|
if hasattr(socket, "ssl"):
|
||||||
def _https_connection(self, host):
|
def _https_connection(self, host):
|
||||||
|
@ -395,7 +395,7 @@ class URLopener:
|
||||||
def open_file(self, url):
|
def open_file(self, url):
|
||||||
"""Use local file or FTP depending on form of URL."""
|
"""Use local file or FTP depending on form of URL."""
|
||||||
if not isinstance(url, str):
|
if not isinstance(url, str):
|
||||||
raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
|
raise IOError('file error', 'proxy support for file protocol currently not implemented')
|
||||||
if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
|
if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
|
||||||
return self.open_ftp(url)
|
return self.open_ftp(url)
|
||||||
else:
|
else:
|
||||||
|
@ -441,16 +441,16 @@ class URLopener:
|
||||||
urlfile = 'file://' + file
|
urlfile = 'file://' + file
|
||||||
return addinfourl(open(localname, 'rb'),
|
return addinfourl(open(localname, 'rb'),
|
||||||
headers, urlfile)
|
headers, urlfile)
|
||||||
raise IOError, ('local file error', 'not on local host')
|
raise IOError('local file error', 'not on local host')
|
||||||
|
|
||||||
def open_ftp(self, url):
|
def open_ftp(self, url):
|
||||||
"""Use FTP protocol."""
|
"""Use FTP protocol."""
|
||||||
if not isinstance(url, str):
|
if not isinstance(url, str):
|
||||||
raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented')
|
raise IOError('ftp error', 'proxy support for ftp protocol currently not implemented')
|
||||||
import mimetypes, mimetools
|
import mimetypes, mimetools
|
||||||
from io import StringIO
|
from io import StringIO
|
||||||
host, path = splithost(url)
|
host, path = splithost(url)
|
||||||
if not host: raise IOError, ('ftp error', 'no host given')
|
if not host: raise IOError('ftp error', 'no host given')
|
||||||
host, port = splitport(host)
|
host, port = splitport(host)
|
||||||
user, host = splituser(host)
|
user, host = splituser(host)
|
||||||
if user: user, passwd = splitpasswd(user)
|
if user: user, passwd = splitpasswd(user)
|
||||||
|
@ -505,7 +505,7 @@ class URLopener:
|
||||||
def open_data(self, url, data=None):
|
def open_data(self, url, data=None):
|
||||||
"""Use "data" URL."""
|
"""Use "data" URL."""
|
||||||
if not isinstance(url, str):
|
if not isinstance(url, str):
|
||||||
raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
|
raise IOError('data error', 'proxy support for data protocol currently not implemented')
|
||||||
# ignore POSTed data
|
# ignore POSTed data
|
||||||
#
|
#
|
||||||
# syntax of data URLs:
|
# syntax of data URLs:
|
||||||
|
@ -518,7 +518,7 @@ class URLopener:
|
||||||
try:
|
try:
|
||||||
[type, data] = url.split(',', 1)
|
[type, data] = url.split(',', 1)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise IOError, ('data error', 'bad data URL')
|
raise IOError('data error', 'bad data URL')
|
||||||
if not type:
|
if not type:
|
||||||
type = 'text/plain;charset=US-ASCII'
|
type = 'text/plain;charset=US-ASCII'
|
||||||
semi = type.rfind(';')
|
semi = type.rfind(';')
|
||||||
|
@ -1032,7 +1032,7 @@ def splitnport(host, defport=-1):
|
||||||
if match:
|
if match:
|
||||||
host, port = match.group(1, 2)
|
host, port = match.group(1, 2)
|
||||||
try:
|
try:
|
||||||
if not port: raise ValueError, "no digits"
|
if not port: raise ValueError("no digits")
|
||||||
nport = int(port)
|
nport = int(port)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
nport = None
|
nport = None
|
||||||
|
|
|
@ -210,7 +210,7 @@ class Request:
|
||||||
if hasattr(Request, 'get_' + name):
|
if hasattr(Request, 'get_' + name):
|
||||||
getattr(self, 'get_' + name)()
|
getattr(self, 'get_' + name)()
|
||||||
return getattr(self, attr)
|
return getattr(self, attr)
|
||||||
raise AttributeError, attr
|
raise AttributeError(attr)
|
||||||
|
|
||||||
def get_method(self):
|
def get_method(self):
|
||||||
if self.has_data():
|
if self.has_data():
|
||||||
|
@ -236,7 +236,7 @@ class Request:
|
||||||
if self.type is None:
|
if self.type is None:
|
||||||
self.type, self.__r_type = splittype(self.__original)
|
self.type, self.__r_type = splittype(self.__original)
|
||||||
if self.type is None:
|
if self.type is None:
|
||||||
raise ValueError, "unknown url type: %s" % self.__original
|
raise ValueError("unknown url type: %s" % self.__original)
|
||||||
return self.type
|
return self.type
|
||||||
|
|
||||||
def get_host(self):
|
def get_host(self):
|
||||||
|
@ -1250,7 +1250,7 @@ class FTPHandler(BaseHandler):
|
||||||
import mimetypes
|
import mimetypes
|
||||||
host = req.get_host()
|
host = req.get_host()
|
||||||
if not host:
|
if not host:
|
||||||
raise IOError, ('ftp error', 'no host given')
|
raise IOError('ftp error', 'no host given')
|
||||||
host, port = splitport(host)
|
host, port = splitport(host)
|
||||||
if port is None:
|
if port is None:
|
||||||
port = ftplib.FTP_PORT
|
port = ftplib.FTP_PORT
|
||||||
|
|
54
Lib/wave.py
54
Lib/wave.py
|
@ -127,9 +127,9 @@ class Wave_read:
|
||||||
self._soundpos = 0
|
self._soundpos = 0
|
||||||
self._file = Chunk(file, bigendian = 0)
|
self._file = Chunk(file, bigendian = 0)
|
||||||
if self._file.getname() != b'RIFF':
|
if self._file.getname() != b'RIFF':
|
||||||
raise Error, 'file does not start with RIFF id'
|
raise Error('file does not start with RIFF id')
|
||||||
if self._file.read(4) != b'WAVE':
|
if self._file.read(4) != b'WAVE':
|
||||||
raise Error, 'not a WAVE file'
|
raise Error('not a WAVE file')
|
||||||
self._fmt_chunk_read = 0
|
self._fmt_chunk_read = 0
|
||||||
self._data_chunk = None
|
self._data_chunk = None
|
||||||
while 1:
|
while 1:
|
||||||
|
@ -144,14 +144,14 @@ class Wave_read:
|
||||||
self._fmt_chunk_read = 1
|
self._fmt_chunk_read = 1
|
||||||
elif chunkname == b'data':
|
elif chunkname == b'data':
|
||||||
if not self._fmt_chunk_read:
|
if not self._fmt_chunk_read:
|
||||||
raise Error, 'data chunk before fmt chunk'
|
raise Error('data chunk before fmt chunk')
|
||||||
self._data_chunk = chunk
|
self._data_chunk = chunk
|
||||||
self._nframes = chunk.chunksize // self._framesize
|
self._nframes = chunk.chunksize // self._framesize
|
||||||
self._data_seek_needed = 0
|
self._data_seek_needed = 0
|
||||||
break
|
break
|
||||||
chunk.skip()
|
chunk.skip()
|
||||||
if not self._fmt_chunk_read or not self._data_chunk:
|
if not self._fmt_chunk_read or not self._data_chunk:
|
||||||
raise Error, 'fmt chunk and/or data chunk missing'
|
raise Error('fmt chunk and/or data chunk missing')
|
||||||
|
|
||||||
def __init__(self, f):
|
def __init__(self, f):
|
||||||
self._i_opened_the_file = None
|
self._i_opened_the_file = None
|
||||||
|
@ -214,11 +214,11 @@ class Wave_read:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def getmark(self, id):
|
def getmark(self, id):
|
||||||
raise Error, 'no marks'
|
raise Error('no marks')
|
||||||
|
|
||||||
def setpos(self, pos):
|
def setpos(self, pos):
|
||||||
if pos < 0 or pos > self._nframes:
|
if pos < 0 or pos > self._nframes:
|
||||||
raise Error, 'position not in range'
|
raise Error('position not in range')
|
||||||
self._soundpos = pos
|
self._soundpos = pos
|
||||||
self._data_seek_needed = 1
|
self._data_seek_needed = 1
|
||||||
|
|
||||||
|
@ -266,7 +266,7 @@ class Wave_read:
|
||||||
sampwidth = struct.unpack_from('<h', chunk.read(2))[0]
|
sampwidth = struct.unpack_from('<h', chunk.read(2))[0]
|
||||||
self._sampwidth = (sampwidth + 7) // 8
|
self._sampwidth = (sampwidth + 7) // 8
|
||||||
else:
|
else:
|
||||||
raise Error, 'unknown format: %r' % (wFormatTag,)
|
raise Error('unknown format: %r' % (wFormatTag,))
|
||||||
self._framesize = self._nchannels * self._sampwidth
|
self._framesize = self._nchannels * self._sampwidth
|
||||||
self._comptype = 'NONE'
|
self._comptype = 'NONE'
|
||||||
self._compname = 'not compressed'
|
self._compname = 'not compressed'
|
||||||
|
@ -328,43 +328,43 @@ class Wave_write:
|
||||||
#
|
#
|
||||||
def setnchannels(self, nchannels):
|
def setnchannels(self, nchannels):
|
||||||
if self._datawritten:
|
if self._datawritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if nchannels < 1:
|
if nchannels < 1:
|
||||||
raise Error, 'bad # of channels'
|
raise Error('bad # of channels')
|
||||||
self._nchannels = nchannels
|
self._nchannels = nchannels
|
||||||
|
|
||||||
def getnchannels(self):
|
def getnchannels(self):
|
||||||
if not self._nchannels:
|
if not self._nchannels:
|
||||||
raise Error, 'number of channels not set'
|
raise Error('number of channels not set')
|
||||||
return self._nchannels
|
return self._nchannels
|
||||||
|
|
||||||
def setsampwidth(self, sampwidth):
|
def setsampwidth(self, sampwidth):
|
||||||
if self._datawritten:
|
if self._datawritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if sampwidth < 1 or sampwidth > 4:
|
if sampwidth < 1 or sampwidth > 4:
|
||||||
raise Error, 'bad sample width'
|
raise Error('bad sample width')
|
||||||
self._sampwidth = sampwidth
|
self._sampwidth = sampwidth
|
||||||
|
|
||||||
def getsampwidth(self):
|
def getsampwidth(self):
|
||||||
if not self._sampwidth:
|
if not self._sampwidth:
|
||||||
raise Error, 'sample width not set'
|
raise Error('sample width not set')
|
||||||
return self._sampwidth
|
return self._sampwidth
|
||||||
|
|
||||||
def setframerate(self, framerate):
|
def setframerate(self, framerate):
|
||||||
if self._datawritten:
|
if self._datawritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if framerate <= 0:
|
if framerate <= 0:
|
||||||
raise Error, 'bad frame rate'
|
raise Error('bad frame rate')
|
||||||
self._framerate = framerate
|
self._framerate = framerate
|
||||||
|
|
||||||
def getframerate(self):
|
def getframerate(self):
|
||||||
if not self._framerate:
|
if not self._framerate:
|
||||||
raise Error, 'frame rate not set'
|
raise Error('frame rate not set')
|
||||||
return self._framerate
|
return self._framerate
|
||||||
|
|
||||||
def setnframes(self, nframes):
|
def setnframes(self, nframes):
|
||||||
if self._datawritten:
|
if self._datawritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
self._nframes = nframes
|
self._nframes = nframes
|
||||||
|
|
||||||
def getnframes(self):
|
def getnframes(self):
|
||||||
|
@ -372,9 +372,9 @@ class Wave_write:
|
||||||
|
|
||||||
def setcomptype(self, comptype, compname):
|
def setcomptype(self, comptype, compname):
|
||||||
if self._datawritten:
|
if self._datawritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
if comptype not in ('NONE',):
|
if comptype not in ('NONE',):
|
||||||
raise Error, 'unsupported compression type'
|
raise Error('unsupported compression type')
|
||||||
self._comptype = comptype
|
self._comptype = comptype
|
||||||
self._compname = compname
|
self._compname = compname
|
||||||
|
|
||||||
|
@ -387,7 +387,7 @@ class Wave_write:
|
||||||
def setparams(self, params):
|
def setparams(self, params):
|
||||||
nchannels, sampwidth, framerate, nframes, comptype, compname = params
|
nchannels, sampwidth, framerate, nframes, comptype, compname = params
|
||||||
if self._datawritten:
|
if self._datawritten:
|
||||||
raise Error, 'cannot change parameters after starting to write'
|
raise Error('cannot change parameters after starting to write')
|
||||||
self.setnchannels(nchannels)
|
self.setnchannels(nchannels)
|
||||||
self.setsampwidth(sampwidth)
|
self.setsampwidth(sampwidth)
|
||||||
self.setframerate(framerate)
|
self.setframerate(framerate)
|
||||||
|
@ -396,15 +396,15 @@ class Wave_write:
|
||||||
|
|
||||||
def getparams(self):
|
def getparams(self):
|
||||||
if not self._nchannels or not self._sampwidth or not self._framerate:
|
if not self._nchannels or not self._sampwidth or not self._framerate:
|
||||||
raise Error, 'not all parameters set'
|
raise Error('not all parameters set')
|
||||||
return self._nchannels, self._sampwidth, self._framerate, \
|
return self._nchannels, self._sampwidth, self._framerate, \
|
||||||
self._nframes, self._comptype, self._compname
|
self._nframes, self._comptype, self._compname
|
||||||
|
|
||||||
def setmark(self, id, pos, name):
|
def setmark(self, id, pos, name):
|
||||||
raise Error, 'setmark() not supported'
|
raise Error('setmark() not supported')
|
||||||
|
|
||||||
def getmark(self, id):
|
def getmark(self, id):
|
||||||
raise Error, 'no marks'
|
raise Error('no marks')
|
||||||
|
|
||||||
def getmarkers(self):
|
def getmarkers(self):
|
||||||
return None
|
return None
|
||||||
|
@ -451,11 +451,11 @@ class Wave_write:
|
||||||
def _ensure_header_written(self, datasize):
|
def _ensure_header_written(self, datasize):
|
||||||
if not self._datawritten:
|
if not self._datawritten:
|
||||||
if not self._nchannels:
|
if not self._nchannels:
|
||||||
raise Error, '# channels not specified'
|
raise Error('# channels not specified')
|
||||||
if not self._sampwidth:
|
if not self._sampwidth:
|
||||||
raise Error, 'sample width not specified'
|
raise Error('sample width not specified')
|
||||||
if not self._framerate:
|
if not self._framerate:
|
||||||
raise Error, 'sampling rate not specified'
|
raise Error('sampling rate not specified')
|
||||||
self._write_header(datasize)
|
self._write_header(datasize)
|
||||||
|
|
||||||
def _write_header(self, initlength):
|
def _write_header(self, initlength):
|
||||||
|
@ -495,6 +495,6 @@ def open(f, mode=None):
|
||||||
elif mode in ('w', 'wb'):
|
elif mode in ('w', 'wb'):
|
||||||
return Wave_write(f)
|
return Wave_write(f)
|
||||||
else:
|
else:
|
||||||
raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
|
raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
|
||||||
|
|
||||||
openfp = open # B/W compatibility
|
openfp = open # B/W compatibility
|
||||||
|
|
|
@ -51,7 +51,7 @@ class WeakValueDictionary(UserDict.UserDict):
|
||||||
def __getitem__(self, key):
|
def __getitem__(self, key):
|
||||||
o = self.data[key]()
|
o = self.data[key]()
|
||||||
if o is None:
|
if o is None:
|
||||||
raise KeyError, key
|
raise KeyError(key)
|
||||||
else:
|
else:
|
||||||
return o
|
return o
|
||||||
|
|
||||||
|
@ -142,7 +142,7 @@ class WeakValueDictionary(UserDict.UserDict):
|
||||||
return args[0]
|
return args[0]
|
||||||
raise
|
raise
|
||||||
if o is None:
|
if o is None:
|
||||||
raise KeyError, key
|
raise KeyError(key)
|
||||||
else:
|
else:
|
||||||
return o
|
return o
|
||||||
|
|
||||||
|
|
|
@ -66,16 +66,16 @@ class Packer:
|
||||||
def pack_float(self, x):
|
def pack_float(self, x):
|
||||||
try: self.__buf.write(struct.pack('>f', x))
|
try: self.__buf.write(struct.pack('>f', x))
|
||||||
except struct.error as msg:
|
except struct.error as msg:
|
||||||
raise ConversionError, msg
|
raise ConversionError(msg)
|
||||||
|
|
||||||
def pack_double(self, x):
|
def pack_double(self, x):
|
||||||
try: self.__buf.write(struct.pack('>d', x))
|
try: self.__buf.write(struct.pack('>d', x))
|
||||||
except struct.error as msg:
|
except struct.error as msg:
|
||||||
raise ConversionError, msg
|
raise ConversionError(msg)
|
||||||
|
|
||||||
def pack_fstring(self, n, s):
|
def pack_fstring(self, n, s):
|
||||||
if n < 0:
|
if n < 0:
|
||||||
raise ValueError, 'fstring size must be nonnegative'
|
raise ValueError('fstring size must be nonnegative')
|
||||||
data = s[:n]
|
data = s[:n]
|
||||||
n = ((n+3)//4)*4
|
n = ((n+3)//4)*4
|
||||||
data = data + (n - len(data)) * b'\0'
|
data = data + (n - len(data)) * b'\0'
|
||||||
|
@ -99,7 +99,7 @@ class Packer:
|
||||||
|
|
||||||
def pack_farray(self, n, list, pack_item):
|
def pack_farray(self, n, list, pack_item):
|
||||||
if len(list) != n:
|
if len(list) != n:
|
||||||
raise ValueError, 'wrong array size'
|
raise ValueError('wrong array size')
|
||||||
for item in list:
|
for item in list:
|
||||||
pack_item(item)
|
pack_item(item)
|
||||||
|
|
||||||
|
@ -187,7 +187,7 @@ class Unpacker:
|
||||||
|
|
||||||
def unpack_fstring(self, n):
|
def unpack_fstring(self, n):
|
||||||
if n < 0:
|
if n < 0:
|
||||||
raise ValueError, 'fstring size must be nonnegative'
|
raise ValueError('fstring size must be nonnegative')
|
||||||
i = self.__pos
|
i = self.__pos
|
||||||
j = i + (n+3)//4*4
|
j = i + (n+3)//4*4
|
||||||
if j > len(self.__buf):
|
if j > len(self.__buf):
|
||||||
|
@ -210,7 +210,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 ConversionError, '0 or 1 expected, got %r' % (x,)
|
raise ConversionError('0 or 1 expected, got %r' % (x,))
|
||||||
item = unpack_item()
|
item = unpack_item()
|
||||||
list.append(item)
|
list.append(item)
|
||||||
return list
|
return list
|
||||||
|
|
|
@ -570,13 +570,13 @@ class Marshaller:
|
||||||
try:
|
try:
|
||||||
value.__dict__
|
value.__dict__
|
||||||
except:
|
except:
|
||||||
raise TypeError, "cannot marshal %s objects" % type(value)
|
raise TypeError("cannot marshal %s objects" % type(value))
|
||||||
# check if this class is a sub-class of a basic type,
|
# check if this class is a sub-class of a basic type,
|
||||||
# because we don't know how to marshal these types
|
# because we don't know how to marshal these types
|
||||||
# (e.g. a string sub-class)
|
# (e.g. a string sub-class)
|
||||||
for type_ in type(value).__mro__:
|
for type_ in type(value).__mro__:
|
||||||
if type_ in self.dispatch.keys():
|
if type_ in self.dispatch.keys():
|
||||||
raise TypeError, "cannot marshal %s objects" % type(value)
|
raise TypeError("cannot marshal %s objects" % type(value))
|
||||||
# XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
|
# XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
|
||||||
# for the p3yk merge, this should probably be fixed more neatly.
|
# for the p3yk merge, this should probably be fixed more neatly.
|
||||||
f = self.dispatch["_arbitrary_instance"]
|
f = self.dispatch["_arbitrary_instance"]
|
||||||
|
@ -584,14 +584,14 @@ class Marshaller:
|
||||||
|
|
||||||
def dump_nil (self, value, write):
|
def dump_nil (self, value, write):
|
||||||
if not self.allow_none:
|
if not self.allow_none:
|
||||||
raise TypeError, "cannot marshal None unless allow_none is enabled"
|
raise TypeError("cannot marshal None unless allow_none is enabled")
|
||||||
write("<value><nil/></value>")
|
write("<value><nil/></value>")
|
||||||
dispatch[type(None)] = dump_nil
|
dispatch[type(None)] = dump_nil
|
||||||
|
|
||||||
def dump_int(self, value, write):
|
def dump_int(self, value, write):
|
||||||
# in case ints are > 32 bits
|
# in case ints are > 32 bits
|
||||||
if value > MAXINT or value < MININT:
|
if value > MAXINT or value < MININT:
|
||||||
raise OverflowError, "int exceeds XML-RPC limits"
|
raise OverflowError("int exceeds XML-RPC limits")
|
||||||
write("<value><int>")
|
write("<value><int>")
|
||||||
write(str(value))
|
write(str(value))
|
||||||
write("</int></value>\n")
|
write("</int></value>\n")
|
||||||
|
@ -606,7 +606,7 @@ class Marshaller:
|
||||||
|
|
||||||
def dump_long(self, value, write):
|
def dump_long(self, value, write):
|
||||||
if value > MAXINT or value < MININT:
|
if value > MAXINT or value < MININT:
|
||||||
raise OverflowError, "long int exceeds XML-RPC limits"
|
raise OverflowError("long int exceeds XML-RPC limits")
|
||||||
write("<value><int>")
|
write("<value><int>")
|
||||||
write(str(int(value)))
|
write(str(int(value)))
|
||||||
write("</int></value>\n")
|
write("</int></value>\n")
|
||||||
|
@ -633,7 +633,7 @@ class Marshaller:
|
||||||
def dump_array(self, value, write):
|
def dump_array(self, value, write):
|
||||||
i = id(value)
|
i = id(value)
|
||||||
if i in self.memo:
|
if i in self.memo:
|
||||||
raise TypeError, "cannot marshal recursive sequences"
|
raise TypeError("cannot marshal recursive sequences")
|
||||||
self.memo[i] = None
|
self.memo[i] = None
|
||||||
dump = self.__dump
|
dump = self.__dump
|
||||||
write("<value><array><data>\n")
|
write("<value><array><data>\n")
|
||||||
|
@ -647,14 +647,14 @@ class Marshaller:
|
||||||
def dump_struct(self, value, write, escape=escape):
|
def dump_struct(self, value, write, escape=escape):
|
||||||
i = id(value)
|
i = id(value)
|
||||||
if i in self.memo:
|
if i in self.memo:
|
||||||
raise TypeError, "cannot marshal recursive dictionaries"
|
raise TypeError("cannot marshal recursive dictionaries")
|
||||||
self.memo[i] = None
|
self.memo[i] = None
|
||||||
dump = self.__dump
|
dump = self.__dump
|
||||||
write("<value><struct>\n")
|
write("<value><struct>\n")
|
||||||
for k, v in value.items():
|
for k, v in value.items():
|
||||||
write("<member>\n")
|
write("<member>\n")
|
||||||
if not isinstance(k, basestring):
|
if not isinstance(k, basestring):
|
||||||
raise TypeError, "dictionary key must be string"
|
raise TypeError("dictionary key must be string")
|
||||||
write("<name>%s</name>\n" % escape(k))
|
write("<name>%s</name>\n" % escape(k))
|
||||||
dump(v, write)
|
dump(v, write)
|
||||||
write("</member>\n")
|
write("</member>\n")
|
||||||
|
@ -724,7 +724,7 @@ class Unmarshaller:
|
||||||
self.append = self._stack.append
|
self.append = self._stack.append
|
||||||
self._use_datetime = use_datetime
|
self._use_datetime = use_datetime
|
||||||
if use_datetime and not datetime:
|
if use_datetime and not datetime:
|
||||||
raise ValueError, "the datetime module is not available"
|
raise ValueError("the datetime module is not available")
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
# return response tuple and target method
|
# return response tuple and target method
|
||||||
|
@ -791,7 +791,7 @@ class Unmarshaller:
|
||||||
elif data == "1":
|
elif data == "1":
|
||||||
self.append(True)
|
self.append(True)
|
||||||
else:
|
else:
|
||||||
raise TypeError, "bad boolean value"
|
raise TypeError("bad boolean value")
|
||||||
self._value = 0
|
self._value = 0
|
||||||
dispatch["boolean"] = end_boolean
|
dispatch["boolean"] = end_boolean
|
||||||
|
|
||||||
|
@ -897,8 +897,7 @@ class MultiCallIterator:
|
||||||
elif type(item) == type([]):
|
elif type(item) == type([]):
|
||||||
return item[0]
|
return item[0]
|
||||||
else:
|
else:
|
||||||
raise ValueError,\
|
raise ValueError("unexpected type in multicall result")
|
||||||
"unexpected type in multicall result"
|
|
||||||
|
|
||||||
class MultiCall:
|
class MultiCall:
|
||||||
"""server -> a object used to boxcar method calls
|
"""server -> a object used to boxcar method calls
|
||||||
|
@ -952,7 +951,7 @@ def getparser(use_datetime=0):
|
||||||
to an unmarshalling object. Return both objects.
|
to an unmarshalling object. Return both objects.
|
||||||
"""
|
"""
|
||||||
if use_datetime and not datetime:
|
if use_datetime and not datetime:
|
||||||
raise ValueError, "the datetime module is not available"
|
raise ValueError("the datetime module is not available")
|
||||||
if FastParser and FastUnmarshaller:
|
if FastParser and FastUnmarshaller:
|
||||||
if use_datetime:
|
if use_datetime:
|
||||||
mkdatetime = _datetime_type
|
mkdatetime = _datetime_type
|
||||||
|
@ -1321,7 +1320,7 @@ class ServerProxy:
|
||||||
import urllib
|
import urllib
|
||||||
type, uri = urllib.splittype(uri)
|
type, uri = urllib.splittype(uri)
|
||||||
if type not in ("http", "https"):
|
if type not in ("http", "https"):
|
||||||
raise IOError, "unsupported XML-RPC protocol"
|
raise IOError("unsupported XML-RPC protocol")
|
||||||
self.__host, self.__handler = urllib.splithost(uri)
|
self.__host, self.__handler = urllib.splithost(uri)
|
||||||
if not self.__handler:
|
if not self.__handler:
|
||||||
self.__handler = "/RPC2"
|
self.__handler = "/RPC2"
|
||||||
|
|
|
@ -277,7 +277,7 @@ class ZipInfo (object):
|
||||||
elif ln == 0:
|
elif ln == 0:
|
||||||
counts = ()
|
counts = ()
|
||||||
else:
|
else:
|
||||||
raise RuntimeError, "Corrupt extra field %s"%(ln,)
|
raise RuntimeError("Corrupt extra field %s"%(ln,))
|
||||||
|
|
||||||
idx = 0
|
idx = 0
|
||||||
|
|
||||||
|
@ -581,10 +581,10 @@ class ZipFile:
|
||||||
pass
|
pass
|
||||||
elif compression == ZIP_DEFLATED:
|
elif compression == ZIP_DEFLATED:
|
||||||
if not zlib:
|
if not zlib:
|
||||||
raise RuntimeError,\
|
raise RuntimeError(
|
||||||
"Compression requires the (missing) zlib module"
|
"Compression requires the (missing) zlib module")
|
||||||
else:
|
else:
|
||||||
raise RuntimeError, "That compression method is not supported"
|
raise RuntimeError("That compression method is not supported")
|
||||||
|
|
||||||
self._allowZip64 = allowZip64
|
self._allowZip64 = allowZip64
|
||||||
self._didModify = False
|
self._didModify = False
|
||||||
|
@ -629,7 +629,7 @@ class ZipFile:
|
||||||
if not self._filePassed:
|
if not self._filePassed:
|
||||||
self.fp.close()
|
self.fp.close()
|
||||||
self.fp = None
|
self.fp = None
|
||||||
raise RuntimeError, 'Mode must be "r", "w" or "a"'
|
raise RuntimeError('Mode must be "r", "w" or "a"')
|
||||||
|
|
||||||
def _GetContents(self):
|
def _GetContents(self):
|
||||||
"""Read the directory, making sure we close the file if the format
|
"""Read the directory, making sure we close the file if the format
|
||||||
|
@ -647,7 +647,7 @@ class ZipFile:
|
||||||
fp = self.fp
|
fp = self.fp
|
||||||
endrec = _EndRecData(fp)
|
endrec = _EndRecData(fp)
|
||||||
if not endrec:
|
if not endrec:
|
||||||
raise BadZipfile, "File is not a zip file"
|
raise BadZipfile("File is not a zip file")
|
||||||
if self.debug > 1:
|
if self.debug > 1:
|
||||||
print(endrec)
|
print(endrec)
|
||||||
size_cd = endrec[5] # bytes in central directory
|
size_cd = endrec[5] # bytes in central directory
|
||||||
|
@ -672,7 +672,7 @@ class ZipFile:
|
||||||
centdir = fp.read(46)
|
centdir = fp.read(46)
|
||||||
total = total + 46
|
total = total + 46
|
||||||
if centdir[0:4] != stringCentralDir:
|
if centdir[0:4] != stringCentralDir:
|
||||||
raise BadZipfile, "Bad magic number for central directory"
|
raise BadZipfile("Bad magic number for central directory")
|
||||||
centdir = struct.unpack(structCentralDir, centdir)
|
centdir = struct.unpack(structCentralDir, centdir)
|
||||||
if self.debug > 2:
|
if self.debug > 2:
|
||||||
print(centdir)
|
print(centdir)
|
||||||
|
@ -752,10 +752,10 @@ class ZipFile:
|
||||||
def open(self, name, mode="r", pwd=None):
|
def open(self, name, mode="r", pwd=None):
|
||||||
"""Return file-like object for 'name'."""
|
"""Return file-like object for 'name'."""
|
||||||
if mode not in ("r", "U", "rU"):
|
if mode not in ("r", "U", "rU"):
|
||||||
raise RuntimeError, 'open() requires mode "r", "U", or "rU"'
|
raise RuntimeError('open() requires mode "r", "U", or "rU"')
|
||||||
if not self.fp:
|
if not self.fp:
|
||||||
raise RuntimeError, \
|
raise RuntimeError(
|
||||||
"Attempt to read ZIP archive that was already closed"
|
"Attempt to read ZIP archive that was already closed")
|
||||||
|
|
||||||
# Only open a new file for instances where we were not
|
# Only open a new file for instances where we were not
|
||||||
# given a file object in the constructor
|
# given a file object in the constructor
|
||||||
|
@ -774,7 +774,7 @@ class ZipFile:
|
||||||
# Skip the file header:
|
# Skip the file header:
|
||||||
fheader = zef_file.read(30)
|
fheader = zef_file.read(30)
|
||||||
if fheader[0:4] != stringFileHeader:
|
if fheader[0:4] != stringFileHeader:
|
||||||
raise BadZipfile, "Bad magic number for file header"
|
raise BadZipfile("Bad magic number for file header")
|
||||||
|
|
||||||
fheader = struct.unpack(structFileHeader, fheader)
|
fheader = struct.unpack(structFileHeader, fheader)
|
||||||
fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
|
fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
|
||||||
|
@ -782,9 +782,9 @@ class ZipFile:
|
||||||
zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
|
zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
|
||||||
|
|
||||||
if fname != zinfo.orig_filename.encode("utf-8"):
|
if fname != zinfo.orig_filename.encode("utf-8"):
|
||||||
raise BadZipfile, \
|
raise BadZipfile(
|
||||||
'File name in directory %r and header %r differ.' % (
|
'File name in directory %r and header %r differ.'
|
||||||
zinfo.orig_filename, fname)
|
% (zinfo.orig_filename, fname))
|
||||||
|
|
||||||
# check for encrypted flag & handle password
|
# check for encrypted flag & handle password
|
||||||
is_encrypted = zinfo.flag_bits & 0x1
|
is_encrypted = zinfo.flag_bits & 0x1
|
||||||
|
@ -793,8 +793,8 @@ class ZipFile:
|
||||||
if not pwd:
|
if not pwd:
|
||||||
pwd = self.pwd
|
pwd = self.pwd
|
||||||
if not pwd:
|
if not pwd:
|
||||||
raise RuntimeError, "File %s is encrypted, " \
|
raise RuntimeError("File %s is encrypted, "
|
||||||
"password required for extraction" % name
|
"password required for extraction" % name)
|
||||||
|
|
||||||
zd = _ZipDecrypter(pwd)
|
zd = _ZipDecrypter(pwd)
|
||||||
# The first 12 bytes in the cypher stream is an encryption header
|
# The first 12 bytes in the cypher stream is an encryption header
|
||||||
|
@ -804,7 +804,7 @@ class ZipFile:
|
||||||
bytes = zef_file.read(12)
|
bytes = zef_file.read(12)
|
||||||
h = list(map(zd, bytes[0:12]))
|
h = list(map(zd, bytes[0:12]))
|
||||||
if h[11] != ((zinfo.CRC>>24) & 255):
|
if h[11] != ((zinfo.CRC>>24) & 255):
|
||||||
raise RuntimeError, "Bad password for file %s" % name
|
raise RuntimeError("Bad password for file %s" % name)
|
||||||
|
|
||||||
# build and return a ZipExtFile
|
# build and return a ZipExtFile
|
||||||
if zd is None:
|
if zd is None:
|
||||||
|
@ -823,22 +823,22 @@ class ZipFile:
|
||||||
if self.debug: # Warning for duplicate names
|
if self.debug: # Warning for duplicate names
|
||||||
print("Duplicate name:", zinfo.filename)
|
print("Duplicate name:", zinfo.filename)
|
||||||
if self.mode not in ("w", "a"):
|
if self.mode not in ("w", "a"):
|
||||||
raise RuntimeError, 'write() requires mode "w" or "a"'
|
raise RuntimeError('write() requires mode "w" or "a"')
|
||||||
if not self.fp:
|
if not self.fp:
|
||||||
raise RuntimeError, \
|
raise RuntimeError(
|
||||||
"Attempt to write ZIP archive that was already closed"
|
"Attempt to write ZIP archive that was already closed")
|
||||||
if zinfo.compress_type == ZIP_DEFLATED and not zlib:
|
if zinfo.compress_type == ZIP_DEFLATED and not zlib:
|
||||||
raise RuntimeError, \
|
raise RuntimeError(
|
||||||
"Compression requires the (missing) zlib module"
|
"Compression requires the (missing) zlib module")
|
||||||
if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED):
|
if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED):
|
||||||
raise RuntimeError, \
|
raise RuntimeError("That compression method is not supported")
|
||||||
"That compression method is not supported"
|
|
||||||
if zinfo.file_size > ZIP64_LIMIT:
|
if zinfo.file_size > ZIP64_LIMIT:
|
||||||
if not self._allowZip64:
|
if not self._allowZip64:
|
||||||
raise LargeZipFile("Filesize would require ZIP64 extensions")
|
raise LargeZipFile("Filesize would require ZIP64 extensions")
|
||||||
if zinfo.header_offset > ZIP64_LIMIT:
|
if zinfo.header_offset > ZIP64_LIMIT:
|
||||||
if not self._allowZip64:
|
if not self._allowZip64:
|
||||||
raise LargeZipFile("Zipfile size would require ZIP64 extensions")
|
raise LargeZipFile(
|
||||||
|
"Zipfile size would require ZIP64 extensions")
|
||||||
|
|
||||||
def write(self, filename, arcname=None, compress_type=None):
|
def write(self, filename, arcname=None, compress_type=None):
|
||||||
"""Put the bytes from filename into the archive under the name
|
"""Put the bytes from filename into the archive under the name
|
||||||
|
@ -1103,8 +1103,8 @@ class PyZipFile(ZipFile):
|
||||||
self.write(fname, arcname)
|
self.write(fname, arcname)
|
||||||
else:
|
else:
|
||||||
if pathname[-3:] != ".py":
|
if pathname[-3:] != ".py":
|
||||||
raise RuntimeError, \
|
raise RuntimeError(
|
||||||
'Files added with writepy() must end with ".py"'
|
'Files added with writepy() must end with ".py"')
|
||||||
fname, arcname = self._get_codename(pathname[0:-3], basename)
|
fname, arcname = self._get_codename(pathname[0:-3], basename)
|
||||||
if self.debug:
|
if self.debug:
|
||||||
print("Adding file", arcname)
|
print("Adding file", arcname)
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue