Change except clauses to use the cleaner as keyword

This commit is contained in:
Kovid Goyal 2011-03-22 22:40:01 -06:00
parent 5be578a9fd
commit 2c782a4938
63 changed files with 128 additions and 128 deletions

View File

@ -282,7 +282,7 @@ def main():
outfile = os.path.join(outfile, path[path.rfind("/")+1:])
try:
outfile = open(outfile, "wb")
except IOError, e:
except IOError as e:
print >> sys.stderr, e
parser.print_help()
return 1
@ -291,13 +291,13 @@ def main():
elif args[1].startswith("prs500:"):
try:
infile = open(args[0], "rb")
except IOError, e:
except IOError as e:
print >> sys.stderr, e
parser.print_help()
return 1
try:
dev.put_file(infile, args[1][7:])
except PathError, err:
except PathError as err:
if options.force and 'exists' in str(err):
dev.del_file(err.path, False)
dev.put_file(infile, args[1][7:])
@ -355,7 +355,7 @@ def main():
return 1
except DeviceLocked:
print >> sys.stderr, "The device is locked. Use the --unlock option"
except (ArgumentError, DeviceError), e:
except (ArgumentError, DeviceError) as e:
print >>sys.stderr, e
return 1
return 0

View File

@ -177,7 +177,7 @@ class PRS500(DeviceConfig, DevicePlugin):
dev.send_validated_command(BeginEndSession(end=True))
dev.in_session = False
raise
except USBError, err:
except USBError as err:
if "No such device" in str(err):
raise DeviceError()
elif "Connection timed out" in str(err):
@ -272,7 +272,7 @@ class PRS500(DeviceConfig, DevicePlugin):
self.bulk_read_max_packet_size = red.MaxPacketSize
self.bulk_write_max_packet_size = wed.MaxPacketSize
self.handle.claim_interface(self.INTERFACE_ID)
except USBError, err:
except USBError as err:
raise DeviceBusy(str(err))
# Large timeout as device may still be initializing
res = self.send_validated_command(GetUSBProtocolVersion(), timeout=20000)
@ -303,7 +303,7 @@ class PRS500(DeviceConfig, DevicePlugin):
try:
self.handle.reset()
self.handle.release_interface(self.INTERFACE_ID)
except Exception, err:
except Exception as err:
print >> sys.stderr, err
self.handle, self.device = None, None
self.in_session = False
@ -509,7 +509,7 @@ class PRS500(DeviceConfig, DevicePlugin):
outfile.write("".join(map(chr, packets[0][16:])))
for i in range(1, len(packets)):
outfile.write("".join(map(chr, packets[i])))
except IOError, err:
except IOError as err:
self.send_validated_command(FileClose(_id))
raise ArgumentError("File get operation failed. " + \
"Could not write to local location: " + str(err))
@ -656,7 +656,7 @@ class PRS500(DeviceConfig, DevicePlugin):
dest = None
try:
dest = self.path_properties(path, end_session=False)
except PathError, err:
except PathError as err:
if "does not exist" in str(err) or "not mounted" in str(err):
return (False, None)
else: raise

View File

@ -128,7 +128,7 @@ class Device(DeviceConfig, DevicePlugin):
try:
sectors_per_cluster, bytes_per_sector, free_clusters, total_clusters = \
win32file.GetDiskFreeSpace(prefix)
except Exception, err:
except Exception as err:
if getattr(err, 'args', [None])[0] == 21: # Disk not ready
time.sleep(3)
sectors_per_cluster, bytes_per_sector, free_clusters, total_clusters = \
@ -771,7 +771,7 @@ class Device(DeviceConfig, DevicePlugin):
for d in drives:
try:
eject(d)
except Exception, e:
except Exception as e:
print 'Udisks eject call for:', d, 'failed:'
print '\t', e
failures = True

View File

@ -57,7 +57,7 @@ class HTMLRenderer(object):
buf.open(QBuffer.WriteOnly)
image.save(buf, 'JPEG')
self.data = str(ba.data())
except Exception, e:
except Exception as e:
self.exception = e
self.traceback = traceback.format_exc()
finally:

View File

@ -151,7 +151,7 @@ class Container(object):
if name in self.mime_map:
try:
raw = self._parse(raw, self.mime_map[name])
except XMLSyntaxError, err:
except XMLSyntaxError as err:
raise ParseError(name, unicode(err))
self.cache[name] = raw
return raw

View File

@ -54,7 +54,7 @@ def main(args=sys.argv):
epub = os.path.abspath(args[1])
try:
run(epub, opts, default_log)
except ParseError, err:
except ParseError as err:
default_log.error(unicode(err))
raise SystemExit(1)

View File

@ -110,7 +110,7 @@ class HTMLFile(object):
try:
with open(self.path, 'rb') as f:
src = f.read()
except IOError, err:
except IOError as err:
msg = 'Could not read from file: %s with error: %s'%(self.path, as_unicode(err))
if level == 0:
raise IOError(msg)
@ -202,7 +202,7 @@ def traverse(path_to_html_file, max_levels=sys.maxint, verbose=0, encoding=None)
raise IgnoreFile('%s is a binary file'%nf.path, -1)
nl.append(nf)
flat.append(nf)
except IgnoreFile, err:
except IgnoreFile as err:
rejects.append(link)
if not err.doesnt_exist or verbose > 1:
print repr(err)

View File

@ -332,7 +332,7 @@ class HTMLConverter(object):
soup = BeautifulSoup(raw,
convertEntities=BeautifulSoup.XHTML_ENTITIES,
markupMassage=nmassage)
except ConversionError, err:
except ConversionError as err:
if 'Failed to coerce to unicode' in str(err):
raw = unicode(raw, 'utf8', 'replace')
soup = BeautifulSoup(raw,
@ -935,7 +935,7 @@ class HTMLConverter(object):
try:
im = PILImage.open(path)
except IOError, err:
except IOError as err:
self.log.warning('Unable to process image: %s\n%s'%( original_path, err))
return
encoding = detect_encoding(im)
@ -953,7 +953,7 @@ class HTMLConverter(object):
pt.close()
self.scaled_images[path] = pt
return pt.name
except (IOError, SystemError), err: # PIL chokes on interlaced PNG images as well a some GIF images
except (IOError, SystemError) as err: # PIL chokes on interlaced PNG images as well a some GIF images
self.log.warning(_('Unable to process image %s. Error: %s')%(path, err))
if width == None or height == None:
@ -1013,7 +1013,7 @@ class HTMLConverter(object):
if not self.images.has_key(path):
try:
self.images[path] = ImageStream(path, encoding=encoding)
except LrsError, err:
except LrsError as err:
self.log.warning(_('Could not process image: %s\n%s')%(
original_path, err))
return
@ -1768,7 +1768,7 @@ class HTMLConverter(object):
tag_css = self.tag_css(tag)[0] # Table should not inherit CSS
try:
self.process_table(tag, tag_css)
except Exception, err:
except Exception as err:
self.log.warning(_('An error occurred while processing a table: %s. Ignoring table markup.')%repr(err))
self.log.exception('')
self.log.debug(_('Bad table:\n%s')%unicode(tag)[:300])
@ -1858,7 +1858,7 @@ def process_file(path, options, logger):
tf.close()
tim.save(tf.name)
tpath = tf.name
except IOError, err: # PIL sometimes fails, for example on interlaced PNG files
except IOError as err: # PIL sometimes fails, for example on interlaced PNG files
logger.warn(_('Could not read cover image: %s'), err)
options.cover = None
else:

View File

@ -108,7 +108,7 @@ def _get_cover_url(br, asin):
q = 'http://amzn.com/'+asin
try:
raw = br.open_novisit(q).read()
except Exception, e:
except Exception as e:
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
return None
@ -139,7 +139,7 @@ def get_metadata(br, asin, mi):
q = 'http://amzn.com/'+asin
try:
raw = br.open_novisit(q).read()
except Exception, e:
except Exception as e:
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
return False

View File

@ -33,7 +33,7 @@ class AmazonFr(MetadataSource):
try:
self.results = search(self.title, self.book_author, self.publisher,
self.isbn, max_results=10, verbose=self.verbose, lang='fr')
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -50,7 +50,7 @@ class AmazonEs(MetadataSource):
try:
self.results = search(self.title, self.book_author, self.publisher,
self.isbn, max_results=10, verbose=self.verbose, lang='es')
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -67,7 +67,7 @@ class AmazonEn(MetadataSource):
try:
self.results = search(self.title, self.book_author, self.publisher,
self.isbn, max_results=10, verbose=self.verbose, lang='en')
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -84,7 +84,7 @@ class AmazonDe(MetadataSource):
try:
self.results = search(self.title, self.book_author, self.publisher,
self.isbn, max_results=10, verbose=self.verbose, lang='de')
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -103,7 +103,7 @@ class Amazon(MetadataSource):
try:
self.results = search(self.title, self.book_author, self.publisher,
self.isbn, max_results=10, verbose=self.verbose, lang='all')
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -193,7 +193,7 @@ class Query(object):
try:
raw = browser.open_novisit(self.urldata, timeout=timeout).read()
except Exception, e:
except Exception as e:
report(verbose)
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
@ -226,7 +226,7 @@ class Query(object):
try:
urldata = self.urldata + '&page=' + str(i)
raw = browser.open_novisit(urldata, timeout=timeout).read()
except Exception, e:
except Exception as e:
continue
if '<title>404 - ' in raw:
continue
@ -413,7 +413,7 @@ class ResultList(list):
def get_individual_metadata(self, browser, linkdata, verbose):
try:
raw = browser.open_novisit(linkdata).read()
except Exception, e:
except Exception as e:
report(verbose)
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
@ -445,7 +445,7 @@ class ResultList(list):
# self.clean_entry(entry, invalid_id=inv_ids)
title = self.get_title(entry)
authors = self.get_authors(entry)
except Exception, e:
except Exception as e:
if verbose:
print 'Failed to get all details for an entry'
print e

View File

@ -91,7 +91,7 @@ class OpenLibraryCovers(CoverDownload): # {{{
br.open_novisit(HeadRequest(self.OPENLIBRARY%mi.isbn), timeout=timeout)
self.debug('cover for', mi.isbn, 'found')
ans.set()
except Exception, e:
except Exception as e:
if callable(getattr(e, 'getcode', None)) and e.getcode() == 302:
self.debug('cover for', mi.isbn, 'found')
ans.set()
@ -106,7 +106,7 @@ class OpenLibraryCovers(CoverDownload): # {{{
try:
ans = br.open(self.OPENLIBRARY%mi.isbn, timeout=timeout).read()
result_queue.put((True, ans, 'jpg', self.name))
except Exception, e:
except Exception as e:
if callable(getattr(e, 'getcode', None)) and e.getcode() == 404:
result_queue.put((False, _('ISBN: %s not found')%mi.isbn, '', self.name))
else:
@ -131,7 +131,7 @@ class AmazonCovers(CoverDownload): # {{{
get_cover_url(mi.isbn, br)
self.debug('cover for', mi.isbn, 'found')
ans.set()
except Exception, e:
except Exception as e:
self.debug(e)
def get_covers(self, mi, result_queue, abort, timeout=5.):
@ -145,7 +145,7 @@ class AmazonCovers(CoverDownload): # {{{
raise ValueError('No cover found for ISBN: %s'%mi.isbn)
cover_data = br.open_novisit(url).read()
result_queue.put((True, cover_data, 'jpg', self.name))
except Exception, e:
except Exception as e:
result_queue.put((False, self.exception_to_string(e),
traceback.format_exc(), self.name))
@ -215,7 +215,7 @@ class DoubanCovers(CoverDownload): # {{{
try:
url = self.DOUBAN_ISBN_URL + isbn + "?apikey=" + self.CALIBRE_DOUBAN_API_KEY
src = br.open(url, timeout=timeout).read()
except Exception, err:
except Exception as err:
if isinstance(getattr(err, 'args', [None])[0], socket.timeout):
err = Exception(_('Douban.com API timed out. Try again later.'))
raise err
@ -248,7 +248,7 @@ class DoubanCovers(CoverDownload): # {{{
if self.get_cover_url(mi.isbn, br, timeout=timeout) != None:
self.debug('cover for', mi.isbn, 'found')
ans.set()
except Exception, e:
except Exception as e:
self.debug(e)
def get_covers(self, mi, result_queue, abort, timeout=5.):
@ -259,7 +259,7 @@ class DoubanCovers(CoverDownload): # {{{
url = self.get_cover_url(mi.isbn, br, timeout=timeout)
cover_data = br.open_novisit(url).read()
result_queue.put((True, cover_data, 'jpg', self.name))
except Exception, e:
except Exception as e:
result_queue.put((False, self.exception_to_string(e),
traceback.format_exc(), self.name))
# }}}

View File

@ -49,7 +49,7 @@ class DoubanBooks(MetadataSource):
self.results = search(self.title, self.book_author, self.publisher,
self.isbn, max_results=10,
verbose=self.verbose)
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -192,7 +192,7 @@ class ResultList(list):
raw = browser.open(id_url).read()
feed = etree.fromstring(raw)
x = entry(feed)[0]
except Exception, e:
except Exception as e:
if verbose:
print 'Failed to get all details for an entry'
print e
@ -212,7 +212,7 @@ def search(title=None, author=None, publisher=None, isbn=None,
api_key = CALIBRE_DOUBAN_API_KEY
while start > 0 and len(entries) <= max_results:
new, start = Query(title=title, author=author, publisher=publisher,
new, start = Query(title=title, author=author, publisher=publisher,
isbn=isbn, max_results=max_results, start_index=start, api_key=api_key)(br, verbose)
if not new:
break

View File

@ -93,7 +93,7 @@ class MetadataSource(Plugin): # {{{
traceback.print_exc()
mi.comments = None
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -186,7 +186,7 @@ class GoogleBooks(MetadataSource): # {{{
self.results = search(self.title, self.book_author, self.publisher,
self.isbn, max_results=10,
verbose=self.verbose)
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -217,7 +217,7 @@ class ISBNDB(MetadataSource): # {{{
try:
opts, args = option_parser().parse_args(args)
self.results = create_books(opts, args)
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -244,7 +244,7 @@ class Amazon(MetadataSource): # {{{
try:
self.results = get_social_metadata(self.title, self.book_author,
self.publisher, self.isbn)
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -264,7 +264,7 @@ class KentDistrictLibrary(MetadataSource): # {{{
from calibre.ebooks.metadata.kdl import get_series
try:
self.results = get_series(self.title, self.book_author)
except Exception, e:
except Exception as e:
import traceback
traceback.print_exc()
self.exception = e

View File

@ -30,7 +30,7 @@ class Fictionwise(MetadataSource): # {{{
try:
self.results = search(self.title, self.book_author, self.publisher,
self.isbn, max_results=10, verbose=self.verbose)
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -91,7 +91,7 @@ class Query(object):
try:
raw = browser.open_novisit(self.BASE_URL, self.urldata, timeout=timeout).read()
except Exception, e:
except Exception as e:
report(verbose)
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
@ -276,7 +276,7 @@ class ResultList(list):
def get_individual_metadata(self, browser, linkdata, verbose):
try:
raw = browser.open_novisit(self.BASE_URL + linkdata).read()
except Exception, e:
except Exception as e:
report(verbose)
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
@ -311,7 +311,7 @@ class ResultList(list):
#maybe strenghten the search
ratings = self.get_rating(entry.xpath("./p/table")[1], verbose)
authors = self.get_authors(entry)
except Exception, e:
except Exception as e:
if verbose:
print _('Failed to get all details for an entry')
print e
@ -328,7 +328,7 @@ class ResultList(list):
#maybe strenghten the search
ratings = self.get_rating(entry.xpath("./p/table")[1], verbose)
authors = self.get_authors(entry)
except Exception, e:
except Exception as e:
if verbose:
print _('Failed to get all details for an entry')
print e

View File

@ -176,7 +176,7 @@ class ResultList(list):
raw = browser.open(id_url).read()
feed = etree.fromstring(raw)
x = entry(feed)[0]
except Exception, e:
except Exception as e:
if verbose:
print 'Failed to get all details for an entry'
print e

View File

@ -38,7 +38,7 @@ def get_metadata(stream):
mi.author = author
if category:
mi.category = category
except Exception, err:
except Exception as err:
msg = u'Couldn\'t read metadata from imp: %s with error %s'%(mi.title, unicode(err))
print >>sys.stderr, msg.encode('utf8')
return mi

View File

@ -25,7 +25,7 @@ def fetch_metadata(url, max=3, timeout=5.):
while len(books) < total_results and max > 0:
try:
raw = br.open(url, timeout=timeout).read()
except Exception, err:
except Exception as err:
raise ISBNDBError('Could not fetch ISBNDB metadata. Error: '+str(err))
soup = BeautifulStoneSoup(raw,
convertEntities=BeautifulStoneSoup.XML_ENTITIES)

View File

@ -43,7 +43,7 @@ def get_series(title, authors, timeout=60):
br = browser()
try:
raw = br.open_novisit(url, timeout=timeout).read()
except URLError, e:
except URLError as e:
if isinstance(e.reason, socket.timeout):
raise Exception('KDL Server busy, try again later')
raise

View File

@ -45,7 +45,7 @@ def check_for_cover(isbn, timeout=5.):
try:
br.open_novisit(HeadRequest(OPENLIBRARY%isbn), timeout=timeout)
return True
except Exception, e:
except Exception as e:
if callable(getattr(e, 'getcode', None)) and e.getcode() == 302:
return True
return False

View File

@ -32,7 +32,7 @@ class NiceBooks(MetadataSource):
try:
self.results = search(self.title, self.book_author, self.publisher,
self.isbn, max_results=10, verbose=self.verbose)
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()
@ -54,7 +54,7 @@ class NiceBooksCovers(CoverDownload):
if Covers(mi.isbn)(entry).check_cover():
self.debug('cover for', mi.isbn, 'found')
ans.set()
except Exception, e:
except Exception as e:
self.debug(e)
def get_covers(self, mi, result_queue, abort, timeout=5.):
@ -67,7 +67,7 @@ class NiceBooksCovers(CoverDownload):
if not ext:
ext = 'jpg'
result_queue.put((True, cover_data, ext, self.name))
except Exception, e:
except Exception as e:
result_queue.put((False, self.exception_to_string(e),
traceback.format_exc(), self.name))
@ -109,7 +109,7 @@ class Query(object):
try:
raw = browser.open_novisit(self.BASE_URL+self.urldata, timeout=timeout).read()
except Exception, e:
except Exception as e:
report(verbose)
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
@ -144,7 +144,7 @@ class Query(object):
try:
urldata = self.urldata + '&p=' + str(i)
raw = browser.open_novisit(self.BASE_URL+urldata, timeout=timeout).read()
except Exception, e:
except Exception as e:
continue
if '<title>404 - ' in raw:
continue
@ -233,7 +233,7 @@ class ResultList(list):
def get_individual_metadata(self, browser, linkdata, verbose):
try:
raw = browser.open_novisit(self.BASE_URL + linkdata).read()
except Exception, e:
except Exception as e:
report(verbose)
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
@ -266,7 +266,7 @@ class ResultList(list):
entry = entry.find("div[@id='book-info']")
title = self.get_title(entry)
authors = self.get_authors(entry)
except Exception, e:
except Exception as e:
if verbose:
print 'Failed to get all details for an entry'
print e
@ -280,7 +280,7 @@ class ResultList(list):
entry = entry.find("div[@id='book-info']")
title = self.get_title(entry)
authors = self.get_authors(entry)
except Exception, e:
except Exception as e:
if verbose:
print 'Failed to get all details for an entry'
print e
@ -315,7 +315,7 @@ class Covers(object):
cover, ext = browser.open_novisit(self.urlimg, timeout=timeout).read(), \
self.urlimg.rpartition('.')[-1]
return cover, ext if ext else 'jpg'
except Exception, err:
except Exception as err:
if isinstance(getattr(err, 'args', [None])[0], socket.timeout):
raise NiceBooksError(_('Nicebooks timed out. Try again later.'))
if not len(self.urlimg):

View File

@ -43,7 +43,7 @@ def get_metadata(stream):
elif key.strip() == 'AUTHOR':
mi.author = value
mi.authors = string_to_authors(value)
except Exception, err:
except Exception as err:
msg = u'Couldn\'t read metadata from rb: %s with error %s'%(mi.title, unicode(err))
print >>sys.stderr, msg.encode('utf8')
raise

View File

@ -46,7 +46,7 @@ class Worker(Thread): # {{{
def get_details(self):
try:
raw = self.browser.open_novisit(self.url, timeout=self.timeout).read().strip()
except Exception, e:
except Exception as e:
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
self.log.error('URL malformed: %r'%self.url)
@ -359,7 +359,7 @@ class Amazon(Source):
br = self.browser
try:
raw = br.open_novisit(query, timeout=timeout).read().strip()
except Exception, e:
except Exception as e:
if callable(getattr(e, 'getcode', None)) and \
e.getcode() == 404:
log.error('Query malformed: %r'%query)

View File

@ -213,7 +213,7 @@ class GoogleBooks(Source):
br = self.browser
try:
raw = br.open_novisit(query, timeout=timeout).read()
except Exception, e:
except Exception as e:
log.exception('Failed to make identify query: %r'%query)
return as_unicode(e)
@ -222,7 +222,7 @@ class GoogleBooks(Source):
feed = etree.fromstring(xml_to_unicode(clean_ascii_chars(raw),
strip_encoding_pats=True)[0], parser=parser)
entries = entry(feed)
except Exception, e:
except Exception as e:
log.exception('Failed to parse identify results')
return as_unicode(e)

View File

@ -147,7 +147,7 @@ class TOC(list):
if path and os.access(path, os.R_OK):
try:
self.read_ncx_toc(path)
except Exception, err:
except Exception as err:
print 'WARNING: Invalid NCX file:', err
return
cwd = os.path.abspath(self.base_path)

View File

@ -884,13 +884,13 @@ class Manifest(object):
def first_pass(data):
try:
data = etree.fromstring(data, parser=parser)
except etree.XMLSyntaxError, err:
except etree.XMLSyntaxError as err:
self.oeb.log.exception('Initial parse failed:')
repl = lambda m: ENTITYDEFS.get(m.group(1), m.group(0))
data = ENTITY_RE.sub(repl, data)
try:
data = etree.fromstring(data, parser=parser)
except etree.XMLSyntaxError, err:
except etree.XMLSyntaxError as err:
self.oeb.logger.warn('Parsing file %r as HTML' % self.href)
if err.args and err.args[0].startswith('Excessive depth'):
from lxml.html import soupparser

View File

@ -103,7 +103,7 @@ def main(args=sys.argv, name=''):
try:
decrypt(args[0], opts.output, args[1])
except DecryptionError, e:
except DecryptionError as e:
print e.value
return 1

View File

@ -50,7 +50,7 @@ def pdftohtml(output_dir, pdf_path, no_images):
try:
p = popen(cmd, stderr=logf._fd, stdout=logf._fd,
stdin=subprocess.PIPE)
except OSError, err:
except OSError as err:
if err.errno == 2:
raise ConversionError(_('Could not find pdftohtml, check it is in your PATH'))
else:
@ -60,7 +60,7 @@ def pdftohtml(output_dir, pdf_path, no_images):
try:
ret = p.wait()
break
except OSError, e:
except OSError as e:
if e.errno == errno.EINTR:
continue
else:

View File

@ -268,7 +268,7 @@ class RTFInput(InputFormatPlugin):
self.log('Converting RTF to XML...')
try:
xml = self.generate_xml(stream.name)
except RtfInvalidCodeException, e:
except RtfInvalidCodeException as e:
raise ValueError(_('This RTF file has a feature calibre does not '
'support. Convert it to HTML first and then try it.\n%s')%e)

View File

@ -85,7 +85,7 @@ class SNBFile:
uncompressedData += bzdc.decompress(data)
else:
uncompressedData += data
except Exception, e:
except Exception as e:
print e
if len(uncompressedData) != self.plainStreamSizeUncompressed:
raise Exception()

View File

@ -32,7 +32,7 @@ class Worker(Thread):
def run(self):
try:
self.doit()
except Exception, err:
except Exception as err:
import traceback
try:
err = unicode(err)

View File

@ -78,7 +78,7 @@ class RecursiveFind(QThread): # {{{
if isinstance(root, unicode):
root = root.encode(filesystem_encoding)
self.walk(root)
except Exception, err:
except Exception as err:
import traceback
traceback.print_exc()
try:

View File

@ -192,7 +192,7 @@ class MetadataWidget(Widget, Ui_Form):
try:
cf = open(_file, "rb")
cover = cf.read()
except IOError, e:
except IOError as e:
d = error_dialog(self.parent(), _('Error reading file'),
_("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+str(e))
d.exec_()

View File

@ -69,7 +69,7 @@ class SearchAndReplaceWidget(Widget, Ui_Form):
try:
pat = unicode(x.regex)
re.compile(pat)
except Exception, err:
except Exception as err:
error_dialog(self, _('Invalid regular expression'),
_('Invalid regular expression: %s')%err, show=True)
return False

View File

@ -64,7 +64,7 @@ class DeviceJob(BaseJob): # {{{
self.result = self.func(*self.args, **self.kwargs)
if self._aborted:
return
except (Exception, SystemExit), err:
except (Exception, SystemExit) as err:
if self._aborted:
return
self.failed = True
@ -162,7 +162,7 @@ class DeviceManager(Thread): # {{{
dev.reset(detected_device=detected_device,
report_progress=self.report_progress)
dev.open(self.current_library_uuid)
except OpenFeedback, e:
except OpenFeedback as e:
if dev not in self.ejected_devices:
self.open_feedback_msg(dev.get_gui_name(), e.feedback_msg)
self.ejected_devices.add(dev)

View File

@ -133,7 +133,7 @@ class ConfigWidget(QWidget, Ui_ConfigWidget):
try:
validation_formatter.validate(tmpl)
return True
except Exception, err:
except Exception as err:
error_dialog(self, _('Invalid template'),
'<p>'+_('The template %s is invalid:')%tmpl + \
'<br>'+unicode(err), show=True)

View File

@ -68,7 +68,7 @@ class DBCheck(QDialog): # {{{
self.start_load()
return
QTimer.singleShot(0, self.do_one_dump)
except Exception, e:
except Exception as e:
import traceback
self.error = (as_unicode(e), traceback.format_exc())
self.reject()
@ -90,7 +90,7 @@ class DBCheck(QDialog): # {{{
self.conn.commit()
QTimer.singleShot(0, self.do_one_load)
except Exception, e:
except Exception as e:
import traceback
self.error = (as_unicode(e), traceback.format_exc())
self.reject()
@ -111,7 +111,7 @@ class DBCheck(QDialog): # {{{
self.pb.setValue(self.pb.value() + 1)
self.count -= 1
QTimer.singleShot(0, self.do_one_load)
except Exception, e:
except Exception as e:
import traceback
self.error = (as_unicode(e), traceback.format_exc())
self.reject()

View File

@ -120,7 +120,7 @@ class MyBlockingBusy(QDialog): # {{{
self.msg.setText(self.msg_text.format(self.phases[self.current_phase],
percent))
self.do_one(id)
except Exception, err:
except Exception as err:
import traceback
try:
err = unicode(err)

View File

@ -76,7 +76,7 @@ class CoverFetcher(Thread): # {{{
self.cover_data, self.errors = download_cover(mi,
timeout=self.timeout)
except Exception, e:
except Exception as e:
self.exception = e
self.traceback = traceback.format_exc()
print self.traceback
@ -183,7 +183,7 @@ class MetadataSingleDialog(ResizableDialog, Ui_MetadataSingleDialog):
try:
cf = open(_file, "rb")
cover = cf.read()
except IOError, e:
except IOError as e:
d = error_dialog(self, _('Error reading file'),
_("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+str(e))
d.exec_()

View File

@ -237,7 +237,7 @@ class %(classname)s(%(base_class)s):
try:
compile_recipe(src)
except Exception, err:
except Exception as err:
error_dialog(self, _('Invalid input'),
_('<p>Could not create recipe. Error:<br>%s')%str(err)).exec_()
return
@ -246,7 +246,7 @@ class %(classname)s(%(base_class)s):
src = unicode(self.source_code.toPlainText())
try:
title = compile_recipe(src).title
except Exception, err:
except Exception as err:
error_dialog(self, _('Invalid input'),
_('<p>Could not create recipe. Error:<br>%s')%str(err)).exec_()
return
@ -333,7 +333,7 @@ class %(classname)s(%(base_class)s):
try:
profile = open(file, 'rb').read().decode('utf-8')
title = compile_recipe(profile).title
except Exception, err:
except Exception as err:
error_dialog(self, _('Invalid input'),
_('<p>Could not create recipe. Error:<br>%s')%str(err)).exec_()
return

View File

@ -35,7 +35,7 @@ class Worker(Thread): # {{{
try:
br = browser()
br.retrieve(self.url, self.fpath, self.callback)
except Exception, e:
except Exception as e:
self.err = as_unicode(e)
import traceback
self.tb = traceback.format_exc()

View File

@ -116,7 +116,7 @@ class Emailer(Thread): # {{{
try:
self.sendmail(job)
break
except Exception, e:
except Exception as e:
if not self._run:
return
import traceback

View File

@ -398,7 +398,7 @@ class CcTemplateDelegate(QStyledItemDelegate): # {{{
val = unicode(editor.textbox.toPlainText())
try:
validation_formatter.validate(val)
except Exception, err:
except Exception as err:
error_dialog(self.parent(), _('Invalid template'),
'<p>'+_('The template %s is invalid:')%val + \
'<br>'+str(err), show=True)

View File

@ -35,7 +35,7 @@ class RenderWorker(QThread):
self.stream = None
if self.aborted:
self.lrf = None
except Exception, err:
except Exception as err:
self.lrf, self.stream = None, None
self.exception = err
self.formatted_traceback = traceback.format_exc()

View File

@ -399,7 +399,7 @@ def main(args=sys.argv):
if __name__ == '__main__':
try:
sys.exit(main())
except Exception, err:
except Exception as err:
if not iswindows: raise
tb = traceback.format_exc()
from PyQt4.QtGui import QErrorMessage

View File

@ -656,7 +656,7 @@ class Cover(ImageView): # {{{
try:
cf = open(_file, "rb")
cover = cf.read()
except IOError, e:
except IOError as e:
d = error_dialog(self, _('Error reading file'),
_("<p>There was an error reading from file: <br /><b>")
+ _file + "</b></p><br />"+str(e))

View File

@ -88,7 +88,7 @@ class DownloadMetadata(Thread):
def run(self):
try:
self._run()
except Exception, e:
except Exception as e:
self.exception = e
self.tb = traceback.format_exc()

View File

@ -303,7 +303,7 @@ class MetadataSingleDialogBase(ResizableDialog):
return False
self.books_to_refresh |= getattr(widget, 'books_to_refresh',
set([]))
except IOError, err:
except IOError as err:
if err.errno == 13: # Permission denied
import traceback
fname = err.filename if err.filename else 'file'

View File

@ -34,7 +34,7 @@ class DBUSNotifier(Notifier):
import dbus
self.dbus = dbus
self._notify = dbus.Interface(dbus.SessionBus().get_object(server, path), interface)
except Exception, err:
except Exception as err:
self.ok = False
self.err = str(err)

View File

@ -251,7 +251,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
if d != 0:
try:
validation_formatter.validate(s)
except Exception, err:
except Exception as err:
error_dialog(self, _('Invalid template'),
'<p>'+_('The template %s is invalid:')%s + \
'<br>'+str(err), show=True)

View File

@ -57,7 +57,7 @@ class SaveTemplate(QWidget, Ui_Form):
return question_dialog(self, _('Constant template'),
_('The template contains no {fields}, so all '
'books will have the same name. Is this OK?'))
except Exception, err:
except Exception as err:
error_dialog(self, _('Invalid template'),
'<p>'+_('The template %s is invalid:')%tmpl + \
'<br>'+str(err), show=True)

View File

@ -36,7 +36,7 @@ class Lookup(QThread):
def run(self):
try:
self.define()
except Exception, e:
except Exception as e:
import traceback
self.exception = e
self.traceback = traceback.format_exc()

View File

@ -97,7 +97,7 @@ class FilenamePattern(QWidget, Ui_Form):
def do_test(self):
try:
pat = self.pattern()
except Exception, err:
except Exception as err:
error_dialog(self, _('Invalid regular expression'),
_('Invalid regular expression: %s')%err).exec_()
return

View File

@ -565,7 +565,7 @@ def move_library(oldloc, newloc, parent, callback_on_complete):
# Try to load existing library at new location
try:
LibraryDatabase2(newloc)
except Exception, err:
except Exception as err:
det = traceback.format_exc()
error_dialog(parent, _('Invalid database'),
_('<p>An invalid library already exists at '
@ -577,7 +577,7 @@ def move_library(oldloc, newloc, parent, callback_on_complete):
else:
callback(newloc)
return
except Exception, err:
except Exception as err:
det = traceback.format_exc()
error_dialog(parent, _('Could not move library'),
unicode(err), det, show=True)

View File

@ -222,7 +222,7 @@ class LibraryServer(ContentServer, MobileServer, XMLServer, OPDSServer, Cache,
# cherrypy.engine.signal_handler.subscribe()
cherrypy.engine.block()
except Exception, e:
except Exception as e:
self.exception = e
finally:
self.is_running = False

View File

@ -169,7 +169,7 @@ class ContentServer(object):
return cover
return save_cover_data_to(img, 'img.jpg', return_data=True,
resize_to=(width, height))
except Exception, err:
except Exception as err:
import traceback
cherrypy.log.error('Failed to generate cover:')
cherrypy.log.error(traceback.print_exc())

View File

@ -69,7 +69,7 @@ def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
except OSError as e:
print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
@ -84,7 +84,7 @@ def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
except OSError as e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)

View File

@ -193,7 +193,7 @@ def load_c_extensions(conn, debug=DEBUG):
conn.load_extension(ext_path)
conn.enable_load_extension(False)
return True
except Exception, e:
except Exception as e:
if debug:
print 'Failed to load high performance sqlite C extension'
print e
@ -247,14 +247,14 @@ class DBThread(Thread):
if func == 'dump':
try:
ok, res = True, tuple(self.conn.iterdump())
except Exception, err:
except Exception as err:
ok, res = False, (err, traceback.format_exc())
elif func == 'create_dynamic_filter':
try:
f = DynamicFilter(args[0])
self.conn.create_function(args[0], 1, f)
ok, res = True, f
except Exception, err:
except Exception as err:
ok, res = False, (err, traceback.format_exc())
else:
bfunc = getattr(self.conn, func)
@ -263,7 +263,7 @@ class DBThread(Thread):
try:
ok, res = True, bfunc(*args, **kwargs)
break
except OperationalError, err:
except OperationalError as err:
# Retry if unable to open db file
e = str(err)
if 'unable to open' not in e or i == 2:
@ -273,10 +273,10 @@ class DBThread(Thread):
reprlib.repr(kwargs))
raise
time.sleep(0.5)
except Exception, err:
except Exception as err:
ok, res = False, (err, traceback.format_exc())
self.results.put((ok, res))
except Exception, err:
except Exception as err:
self.unhandled_error = (err, traceback.format_exc())
class DatabaseException(Exception):

View File

@ -59,7 +59,7 @@ for x in {manifest!r}:
shutil.rmtree(x)
else:
os.unlink(x)
except Exception, e:
except Exception as e:
print 'Failed to delete', x
print '\t', e
@ -285,7 +285,7 @@ class PostInstall:
complete -o nospace -C calibre-complete ebook-convert
'''))
except TypeError, err:
except TypeError as err:
if 'resolve_entities' in str(err):
print 'You need python-lxml >= 2.0.5 for calibre'
sys.exit(1)

View File

@ -863,7 +863,7 @@ class Engine(threading.Thread):
for socket in rr:
try:
self.readers[socket].handle_read()
except NonLocalNameException, err:
except NonLocalNameException as err:
print err
except UnicodeDecodeError:
if DEBUG:

View File

@ -316,7 +316,7 @@ class TemplateFormatter(string.Formatter):
self.locals = {}
try:
ans = self.vformat(fmt, [], kwargs).strip()
except Exception, e:
except Exception as e:
if DEBUG:
traceback.print_exc()
ans = error_value + ' ' + e.message

View File

@ -32,7 +32,7 @@ class WindowsExclFile(object):
None, #No template file
)
break
except pywintypes.error, err:
except pywintypes.error as err:
if getattr(err, 'args', [-1])[0] in (0x20, 0x21):
time.sleep(1)
continue

View File

@ -56,7 +56,7 @@ def set_metadata(stream, mi):
try:
p.wait()
break
except OSError, e:
except OSError as e:
if e.errno == errno.EINTR:
continue
else:

View File

@ -76,7 +76,7 @@ def sendmail_direct(from_, to, msg, timeout, localhost, verbose,
s.connect(host, 25)
s.sendmail(from_, [to], msg)
return s.quit()
except Exception, e:
except Exception as e:
last_error, last_traceback = e, traceback.format_exc()
if last_error is not None:
print last_traceback