diff --git a/pyproject.toml b/pyproject.toml index b3697bd7e0..679f1d6fd9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,7 +37,7 @@ quote-style = 'single' [tool.ruff.lint] explicit-preview-rules = true ignore = [ - 'E402', 'E722', 'E741', + 'E402', 'E741', 'UP012', 'UP030', 'UP038', 'C413', 'C420', 'PIE790', 'ISC003', 'RUF001', 'RUF002', 'RUF003', 'RUF005', 'RUF012', 'RUF013', 'RUF015', 'RUF031', 'RUF100', 'RUF059', # unused unpacked variable diff --git a/recipes/al_monitor.recipe b/recipes/al_monitor.recipe index d57e602275..94d62adb43 100644 --- a/recipes/al_monitor.recipe +++ b/recipes/al_monitor.recipe @@ -92,7 +92,7 @@ class AlMonitor(BasicNewsRecipe): try: self._p('process section ' + section + ', url: ' + url) soup = self.index_to_soup(url) - except: + except Exception: self._p('Unable to spider section') return [] @@ -175,7 +175,7 @@ class AlMonitor(BasicNewsRecipe): try: # eg: Posted September 17, 2014 dt = datetime.datetime.strptime(datestring, 'Posted %B %d, %Y') - except: + except Exception: dt = None if dt: diff --git a/recipes/am730.recipe b/recipes/am730.recipe index d5114f119e..4a45e1183b 100644 --- a/recipes/am730.recipe +++ b/recipes/am730.recipe @@ -69,7 +69,7 @@ class AM730(BasicNewsRecipe): if articles.index({'title':title,'url':href})>=0: # print('already added') continue # already added - except: + except Exception: pass articles.append({'title':title,'url':href}) diff --git a/recipes/birmingham_evening_mail.recipe b/recipes/birmingham_evening_mail.recipe index 8549dd2216..a6aec2102e 100644 --- a/recipes/birmingham_evening_mail.recipe +++ b/recipes/birmingham_evening_mail.recipe @@ -71,7 +71,7 @@ class AdvancedUserRecipe1306097511(BasicNewsRecipe): try: br.open_novisit(cov) cover_url = cov - except: + except Exception: cover_url = 'http://s.birminghammail.co.uk/skins/birminghammail/gfx/follow-media.jpg' return cover_url diff --git a/recipes/boston_globe_print_edition.recipe b/recipes/boston_globe_print_edition.recipe index 7a48a86b43..e82f55e21f 100644 --- a/recipes/boston_globe_print_edition.recipe +++ b/recipes/boston_globe_print_edition.recipe @@ -66,7 +66,7 @@ class BostonGlobePrint(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self, verify_ssl_certificates=False) try: br.open(cover) - except: + except Exception: index = 'https://en.kiosko.net/us/np/boston_globe.html' soup = self.index_to_soup(index) for image in soup.findAll('img', src=True): diff --git a/recipes/calgary_herald.recipe b/recipes/calgary_herald.recipe index eef67df749..99cb4f5bd1 100644 --- a/recipes/calgary_herald.recipe +++ b/recipes/calgary_herald.recipe @@ -151,14 +151,14 @@ class CanWestPaper(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break @@ -295,7 +295,7 @@ class CanWestPaper(BasicNewsRecipe): print('Section: ' + key + ': ' + self.url_prefix + keyurl) try: soup = self.index_to_soup(self.url_prefix + keyurl) - except: + except Exception: print('Section: ' + key + ' NOT FOUND') return ans.append(key) diff --git a/recipes/caravan_magazine.recipe b/recipes/caravan_magazine.recipe index 938fc7b393..f9ebae047d 100644 --- a/recipes/caravan_magazine.recipe +++ b/recipes/caravan_magazine.recipe @@ -118,7 +118,7 @@ class CaravanMagazine(BasicNewsRecipe): res = json.loads(res) self.log(safe_dict(res[0], 'result', 'data', 'json', 'message')) self.logged = True - except: + except Exception: self.log.warn('\n**Login failed, check your username and password\n') return br return br diff --git a/recipes/cnn.recipe b/recipes/cnn.recipe index b8a80131cc..7a19df2dd6 100644 --- a/recipes/cnn.recipe +++ b/recipes/cnn.recipe @@ -71,7 +71,7 @@ class CNN(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(masthead) - except: + except Exception: self.log('\nCover unavailable') masthead = None return masthead diff --git a/recipes/daily_mirror.recipe b/recipes/daily_mirror.recipe index 064aaa5d00..eaf80aebe4 100644 --- a/recipes/daily_mirror.recipe +++ b/recipes/daily_mirror.recipe @@ -92,7 +92,7 @@ class AdvancedUserRecipe1306061239(BasicNewsRecipe): try: br.open_novisit(cov2) cover_url = cov2 - except: + except Exception: cover_url = 'http://profile.ak.fbcdn.net/hprofile-ak-snc4/373019_6149699161_1710984811_n.jpg' return cover_url diff --git a/recipes/edmonton_journal.recipe b/recipes/edmonton_journal.recipe index f6a054a5e0..90490cea83 100644 --- a/recipes/edmonton_journal.recipe +++ b/recipes/edmonton_journal.recipe @@ -151,14 +151,14 @@ class CanWestPaper(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break @@ -295,7 +295,7 @@ class CanWestPaper(BasicNewsRecipe): print('Section: ' + key + ': ' + self.url_prefix + keyurl) try: soup = self.index_to_soup(self.url_prefix + keyurl) - except: + except Exception: print('Section: ' + key + ' NOT FOUND') return ans.append(key) diff --git a/recipes/el_pais.recipe b/recipes/el_pais.recipe index d1a929c506..4b32f85aa5 100644 --- a/recipes/el_pais.recipe +++ b/recipes/el_pais.recipe @@ -118,7 +118,7 @@ div.a_md_a {text-align: center; text-transform: uppercase; font-size: .8rem;} br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: self.log('\nCover unavailable') cover = None return cover diff --git a/recipes/elmundo.recipe b/recipes/elmundo.recipe index 21c7f832b0..64e43f9cd4 100644 --- a/recipes/elmundo.recipe +++ b/recipes/elmundo.recipe @@ -88,7 +88,7 @@ class ElMundo(BasicNewsRecipe): cover = 'http://img.kiosko.net/' + '/'.join([year, month, day]) + '/es/elmundo.750.jpg' try: self.browser.open(cover) - except: + except Exception: self.log('\nPortada no disponible') return cover @@ -101,7 +101,7 @@ class ElMundo(BasicNewsRecipe): response = self.browser.open(url) html = response.read() count = tries - except: + except Exception: print('Retrying download...') count += 1 if html is not None: diff --git a/recipes/esenja.recipe b/recipes/esenja.recipe index 5836913ab4..e7abab2725 100644 --- a/recipes/esenja.recipe +++ b/recipes/esenja.recipe @@ -114,7 +114,7 @@ class Esensja(BasicNewsRecipe): nr = r.findAll(attrs={'class': 'tn-link'})[-1] try: nr = int(nr.a.string) - except: + except Exception: return baseurl = soup.find(attrs={'property': 'og:url'})[ 'content'] + '&strona={0}' diff --git a/recipes/esensja_(rss).recipe b/recipes/esensja_(rss).recipe index 1e301e4822..c8336d2ac1 100644 --- a/recipes/esensja_(rss).recipe +++ b/recipes/esensja_(rss).recipe @@ -62,7 +62,7 @@ class EsensjaRSS(BasicNewsRecipe): nr = r.findAll(attrs={'class': 'tn-link'})[-1] try: nr = int(nr.a.string) - except: + except Exception: return baseurl = soup.find(attrs={'property': 'og:url'})[ 'content'] + '&strona={0}' diff --git a/recipes/expansion_spanish.recipe b/recipes/expansion_spanish.recipe index bc72f2637f..1ec8d7a614 100644 --- a/recipes/expansion_spanish.recipe +++ b/recipes/expansion_spanish.recipe @@ -112,7 +112,7 @@ class expansion_spanish(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: self.log('\nPortada no disponible') cover = 'http://www.aproahp.org/enlaces/images/diario_expansion.gif' return cover diff --git a/recipes/gazeta_pl_krakow.recipe b/recipes/gazeta_pl_krakow.recipe index cc3067dec3..289a05e17d 100644 --- a/recipes/gazeta_pl_krakow.recipe +++ b/recipes/gazeta_pl_krakow.recipe @@ -75,7 +75,7 @@ class gw_krakow(BasicNewsRecipe): try: baseurl = soup.find(name='meta', attrs={ 'property': 'og:url'})['content'] - except: + except Exception: return 1 link = tag.findAll('a')[-1] while link: diff --git a/recipes/gazeta_pl_warszawa.recipe b/recipes/gazeta_pl_warszawa.recipe index df3dcd3b40..a28f8c23da 100644 --- a/recipes/gazeta_pl_warszawa.recipe +++ b/recipes/gazeta_pl_warszawa.recipe @@ -74,7 +74,7 @@ class gw_wawa(BasicNewsRecipe): try: baseurl = soup.find(name='meta', attrs={ 'property': 'og:url'})['content'] - except: + except Exception: return 1 link = tag.findAll('a')[-1] while link: diff --git a/recipes/gry_online_pl.recipe b/recipes/gry_online_pl.recipe index d9a8771873..1f5e07024d 100644 --- a/recipes/gry_online_pl.recipe +++ b/recipes/gry_online_pl.recipe @@ -38,7 +38,7 @@ class GryOnlinePl(BasicNewsRecipe): try: soup2 = self.index_to_soup(finalurl) break - except: + except Exception: print('retrying in 0.5s') time.sleep(0.5) pagetext = soup2.find(attrs={'class': 'gc660'}) @@ -73,7 +73,7 @@ class GryOnlinePl(BasicNewsRecipe): try: soup2 = self.index_to_soup(finalurl) break - except: + except Exception: print('retrying in 0.5s') time.sleep(0.5) tag = soup2.find('div', attrs={'class': 'S018stronyr'}) diff --git a/recipes/il_messaggero.recipe b/recipes/il_messaggero.recipe index 26feeb0153..34de97fcd5 100644 --- a/recipes/il_messaggero.recipe +++ b/recipes/il_messaggero.recipe @@ -49,7 +49,7 @@ class IlMessaggero(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: self.log('\nCover unavailable') cover = 'http://www.ilmessaggero.it/img_tst/logomsgr.gif' diff --git a/recipes/inc.recipe b/recipes/inc.recipe index 501bff65e8..e1ec521426 100644 --- a/recipes/inc.recipe +++ b/recipes/inc.recipe @@ -41,7 +41,7 @@ class IncMagazineRecipe(BasicNewsRecipe): def has_login_name(form): try: form.find_control(name='email') - except: + except Exception: return False else: return True diff --git a/recipes/korben.recipe b/recipes/korben.recipe index aa1b0f3492..f26b17af97 100644 --- a/recipes/korben.recipe +++ b/recipes/korben.recipe @@ -16,7 +16,7 @@ class BasicUserRecipe1318619728(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(masthead) - except: + except Exception: self.log('\nCover unavailable') masthead = None return masthead diff --git a/recipes/la_republica.recipe b/recipes/la_republica.recipe index 9efeaeacbd..f616d7efa5 100644 --- a/recipes/la_republica.recipe +++ b/recipes/la_republica.recipe @@ -49,7 +49,7 @@ class LaRepubblica(BasicNewsRecipe): response = self.browser.open(url) html = response.read() count = 10 - except: + except Exception: print('Retrying download...') count += 1 self.temp_files.append(PersistentTemporaryFile('_fa.html')) diff --git a/recipes/latimes.recipe b/recipes/latimes.recipe index b3e2362071..3dcc727d6e 100644 --- a/recipes/latimes.recipe +++ b/recipes/latimes.recipe @@ -105,7 +105,7 @@ class LATimes(BasicNewsRecipe): self.log('Pattern: ', pattern) try: soup = self.index_to_soup(index) - except: + except Exception: self.log('Failed to download ', index) return [] if soup.main is not None: diff --git a/recipes/leggo_it.recipe b/recipes/leggo_it.recipe index 3a5393c192..1e80131e01 100644 --- a/recipes/leggo_it.recipe +++ b/recipes/leggo_it.recipe @@ -59,12 +59,12 @@ class LeggoIT(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: cover = 'http://www.leggo.it/' + year + month + day + '/jpeg/LEGGO_ROMA_3.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: self.log('\nCover unavailable') cover = 'http://www.leggo.it/img/logo-leggo2.gif' return cover diff --git a/recipes/lepoint.recipe b/recipes/lepoint.recipe index db8bfe6165..167b501e73 100644 --- a/recipes/lepoint.recipe +++ b/recipes/lepoint.recipe @@ -70,7 +70,7 @@ class lepoint(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(masthead) - except: + except Exception: self.log('\nCover unavailable') masthead = None return masthead diff --git a/recipes/lexpress.recipe b/recipes/lexpress.recipe index a8ba0a30b0..a015084f63 100644 --- a/recipes/lexpress.recipe +++ b/recipes/lexpress.recipe @@ -72,7 +72,7 @@ class lepoint(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(masthead) - except: + except Exception: self.log('\nCover unavailable') masthead = None return masthead diff --git a/recipes/montreal_gazette.recipe b/recipes/montreal_gazette.recipe index 5b9bc97f92..7dd5aef2fe 100644 --- a/recipes/montreal_gazette.recipe +++ b/recipes/montreal_gazette.recipe @@ -151,14 +151,14 @@ class CanWestPaper(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break @@ -295,7 +295,7 @@ class CanWestPaper(BasicNewsRecipe): print('Section: ' + key + ': ' + self.url_prefix + keyurl) try: soup = self.index_to_soup(self.url_prefix + keyurl) - except: + except Exception: print('Section: ' + key + ' NOT FOUND') return ans.append(key) diff --git a/recipes/nature.recipe b/recipes/nature.recipe index 1484c44903..6fdabf47f3 100644 --- a/recipes/nature.recipe +++ b/recipes/nature.recipe @@ -57,7 +57,7 @@ class Nature(BasicNewsRecipe): )['src'] try: self.cover_url = re.sub(r'\bw\d+\b', 'w1000', self.cover_url) # enlarge cover size resolution - except: + except Exception: ''' failed, img src might have changed, use default width 200 ''' diff --git a/recipes/newrepublicmag.recipe b/recipes/newrepublicmag.recipe index 621944570c..191db2fe62 100644 --- a/recipes/newrepublicmag.recipe +++ b/recipes/newrepublicmag.recipe @@ -236,7 +236,7 @@ fragment ArticlePageFields on Article { ) img['src'] = img_src del img['data-serialized'] - except: + except Exception: pass return f''' diff --git a/recipes/nikkei_news.recipe b/recipes/nikkei_news.recipe index 7c4f02cfb6..0c19296168 100644 --- a/recipes/nikkei_news.recipe +++ b/recipes/nikkei_news.recipe @@ -100,6 +100,6 @@ class NikkeiNet_paper_subscription(BasicNewsRecipe): [self.tag_to_string(elm).strip() for elm in elms]) elm_text = unicodedata.normalize('NFKC', elm_text) article.summary = article.text_summary = elm_text - except: + except Exception: self.log('Error: Failed to get article summary.') return diff --git a/recipes/observer_gb.recipe b/recipes/observer_gb.recipe index 7a844061de..b53a4fe1e9 100644 --- a/recipes/observer_gb.recipe +++ b/recipes/observer_gb.recipe @@ -144,7 +144,7 @@ class Guardian(BasicNewsRecipe): for title, href in self.find_sections(): feeds.append((title, list(self.find_articles(href)))) return feeds - except: + except Exception: raise NotImplementedError def postprocess_html(self, soup, first): diff --git a/recipes/ottawa_citizen.recipe b/recipes/ottawa_citizen.recipe index b3b35e4155..efe993007b 100644 --- a/recipes/ottawa_citizen.recipe +++ b/recipes/ottawa_citizen.recipe @@ -151,14 +151,14 @@ class CanWestPaper(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break @@ -295,7 +295,7 @@ class CanWestPaper(BasicNewsRecipe): print('Section: ' + key + ': ' + self.url_prefix + keyurl) try: soup = self.index_to_soup(self.url_prefix + keyurl) - except: + except Exception: print('Section: ' + key + ' NOT FOUND') return ans.append(key) diff --git a/recipes/pagina12.recipe b/recipes/pagina12.recipe index a91d2871fb..aae82dea6b 100644 --- a/recipes/pagina12.recipe +++ b/recipes/pagina12.recipe @@ -110,7 +110,7 @@ class Pagina12(BasicNewsRecipe): tfile.close() self.temp_files.append(tfile) result = tfile.name - except: + except Exception: self.info('Retrying download...') count += 1 return result diff --git a/recipes/people_daily.recipe b/recipes/people_daily.recipe index e03f10a52d..528370a048 100644 --- a/recipes/people_daily.recipe +++ b/recipes/people_daily.recipe @@ -133,7 +133,7 @@ class AdvancedUserRecipe1277129332(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: self.log('\nCover unavailable: ' + cover) cover = None return cover diff --git a/recipes/readitlater.recipe b/recipes/readitlater.recipe index 1c99c8b367..6b9f731ee3 100644 --- a/recipes/readitlater.recipe +++ b/recipes/readitlater.recipe @@ -161,7 +161,7 @@ class Pocket(BasicNewsRecipe): img_data = calibre_cover2(title, date, time) cover_file.write(img_data) cover_file.flush() - except: + except Exception: self.log.exception('Failed to generate default cover') return False return True diff --git a/recipes/regina_leader_post.recipe b/recipes/regina_leader_post.recipe index e176bf8b9e..badc8fe421 100644 --- a/recipes/regina_leader_post.recipe +++ b/recipes/regina_leader_post.recipe @@ -110,14 +110,14 @@ class CanWestPaper(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break diff --git a/recipes/respekt_magazine.recipe b/recipes/respekt_magazine.recipe index 28faad637a..9197bec5c2 100644 --- a/recipes/respekt_magazine.recipe +++ b/recipes/respekt_magazine.recipe @@ -145,7 +145,7 @@ class respektRecipe(BasicNewsRecipe): t = root.xpath("//span[@class='post-author-name']")[0] t.text = ('Autor: ' + t.text + ' ') root.xpath("//div[@class='authorship-names']")[0].append(E.span(article_length)) - except: + except Exception: pass # Make images visible pictures = root.xpath('//picture') @@ -169,6 +169,6 @@ class respektRecipe(BasicNewsRecipe): e = E.h2({'class':'post-subtitle'}) e.text = o.text o.getparent().replace(o,e) - except: + except Exception: pass return BeautifulSoup(lxml.etree.tostring(root,encoding='unicode')) diff --git a/recipes/saskatoon_star_phoenix.recipe b/recipes/saskatoon_star_phoenix.recipe index 1d580ca01c..7fa09eaf7b 100644 --- a/recipes/saskatoon_star_phoenix.recipe +++ b/recipes/saskatoon_star_phoenix.recipe @@ -110,14 +110,14 @@ class CanWestPaper(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break diff --git a/recipes/the_sun.recipe b/recipes/the_sun.recipe index 0382fb25e7..5724ef970e 100644 --- a/recipes/the_sun.recipe +++ b/recipes/the_sun.recipe @@ -61,7 +61,7 @@ class AdvancedUserRecipe1325006965(BasicNewsRecipe): try: br.open_novisit( 'http://www.thepaperboy.com/frontpages/current/The_Sun_newspaper_front_page.jpg') - except: + except Exception: cover_url = random.choice([ 'http://img.thesun.co.uk/multimedia/archive/00905/errorpage6_677961a_905507a.jpg', 'http://img.thesun.co.uk/multimedia/archive/00905/errorpage7_677962a_905505a.jpg', 'http://img.thesun.co.uk/multimedia/archive/00905/errorpage5_677960a_905512a.jpg', 'http://img.thesun.co.uk/multimedia/archive/00905/errorpage2_677957a_905502a.jpg', 'http://img.thesun.co.uk/multimedia/archive/00905/errorpage3_677958a_905503a.jpg' # noqa: E501 ]) diff --git a/recipes/theeconomictimes_india_print_edition.recipe b/recipes/theeconomictimes_india_print_edition.recipe index 34da739c6c..1a3b3f70d9 100644 --- a/recipes/theeconomictimes_india_print_edition.recipe +++ b/recipes/theeconomictimes_india_print_edition.recipe @@ -39,7 +39,7 @@ class TheEconomicTimes(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: self.log('\nCover unavailable') cover = None return cover diff --git a/recipes/thenewcriterion.recipe b/recipes/thenewcriterion.recipe index 732d1ecac7..08f6e8e111 100644 --- a/recipes/thenewcriterion.recipe +++ b/recipes/thenewcriterion.recipe @@ -111,7 +111,7 @@ class TheNewCriterion(BasicNewsRecipe): tfile.close() self.temp_files.append(tfile) result = tfile.name - except: + except Exception: print('Retrying download...') count += 1 return result diff --git a/recipes/vancouver_province.recipe b/recipes/vancouver_province.recipe index 0644c70dda..deb46aa06f 100644 --- a/recipes/vancouver_province.recipe +++ b/recipes/vancouver_province.recipe @@ -151,14 +151,14 @@ class CanWestPaper(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break @@ -308,7 +308,7 @@ class CanWestPaper(BasicNewsRecipe): print('Section: ' + key + ': ' + self.url_prefix + keyurl) try: soup = self.index_to_soup(self.url_prefix + keyurl) - except: + except Exception: print('Section: ' + key + ' NOT FOUND') return ans.append(key) diff --git a/recipes/vancouver_sun.recipe b/recipes/vancouver_sun.recipe index 603ada2e93..9b78380d83 100644 --- a/recipes/vancouver_sun.recipe +++ b/recipes/vancouver_sun.recipe @@ -152,14 +152,14 @@ class CanWestPaper(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break @@ -296,7 +296,7 @@ class CanWestPaper(BasicNewsRecipe): print('Section: ' + key + ': ' + self.url_prefix + keyurl) try: soup = self.index_to_soup(self.url_prefix + keyurl) - except: + except Exception: print('Section: ' + key + ' NOT FOUND') return ans.append(key) diff --git a/recipes/vic_times.recipe b/recipes/vic_times.recipe index 113086da9c..c5d2e76ca8 100644 --- a/recipes/vic_times.recipe +++ b/recipes/vic_times.recipe @@ -114,14 +114,14 @@ class TimesColonist(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break @@ -235,7 +235,7 @@ class TimesColonist(BasicNewsRecipe): print('Add section url=' + self.url_prefix + '/' + securl + '\n\r') try: soup = self.index_to_soup(self.url_prefix + '/' + securl) - except: + except Exception: return ans mainsoup = soup.find( 'div', attrs={'class': re.compile(r'main.content')}) diff --git a/recipes/windsor_star.recipe b/recipes/windsor_star.recipe index 24c041f9c3..d33d75b58f 100644 --- a/recipes/windsor_star.recipe +++ b/recipes/windsor_star.recipe @@ -110,14 +110,14 @@ class CanWestPaper(BasicNewsRecipe): daysback = 1 try: br.open(cover) - except: + except Exception: while daysback < 7: cover = 'http://webmedia.newseum.org/newseum-multimedia/dfp/jpg' + \ str((date.today() - timedelta(days=daysback)).day) + '/lg/' + self.fp_tag + '.jpg' br = BasicNewsRecipe.get_browser(self) try: br.open(cover) - except: + except Exception: daysback = daysback + 1 continue break diff --git a/recipes/zdnet.fr.recipe b/recipes/zdnet.fr.recipe index 00c83323e4..bd9b027121 100644 --- a/recipes/zdnet.fr.recipe +++ b/recipes/zdnet.fr.recipe @@ -61,7 +61,7 @@ class zdnet(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) try: br.open(masthead) - except: + except Exception: self.log('\nCover unavailable') masthead = None return masthead diff --git a/recipes/zeitde_sub.recipe b/recipes/zeitde_sub.recipe index bb36ab6640..e7f46b8d9d 100644 --- a/recipes/zeitde_sub.recipe +++ b/recipes/zeitde_sub.recipe @@ -285,13 +285,13 @@ class ZeitEPUBAbo(BasicNewsRecipe): save_cover_data_to(cdata, cpath) cover_url = cpath - except: + except Exception: self.log.warning('Trying low-res cover') try: inhalt = self.index_to_soup('http://www.zeit.de/inhalt') cover_url = inhalt.find('div', attrs={'class': 'singlearchive clearfix'}).img[ 'src'].replace('icon_', '') - except: + except Exception: self.log.warning('Using static old low-res cover') cover_url = 'http://images.zeit.de/bilder/titelseiten_zeit/1946/001_001.jpg' return cover_url diff --git a/setup/build.py b/setup/build.py index 3e9f3975cc..2af07d649b 100644 --- a/setup/build.py +++ b/setup/build.py @@ -615,7 +615,7 @@ class Build(Command): ''' try: subprocess.check_call(*args, **kwargs) - except: + except Exception: cmdline = ' '.join([f'"{arg}"' if ' ' in arg else arg for arg in args[0]]) print(f'Error while executing: {cmdline}\n') raise diff --git a/setup/build_environment.py b/setup/build_environment.py index 78640e8771..754ab4ce03 100644 --- a/setup/build_environment.py +++ b/setup/build_environment.py @@ -85,7 +85,7 @@ def run_pkgconfig(name, envvar, default, flag, prefix): stdout=subprocess.PIPE).stdout.read().decode('utf-8') ans = [x.strip() for x in raw.split(prefix)] ans = [x for x in ans if x and (prefix=='-l' or os.path.exists(x))] - except: + except Exception: print('Failed to run pkg-config:', PKGCONFIG, 'for:', name) return ans or ([default] if default else []) diff --git a/setup/git_pre_commit_hook.py b/setup/git_pre_commit_hook.py index a5b6a79038..04169204f4 100755 --- a/setup/git_pre_commit_hook.py +++ b/setup/git_pre_commit_hook.py @@ -47,7 +47,7 @@ class Bug: raw = urllib.request.urlopen(LAUNCHPAD_BUG.format(bug)).read() h1 = html.fromstring(raw).xpath('//h1[@id="edit-title"]')[0] summary = html.tostring(h1, method='text', encoding=str).strip() - except: + except Exception: summary = 'Private bug' else: summary = json.loads(urllib.request.urlopen(GITHUB_BUG.format(bug)).read())['title'] diff --git a/setup/hosting.py b/setup/hosting.py index 7ce85ced49..0a8d1b601a 100644 --- a/setup/hosting.py +++ b/setup/hosting.py @@ -118,7 +118,7 @@ class SourceForge(Base): # {{{ ]) except KeyboardInterrupt: raise SystemExit(1) - except: + except Exception: print('\nUpload failed, trying again in 30 seconds') time.sleep(30) else: @@ -421,7 +421,7 @@ def upload_to_servers(files, version): # {{{ # f'root@{server}:{rdir}']) # except KeyboardInterrupt: # raise SystemExit(1) - # except: + # except Exception: # print('\nUpload failed, trying again in 30 seconds') # time.sleep(30) # else: diff --git a/setup/resources.py b/setup/resources.py index 15edea7e88..bb1c42990a 100644 --- a/setup/resources.py +++ b/setup/resources.py @@ -187,7 +187,7 @@ class Resources(Command): # {{{ lambda x: inspect.ismethod(x) and x.__name__ == 'evaluate') try: lines = [l[4:] for l in inspect.getsourcelines(eval_func[0][1])[0]] - except: + except Exception: continue lines = ''.join(lines) function_dict[obj.name] = lines diff --git a/setup/upload.py b/setup/upload.py index ca45522b75..2b230e7213 100644 --- a/setup/upload.py +++ b/setup/upload.py @@ -281,7 +281,7 @@ class UploadInstallers(Command): # {{{ while True: try: send_data(tdir) - except: + except Exception: print('\nUpload to staging failed, retrying in a minute') time.sleep(60) else: @@ -290,7 +290,7 @@ class UploadInstallers(Command): # {{{ while True: try: send_to_backup(tdir) - except: + except Exception: print('\nUpload to backup failed, retrying in a minute') time.sleep(60) else: diff --git a/src/calibre/__init__.py b/src/calibre/__init__.py index 8a9c97974b..86ac8c957f 100644 --- a/src/calibre/__init__.py +++ b/src/calibre/__init__.py @@ -273,7 +273,7 @@ def get_parsed_proxy(typ='http', debug=True): } if ans['port']: ans['port'] = int(ans['port']) - except: + except Exception: if debug: import traceback traceback.print_exc() diff --git a/src/calibre/constants.py b/src/calibre/constants.py index a2dfc853cf..349df5b0bf 100644 --- a/src/calibre/constants.py +++ b/src/calibre/constants.py @@ -54,7 +54,7 @@ TOC_DIALOG_APP_UID = 'com.calibre-ebook.toc-editor' try: preferred_encoding = locale.getpreferredencoding() codecs.lookup(preferred_encoding) -except: +except Exception: preferred_encoding = 'utf-8' dark_link_color = '#6cb4ee' @@ -391,7 +391,7 @@ else: config_dir = os.path.join(bdir, 'calibre') try: os.makedirs(config_dir, mode=CONFIG_DIR_MODE) - except: + except Exception: pass if not os.path.exists(config_dir) or \ not os.access(config_dir, os.W_OK) or not \ @@ -405,7 +405,7 @@ else: try: import shutil shutil.rmtree(config_dir) - except: + except Exception: pass atexit.register(cleanup_cdir) # }}} diff --git a/src/calibre/customize/__init__.py b/src/calibre/customize/__init__.py index 7f63ea7a3c..7f8f4c53d9 100644 --- a/src/calibre/customize/__init__.py +++ b/src/calibre/customize/__init__.py @@ -623,7 +623,7 @@ class CatalogPlugin(Plugin): # {{{ for file in files_to_copy: try: resources.extract(file, self.resources_path) - except: + except Exception: print(f' customize:__init__.initialize(): {file} not found in {os.path.basename(self.plugin_path)}') continue resources.close() diff --git a/src/calibre/customize/builtins.py b/src/calibre/customize/builtins.py index 4e2ef8cdaa..5b2e66757a 100644 --- a/src/calibre/customize/builtins.py +++ b/src/calibre/customize/builtins.py @@ -144,7 +144,7 @@ class ComicMetadataReader(MetadataReaderPlugin): series_index = 'volume' try: mi.smart_update(get_comic_metadata(stream, ftype, series_index=series_index)) - except: + except Exception: pass if ret is not None: path, data = ret diff --git a/src/calibre/customize/conversion.py b/src/calibre/customize/conversion.py index 25e6990079..64158db28b 100644 --- a/src/calibre/customize/conversion.py +++ b/src/calibre/customize/conversion.py @@ -231,7 +231,7 @@ class InputFormatPlugin(Plugin): log(f'InputFormatPlugin: {self.name} running') if hasattr(stream, 'name'): log('on', stream.name) - except: + except Exception: # In case stdout is broken pass diff --git a/src/calibre/customize/ui.py b/src/calibre/customize/ui.py index 6313da5e50..4e76e8e0e9 100644 --- a/src/calibre/customize/ui.py +++ b/src/calibre/customize/ui.py @@ -212,7 +212,7 @@ def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'): pass try: nfp = plugin.run(nfp) or nfp - except: + except Exception: print(f'Running file type plugin {plugin.name} failed with traceback:', file=oe) traceback.print_exc(file=oe) sys.stdout, sys.stderr = oo, oe @@ -495,7 +495,7 @@ def get_file_type_metadata(stream, ftype): stream.seek(0) mi = plugin.get_metadata(stream, ftype.lower().strip()) break - except: + except Exception: traceback.print_exc() continue return mi @@ -514,7 +514,7 @@ def set_file_type_metadata(stream, mi, ftype, report_error=None): plugin.site_customization = customization.get(plugin.name, '') plugin.set_metadata(stream, mi, ftype.lower().strip()) break - except: + except Exception: if report_error is None: from calibre import prints prints('Failed to set metadata for the', ftype.upper(), 'format of:', getattr(mi, 'title', ''), file=sys.stderr) @@ -569,7 +569,7 @@ def remove_plugin(plugin_or_name): zfp = plugins[name] if os.path.exists(zfp): os.remove(zfp) - except: + except Exception: pass plugins.pop(name) config['plugins'] = plugins @@ -829,7 +829,7 @@ def initialize_plugins(perf=False): if perf: times[plugin.name] = time.time() - st _initialized_plugins.append(plugin) - except: + except Exception: print('Failed to initialize plugin:', repr(zfp), file=sys.stderr) if DEBUG: traceback.print_exc() diff --git a/src/calibre/customize/zipplugin.py b/src/calibre/customize/zipplugin.py index fcf52013b5..3e7bc5fa4d 100644 --- a/src/calibre/customize/zipplugin.py +++ b/src/calibre/customize/zipplugin.py @@ -44,7 +44,7 @@ def get_resources(zfp, name_or_list_of_names, print_tracebacks_for_missing_resou for name in names: try: ans[name] = zf.read(name) - except: + except Exception: if print_tracebacks_for_missing_resources: print('Failed to load resource:', repr(name), 'from the plugin zip file:', zfp, file=sys.stderr) import traceback @@ -331,7 +331,7 @@ class CalibrePluginFinder: f'The plugin at {as_unicode(path_to_zip_file)} cannot be used on {platform}') return ans - except: + except Exception: with self._lock: del self.loaded_plugins[plugin_name] raise diff --git a/src/calibre/db/__init__.py b/src/calibre/db/__init__.py index 5360706d80..10ca306f08 100644 --- a/src/calibre/db/__init__.py +++ b/src/calibre/db/__init__.py @@ -63,7 +63,7 @@ def _get_series_values(val): try: idx = float(idx) return match.group(1).strip(), idx - except: + except Exception: pass return val, None diff --git a/src/calibre/db/backend.py b/src/calibre/db/backend.py index d6c7298e26..6e3ac19f7e 100644 --- a/src/calibre/db/backend.py +++ b/src/calibre/db/backend.py @@ -113,7 +113,7 @@ class DBPrefs(dict): # {{{ for key, val in self.db.conn.get('SELECT key,val FROM preferences'): try: val = self.raw_to_object(val) - except: + except Exception: prints('Failed to read value for:', key, 'from db') continue dict.__setitem__(self, key, val) @@ -185,7 +185,7 @@ class DBPrefs(dict): # {{{ data = data.encode('utf-8') with open(to_filename, 'wb') as f: f.write(data) - except: + except Exception: import traceback traceback.print_exc() @@ -204,12 +204,12 @@ def pynocase(one, two, encoding='utf-8'): if isbytestring(one): try: one = one.decode(encoding, 'replace') - except: + except Exception: pass if isbytestring(two): try: two = two.decode(encoding, 'replace') - except: + except Exception: pass return cmp(one.lower(), two.lower()) @@ -648,7 +648,7 @@ class DB: rules = migrate_old_rule(self.field_metadata, templ) for templ in rules: old_rules.append((col, templ)) - except: + except Exception: pass if old_rules: self.prefs['column_color_rules'] += old_rules @@ -673,7 +673,7 @@ class DB: for t in ogst: ngst[icu_lower(t)] = ogst[t] self.prefs.set('grouped_search_terms', ngst) - except: + except Exception: pass # migrate the gui_restriction preference to a virtual library @@ -1467,7 +1467,7 @@ class DB: cur.execute('BEGIN EXCLUSIVE TRANSACTION') try: cur.execute(metadata_sqlite) - except: + except Exception: cur.execute('ROLLBACK') raise else: @@ -1597,7 +1597,7 @@ class DB: for table in itervalues(self.tables): try: table.read(self) - except: + except Exception: prints('Failed to read table:', table.name) import pprint pprint.pprint(table.metadata) @@ -1756,7 +1756,7 @@ class DB: try: hardlink_file(path, dest) return True - except: + except Exception: pass with open(dest, 'wb') as d: shutil.copyfileobj(f, d) @@ -1848,7 +1848,7 @@ class DB: try: if path != dest: os.rename(path, dest) - except: + except Exception: pass # Nothing too catastrophic happened, the cases mismatch, that's all else: windows_atomic_move.copy_path_to(path, dest) @@ -1875,7 +1875,7 @@ class DB: try: hardlink_file(path, dest) return True - except: + except Exception: pass with open(path, 'rb') as f, open(make_long_path_useable(dest), 'wb') as d: shutil.copyfileobj(f, d) @@ -2386,7 +2386,7 @@ class DB: def safe_load(val): try: return json.loads(val, object_hook=from_json) - except: + except Exception: return default if len(book_ids) == 1: diff --git a/src/calibre/db/backup.py b/src/calibre/db/backup.py index 23c8429c96..907864fa2f 100644 --- a/src/calibre/db/backup.py +++ b/src/calibre/db/backup.py @@ -77,7 +77,7 @@ class MetadataBackup(Thread): return except Abort: raise - except: + except Exception: # Happens during interpreter shutdown return @@ -85,13 +85,13 @@ class MetadataBackup(Thread): try: mi, sequence = self.db.get_metadata_for_dump(book_id) - except: + except Exception: prints('Failed to get backup metadata for id:', book_id, 'once') traceback.print_exc() self.wait(self.interval) try: mi, sequence = self.db.get_metadata_for_dump(book_id) - except: + except Exception: prints('Failed to get backup metadata for id:', book_id, 'again, giving up') traceback.print_exc() return @@ -107,7 +107,7 @@ class MetadataBackup(Thread): try: raw = metadata_to_opf(mi) - except: + except Exception: prints('Failed to convert to opf for id:', book_id) traceback.print_exc() self.db.clear_dirtied(book_id, sequence) @@ -117,13 +117,13 @@ class MetadataBackup(Thread): try: self.db.write_backup(book_id, raw) - except: + except Exception: prints('Failed to write backup metadata for id:', book_id, 'once') traceback.print_exc() self.wait(self.interval) try: self.db.write_backup(book_id, raw) - except: + except Exception: prints('Failed to write backup metadata for id:', book_id, 'again, giving up') traceback.print_exc() return diff --git a/src/calibre/db/cache.py b/src/calibre/db/cache.py index 3c599c6f9d..56d7bf13f3 100644 --- a/src/calibre/db/cache.py +++ b/src/calibre/db/cache.py @@ -127,7 +127,7 @@ def _add_default_custom_column_values(mi, fm): if dt == 'datetime' and icu_lower(dv) == 'now': dv = nowf() mi.set(cc, dv) - except: + except Exception: traceback.print_exc() @@ -1003,7 +1003,7 @@ class Cache: try: name = self.fields['formats'].format_fname(book_id, fmt) path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: raise NoSuchFormat(f'Record {book_id} has no fmt: {fmt}') return self.backend.format_hash(book_id, fmt, name, path) @@ -1033,7 +1033,7 @@ class Cache: try: name = self.fields['formats'].format_fname(book_id, fmt) path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: return {} ans = {} @@ -1256,7 +1256,7 @@ class Cache: fmt = (fmt or '').upper() try: path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: return None if path: if fmt == '__COVER_INTERNAL__': @@ -1264,7 +1264,7 @@ class Cache: else: try: name = self.fields['formats'].format_fname(book_id, fmt) - except: + except Exception: return None if name: return self.backend.format_abspath(book_id, fmt, name, path) @@ -1276,7 +1276,7 @@ class Cache: try: name = self.fields['formats'].format_fname(book_id, fmt) path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: return False return self.backend.has_format(book_id, fmt, name, path) @@ -1324,13 +1324,13 @@ class Cache: if verify_formats and ans: try: path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: return () def verify(fmt): try: name = self.fields['formats'].format_fname(book_id, fmt) - except: + except Exception: return False return self.backend.has_format(book_id, fmt, name, path) @@ -1361,7 +1361,7 @@ class Cache: with self.safe_read_lock: try: fname = self.fields['formats'].format_fname(book_id, fmt) - except: + except Exception: return None fname += ext @@ -1369,7 +1369,7 @@ class Cache: d = os.path.join(bd, 'format_abspath') try: os.makedirs(d) - except: + except Exception: pass ret = os.path.join(d, fname) try: @@ -1387,7 +1387,7 @@ class Cache: with self.safe_read_lock: try: fname = self.fields['formats'].format_fname(book_id, fmt) - except: + except Exception: return None fname += ext @@ -1703,7 +1703,7 @@ class Cache: # try to write the opf, because it will go to the wrong folder. if self._field_for('path', book_id): mi = self._metadata_as_object_for_dump(book_id) - except: + except Exception: # This almost certainly means that the book has been deleted while # the backup operation sat in the queue. traceback.print_exc() @@ -1723,7 +1723,7 @@ class Cache: def write_backup(self, book_id, raw): try: path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: return self.backend.write_backup(path, raw) @@ -1738,7 +1738,7 @@ class Cache: if no such backup exists. ''' try: path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: return try: @@ -1774,7 +1774,7 @@ class Cache: self._write_backup(book_id, raw) if remove_from_dirtied: self._clear_dirtied(book_id, sequence) - except: + except Exception: pass if callback is not None: callback(book_id, mi, True) @@ -1856,7 +1856,7 @@ class Cache: def protected_set_field(name, val): try: set_field(name, val) - except: + except Exception: if ignore_errors: traceback.print_exc() else: @@ -1870,7 +1870,7 @@ class Cache: cdata = f.read() or None if cdata is not None: self._set_cover({book_id: cdata}) - except: + except Exception: if ignore_errors: traceback.print_exc() else: @@ -1925,7 +1925,7 @@ class Cache: extra = mi.get_extra(key) if extra is not None or force_changes: protected_set_field(idx, extra) - except: + except Exception: # sqlite will rollback the entire transaction, thanks to the with # statement, so we have to re-read everything form the db to ensure # the db and Cache are in sync @@ -2035,12 +2035,12 @@ class Cache: for book_id, fmts in iteritems(formats_map): try: path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: continue for fmt in fmts: try: name = self.fields['formats'].format_fname(book_id, fmt) - except: + except Exception: continue if name and path: removes[book_id].add((fmt, name, path)) @@ -2725,7 +2725,7 @@ class Cache: return identical_book_ids try: book_ids = self._search(query, restriction=search_restriction, book_ids=book_ids) - except: + except Exception: traceback.print_exc() return identical_book_ids if qauthors and book_ids: @@ -3061,14 +3061,14 @@ class Cache: mi.cover_data = ('jpeg', cdata) try: path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: continue for fmt in fmts: if only_fmts is not None and fmt.lower() not in only_fmts: continue try: name = self.fields['formats'].format_fname(book_id, fmt) - except: + except Exception: continue if name and path: try: @@ -3333,7 +3333,7 @@ class Cache: def are_paths_inside_book_dir(self, book_id, paths, sub_path=''): try: path = self._field_for('path', book_id).replace('/', os.sep) - except: + except Exception: return set() return {x for x in paths if self.backend.is_path_inside_book_dir(x, path, sub_path)} diff --git a/src/calibre/db/categories.py b/src/calibre/db/categories.py index 79f9fc2d9b..42ab1063db 100644 --- a/src/calibre/db/categories.py +++ b/src/calibre/db/categories.py @@ -133,7 +133,7 @@ def clean_user_categories(dbcache): try: if new_cats != user_cats: dbcache.set_pref('user_categories', new_cats) - except: + except Exception: pass return new_cats diff --git a/src/calibre/db/cli/cmd_set_metadata.py b/src/calibre/db/cli/cmd_set_metadata.py index 6887661e6c..c2b99096a3 100644 --- a/src/calibre/db/cli/cmd_set_metadata.py +++ b/src/calibre/db/cli/cmd_set_metadata.py @@ -127,7 +127,7 @@ def main(opts, args, dbctx): try: int(x) return True - except: + except Exception: return False if len(args) < 1 or not verify_int(args[0]): diff --git a/src/calibre/db/lazy.py b/src/calibre/db/lazy.py index 1f0c310ab9..b29b7919d9 100644 --- a/src/calibre/db/lazy.py +++ b/src/calibre/db/lazy.py @@ -86,7 +86,7 @@ class FormatMetadata(MutableBase, MutableMapping): for f in self._formats: try: self._values[f] = db.format_metadata(self._id, f) - except: + except Exception: pass diff --git a/src/calibre/db/legacy.py b/src/calibre/db/legacy.py index 45cb35b5da..6771bebd47 100644 --- a/src/calibre/db/legacy.py +++ b/src/calibre/db/legacy.py @@ -316,7 +316,7 @@ class LibraryDatabase: for listener in self.listeners: try: listener(event, ids) - except: + except Exception: traceback.print_exc() continue diff --git a/src/calibre/db/restore.py b/src/calibre/db/restore.py index 514a784668..36203e4f27 100644 --- a/src/calibre/db/restore.py +++ b/src/calibre/db/restore.py @@ -154,7 +154,7 @@ class Restore(Thread): if self.successes == 0 and len(self.dirs) > 0: raise Exception('Something bad happened') self.replace_db() - except: + except Exception: self.tb = traceback.format_exc() if self.failed_dirs: for x in self.failed_dirs: @@ -183,7 +183,7 @@ class Restore(Thread): return True self.progress_callback(_('Finished restoring preferences'), 1) return False - except: + except Exception: traceback.print_exc() self.progress_callback(None, 1) self.progress_callback(_('Restoring preferences and column metadata failed'), 0) diff --git a/src/calibre/db/schema_upgrades.py b/src/calibre/db/schema_upgrades.py index e73f01a57e..b4a7795f1e 100644 --- a/src/calibre/db/schema_upgrades.py +++ b/src/calibre/db/schema_upgrades.py @@ -30,7 +30,7 @@ class SchemaUpgrade: prints(f'Upgrading database to version {uv + 1}...') meth() self.db.execute(f'pragma user_version={uv + 1}') - except: + except Exception: self.db.execute('ROLLBACK') raise else: diff --git a/src/calibre/db/search.py b/src/calibre/db/search.py index 5603908b9e..bd9951006b 100644 --- a/src/calibre/db/search.py +++ b/src/calibre/db/search.py @@ -196,13 +196,13 @@ class DateSearch: # {{{ num = query[:-len(m.group(1))] try: qd = now() - timedelta(int(num)) - except: + except Exception: raise ParseException(_('Number conversion error: {0}').format(num)) field_count = 3 else: try: qd = parse_date(query, as_utc=False) - except: + except Exception: raise ParseException(_('Date conversion error: {0}').format(query)) if '-' in query: field_count = query.count('-') + 1 @@ -588,7 +588,7 @@ class Parser(SearchQueryParser): # {{{ c -= m if len(c) == 0: break - except: + except Exception: pass return matches @@ -662,7 +662,7 @@ class Parser(SearchQueryParser): # {{{ sep = sep.lower() else: sep = 't' - except: + except Exception: if DEBUG: import traceback traceback.print_exc() @@ -720,17 +720,17 @@ class Parser(SearchQueryParser): # {{{ try: rating_query = int(float(query)) * 2 - except: + except Exception: rating_query = None try: int_query = int(float(query)) - except: + except Exception: int_query = None try: float_query = float(query) - except: + except Exception: float_query = None for location in locations: diff --git a/src/calibre/db/tables.py b/src/calibre/db/tables.py index ff3a2ae1db..c81f4b3b28 100644 --- a/src/calibre/db/tables.py +++ b/src/calibre/db/tables.py @@ -31,7 +31,7 @@ def c_parse(val): return datetime(int(val), 1, 3, tzinfo=utc_tz) if val is None: return UNDEFINED_DATE - except: + except Exception: pass else: try: diff --git a/src/calibre/db/tests/reading.py b/src/calibre/db/tests/reading.py index 42783b680c..9feb4277b1 100644 --- a/src/calibre/db/tests/reading.py +++ b/src/calibre/db/tests/reading.py @@ -628,7 +628,7 @@ class ReadingTest(BaseTest): def f(x): try: x.pop('rec_index', None) - except: + except Exception: pass return x if field not in {'#series_index'}: diff --git a/src/calibre/db/utils.py b/src/calibre/db/utils.py index 5a39cff7f6..7ea9c09e4f 100644 --- a/src/calibre/db/utils.py +++ b/src/calibre/db/utils.py @@ -35,7 +35,7 @@ def force_to_bool(val): val = False else: val = bool(int(val)) - except: + except Exception: val = None return val diff --git a/src/calibre/db/write.py b/src/calibre/db/write.py index ec704b5858..b6d727494b 100644 --- a/src/calibre/db/write.py +++ b/src/calibre/db/write.py @@ -47,7 +47,7 @@ def get_series_values(val): try: idx = float(idx) return match.group(1).strip(), idx - except: + except Exception: pass return val, None diff --git a/src/calibre/debug.py b/src/calibre/debug.py index 4453916de5..df44014610 100644 --- a/src/calibre/debug.py +++ b/src/calibre/debug.py @@ -174,7 +174,7 @@ def print_basic_debug_info(out=None): out('OSX:', platform.mac_ver()) else: out('Linux:', platform.linux_distribution()) - except: + except Exception: pass out('Interface language:', str(set_translators.lang)) out('EXE path:', sys.executable) diff --git a/src/calibre/devices/__init__.py b/src/calibre/devices/__init__.py index b7cd66642e..64eca54f39 100644 --- a/src/calibre/devices/__init__.py +++ b/src/calibre/devices/__init__.py @@ -52,7 +52,7 @@ def get_connected_device(): for det, d in connected_devices: try: d.open(det, None) - except: + except Exception: continue else: dev = d @@ -89,7 +89,7 @@ def debug(ioreg_to_tmp=False, buf=None, plugins=None, for d in devplugins: try: d.startup() - except: + except Exception: out(f'Startup failed for device plugin: {d}') if disabled_plugins is None: @@ -165,7 +165,7 @@ def debug(ioreg_to_tmp=False, buf=None, plugins=None, dev.reset(detected_device=det) dev.open(det, None) out('OK') - except: + except Exception: import traceback errors[dev] = traceback.format_exc() out('failed') @@ -203,7 +203,7 @@ def debug(ioreg_to_tmp=False, buf=None, plugins=None, for d in devplugins: try: d.shutdown() - except: + except Exception: pass diff --git a/src/calibre/devices/android/driver.py b/src/calibre/devices/android/driver.py index 08964f3217..56cdd5536b 100644 --- a/src/calibre/devices/android/driver.py +++ b/src/calibre/devices/android/driver.py @@ -313,7 +313,7 @@ class ANDROID(USBMS): def windows_sort_drives(self, drives): try: vid, pid, bcd = self.device_being_opened[:3] - except: + except Exception: vid, pid, bcd = -1, -1, -1 if (vid, pid, bcd) == (0x0e79, 0x1408, 0x0222): letter_a = drives.get('carda', None) diff --git a/src/calibre/devices/cli.py b/src/calibre/devices/cli.py index 3d30a3ba4c..f3164690b5 100755 --- a/src/calibre/devices/cli.py +++ b/src/calibre/devices/cli.py @@ -175,7 +175,7 @@ def shutdown_plugins(): for d in device_plugins(): try: d.shutdown() - except: + except Exception: pass @@ -207,7 +207,7 @@ def main(): for d in device_plugins(): try: d.startup() - except: + except Exception: print(f'Startup failed for device plugin: {d}') if d.MANAGES_DEVICE_PRESENCE: cd = d.detect_managed_devices(scanner.devices) @@ -230,7 +230,7 @@ def main(): for det, d in connected_devices: try: d.open(det, None) - except: + except Exception: continue else: dev = d diff --git a/src/calibre/devices/hanlin/driver.py b/src/calibre/devices/hanlin/driver.py index ba4b9208eb..c0bf885833 100644 --- a/src/calibre/devices/hanlin/driver.py +++ b/src/calibre/devices/hanlin/driver.py @@ -44,11 +44,11 @@ class HANLINV3(USBMS): try: main_num = int(re.findall(r'\d+', main)[0]) if main else None - except: + except Exception: main_num = None try: card_num = int(re.findall(r'\d+', card)[0]) if card else None - except: + except Exception: card_num = None if card_num is not None and main_num is not None and card_num > main_num: diff --git a/src/calibre/devices/hanvon/driver.py b/src/calibre/devices/hanvon/driver.py index 83cdd122b2..00b0b89845 100644 --- a/src/calibre/devices/hanvon/driver.py +++ b/src/calibre/devices/hanvon/driver.py @@ -142,7 +142,7 @@ class ALEX(N516): cpath = self.alex_cpath(path) if os.path.exists(cpath): os.remove(cpath) - except: + except Exception: pass self.report_progress(1.0, _('Removing books from device...')) diff --git a/src/calibre/devices/kindle/bookmark.py b/src/calibre/devices/kindle/bookmark.py index b0f2a79897..6ef5e0ce52 100644 --- a/src/calibre/devices/kindle/bookmark.py +++ b/src/calibre/devices/kindle/bookmark.py @@ -27,7 +27,7 @@ class Bookmark: # {{{ self.get_book_length() try: self.percent_read = min(float(100*self.last_read / self.book_length),100) - except: + except Exception: self.percent_read = 0 def record(self, n): @@ -167,7 +167,7 @@ class Bookmark: # {{{ text += line.strip() else: raise Exception('error') - except: + except Exception: text = '(Unable to extract highlight text from My Clippings.txt)' return text @@ -288,7 +288,7 @@ class Bookmark: # {{{ self.nrecs, = unpack('>H', self.data[76:78]) record0 = self.record(0) self.book_length = int(unpack('>I', record0[0x04:0x08])[0]) - except: + except Exception: pass elif self.bookmark_extension == 'tan': # Read bookLength from metadata @@ -297,7 +297,7 @@ class Bookmark: # {{{ with open(book_fs,'rb') as f: mu = MetadataUpdater(f) self.book_length = mu.book_length - except: + except Exception: pass else: print(f'unsupported bookmark_extension: {self.bookmark_extension}') diff --git a/src/calibre/devices/kindle/driver.py b/src/calibre/devices/kindle/driver.py index b7f8723d56..6e61d322fc 100644 --- a/src/calibre/devices/kindle/driver.py +++ b/src/calibre/devices/kindle/driver.py @@ -463,7 +463,7 @@ class KINDLE2(KINDLE): if os.access(collections, os.R_OK): try: self.kindle_update_booklist(bl, collections) - except: + except Exception: import traceback traceback.print_exc() return bl @@ -513,7 +513,7 @@ class KINDLE2(KINDLE): # Upload the cover thumbnail try: self.upload_kindle_thumbnail(metadata, filepath) - except: + except Exception: import traceback traceback.print_exc() # Upload the apnx file @@ -621,7 +621,7 @@ class KINDLE2(KINDLE): if cust_col_name: try: custom_page_count = int(metadata.get(cust_col_name, 0)) - except: + except Exception: pass apnx_path = f'{os.path.join(path, filename)}.apnx' @@ -638,10 +638,10 @@ class KINDLE2(KINDLE): method = temp else: print(f'Invalid method choice for this book ({temp!r}), ignoring.') - except: + except Exception: print('Could not retrieve override method choice, using default.') apnx_builder.write_apnx(filepath, apnx_path, method=method, page_count=custom_page_count) - except: + except Exception: print('Failed to generate APNX') import traceback traceback.print_exc() diff --git a/src/calibre/devices/kobo/bookmark.py b/src/calibre/devices/kobo/bookmark.py index 0d55c3e299..239d156283 100644 --- a/src/calibre/devices/kobo/bookmark.py +++ b/src/calibre/devices/kobo/bookmark.py @@ -67,7 +67,7 @@ class Bookmark: # {{{ 'chapter_index': chapter_row['VolumeIndex'] } debug_print(f'Kobo::Bookmark::get_bookmark_data - getting kepub chapter: kepub chapters={kepub_chapters}') - except: + except Exception: debug_print('Kobo::Bookmark::get_bookmark_data - No chapters found') cursor.execute(bookmark_query, book_query_values) diff --git a/src/calibre/devices/kobo/books.py b/src/calibre/devices/kobo/books.py index 598fb48af1..7b458f20a1 100644 --- a/src/calibre/devices/kobo/books.py +++ b/src/calibre/devices/kobo/books.py @@ -46,20 +46,20 @@ class Book(Book_): if ContentType == '6' and date is not None: try: self.datetime = time.strptime(date, '%Y-%m-%dT%H:%M:%S.%f') - except: + except Exception: try: self.datetime = time.strptime(date.split('+')[0], '%Y-%m-%dT%H:%M:%S') - except: + except Exception: try: self.datetime = time.strptime(date.split('+')[0], '%Y-%m-%d') - except: + except Exception: try: self.datetime = parse_date(date, assume_utc=True).timetuple() - except: + except Exception: try: self.datetime = time.gmtime(os.path.getctime(self.path)) - except: + except Exception: self.datetime = time.gmtime() self.kobo_metadata = Metadata(title, self.authors) diff --git a/src/calibre/devices/kobo/driver.py b/src/calibre/devices/kobo/driver.py index 1e1f3cd925..1d8040f158 100644 --- a/src/calibre/devices/kobo/driver.py +++ b/src/calibre/devices/kobo/driver.py @@ -332,7 +332,7 @@ class KOBO(USBMS): title = 'FILE MISSING: ' + title book = self.book_class(prefix, lpath, title, authors, mime, date, ContentType, ImageID, size=1048576) - except: + except Exception: debug_print('prefix: ', prefix, 'lpath: ', lpath, 'title: ', title, 'authors: ', authors, 'mime: ', mime, 'date: ', date, 'ContentType: ', ContentType, 'ImageID: ', ImageID) raise @@ -342,7 +342,7 @@ class KOBO(USBMS): if bl.add_book(book, replace_metadata=False): changed = True - except: # Probably a path encoding error + except Exception: # Probably a path encoding error import traceback traceback.print_exc() return changed @@ -809,7 +809,7 @@ class KOBO(USBMS): try: cursor.execute(query) - except: + except Exception: debug_print(' Database Exception: Unable to reset ReadStatus list') raise finally: @@ -839,7 +839,7 @@ class KOBO(USBMS): try: debug_print(f'Kobo::set_readstatus - Making change - ContentID={ContentID}, ReadStatus={ReadStatus}, DateLastRead={datelastread}') cursor.execute("update content set ReadStatus=?,FirstTimeReading='false',DateLastRead=? where BookID is Null and ContentID = ?", t) - except: + except Exception: debug_print(' Database Exception: Unable to update ReadStatus') raise @@ -1038,7 +1038,7 @@ class KOBO(USBMS): debug_print('KOBO: uploading cover') try: self._upload_cover(path, filename, metadata, filepath, uploadgrayscale) - except: + except Exception: debug_print('FAILED to upload cover', filepath) def _upload_cover(self, path, filename, metadata, filepath, uploadgrayscale): @@ -1248,13 +1248,13 @@ class KOBO(USBMS): if bookmark.last_read is not None: try: last_read = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(calendar.timegm(time.strptime(bookmark.last_read, '%Y-%m-%dT%H:%M:%S')))) - except: + except Exception: try: last_read = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(calendar.timegm(time.strptime(bookmark.last_read, '%Y-%m-%dT%H:%M:%S.%f')))) - except: + except Exception: try: last_read = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(calendar.timegm(time.strptime(bookmark.last_read, '%Y-%m-%dT%H:%M:%SZ')))) - except: + except Exception: last_read = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()) else: # self.datetime = time.gmtime() @@ -1846,10 +1846,10 @@ class KOBOTOUCH(KOBO): if DateCreated is not None: try: kobo_metadata.pubdate = parse_date(DateCreated, assume_utc=True) - except: + except Exception: try: kobo_metadata.pubdate = datetime.strptime(DateCreated, '%Y-%m-%dT%H:%M:%S.%fZ') - except: + except Exception: debug_print(f"KoboTouch:update_booklist - Cannot convert date - DateCreated='{DateCreated}'") idx = bl_cache.get(lpath, None) @@ -1966,7 +1966,7 @@ class KOBOTOUCH(KOBO): if show_debug: debug_print(' book.device_collections', book.device_collections) debug_print(' book.title', book.title) - except: # Probably a path encoding error + except Exception: # Probably a path encoding error import traceback traceback.print_exc() return changed @@ -3338,7 +3338,7 @@ class KOBOTOUCH(KOBO): if book.kobo_series_number is not None: try: kobo_series_number = float(book.kobo_series_number) - except: + except Exception: kobo_series_number = None if kobo_series_number == book.series_index: if show_debug: @@ -3359,7 +3359,7 @@ class KOBOTOUCH(KOBO): debug_print('KoboTouch:set_series - about to set - parameters:', update_values) cursor.execute(update_query, update_values) self.series_set += 1 - except: + except Exception: debug_print(' Database Exception: Unable to set series info') raise finally: @@ -3435,7 +3435,7 @@ class KOBOTOUCH(KOBO): self.series_index_template, newmi, 'Kobo series number template', newmi) else: new_series_number = f'{newmi.series_index:g}' - except: + except Exception: new_series_number = None else: new_series = None @@ -3590,7 +3590,7 @@ class KOBOTOUCH(KOBO): debug_print('KoboTouch:set_core_metadata - about to set - update_query:', update_query) cursor.execute(update_query, update_values) self.core_metadata_set += 1 - except: + except Exception: debug_print(' Database Exception: Unable to set the core metadata') debug_print(f' Query was: {update_query}') debug_print(f' Values were: {update_values}') @@ -3623,7 +3623,7 @@ class KOBOTOUCH(KOBO): cls.opts = cls.settings() try: return getattr(cls.opts, key) - except: + except Exception: debug_print('KoboTouch::get_prefs - probably an extra_customization:', key) return None @@ -4342,7 +4342,7 @@ class KOBOTOUCH(KOBO): self.debugging_title = self.get_debugging_title() try: is_debugging = (len(self.debugging_title) > 0 and title.lower().find(self.debugging_title.lower()) >= 0) or len(title) == 0 - except: + except Exception: debug_print(f"KoboTouch::is_debugging_title - Exception checking debugging title for title '{title}'.") is_debugging = False diff --git a/src/calibre/devices/mtp/defaults.py b/src/calibre/devices/mtp/defaults.py index f79c25dd4c..3877d84743 100644 --- a/src/calibre/devices/mtp/defaults.py +++ b/src/calibre/devices/mtp/defaults.py @@ -51,7 +51,7 @@ class DeviceDefaults: if m is not None: try: vid, pid = int(m.group(1), 16), int(m.group(2), 16) - except: + except Exception: traceback.print_exc() else: vid, pid = device.vendor_id, device.product_id diff --git a/src/calibre/devices/mtp/driver.py b/src/calibre/devices/mtp/driver.py index 68299022b2..d91c9a72a9 100644 --- a/src/calibre/devices/mtp/driver.py +++ b/src/calibre/devices/mtp/driver.py @@ -228,7 +228,7 @@ class MTP_DEVICE(BASE): try: stream = self.get_mtp_file(f) dinfo = json.load(stream, object_hook=from_json) - except: + except Exception: prints('Failed to load existing driveinfo.calibre file, with error:') traceback.print_exc() dinfo = {} @@ -304,7 +304,7 @@ class MTP_DEVICE(BASE): try: stream = self.get_mtp_file(cache) json_codec.decode_from_file(stream, bl, Book, sid) - except: + except Exception: need_sync = True relpath_cache = {b.mtp_relpath:i for i, b in enumerate(bl)} @@ -333,7 +333,7 @@ class MTP_DEVICE(BASE): try: book.smart_update(self.read_file_metadata(mtp_file)) debug('Read metadata for', '/'.join(mtp_file.full_path)) - except: + except Exception: prints('Failed to read metadata from', '/'.join(mtp_file.full_path)) traceback.print_exc() @@ -723,7 +723,7 @@ class MTP_DEVICE(BASE): if parent.empty and parent.can_delete and not parent.is_system: try: self.recursive_delete(parent) - except: + except Exception: prints('Failed to delete parent: {}, ignoring'.format('/'.join(parent.full_path))) def delete_books(self, paths, end_session=True): diff --git a/src/calibre/devices/mtp/unix/driver.py b/src/calibre/devices/mtp/unix/driver.py index 7e0c49885d..d5d56e4cf2 100644 --- a/src/calibre/devices/mtp/unix/driver.py +++ b/src/calibre/devices/mtp/unix/driver.py @@ -159,7 +159,7 @@ class MTP_DEVICE(MTPDeviceBase): except BlacklistedDevice: p('This device has been blacklisted by the user') continue - except: + except Exception: p('Opening device failed:') p(traceback.format_exc()) return False diff --git a/src/calibre/devices/mtp/windows/driver.py b/src/calibre/devices/mtp/windows/driver.py index e3d46eab16..983681463e 100644 --- a/src/calibre/devices/mtp/windows/driver.py +++ b/src/calibre/devices/mtp/windows/driver.py @@ -116,7 +116,7 @@ class MTP_DEVICE(MTPDeviceBase): self.last_refresh_devices_time = time.time() try: pnp_ids = frozenset(self.wpd.enumerate_devices()) - except: + except Exception: return None self.detected_devices = {dev:self.detected_devices.get(dev, None) @@ -168,7 +168,7 @@ class MTP_DEVICE(MTPDeviceBase): return False try: pnp_ids = frozenset(self.wpd.enumerate_devices()) - except: + except Exception: p('Failed to get list of PNP ids on system') p(traceback.format_exc()) return False @@ -183,7 +183,7 @@ class MTP_DEVICE(MTPDeviceBase): for pnp_id in pnp_ids: try: data = self.wpd.device_info(pnp_id) - except: + except Exception: p('Failed to get data for device:', pnp_id) p(traceback.format_exc()) continue @@ -201,7 +201,7 @@ class MTP_DEVICE(MTPDeviceBase): except BlacklistedDevice: p('This device has been blacklisted by the user') continue - except: + except Exception: p('Open failed:') p(traceback.format_exc()) continue diff --git a/src/calibre/devices/prs505/driver.py b/src/calibre/devices/prs505/driver.py index 6b3d33a16b..bf8fe6c171 100644 --- a/src/calibre/devices/prs505/driver.py +++ b/src/calibre/devices/prs505/driver.py @@ -132,7 +132,7 @@ class PRS505(USBMS): if not os.path.exists(dname): try: os.makedirs(dname, mode=0o777) - except: + except Exception: time.sleep(5) os.makedirs(dname, mode=0o777) with open(cachep, 'wb') as f: @@ -142,7 +142,7 @@ class PRS505(USBMS): ''') fsync(f) return True - except: + except Exception: import traceback traceback.print_exc() return False @@ -237,7 +237,7 @@ class PRS505(USBMS): self._upload_cover(os.path.dirname(p), os.path.splitext(os.path.basename(p))[0], book, p) - except: + except Exception: debug_print('FAILED to upload cover', prefix, book.lpath) else: @@ -266,7 +266,7 @@ class PRS505(USBMS): debug_print('PRS505: uploading cover') try: self._upload_cover(path, filename, metadata, filepath) - except: + except Exception: debug_print('FAILED to upload cover', filepath) def _upload_cover(self, path, filename, metadata, filepath): diff --git a/src/calibre/devices/prs505/sony_cache.py b/src/calibre/devices/prs505/sony_cache.py index c639c78016..277b13304f 100644 --- a/src/calibre/devices/prs505/sony_cache.py +++ b/src/calibre/devices/prs505/sony_cache.py @@ -72,7 +72,7 @@ def strptime(src): def strftime(epoch, zone=time.localtime): try: src = time.strftime('%w, %d %m %Y %H:%M:%S GMT', zone(epoch)).split() - except: + except Exception: src = time.strftime('%w, %d %m %Y %H:%M:%S GMT', zone()).split() src[0] = INVERSE_DAY_MAP[int(src[0][:-1])]+',' @@ -127,7 +127,7 @@ class XMLCache: with open(path, 'wb') as f: f.write(EMPTY_EXT_CACHE) fsync(f) - except: + except Exception: pass if os.access(path, os.W_OK): try: @@ -136,7 +136,7 @@ class XMLCache: xml_to_unicode(f.read(), strip_encoding_pats=True, assume_utf8=True, verbose=DEBUG)[0] ) self.ext_paths[source_id] = path - except: + except Exception: pass # }}} @@ -286,7 +286,7 @@ class XMLCache: id_ = x.get('id') try: id_ = int(id_) - except: + except Exception: x.set('id', '-1') idmap[id_] = '-1' @@ -471,7 +471,7 @@ class XMLCache: if not name: try: name = [t for t in book.tags if t != _('News')][0] - except: + except Exception: name = None if not name: @@ -483,7 +483,7 @@ class XMLCache: pubdate = strftime(book.pubdate.utctimetuple(), zone=lambda x: x) record.set('publicationDate', pubdate) - except: + except Exception: pass def rebuild_collections(self, booklist, bl_index): @@ -616,7 +616,7 @@ class XMLCache: # matches. Use localtime if the case of a tie, and hope it is right. try: timestamp = os.path.getmtime(path) - except: + except Exception: debug_print('Failed to get timestamp for:', path) timestamp = time.time() rec_date = record.get('date', None) @@ -630,7 +630,7 @@ class XMLCache: def record_set(k, v): try: record.set(k, clean(v)) - except: + except Exception: # v is not suitable for XML, ignore pass @@ -656,7 +656,7 @@ class XMLCache: record.set('date', clean(date)) try: record.set('size', clean(str(os.stat(path).st_size))) - except: + except Exception: record.set('size', '0') title = book.title if book.title else _('Unknown') record_set('title', title) @@ -731,7 +731,7 @@ class XMLCache: try: raw = etree.tostring(self.ext_roots[i], encoding='UTF-8', xml_declaration=True) - except: + except Exception: continue raw = raw.replace(b"", b'') @@ -768,7 +768,7 @@ class XMLCache: num = int(id_) if num > ans: ans = num - except: + except Exception: continue return ans diff --git a/src/calibre/devices/prst1/driver.py b/src/calibre/devices/prst1/driver.py index f205c18d6c..0e230b2ba9 100644 --- a/src/calibre/devices/prst1/driver.py +++ b/src/calibre/devices/prst1/driver.py @@ -470,7 +470,7 @@ class PRST1(USBMS): author = newmi.authors[0] else: author = authors_to_string(newmi.authors) - except: + except Exception: author = _('Unknown') title = newmi.title or _('Unknown') @@ -796,7 +796,7 @@ class PRST1(USBMS): if not name: try: name = [t for t in book.tags if t != _('News')][0] - except: + except Exception: name = None if not name: @@ -805,7 +805,7 @@ class PRST1(USBMS): pubdate = None try: pubdate = int(time.mktime(book.pubdate.timetuple()) * 1000) - except: + except Exception: pass cursor = connection.cursor() diff --git a/src/calibre/devices/smart_device_app/driver.py b/src/calibre/devices/smart_device_app/driver.py index 45cc480ec6..4eb2b741ca 100644 --- a/src/calibre/devices/smart_device_app/driver.py +++ b/src/calibre/devices/smart_device_app/driver.py @@ -74,7 +74,7 @@ class ConnectionListener(Thread): def _close_socket(self, the_socket): try: the_socket.shutdown(socket.SHUT_RDWR) - except: + except Exception: # the shutdown can fail if the socket isn't fully connected. Ignore it pass the_socket.close() @@ -86,7 +86,7 @@ class ConnectionListener(Thread): while self.keep_running: try: time.sleep(1) - except: + except Exception: # Happens during interpreter shutdown break @@ -131,7 +131,7 @@ class ConnectionListener(Thread): ',' + str(self.driver.port)).encode('utf-8') self.driver._debug('received broadcast', packet, message) self.driver.broadcast_socket.sendto(message, remote) - except: + except Exception: pass else: break @@ -415,7 +415,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): prints('', printable, end='') else: prints('', a, end='') - except: + except Exception: prints('', 'value too long', end='') print() self.debug_time = time.time() @@ -461,7 +461,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): # Fall back to the ch if the UUID doesn't exist. if self.client_wants_uuid_file_names and mdata.uuid: return (mdata.uuid + ext) - except: + except Exception: pass dotless_ext = ext[1:] if len(ext) > 0 else ext @@ -481,7 +481,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): try: p = mdata.pubdate date = (p.year, p.month, p.day) - except: + except Exception: today = time.localtime() date = (today[0], today[1], today[2]) template = f'{{title}}_{date[0]}-{date[1]}-{date[2]}' @@ -572,7 +572,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): try: v = self.device_socket.recv(length) return v - except: + except Exception: self._close_device_socket() raise @@ -621,7 +621,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): self._close_device_socket() raise time.sleep(0.1) # lets not hammer the OS too hard - except: + except Exception: self._close_device_socket() raise @@ -656,7 +656,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): self._debug('device went away') self._close_device_socket() raise ControlError(desc='Device closed the network connection') - except: + except Exception: self._debug('other exception') traceback.print_exc() self._close_device_socket() @@ -684,7 +684,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): self._debug('device went away') self._close_device_socket() raise ControlError(desc='Device closed the network connection') - except: + except Exception: self._debug('other exception') traceback.print_exc() self._close_device_socket() @@ -745,7 +745,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): if key in self.device_book_cache and self.device_book_cache[key]['book'].last_modified == lastmod: self.device_book_cache[key]['last_used'] = now() return self.device_book_cache[key]['book'].deepcopy(lambda: SDBook('', '')) - except: + except Exception: traceback.print_exc() return None @@ -763,7 +763,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): if bool(v_thumb) != bool(b_thumb): return False return not v_thumb or v_thumb[1] == b_thumb[1] - except: + except Exception: traceback.print_exc() return False @@ -775,7 +775,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): continue if metadata.get('lpath', '').endswith(ext): return metadata - except: + except Exception: traceback.print_exc() return None @@ -788,7 +788,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): '_metadata_cache.pickle') if os.path.exists(old_cache_file_name): os.remove(old_cache_file_name) - except: + except Exception: pass try: @@ -797,7 +797,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): '_metadata_cache.json') if os.path.exists(old_cache_file_name): os.remove(old_cache_file_name) - except: + except Exception: pass cache_file_name = os.path.join(cache_dir(), @@ -825,14 +825,14 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): self.known_metadata[lpath] = metadata count += 1 self._debug('loaded', count, 'cache items') - except: + except Exception: traceback.print_exc() self.device_book_cache = defaultdict(dict) self.known_metadata = {} try: if os.path.exists(cache_file_name): os.remove(cache_file_name) - except: + except Exception: traceback.print_exc() def _write_metadata_cache(self): @@ -862,7 +862,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): from calibre.utils.filenames import atomic_rename atomic_rename(fd.name, prefix + '.json') - except: + except Exception: traceback.print_exc() def _make_metadata_cache_key(self, uuid, lpath_or_ext): @@ -904,7 +904,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): def _close_socket(self, the_socket): try: the_socket.shutdown(socket.SHUT_RDWR) - except: + except Exception: # the shutdown can fail if the socket isn't fully connected. Ignore it pass the_socket.close() @@ -913,7 +913,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): if self.device_socket is not None: try: self._close_socket(self.device_socket) - except: + except Exception: pass self.device_socket = None self._write_metadata_cache() @@ -930,7 +930,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): except OSError: self._debug('socket error on port', port) port = 0 - except: + except Exception: self._debug('Unknown exception while attaching port to socket') traceback.print_exc() raise @@ -972,7 +972,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): # protocol, this can only be a disconnect notification. Fall # through and actually try to talk to the client. # This will usually toss an exception if the socket is gone. - except: + except Exception: pass if (self.settings().extra_customization[self.OPT_AUTODISCONNECT] and self.noop_counter > self.DISCONNECT_AFTER_N_SECONDS): @@ -983,7 +983,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): try: if self._call_client('NOOP', {})[0] is None: self._close_device_socket() - except: + except Exception: self._close_device_socket() return self if self.is_connected else None @@ -1003,7 +1003,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): self.connection_attempts[peer] = attempts + 1 except InitialConnectionError: raise - except: + except Exception: pass except queue.Empty: self.is_connected = False @@ -1136,7 +1136,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): self._call_client('DISPLAY_MESSAGE', {'messageKind': self.MESSAGE_UPDATE_NEEDED, 'lastestKnownAppVersion': self.CURRENT_CC_VERSION}) - except: + except Exception: pass self.max_book_packet_len = result.get('maxBookContentPacketLen', @@ -1190,7 +1190,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): {'messageKind': self.MESSAGE_PASSWORD_ERROR, 'currentLibraryName': self.current_library_name, 'currentLibraryUUID': library_uuid}) - except: + except Exception: pass self._close_device_socket() # Don't bother with a message. The user will be informed on @@ -1199,7 +1199,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): try: peer = self.device_socket.getpeername()[0] self.connection_attempts[peer] = 0 - except: + except Exception: pass return True @@ -1342,7 +1342,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): self.device_book_cache.pop(key, None) self.known_metadata.pop(lpath, None) count_of_cache_items_deleted += 1 - except: + except Exception: self._debug('Exception while deleting book from caches', lpath) traceback.print_exc() self._debug('removed', count_of_cache_items_deleted, 'books from caches') @@ -1374,7 +1374,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): book.set('_new_book_', True) else: self._set_known_metadata(book) - except: + except Exception: self._debug('exception retrieving metadata for book', result.get('title', 'Unknown')) traceback.print_exc() else: @@ -1446,7 +1446,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): try: if bool(self.is_read_sync_col): book.set('_is_read_', book.get(self.is_read_sync_col, None)) - except: + except Exception: self._debug('failed to set local copy of _is_read_') traceback.print_exc() @@ -1454,7 +1454,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): if bool(self.is_read_date_sync_col): book.set('_last_read_date_', book.get(self.is_read_date_sync_col, None)) - except: + except Exception: self._debug('failed to set local copy of _last_read_date_') traceback.print_exc() # Write the cache here so that if we are interrupted on disconnect then the @@ -1655,7 +1655,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): if cc_mtime < calibre_mtime: book.set('_format_mtime_', isoformat(self.now)) return posixpath.basename(book.lpath), False - except: + except Exception: self._debug('exception checking if must send format', book.title) traceback.print_exc() return None, False @@ -1770,7 +1770,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): book.get('title', 'huh?'), 'to', calibre_val) book.set('_force_send_metadata_', True) force_return_changed_books = True - except: + except Exception: self._debug('exception special syncing is_read', self.is_read_sync_col) traceback.print_exc() @@ -1793,7 +1793,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): book.get('title', 'huh?'), 'to', calibre_val) book.set('_force_send_metadata_', True) force_return_changed_books = True - except: + except Exception: self._debug('exception special syncing is_read_date', self.is_read_sync_col) traceback.print_exc() @@ -1816,7 +1816,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): {id_: is_read}) if self.set_temp_mark_when_syncing_read: db.data.toggle_marked_ids({id_}) - except: + except Exception: self._debug('exception standard syncing is_read', self.is_read_sync_col) traceback.print_exc() @@ -1833,7 +1833,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): {id_: is_read_date}) if self.set_temp_mark_when_syncing_read: db.data.toggle_marked_ids({id_}) - except: + except Exception: self._debug('Exception standard syncing is_read_date', self.is_read_date_sync_col) traceback.print_exc() @@ -1892,7 +1892,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): compression_quality_ok = False else: self.THUMBNAIL_COMPRESSION_QUALITY = cq - except: + except Exception: compression_quality_ok = False if not compression_quality_ok: self.THUMBNAIL_COMPRESSION_QUALITY = 70 @@ -1905,7 +1905,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): try: self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) set_socket_inherit(self.listen_socket, False) - except: + except Exception: traceback.print_exc() message = 'creation of listen socket failed' self._debug(message) @@ -1916,7 +1916,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): if self.settings().extra_customization[self.OPT_USE_PORT]: try: opt_port = int(self.settings().extra_customization[self.OPT_PORT_NUMBER]) - except: + except Exception: message = _('Invalid port in options: %s')% \ self.settings().extra_customization[self.OPT_PORT_NUMBER] self._debug(message) @@ -1944,7 +1944,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): try: self.listen_socket.listen(1) - except: + except Exception: message = f'listen on port {port} failed' self._debug(message) self._close_listen_socket() @@ -1955,7 +1955,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): publish_zeroconf('calibre smart device client', '_calibresmartdeviceapp._tcp', port, {}, use_ip_address=ip_addr, strict=False) - except: + except Exception: self._debug('registration with bonjour failed') traceback.print_exc() @@ -1967,7 +1967,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): try: self.broadcast_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) set_socket_inherit(self.broadcast_socket, False) - except: + except Exception: message = 'creation of broadcast socket failed. This is not fatal.' self._debug(message) self.broadcast_socket = None @@ -2001,7 +2001,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin): try: unpublish_zeroconf('calibre smart device client', '_calibresmartdeviceapp._tcp', self.port, {}) - except: + except Exception: self._debug('deregistration with bonjour failed') traceback.print_exc() self._close_listen_socket() diff --git a/src/calibre/devices/usbms/books.py b/src/calibre/devices/usbms/books.py index a37cca5c3d..8fd0830a0b 100644 --- a/src/calibre/devices/usbms/books.py +++ b/src/calibre/devices/usbms/books.py @@ -67,7 +67,7 @@ class Book(Metadata): self.size = size # will be set later if None try: self.datetime = time.gmtime(os.path.getctime(self.path)) - except: + except Exception: self.datetime = time.gmtime() if other: self.smart_update(other) diff --git a/src/calibre/devices/usbms/device.py b/src/calibre/devices/usbms/device.py index 7622baa975..8fc114bbd1 100644 --- a/src/calibre/devices/usbms/device.py +++ b/src/calibre/devices/usbms/device.py @@ -550,7 +550,7 @@ class Device(DeviceConfig, DevicePlugin): ok[node] = True else: ok[node] = False - except: + except Exception: ok[node] = False if is_debugging() and not ok[node]: print(f'\nIgnoring the node: {node} as could not read size from: {sz}') @@ -580,7 +580,7 @@ class Device(DeviceConfig, DevicePlugin): try: with open(sz, 'rb') as szf: sz = int(szf.read().decode('utf-8')) - except: + except Exception: continue if sz > 0: nodes.append((x.split('/')[-1], sz)) @@ -602,7 +602,7 @@ class Device(DeviceConfig, DevicePlugin): from calibre.devices.udisks import mount mount(node) return 0 - except: + except Exception: print('Udisks mount call failed:') import traceback traceback.print_exc() @@ -658,12 +658,12 @@ class Device(DeviceConfig, DevicePlugin): try: with open(path, 'wb'): ro = False - except: + except Exception: pass else: try: os.remove(path) - except: + except Exception: pass if is_debugging() and ro: print('\nThe mountpoint', mp, 'is readonly, ignoring it') @@ -889,7 +889,7 @@ class Device(DeviceConfig, DevicePlugin): if x is not None: try: subprocess.Popen(self.OSX_EJECT_COMMAND + [x]) - except: + except Exception: pass def eject_linux(self): @@ -898,7 +898,7 @@ class Device(DeviceConfig, DevicePlugin): for d in drives: try: umount(d) - except: + except Exception: pass for d in drives: try: @@ -918,22 +918,22 @@ class Device(DeviceConfig, DevicePlugin): if islinux: try: self.eject_linux() - except: + except Exception: pass if isfreebsd: try: self.eject_freebsd() - except: + except Exception: pass if iswindows: try: self.eject_windows() - except: + except Exception: pass if ismacos: try: self.eject_osx() - except: + except Exception: pass self._main_prefix = self._card_a_prefix = self._card_b_prefix = None self.on_device_close() @@ -945,7 +945,7 @@ class Device(DeviceConfig, DevicePlugin): if islinux: try: self.linux_post_yank() - except: + except Exception: import traceback traceback.print_exc() self._main_prefix = self._card_a_prefix = self._card_b_prefix = None diff --git a/src/calibre/devices/usbms/driver.py b/src/calibre/devices/usbms/driver.py index f2598e047d..05884abfc2 100644 --- a/src/calibre/devices/usbms/driver.py +++ b/src/calibre/devices/usbms/driver.py @@ -115,7 +115,7 @@ class USBMS(CLI, Device): with open(os.path.join(prefix, self.DRIVEINFO), 'rb') as f: try: driveinfo = json.loads(f.read(), object_hook=from_json) - except: + except Exception: driveinfo = None driveinfo = self._update_driveinfo_record(driveinfo, prefix, location_code, name) @@ -252,7 +252,7 @@ class USBMS(CLI, Device): if bl.add_book(self.book_from_path(prefix, lpath), replace_metadata=False): changed = True - except: # Probably a filename encoding error + except Exception: # Probably a filename encoding error import traceback traceback.print_exc() return changed @@ -333,7 +333,7 @@ class USBMS(CLI, Device): self.upload_cover(os.path.dirname(filepath), os.path.splitext(os.path.basename(filepath))[0], mdata, filepath) - except: # Failure to upload cover is not catastrophic + except Exception: # Failure to upload cover is not catastrophic import traceback traceback.print_exc() @@ -413,7 +413,7 @@ class USBMS(CLI, Device): if self.SUPPORTS_SUB_DIRS: try: os.removedirs(os.path.dirname(path)) - except: + except Exception: pass def delete_books(self, paths, end_session=True): @@ -504,7 +504,7 @@ class USBMS(CLI, Device): try: with open(cache_file, 'rb') as f: json_codec.decode_from_file(f, bl, cls.book_class, prefix) - except: + except Exception: import traceback traceback.print_exc() bl = [] diff --git a/src/calibre/devices/user_defined/driver.py b/src/calibre/devices/user_defined/driver.py index c1f421b561..5d021a6b38 100644 --- a/src/calibre/devices/user_defined/driver.py +++ b/src/calibre/devices/user_defined/driver.py @@ -106,7 +106,7 @@ class USER_DEFINED(USBMS): self.WINDOWS_CARD_A_MEM = e[self.OPT_USB_WINDOWS_CA_ID] + '&' self.EBOOK_DIR_MAIN = e[self.OPT_MAIN_MEM_FOLDER] self.EBOOK_DIR_CARD_A = e[self.OPT_CARD_A_FOLDER] - except: + except Exception: import traceback traceback.print_exc() self.plugin_needs_delayed_initialization = False diff --git a/src/calibre/devices/utils.py b/src/calibre/devices/utils.py index 0c8a10d329..66d1780f89 100644 --- a/src/calibre/devices/utils.py +++ b/src/calibre/devices/utils.py @@ -59,7 +59,7 @@ def build_template_regexp(template): try: template = template.rpartition('/')[2] return re.compile(re.sub(r'{([^}]*)}', f, template) + r'([_\d]*$)') - except: + except Exception: prints(f'Failed to parse template: {template!r}') template = '{title} - {authors}' return re.compile(re.sub(r'{([^}]*)}', f, template) + r'([_\d]*$)') @@ -88,7 +88,7 @@ def create_upload_path(mdata, fname, template, sanitize, try: p = mdata.pubdate date = (p.year, p.month, p.day) - except: + except Exception: today = time.localtime() date = (today[0], today[1], today[2]) template = f'{{title}}_{date[0]}-{date[1]}-{date[2]}' diff --git a/src/calibre/ebooks/chm/metadata.py b/src/calibre/ebooks/chm/metadata.py index 3e43f086e3..decb4af94e 100644 --- a/src/calibre/ebooks/chm/metadata.py +++ b/src/calibre/ebooks/chm/metadata.py @@ -81,7 +81,7 @@ def _get_comments(soup): # and pages often comes as '(\d+ pages)' pages = re.search(r'\d+', pages).group(0) return f'Published {date}, {pages} pages.' - except: + except Exception: pass return None @@ -108,7 +108,7 @@ def _get_cover(soup, rdr): # interestingly, occasionally the only image without height # or width attrs is the cover... r[0] = img['src'] - except: + except Exception: # Probably invalid width, height aattributes, ignore continue if r: @@ -118,11 +118,11 @@ def _get_cover(soup, rdr): if ans is not None: try: ans = rdr.GetFile(ans) - except: + except Exception: ans = rdr.root + '/' + ans try: ans = rdr.GetFile(ans) - except: + except Exception: ans = None if ans is not None: import io @@ -132,7 +132,7 @@ def _get_cover(soup, rdr): try: Image.open(io.BytesIO(ans)).convert('RGB').save(buf, 'JPEG') ans = buf.getvalue() - except: + except Exception: ans = None return ans @@ -147,7 +147,7 @@ def get_metadata_from_reader(rdr): x = rdr.GetEncoding() codecs.lookup(x) enc = x - except: + except Exception: enc = 'cp1252' title = force_unicode(title, enc) authors = _get_authors(home) diff --git a/src/calibre/ebooks/chm/reader.py b/src/calibre/ebooks/chm/reader.py index d4561718f9..4669749866 100644 --- a/src/calibre/ebooks/chm/reader.py +++ b/src/calibre/ebooks/chm/reader.py @@ -187,7 +187,7 @@ class CHMReader(CHMFile): self._ensure_dir(lpath) try: data = self.GetFile(path) - except: + except Exception: self.log.exception(f'Failed to extract {path} from CHM, ignoring') continue if lpath.find(';') != -1: @@ -199,9 +199,9 @@ class CHMReader(CHMFile): try: if 'html' in guess_mimetype(path)[0]: html_files.add(lpath) - except: + except Exception: pass - except: + except Exception: if iswindows and len(lpath) > 250: self.log.warn(f'{path!r} filename too long, skipping') continue @@ -278,14 +278,14 @@ class CHMReader(CHMFile): alt = t[0].img['alt'].lower() if alt.find('prev') != -1 or alt.find('next') != -1 or alt.find('team') != -1: t[0].extract() - except: + except Exception: pass if (t[-1].nextSibling is None or t[-1].nextSibling.nextSibling is None): try: alt = t[-1].img['alt'].lower() if alt.find('prev') != -1 or alt.find('next') != -1 or alt.find('team') != -1: t[-1].extract() - except: + except Exception: pass # for some very odd reason each page's content appears to be in a table # too. and this table has sub-tables for random asides... grr. @@ -325,7 +325,7 @@ class CHMReader(CHMFile): tables[0].extract() while tdContents: soup.body.insert(tableIdx, tdContents.pop()) - except: + except Exception: pass # do not prettify, it would reformat the
 tags!
         try:
diff --git a/src/calibre/ebooks/comic/input.py b/src/calibre/ebooks/comic/input.py
index 6771bdc42d..3d47605783 100644
--- a/src/calibre/ebooks/comic/input.py
+++ b/src/calibre/ebooks/comic/input.py
@@ -169,7 +169,7 @@ class PageProcessor(list):  # {{{
                 if self.opts.comic_image_size:
                     SCRWIDTH, SCRHEIGHT = map(int, [x.strip() for x in
                         self.opts.comic_image_size.split('x')])
-            except:
+            except Exception:
                 pass  # Ignore
 
             if self.opts.keep_aspect_ratio:
@@ -253,7 +253,7 @@ def render_pages(tasks, dest, opts, notification=lambda x, y: x):
         try:
             pages.extend(PageProcessor(path, dest, opts, num))
             msg = _('Rendered %s')%path
-        except:
+        except Exception:
             failures.append(path)
             msg = _('Failed %s')%path
             if opts.verbose:
diff --git a/src/calibre/ebooks/conversion/cli.py b/src/calibre/ebooks/conversion/cli.py
index cba93eadbf..e811d84e7b 100644
--- a/src/calibre/ebooks/conversion/cli.py
+++ b/src/calibre/ebooks/conversion/cli.py
@@ -318,7 +318,7 @@ def create_option_parser(args, log):
         for title in titles:
             try:
                 log('\t'+title)
-            except:
+            except Exception:
                 log('\t'+repr(title))
         log(f'{len(titles)} recipes available')
         raise SystemExit(0)
@@ -370,7 +370,7 @@ def read_sr_patterns(path, log=None):
             line = line.replace('\ue123', '\n')
             try:
                 re.compile(line)
-            except:
+            except Exception:
                 msg = f'Invalid regular expression: {line!r} from file: {path!r}'
                 if log is not None:
                     log.error(msg)
diff --git a/src/calibre/ebooks/conversion/plugins/epub_input.py b/src/calibre/ebooks/conversion/plugins/epub_input.py
index 25051692e9..0b4b71b214 100644
--- a/src/calibre/ebooks/conversion/plugins/epub_input.py
+++ b/src/calibre/ebooks/conversion/plugins/epub_input.py
@@ -59,7 +59,7 @@ class EPUBInput(InputFormatPlugin):
                 try:
                     key = item.text.rpartition(':')[-1]
                     key = uuid.UUID(key).bytes
-                except:
+                except Exception:
                     import traceback
                     traceback.print_exc()
                     key = None
@@ -78,7 +78,7 @@ class EPUBInput(InputFormatPlugin):
                     self._encrypted_font_uris.append(uri)
                     decrypt_font(tkey, path, algorithm)
             return True
-        except:
+        except Exception:
             import traceback
             traceback.print_exc()
         return False
@@ -265,7 +265,7 @@ class EPUBInput(InputFormatPlugin):
         try:
             zf = ZipFile(stream)
             zf.extractall(os.getcwd())
-        except:
+        except Exception:
             log.exception('EPUB appears to be invalid ZIP file, trying a'
                     ' more forgiving ZIP parser')
             from calibre.utils.localunzip import extractall
diff --git a/src/calibre/ebooks/conversion/plugins/epub_output.py b/src/calibre/ebooks/conversion/plugins/epub_output.py
index 83a09ae46c..7cdf48de04 100644
--- a/src/calibre/ebooks/conversion/plugins/epub_output.py
+++ b/src/calibre/ebooks/conversion/plugins/epub_output.py
@@ -467,7 +467,7 @@ class EPUBOutput(OutputFormatPlugin):
                         prior = next(br.itersiblings(preceding=True))
                         priortag = barename(prior.tag)
                         priortext = prior.tail
-                    except:
+                    except Exception:
                         priortag = 'body'
                         priortext = body.text
                     if priortext:
diff --git a/src/calibre/ebooks/conversion/plugins/html_input.py b/src/calibre/ebooks/conversion/plugins/html_input.py
index 04a2df3c00..3b7f2ce92f 100644
--- a/src/calibre/ebooks/conversion/plugins/html_input.py
+++ b/src/calibre/ebooks/conversion/plugins/html_input.py
@@ -253,7 +253,7 @@ class HTMLInput(InputFormatPlugin):
         if not isinstance(link_, str):
             try:
                 link_ = link_.decode('utf-8', 'error')
-            except:
+            except Exception:
                 self.log.warn(f'Failed to decode link {link_!r}. Ignoring')
                 return None, None
         if self.root_dir_for_absolute_links and link_.startswith('/'):
@@ -261,7 +261,7 @@ class HTMLInput(InputFormatPlugin):
             base = self.root_dir_for_absolute_links
         try:
             l = Link(link_, base if base else os.getcwd())
-        except:
+        except Exception:
             self.log.exception(f'Failed to process link: {link_!r}')
             return None, None
         if l.path is None:
@@ -289,7 +289,7 @@ class HTMLInput(InputFormatPlugin):
             if base and not os.path.isabs(link):
                 link = os.path.join(base, link)
             link = os.path.abspath(link)
-        except:
+        except Exception:
             return link_
         if not os.access(link, os.R_OK):
             corrected = False
diff --git a/src/calibre/ebooks/conversion/plugins/htmlz_output.py b/src/calibre/ebooks/conversion/plugins/htmlz_output.py
index 98b5c6057b..44fbfb5f90 100644
--- a/src/calibre/ebooks/conversion/plugins/htmlz_output.py
+++ b/src/calibre/ebooks/conversion/plugins/htmlz_output.py
@@ -115,7 +115,7 @@ class HTMLZOutput(OutputFormatPlugin):
                     with open(cover_path, 'w') as cf:
                         cf.write('')
                     save_cover_data_to(cover_data, cover_path)
-            except:
+            except Exception:
                 import traceback
                 traceback.print_exc()
 
diff --git a/src/calibre/ebooks/conversion/plugins/lrf_output.py b/src/calibre/ebooks/conversion/plugins/lrf_output.py
index bf5a1623db..0e47b12fe9 100644
--- a/src/calibre/ebooks/conversion/plugins/lrf_output.py
+++ b/src/calibre/ebooks/conversion/plugins/lrf_output.py
@@ -17,7 +17,7 @@ class LRFOptions:
         def f2s(f):
             try:
                 return str(f[0])
-            except:
+            except Exception:
                 return ''
         m = oeb.metadata
         for x in ('left', 'top', 'right', 'bottom'):
diff --git a/src/calibre/ebooks/conversion/plugins/mobi_input.py b/src/calibre/ebooks/conversion/plugins/mobi_input.py
index 177df9f0bd..0c7d2faba4 100644
--- a/src/calibre/ebooks/conversion/plugins/mobi_input.py
+++ b/src/calibre/ebooks/conversion/plugins/mobi_input.py
@@ -30,7 +30,7 @@ class MOBIInput(InputFormatPlugin):
             if mr.kf8_type is None:
                 mr.extract_content('.', parse_cache)
 
-        except:
+        except Exception:
             mr = MobiReader(stream, log, options.input_encoding,
                         options.debug_pipeline, try_extra_data_fix=True)
             if mr.kf8_type is None:
diff --git a/src/calibre/ebooks/conversion/plugins/oeb_output.py b/src/calibre/ebooks/conversion/plugins/oeb_output.py
index c106b2b508..fba7bc2543 100644
--- a/src/calibre/ebooks/conversion/plugins/oeb_output.py
+++ b/src/calibre/ebooks/conversion/plugins/oeb_output.py
@@ -36,12 +36,12 @@ class OEBOutput(OutputFormatPlugin):
                     if key == OPF_MIME:
                         try:
                             self.workaround_nook_cover_bug(root)
-                        except:
+                        except Exception:
                             self.log.exception('Something went wrong while trying to'
                                     ' workaround Nook cover bug, ignoring')
                         try:
                             self.workaround_pocketbook_cover_bug(root)
-                        except:
+                        except Exception:
                             self.log.exception('Something went wrong while trying to'
                                     ' workaround Pocketbook cover bug, ignoring')
                         self.migrate_lang_code(root)
diff --git a/src/calibre/ebooks/conversion/plugins/pdf_output.py b/src/calibre/ebooks/conversion/plugins/pdf_output.py
index 79f9ee0293..e7b0a25dd7 100644
--- a/src/calibre/ebooks/conversion/plugins/pdf_output.py
+++ b/src/calibre/ebooks/conversion/plugins/pdf_output.py
@@ -216,7 +216,7 @@ class PDFOutput(OutputFormatPlugin):
                     try:
                         s = rule.style
                         src = s.getProperty('src').propertyValue[0].uri
-                    except:
+                    except Exception:
                         continue
                     path = item.abshref(src)
                     ff = self.oeb.manifest.hrefs.get(urlnormalize(path), None)
@@ -228,7 +228,7 @@ class PDFOutput(OutputFormatPlugin):
                         processed.add(path)
                         try:
                             nraw = remove_embed_restriction(raw)
-                        except:
+                        except Exception:
                             continue
                         if nraw != raw:
                             ff.data = nraw
diff --git a/src/calibre/ebooks/conversion/plugins/recipe_input.py b/src/calibre/ebooks/conversion/plugins/recipe_input.py
index 9ebac38d85..449eb1ddcc 100644
--- a/src/calibre/ebooks/conversion/plugins/recipe_input.py
+++ b/src/calibre/ebooks/conversion/plugins/recipe_input.py
@@ -113,7 +113,7 @@ class RecipeInput(InputFormatPlugin):
                         log.warn(
                         'Downloaded recipe needs calibre version at least: {}'.format('.'.join(recipe.requires_version)))
                         builtin = True
-                except:
+                except Exception:
                     log.exception('Failed to compile downloaded recipe. Falling '
                             'back to builtin one')
                     builtin = True
diff --git a/src/calibre/ebooks/conversion/plugins/rtf_input.py b/src/calibre/ebooks/conversion/plugins/rtf_input.py
index b0b813406c..5c4d347f14 100644
--- a/src/calibre/ebooks/conversion/plugins/rtf_input.py
+++ b/src/calibre/ebooks/conversion/plugins/rtf_input.py
@@ -66,7 +66,7 @@ class RTFInput(InputFormatPlugin):
                 run_lev = 4
                 indent_out = 1
                 self.log('Running RTFParser in debug mode')
-            except:
+            except Exception:
                 self.log.warn('Impossible to run RTFParser in debug mode')
         parser = ParseRtf(
             in_file=stream,
@@ -154,7 +154,7 @@ class RTFInput(InputFormatPlugin):
         for count, val in iteritems(imap):
             try:
                 imap[count] = self.convert_image(val)
-            except:
+            except Exception:
                 self.log.exception('Failed to convert', val)
         return imap
 
@@ -270,7 +270,7 @@ class RTFInput(InputFormatPlugin):
             imap = {}
             try:
                 imap = self.extract_images(d[0])
-            except:
+            except Exception:
                 self.log.exception('Failed to extract images...')
 
         self.log('Parsing XML...')
diff --git a/src/calibre/ebooks/conversion/plugins/snb_input.py b/src/calibre/ebooks/conversion/plugins/snb_input.py
index af5f7e625d..3df5283a77 100644
--- a/src/calibre/ebooks/conversion/plugins/snb_input.py
+++ b/src/calibre/ebooks/conversion/plugins/snb_input.py
@@ -37,7 +37,7 @@ class SNBInput(InputFormatPlugin):
         snbFile = SNBFile()
         try:
             snbFile.Parse(stream)
-        except:
+        except Exception:
             raise ValueError('Invalid SNB file')
         if not snbFile.IsValid():
             log.debug('Invalid SNB file')
diff --git a/src/calibre/ebooks/conversion/plumber.py b/src/calibre/ebooks/conversion/plumber.py
index 1866abef2e..b59d67c0df 100644
--- a/src/calibre/ebooks/conversion/plumber.py
+++ b/src/calibre/ebooks/conversion/plumber.py
@@ -894,7 +894,7 @@ OptionRecommendation(name='search_replace',
                 elif x in ('timestamp', 'pubdate'):
                     try:
                         val = parse_date(val, assume_utc=x=='timestamp')
-                    except:
+                    except Exception:
                         self.log.exception(_('Failed to parse date/time') + ' ' + str(val))
                         continue
                 setattr(mi, x, val)
@@ -987,7 +987,7 @@ OptionRecommendation(name='search_replace',
                 for x in ('username', 'password'):
                     odict.pop(x, None)
                 self.log.debug(pprint.pformat(odict))
-            except:
+            except Exception:
                 self.log.exception('Failed to get resolved conversion options')
 
     def flush(self):
diff --git a/src/calibre/ebooks/conversion/preprocess.py b/src/calibre/ebooks/conversion/preprocess.py
index 37e29203d9..1e20ca578a 100644
--- a/src/calibre/ebooks/conversion/preprocess.py
+++ b/src/calibre/ebooks/conversion/preprocess.py
@@ -212,7 +212,7 @@ class Dehyphenator:
         secondhalf = match.group('secondpart')
         try:
             wraptags = match.group('wraptags')
-        except:
+        except Exception:
             wraptags = ''
         hyphenated = str(firsthalf) + '-' + str(secondhalf)
         dehyphenated = str(firsthalf) + str(secondhalf)
@@ -226,7 +226,7 @@ class Dehyphenator:
             self.log('lookup word is: '+lookupword+', orig is: ' + hyphenated)
         try:
             searchresult = self.html.find(lookupword.lower())
-        except:
+        except Exception:
             return hyphenated
         if self.format == 'html_cleanup' or self.format == 'txt_cleanup':
             if self.html.find(lookupword) != -1 or searchresult != -1:
@@ -305,7 +305,7 @@ class CSSPreProcessor:
         end = match.group('end')
         try:
             start = match.group('start')
-        except:
+        except Exception:
             start = ''
         if end == ';':
             end = ''
diff --git a/src/calibre/ebooks/conversion/utils.py b/src/calibre/ebooks/conversion/utils.py
index 6518821379..b8ecffbb4d 100644
--- a/src/calibre/ebooks/conversion/utils.py
+++ b/src/calibre/ebooks/conversion/utils.py
@@ -601,7 +601,7 @@ class HeuristicProcessor:
                 if replacement_break.find('width') != -1:
                     try:
                         width = int(re.sub(r'.*?width(:|=)(?P\d+).*', r'\g', replacement_break))
-                    except:
+                    except Exception:
                         scene_break = hr_open+'
' self.log.warn('Invalid replacement scene break' ' expression, using default') @@ -733,7 +733,7 @@ class HeuristicProcessor: # other types of processing are attempted try: self.totalwords = self.get_word_count(html) - except: + except Exception: self.log.warn("Can't get wordcount") if self.totalwords < 50: diff --git a/src/calibre/ebooks/docx/cleanup.py b/src/calibre/ebooks/docx/cleanup.py index 5fed992ad1..4cee3a633a 100644 --- a/src/calibre/ebooks/docx/cleanup.py +++ b/src/calibre/ebooks/docx/cleanup.py @@ -230,7 +230,7 @@ def cleanup_markup(log, root, styles, dest_dir, detect_cover, XPath, uuid): try: with open(path, 'rb') as imf: fmt, width, height = identify(imf) - except: + except Exception: width, height, fmt = 0, 0, None del fmt try: diff --git a/src/calibre/ebooks/docx/container.py b/src/calibre/ebooks/docx/container.py index 28b7981412..a043f3a8f1 100644 --- a/src/calibre/ebooks/docx/container.py +++ b/src/calibre/ebooks/docx/container.py @@ -111,7 +111,7 @@ class DOCX: try: zf = ZipFile(stream) zf.extractall(self.tdir) - except: + except Exception: self.log.exception('DOCX appears to be invalid ZIP file, trying a' ' more forgiving ZIP parser') from calibre.utils.localunzip import extractall diff --git a/src/calibre/ebooks/epub/periodical.py b/src/calibre/ebooks/epub/periodical.py index f4f599ef8c..87f9efabf5 100644 --- a/src/calibre/ebooks/epub/periodical.py +++ b/src/calibre/ebooks/epub/periodical.py @@ -87,17 +87,17 @@ def sony_metadata(oeb): try: pt = str(oeb.metadata.publication_type[0]) short_title = ':'.join(pt.split(':')[2:]) - except: + except Exception: pass try: date = parse_date(str(m.date[0]), as_utc=False).strftime('%Y-%m-%d') - except: + except Exception: date = strftime('%Y-%m-%d') try: language = str(m.language[0]).replace('_', '-') - except: + except Exception: language = 'en' short_title = xml(short_title, True) @@ -115,7 +115,7 @@ def sony_metadata(oeb): try: base_id = str(list(filter(cal_id, m.identifier))[0]) - except: + except Exception: base_id = str(uuid4()) toc = oeb.toc diff --git a/src/calibre/ebooks/fb2/fb2ml.py b/src/calibre/ebooks/fb2/fb2ml.py index 8a771d8810..4e05ddb127 100644 --- a/src/calibre/ebooks/fb2/fb2ml.py +++ b/src/calibre/ebooks/fb2/fb2ml.py @@ -433,7 +433,7 @@ class FB2MLizer: ems = round((float(style.marginTop) / style.fontSize) - 1) if ems < 0: ems = 0 - except: + except Exception: ems = 0 # Convert TOC entries to s and add <section>s diff --git a/src/calibre/ebooks/html_entities.py b/src/calibre/ebooks/html_entities.py index 397537923a..ec2a4f93f4 100644 --- a/src/calibre/ebooks/html_entities.py +++ b/src/calibre/ebooks/html_entities.py @@ -2153,7 +2153,7 @@ def entity_to_unicode_in_python(match, exceptions=(), encoding='cp1252', result_ num = int(ent[2:], 16) else: num = int(ent[1:]) - except: + except Exception: return '&'+ent+';' if encoding is None or num > 255: return check(my_unichr(num)) diff --git a/src/calibre/ebooks/lrf/html/convert_from.py b/src/calibre/ebooks/lrf/html/convert_from.py index 228341bdba..4c3ef1e51f 100644 --- a/src/calibre/ebooks/lrf/html/convert_from.py +++ b/src/calibre/ebooks/lrf/html/convert_from.py @@ -298,7 +298,7 @@ class HTMLConverter: self.add_file(path) except KeyboardInterrupt: raise - except: + except Exception: if self.link_level == 0: # Die on errors in the first level raise for link in self.links: @@ -370,7 +370,7 @@ class HTMLConverter: with open(os.path.join(tdir, 'html2lrf-verbose.html'), 'wb') as f: f.write(str(soup).encode('utf-8')) self.log.info(_('Written preprocessed HTML to ')+f.name) - except: + except Exception: pass return soup @@ -1521,7 +1521,7 @@ class HTMLConverter: try: width = int(tag['width']) height = int(tag['height']) - except: + except Exception: pass dropcaps = tag.get('class') in ('libprs500_dropcaps', ['libprs500_dropcaps']) self.process_image(path, tag_css, width, height, @@ -1579,7 +1579,7 @@ class HTMLConverter: self.list_counter = 1 try: self.list_counter = int(tag['start']) - except: + except Exception: pass prev_bs = self.current_block.blockStyle self.end_current_block() @@ -1949,7 +1949,7 @@ def try_opf(path, options, logger): try: PILImage.open(cover) options.cover = cover - except: + except Exception: pass if not getattr(options, 'cover', None) and orig_cover is not None: options.cover = orig_cover diff --git a/src/calibre/ebooks/lrf/html/table.py b/src/calibre/ebooks/lrf/html/table.py index 617196b474..b827ba2972 100644 --- a/src/calibre/ebooks/lrf/html/table.py +++ b/src/calibre/ebooks/lrf/html/table.py @@ -89,7 +89,7 @@ class Cell: try: self.colspan = int(tag['colspan']) if tag.has_attr('colspan') else 1 self.rowspan = int(tag['rowspan']) if tag.has_attr('rowspan') else 1 - except: + except Exception: pass pp = conv.current_page diff --git a/src/calibre/ebooks/lrf/input.py b/src/calibre/ebooks/lrf/input.py index 754838a126..42feaf03c8 100644 --- a/src/calibre/ebooks/lrf/input.py +++ b/src/calibre/ebooks/lrf/input.py @@ -321,7 +321,7 @@ class Styles(etree.XSLTExtension): def px_to_pt(self, px): try: return px * 72/166 - except: + except Exception: return None def color(self, val): @@ -333,7 +333,7 @@ class Styles(etree.XSLTExtension): if a == 0: return f'rgb({r},{g},{b})' return f'rgba({r},{g},{b},{1.0 - a / 255.0:f})' - except: + except Exception: return None def get_block_styles(self, node): @@ -364,7 +364,7 @@ class Styles(etree.XSLTExtension): def to_num(self, val, factor=1.): try: return float(val)*factor - except: + except Exception: return None def get_text_styles(self, node): diff --git a/src/calibre/ebooks/lrf/meta.py b/src/calibre/ebooks/lrf/meta.py index 435c0a7a54..76dd552e5b 100644 --- a/src/calibre/ebooks/lrf/meta.py +++ b/src/calibre/ebooks/lrf/meta.py @@ -277,13 +277,13 @@ def get_metadata(stream): mi.title_sort = lrf.title_reading.strip() if not mi.title_sort: mi.title_sort = None - except: + except Exception: pass try: mi.author_sort = lrf.author_reading.strip() if not mi.author_sort: mi.author_sort = None - except: + except Exception: pass if not mi.title or 'unknown' in mi.title.lower(): mi.title = None @@ -733,7 +733,7 @@ def main(args=sys.argv): if options.get_cover: try: ext, data = lrf.get_cover() - except: # Fails on books created by LRFCreator 1.0 + except Exception: # Fails on books created by LRFCreator 1.0 ext, data = None, None if data: cover = os.path.splitext(os.path.basename(args[1]))[0]+'_cover.'+ext diff --git a/src/calibre/ebooks/lrf/objects.py b/src/calibre/ebooks/lrf/objects.py index dc2994aec8..2c83493b9b 100644 --- a/src/calibre/ebooks/lrf/objects.py +++ b/src/calibre/ebooks/lrf/objects.py @@ -827,7 +827,7 @@ class Text(LRFStream): return pos-1 return find_first_tag(pos+1) - except: + except Exception: return find_first_tag(pos+1) start_pos = stream.tell() diff --git a/src/calibre/ebooks/lrf/pylrs/pylrs.py b/src/calibre/ebooks/lrf/pylrs/pylrs.py index 4de0ac55b6..d166d9b366 100644 --- a/src/calibre/ebooks/lrf/pylrs/pylrs.py +++ b/src/calibre/ebooks/lrf/pylrs/pylrs.py @@ -2414,11 +2414,11 @@ class Font(LrsContainer): try: _checkExists(fontfilename) self.truefile = fontfilename - except: + except Exception: try: _checkExists(file) self.truefile = file - except: + except Exception: raise LrsError(f"neither '{fontfilename}' nor '{file}' exists") self.file = file diff --git a/src/calibre/ebooks/metadata/__init__.py b/src/calibre/ebooks/metadata/__init__.py index 1da348443f..ef6b3134f6 100644 --- a/src/calibre/ebooks/metadata/__init__.py +++ b/src/calibre/ebooks/metadata/__init__.py @@ -170,7 +170,7 @@ def get_title_sort_pat(lang=None): ans = f'^({ans})' try: ans = re.compile(ans, re.IGNORECASE) - except: + except Exception: ans = re.compile(r'^(A|The|An)\s+', re.IGNORECASE) else: ans = re.compile(r'^$') # matches only the empty string @@ -279,7 +279,7 @@ class Resource: self.fragment = '' try: self.mime_type = guess_type(href_or_path)[0] - except: + except Exception: self.mime_type = None if self.mime_type is None: self.mime_type = 'application/octet-stream' diff --git a/src/calibre/ebooks/metadata/archive.py b/src/calibre/ebooks/metadata/archive.py index c86f1c5dcb..7da45b5ab9 100644 --- a/src/calibre/ebooks/metadata/archive.py +++ b/src/calibre/ebooks/metadata/archive.py @@ -23,7 +23,7 @@ def archive_type(stream): from calibre.utils.zipfile import stringFileHeader try: pos = stream.tell() - except: + except Exception: pos = 0 id_ = stream.read(4) ans = None diff --git a/src/calibre/ebooks/metadata/book/base.py b/src/calibre/ebooks/metadata/book/base.py index c957015e67..3da46333d6 100644 --- a/src/calibre/ebooks/metadata/book/base.py +++ b/src/calibre/ebooks/metadata/book/base.py @@ -123,7 +123,7 @@ class Metadata: null_val = NULL_VALUES.get(field, None) val = getattr(self, field, None) return not val or val == null_val - except: + except Exception: return True def set_null(self, field): @@ -139,7 +139,7 @@ class Metadata: if field == 'language': try: return _data.get('languages', [])[0] - except: + except Exception: return NULL_VALUES['language'] try: return object.__getattribute__(self, field) @@ -160,7 +160,7 @@ class Metadata: if field.startswith('#') and field.endswith('_index'): try: return self.get_extra(field[:-6]) - except: + except Exception: pass raise AttributeError( 'Metadata object has no attribute named: '+ repr(field)) @@ -251,7 +251,7 @@ class Metadata: if field in _data['user_metadata']: try: return _data['user_metadata'][field]['#extra#'] - except: + except Exception: return default raise AttributeError( 'Metadata object has no attribute named: '+ repr(field)) @@ -498,7 +498,7 @@ class Metadata: self.set(dest, [f.strip() for f in val.split('&') if f.strip()]) else: self.set(dest, val) - except: + except Exception: if DEBUG: traceback.print_exc() @@ -713,7 +713,7 @@ class Metadata: try: fmt = cmeta['display'].get('number_format', None) res = fmt.format(res) - except: + except Exception: pass return (name, str(res), orig_res, cmeta) diff --git a/src/calibre/ebooks/metadata/book/formatter.py b/src/calibre/ebooks/metadata/book/formatter.py index 7abb794987..0cfd3edd55 100644 --- a/src/calibre/ebooks/metadata/book/formatter.py +++ b/src/calibre/ebooks/metadata/book/formatter.py @@ -31,7 +31,7 @@ class SafeFormat(TemplateFormatter): raise ValueError(_('Value: unknown field ') + orig_key) try: b = self.book.get_user_metadata(key, False) - except: + except Exception: b = None if b and b['datatype'] in {'int', 'float'} and self.book.get(key, None) is None: v = '' diff --git a/src/calibre/ebooks/metadata/book/json_codec.py b/src/calibre/ebooks/metadata/book/json_codec.py index 9495bac505..62ec86f974 100644 --- a/src/calibre/ebooks/metadata/book/json_codec.py +++ b/src/calibre/ebooks/metadata/book/json_codec.py @@ -180,7 +180,7 @@ class JsonCodec: entry = self.raw_to_book(item, book_class, prefix) if entry is not None: booklist.append(entry) - except: + except Exception: print('exception during JSON decode_from_file') traceback.print_exc() @@ -196,7 +196,7 @@ class JsonCodec: key = 'identifiers' setattr(book, key, meta) return book - except: + except Exception: print('exception during JSON decoding') traceback.print_exc() diff --git a/src/calibre/ebooks/metadata/book/render.py b/src/calibre/ebooks/metadata/book/render.py index 03c94aa655..7336016e50 100644 --- a/src/calibre/ebooks/metadata/book/render.py +++ b/src/calibre/ebooks/metadata/book/render.py @@ -29,7 +29,7 @@ default_sort = ('title', 'title_sort', 'authors', 'author_sort', 'series', 'rati def field_sort(mi, name): try: title = mi.metadata_for_field(name)['name'] - except: + except Exception: title = 'zzz' return {x:(i, None) for i, x in enumerate(default_sort)}.get(name, (10000, sort_key(title))) @@ -38,7 +38,7 @@ def displayable_field_keys(mi): for k in mi.all_field_keys(): try: m = mi.metadata_for_field(k) - except: + except Exception: continue if ( m is not None and m.get('kind') == 'field' and m.get('datatype') is not None and @@ -187,7 +187,7 @@ def mi_to_html( for field in (field for field, display in field_list if display): try: metadata = mi.metadata_for_field(field) - except: + except Exception: continue if not metadata: continue @@ -485,7 +485,7 @@ def mi_to_html( def classname(field): try: dt = mi.metadata_for_field(field)['datatype'] - except: + except Exception: dt = 'text' return f'datatype_{dt}' diff --git a/src/calibre/ebooks/metadata/epub.py b/src/calibre/ebooks/metadata/epub.py index ab640b5501..135c7ba4f3 100644 --- a/src/calibre/ebooks/metadata/epub.py +++ b/src/calibre/ebooks/metadata/epub.py @@ -97,7 +97,7 @@ class OCFReader(OCF): mimetype = self.read_bytes('mimetype').decode('utf-8').rstrip() if mimetype != OCF.MIMETYPE: print('WARNING: Invalid mimetype declaration', mimetype) - except: + except Exception: print("WARNING: Epub doesn't contain a valid mimetype declaration") try: diff --git a/src/calibre/ebooks/metadata/extz.py b/src/calibre/ebooks/metadata/extz.py index ebaa9b58fc..7ba88ab6e2 100644 --- a/src/calibre/ebooks/metadata/extz.py +++ b/src/calibre/ebooks/metadata/extz.py @@ -70,11 +70,11 @@ def set_metadata(stream, mi): new_cdata = mi.cover_data[1] if not new_cdata: raise Exception('no cover') - except: + except Exception: try: with open(mi.cover, 'rb') as f: new_cdata = f.read() - except: + except Exception: pass if new_cdata: cpath = opf.raster_cover @@ -94,7 +94,7 @@ def set_metadata(stream, mi): if cpath is not None: replacements[cpath].close() os.remove(replacements[cpath].name) - except: + except Exception: pass diff --git a/src/calibre/ebooks/metadata/fb2.py b/src/calibre/ebooks/metadata/fb2.py index 0f9ea63e2e..e378ccb9a8 100644 --- a/src/calibre/ebooks/metadata/fb2.py +++ b/src/calibre/ebooks/metadata/fb2.py @@ -123,36 +123,36 @@ def get_metadata(stream): try: _parse_cover(root, mi, ctx) - except: + except Exception: pass try: _parse_comments(root, mi, ctx) - except: + except Exception: pass try: _parse_tags(root, mi, ctx) - except: + except Exception: pass try: _parse_series(root, mi, ctx) - except: + except Exception: pass try: _parse_isbn(root, mi, ctx) - except: + except Exception: pass try: _parse_publisher(root, mi, ctx) - except: + except Exception: pass try: _parse_pubdate(root, mi, ctx) - except: + except Exception: pass try: _parse_language(root, mi, ctx) - except: + except Exception: pass return mi @@ -218,7 +218,7 @@ def _parse_cover(root, mi, ctx): if imgid: try: _parse_cover_data(root, imgid, mi, ctx) - except: + except Exception: pass @@ -385,7 +385,7 @@ def _set_series(title_info, mi, ctx): seq.set('name', mi.series) try: seq.set('number', f'{mi.series_index:g}') - except: + except Exception: seq.set('number', '1') diff --git a/src/calibre/ebooks/metadata/html.py b/src/calibre/ebooks/metadata/html.py index ead1ebc35a..47d1c11e04 100644 --- a/src/calibre/ebooks/metadata/html.py +++ b/src/calibre/ebooks/metadata/html.py @@ -184,7 +184,7 @@ def get_metadata_(src, encoding=None): for field in ('pubdate', 'timestamp'): try: val = parse_date(get(field)) - except: + except Exception: pass else: if not is_date_undefined(val): @@ -199,7 +199,7 @@ def get_metadata_(src, encoding=None): if match is not None: try: series_index = float(match.group(1)) - except: + except Exception: pass series = series.replace(match.group(), '').strip() mi.series = series @@ -207,7 +207,7 @@ def get_metadata_(src, encoding=None): series_index = get('series_index') try: series_index = float(series_index) - except: + except Exception: pass if series_index is not None: mi.series_index = series_index @@ -221,7 +221,7 @@ def get_metadata_(src, encoding=None): mi.rating = 0 if mi.rating > 10: mi.rating = 0 - except: + except Exception: pass # TAGS diff --git a/src/calibre/ebooks/metadata/lrx.py b/src/calibre/ebooks/metadata/lrx.py index 809dd122f5..b2c5827454 100644 --- a/src/calibre/ebooks/metadata/lrx.py +++ b/src/calibre/ebooks/metadata/lrx.py @@ -48,7 +48,7 @@ def get_metadata(f): offset += word_be(buf[:4]) try: buf = read(offset, 8) - except: + except Exception: raise ValueError('Not a valid LRX file') if buf[4:] == b'bbeb': break diff --git a/src/calibre/ebooks/metadata/meta.py b/src/calibre/ebooks/metadata/meta.py index 03f2a2d6f9..d9b03533e4 100644 --- a/src/calibre/ebooks/metadata/meta.py +++ b/src/calibre/ebooks/metadata/meta.py @@ -32,7 +32,7 @@ def path_to_ext(path): def metadata_from_formats(formats, force_read_metadata=False, pattern=None): try: return _metadata_from_formats(formats, force_read_metadata, pattern) - except: + except Exception: mi = metadata_from_filename(list(iter(formats))[0], pat=pattern) if not mi.authors: mi.authors = [_('Unknown')] @@ -193,7 +193,7 @@ def metadata_from_filename(name, pat=None, fallback_pat=None): if pubdate: from calibre.utils.date import parse_only_date mi.pubdate = parse_only_date(pubdate) - except: + except Exception: pass try: comments = match.group('comments') diff --git a/src/calibre/ebooks/metadata/mobi.py b/src/calibre/ebooks/metadata/mobi.py index a8f447c7fa..9432930106 100644 --- a/src/calibre/ebooks/metadata/mobi.py +++ b/src/calibre/ebooks/metadata/mobi.py @@ -343,7 +343,7 @@ class MetadataUpdater: pas = prefs.get('prefer_author_sort', False) kindle_pdoc = prefs.get('personal_doc', None) share_not_sync = prefs.get('share_not_sync', False) - except: + except Exception: pas = False kindle_pdoc = None share_not_sync = False @@ -452,7 +452,7 @@ class MetadataUpdater: if not data: with open(mi.cover, 'rb') as f: data = f.read() - except: + except Exception: pass else: if is_image(self.cover_record): @@ -496,7 +496,7 @@ def get_metadata(stream): log = Log() try: mi = MetaInformation(os.path.basename(stream.name), [_('Unknown')]) - except: + except Exception: mi = MetaInformation(_('Unknown'), [_('Unknown')]) mh = MetadataHeader(stream, log) if mh.title and mh.title != _('Unknown'): diff --git a/src/calibre/ebooks/metadata/opf2.py b/src/calibre/ebooks/metadata/opf2.py index 1fbe725b11..9f47019830 100644 --- a/src/calibre/ebooks/metadata/opf2.py +++ b/src/calibre/ebooks/metadata/opf2.py @@ -77,7 +77,7 @@ class Resource: # {{{ self.fragment = '' try: self.mime_type = guess_type(href_or_path)[0] - except: + except Exception: self.mime_type = None if self.mime_type is None: self.mime_type = 'application/octet-stream' @@ -339,7 +339,7 @@ class Spine(ResourceCollection): # {{{ for path in paths: try: s.append(Spine.Item(s.manifest.id_for_path, path, is_path=True)) - except: + except Exception: continue return s @@ -402,7 +402,7 @@ class Guide(ResourceCollection): # {{{ try: ref = Guide.Reference.from_opf_resource_item(ref, base_dir) coll.append(ref) - except: + except Exception: continue return coll @@ -438,7 +438,7 @@ class MetadataField: if self.formatter is not None: try: ans = self.formatter(ans) - except: + except Exception: return None if hasattr(ans, 'strip'): ans = ans.strip() @@ -534,7 +534,7 @@ def serialize_user_metadata(metadata_elem, all_user_metadata, tail='\n'+(' '*8)) encode_is_multiple(fm) fm = object_to_unicode(fm) fm = json.dumps(fm, default=to_json, ensure_ascii=False) - except: + except Exception: prints('Failed to write user metadata:', name) import traceback traceback.print_exc() @@ -687,7 +687,7 @@ class OPF: # {{{ fm = json.loads(fm, object_hook=from_json) decode_is_multiple(fm) temp.set_user_metadata(name, fm) - except: + except Exception: prints('Failed to read user metadata:', name) import traceback traceback.print_exc() @@ -766,7 +766,7 @@ class OPF: # {{{ not os.path.isfile(self.path_to_html_toc): self.path_to_html_toc = None self.toc.read_html_toc(toc) - except: + except Exception: pass def get_text(self, elem): @@ -964,7 +964,7 @@ class OPF: # {{{ try: val = parse_date(etree.tostring(match, encoding='unicode', method='text', with_tail=False).strip()) - except: + except Exception: continue if ans is None or val < ans: ans = val @@ -977,7 +977,7 @@ class OPF: # {{{ try: cval = parse_date(etree.tostring(match, encoding='unicode', method='text', with_tail=False).strip()) - except: + except Exception: match.getparent().remove(match) else: if not val: diff --git a/src/calibre/ebooks/metadata/opf3.py b/src/calibre/ebooks/metadata/opf3.py index 9855854890..8837368ff5 100644 --- a/src/calibre/ebooks/metadata/opf3.py +++ b/src/calibre/ebooks/metadata/opf3.py @@ -799,7 +799,7 @@ def read_series(root, prefixes, refines): try: series_index = float(si) break - except: + except Exception: pass for s in XPath('./opf:metadata/opf:meta[@name="calibre:series"]/@content')(root): s = normalize_whitespace(s) diff --git a/src/calibre/ebooks/metadata/sources/amazon.py b/src/calibre/ebooks/metadata/sources/amazon.py index d1e337cdae..de27f97440 100644 --- a/src/calibre/ebooks/metadata/sources/amazon.py +++ b/src/calibre/ebooks/metadata/sources/amazon.py @@ -410,7 +410,7 @@ class Worker(Thread): # Get details {{{ def run(self): try: self.get_details() - except: + except Exception: self.log.exception('get_details failed for url: %r' % self.url) def get_details(self): @@ -439,13 +439,13 @@ class Worker(Thread): # Get details {{{ try: title = self.parse_title(root) - except: + except Exception: self.log.exception('Error parsing title for url: %r' % self.url) title = None try: authors = self.parse_authors(root) - except: + except Exception: self.log.exception('Error parsing authors for url: %r' % self.url) authors = [] @@ -463,12 +463,12 @@ class Worker(Thread): # Get details {{{ try: mi.rating = self.parse_rating(root) - except: + except Exception: self.log.exception('Error parsing ratings for url: %r' % self.url) try: mi.comments = self.parse_comments(root, raw) - except: + except Exception: self.log.exception('Error parsing comments for url: %r' % self.url) try: @@ -477,17 +477,17 @@ class Worker(Thread): # Get details {{{ mi.series, mi.series_index = series, series_index elif self.testing: mi.series, mi.series_index = 'Dummy series for testing', 1 - except: + except Exception: self.log.exception('Error parsing series for url: %r' % self.url) try: mi.tags = self.parse_tags(root) - except: + except Exception: self.log.exception('Error parsing tags for url: %r' % self.url) try: self.cover_url = self.parse_cover(root, raw) - except: + except Exception: self.log.exception('Error parsing cover for url: %r' % self.url) if self.cover_url_processor is not None and self.cover_url and self.cover_url.startswith('/'): self.cover_url = self.cover_url_processor(self.cover_url) @@ -503,7 +503,7 @@ class Worker(Thread): # Get details {{{ elif non_hero: try: self.parse_new_details(root, mi, non_hero[0]) - except: + except Exception: self.log.exception( 'Failed to parse new-style book details section') elif feature_and_detail_bullets: @@ -518,19 +518,19 @@ class Worker(Thread): # Get details {{{ isbn = self.parse_isbn(pd) if isbn: self.isbn = mi.isbn = isbn - except: + except Exception: self.log.exception( 'Error parsing ISBN for url: %r' % self.url) try: mi.publisher = self.parse_publisher(pd) - except: + except Exception: self.log.exception( 'Error parsing publisher for url: %r' % self.url) try: mi.pubdate = self.parse_pubdate(pd) - except: + except Exception: self.log.exception( 'Error parsing publish date for url: %r' % self.url) @@ -538,7 +538,7 @@ class Worker(Thread): # Get details {{{ lang = self.parse_language(pd) if lang: mi.language = lang - except: + except Exception: self.log.exception( 'Error parsing language for url: %r' % self.url) @@ -1025,7 +1025,7 @@ class Worker(Thread): # Get details {{{ from calibre.utils.date import parse_only_date date = self.delocalize_datestr(date) mi.pubdate = parse_only_date(date, assume_utc=True) - except: + except Exception: self.log.exception('Failed to parse pubdate: %s' % val) elif name in {'ISBN', 'ISBN-10', 'ISBN-13'}: ans = check_isbn(val) @@ -1762,7 +1762,7 @@ class Amazon(Source): cdata = br.open_novisit( cached_url, timeout=timeout).read() result_queue.put((self, cdata)) - except: + except Exception: log.exception('Failed to download cover from:', cached_url) # }}} diff --git a/src/calibre/ebooks/metadata/sources/covers.py b/src/calibre/ebooks/metadata/sources/covers.py index 270e09738b..bd3572a540 100644 --- a/src/calibre/ebooks/metadata/sources/covers.py +++ b/src/calibre/ebooks/metadata/sources/covers.py @@ -46,7 +46,7 @@ class Worker(Thread): self.plugin.download_cover(self.log, self.rq, self.abort, title=self.title, authors=self.authors, identifiers=self.identifiers, timeout=self.timeout) - except: + except Exception: self.log.exception('Failed to download cover from', self.plugin.name) self.time_spent = time.time() - start_time diff --git a/src/calibre/ebooks/metadata/sources/edelweiss.py b/src/calibre/ebooks/metadata/sources/edelweiss.py index 55c1d3baf5..1f7531333b 100644 --- a/src/calibre/ebooks/metadata/sources/edelweiss.py +++ b/src/calibre/ebooks/metadata/sources/edelweiss.py @@ -54,7 +54,7 @@ class Worker(Thread): # {{{ 'sku={0}&idPrefix=content_1_{0}&mode=0'.format(self.sku)) try: raw = self.br.open_novisit(url, timeout=self.timeout).read() - except: + except Exception: self.log.exception('Failed to load comments page: %r'%url) return @@ -63,7 +63,7 @@ class Worker(Thread): # {{{ mi.source_relevance = self.relevance self.plugin.clean_downloaded_metadata(mi) self.result_queue.put(mi) - except: + except Exception: self.log.exception('Failed to parse details for sku: %s'%self.sku) def parse(self, raw): @@ -375,7 +375,7 @@ class Edelweiss(Source): try: cdata = br.open_novisit(cached_url, timeout=timeout).read() result_queue.put((self, cdata)) - except: + except Exception: log.exception('Failed to download cover from:', cached_url) # }}} diff --git a/src/calibre/ebooks/metadata/sources/google.py b/src/calibre/ebooks/metadata/sources/google.py index 7dc6c3fc6c..8777babc88 100644 --- a/src/calibre/ebooks/metadata/sources/google.py +++ b/src/calibre/ebooks/metadata/sources/google.py @@ -101,7 +101,7 @@ def to_metadata(browser, log, entry_, timeout, running_a_test=False): # {{{ ans = ans[0].text if ans and ans.strip(): return ans.strip() - except: + except Exception: log.exception('Programming error:') return None @@ -170,7 +170,7 @@ def to_metadata(browser, log, entry_, timeout, running_a_test=False): # {{{ for tag in atags: if tag not in tags: tags.append(tag) - except: + except Exception: log.exception('Failed to parse tags:') tags = [] if tags: @@ -183,7 +183,7 @@ def to_metadata(browser, log, entry_, timeout, running_a_test=False): # {{{ try: default = utcnow().replace(day=15) mi.pubdate = parse_date(pubdate, assume_utc=True, default=default) - except: + except Exception: log.error('Failed to parse pubdate %r' % pubdate) # Cover @@ -469,7 +469,7 @@ class GoogleBooks(Source): ans = self.postprocess_downloaded_google_metadata(ans, relevance) result_queue.put(ans) found = True - except: + except Exception: log.exception('Failed to get metadata for google books id:', gid) if abort.is_set(): break diff --git a/src/calibre/ebooks/metadata/sources/identify.py b/src/calibre/ebooks/metadata/sources/identify.py index 584922e47d..407fe83f57 100644 --- a/src/calibre/ebooks/metadata/sources/identify.py +++ b/src/calibre/ebooks/metadata/sources/identify.py @@ -45,7 +45,7 @@ class Worker(Thread): start = time.time() try: self.plugin.identify(self.log, self.rq, self.abort, **self.kwargs) - except: + except Exception: self.log.exception('Plugin', self.plugin.name, 'failed') self.plugin.dl_time_spent = time.time() - start diff --git a/src/calibre/ebooks/metadata/sources/worker.py b/src/calibre/ebooks/metadata/sources/worker.py index 66d5122ad8..ddf1a591f7 100644 --- a/src/calibre/ebooks/metadata/sources/worker.py +++ b/src/calibre/ebooks/metadata/sources/worker.py @@ -81,7 +81,7 @@ def main(do_identify, covers, metadata, ensure_fields, tdir): try: results = identify(log, Event(), title=title, authors=authors, identifiers=identifiers) - except: + except Exception: pass if results: all_failed = False diff --git a/src/calibre/ebooks/metadata/toc.py b/src/calibre/ebooks/metadata/toc.py index 0b164b154b..d49d3ff710 100644 --- a/src/calibre/ebooks/metadata/toc.py +++ b/src/calibre/ebooks/metadata/toc.py @@ -138,7 +138,7 @@ class TOC(list): if toc is None: try: toc = opfreader.soup.find('guide').find('reference', attrs={'type':'toc'})['href'] - except: + except Exception: for item in opfreader.manifest: if 'toc' in item.href().lower(): toc = item.href() @@ -157,7 +157,7 @@ class TOC(list): toc = os.path.join(os.path.dirname(toc), bn) self.read_html_toc(toc) - except: + except Exception: print('WARNING: Could not read Table of Contents. Continuing anyway.') else: path = opfreader.manifest.item(toc.lower()) @@ -198,7 +198,7 @@ class TOC(list): def process_navpoint(np, dest): try: play_order = int(get_attr(np, 1)) - except: + except Exception: play_order = 1 href = fragment = text = None nd = dest diff --git a/src/calibre/ebooks/metadata/topaz.py b/src/calibre/ebooks/metadata/topaz.py index 374da028e0..4d428e4a43 100644 --- a/src/calibre/ebooks/metadata/topaz.py +++ b/src/calibre/ebooks/metadata/topaz.py @@ -341,7 +341,7 @@ class MetadataUpdater: from calibre.ebooks.conversion.config import load_defaults prefs = load_defaults('mobi_output') pas = prefs.get('prefer_author_sort', False) - except: + except Exception: pas = False if mi.author_sort and pas: diff --git a/src/calibre/ebooks/metadata/xisbn.py b/src/calibre/ebooks/metadata/xisbn.py index 732efdc47c..c77315c30d 100644 --- a/src/calibre/ebooks/metadata/xisbn.py +++ b/src/calibre/ebooks/metadata/xisbn.py @@ -60,7 +60,7 @@ class xISBN: if isbn not in self._map: try: data = self.fetch_data(isbn) - except: + except Exception: import traceback traceback.print_exc() data = [] @@ -92,7 +92,7 @@ class xISBN: year = int(x['year']) if year < min_year: min_year = year - except: + except Exception: continue if min_year == 100000: min_year = None diff --git a/src/calibre/ebooks/metadata/xmp.py b/src/calibre/ebooks/metadata/xmp.py index c52a31d03a..fab264cf25 100644 --- a/src/calibre/ebooks/metadata/xmp.py +++ b/src/calibre/ebooks/metadata/xmp.py @@ -192,7 +192,7 @@ def read_user_metadata(mi, root): decode_is_multiple(fm) mi.set_user_metadata(name, fm) fields.add(name) - except: + except Exception: prints('Failed to read user metadata:', name) import traceback traceback.print_exc() @@ -263,7 +263,7 @@ def metadata_from_xmp_packet(raw_bytes): mi.publisher = publishers[0] try: pubdate = parse_date(first_sequence('//dc:date', root) or first_simple('//xmp:CreateDate', root), assume_utc=False) - except: + except Exception: pass else: mi.pubdate = pubdate @@ -458,7 +458,7 @@ def create_user_metadata(calibre, all_user_metadata): encode_is_multiple(fm) fm = object_to_unicode(fm) fm = json.dumps(fm, default=to_json, ensure_ascii=False) - except: + except Exception: prints('Failed to write user metadata:', name) import traceback traceback.print_exc() diff --git a/src/calibre/ebooks/metadata/zip.py b/src/calibre/ebooks/metadata/zip.py index ec6f575cb1..2883144f17 100644 --- a/src/calibre/ebooks/metadata/zip.py +++ b/src/calibre/ebooks/metadata/zip.py @@ -35,7 +35,7 @@ def get_metadata(stream): nmi = zip_opf_metadata(path, zf) nmi.timestamp = None return nmi - except: + except Exception: pass mi.timestamp = None return mi diff --git a/src/calibre/ebooks/mobi/debug/main.py b/src/calibre/ebooks/mobi/debug/main.py index b2edacd7d6..15ee2bb12a 100644 --- a/src/calibre/ebooks/mobi/debug/main.py +++ b/src/calibre/ebooks/mobi/debug/main.py @@ -22,7 +22,7 @@ def inspect_mobi(path_or_stream, ddir=None): # {{{ ddir = 'decompiled_' + os.path.splitext(os.path.basename(stream.name))[0] try: shutil.rmtree(ddir) - except: + except Exception: pass os.makedirs(ddir) if f.kf8_type is None: diff --git a/src/calibre/ebooks/mobi/debug/mobi6.py b/src/calibre/ebooks/mobi/debug/mobi6.py index 7ea630cf18..21acbcda29 100644 --- a/src/calibre/ebooks/mobi/debug/mobi6.py +++ b/src/calibre/ebooks/mobi/debug/mobi6.py @@ -451,7 +451,7 @@ class CNCX: # {{{ try: self.records[pos+record_offset] = raw[ pos+consumed:pos+consumed+length].decode(codec) - except: + except Exception: byts = raw[pos:] r = format_bytes(byts) print(f'CNCX entry at offset {pos + record_offset} has unknown format {r}') @@ -612,7 +612,7 @@ class TBSIndexing: # {{{ try: byts, a = self.interpret_periodical(tbs_type, byts, dat['geom'][0]) - except: + except Exception: import traceback traceback.print_exc() a = [] @@ -755,7 +755,7 @@ class MOBIFile: # {{{ b'AUDI', b'VIDE', b'FONT', b'CRES', b'CONT', b'CMET'}: try: fmt = what(None, r.raw) - except: + except Exception: pass if fmt is not None: self.image_records.append(ImageRecord(image_index, r, fmt)) diff --git a/src/calibre/ebooks/mobi/debug/mobi8.py b/src/calibre/ebooks/mobi/debug/mobi8.py index 0fa06c5bdd..2f413c3e77 100644 --- a/src/calibre/ebooks/mobi/debug/mobi8.py +++ b/src/calibre/ebooks/mobi/debug/mobi8.py @@ -277,7 +277,7 @@ class MOBIFile: while tbs_bytes: try: val, extra, consumed = decode_tbs(tbs_bytes, flag_size=flag_sz) - except: + except Exception: break flag_sz = 4 tbs_bytes = tbs_bytes[consumed:] @@ -291,7 +291,7 @@ class MOBIFile: tbs_type=tbs_type) try: calculated_bytes = sequences_to_bytes(calculated_sequences) - except: + except Exception: calculated_bytes = b'failed to calculate tbs bytes' if calculated_bytes != otbs: print(f'WARNING: TBS mismatch for record {i}') diff --git a/src/calibre/ebooks/mobi/mobiml.py b/src/calibre/ebooks/mobi/mobiml.py index 0e2376c147..066d2125b9 100644 --- a/src/calibre/ebooks/mobi/mobiml.py +++ b/src/calibre/ebooks/mobi/mobiml.py @@ -252,7 +252,7 @@ class MobiMLizer: pstate = bstate.istate = None try: etree.SubElement(para, XHTML(tag), attrib=istate.attrib) - except: + except Exception: print('Invalid subelement:', para, tag, istate.attrib) raise elif tag in TABLE_TAGS: @@ -263,7 +263,7 @@ class MobiMLizer: if tag == 'li': try: last = bstate.body[-1][-1] - except: + except Exception: break last.insert(0, anchor) anchor.tail = last.text @@ -357,7 +357,7 @@ class MobiMLizer: if tag == 'ol' and 'start' in elem.attrib: try: istate.list_num = int(elem.attrib['start'])-1 - except: + except Exception: pass istates.append(istate) left = 0 @@ -461,7 +461,7 @@ class MobiMLizer: try: pixs = round(float(value) / (72/self.profile.dpi)) - except: + except Exception: continue result = str(pixs) istate.attrib[prop] = result @@ -469,7 +469,7 @@ class MobiMLizer: href = self.current_spine_item.abshref(elem.attrib['src']) try: item = self.oeb.manifest.hrefs[urlnormalize(href)] - except: + except Exception: self.oeb.logger.warn('Failed to find image:', href) else: @@ -487,13 +487,13 @@ class MobiMLizer: if 'width' not in istate.attrib: try: width = int(istate.attrib['height'])*ar - except: + except Exception: pass istate.attrib['width'] = str(int(width)) else: try: height = int(istate.attrib['width'])/ar - except: + except Exception: pass istate.attrib['height'] = str(int(height)) item.unload_data_from_memory() @@ -593,7 +593,7 @@ class MobiMLizer: try: value = int(elem.attrib['value']) istates[-2].list_num = value - 1 - except: + except Exception: pass self.mobimlize_content(tag, text, bstate, istates) for child in elem: diff --git a/src/calibre/ebooks/mobi/reader/headers.py b/src/calibre/ebooks/mobi/reader/headers.py index 2c61f30849..8d34653cc4 100644 --- a/src/calibre/ebooks/mobi/reader/headers.py +++ b/src/calibre/ebooks/mobi/reader/headers.py @@ -169,7 +169,7 @@ class EXTHHeader: # {{{ cid = content[len('calibre:'):] if cid: self.mi.application_id = self.mi.uuid = cid - except: + except Exception: pass elif idx == 113: # ASIN or other id try: @@ -259,9 +259,9 @@ class BookHeader: if self.exth.mi.is_null('language'): try: self.exth.mi.language = mobi2iana(langid, sublangid) - except: + except Exception: self.log.exception('Unknown language code') - except: + except Exception: self.log.exception('Invalid EXTH header') self.exth_flag = 0 diff --git a/src/calibre/ebooks/mobi/reader/index.py b/src/calibre/ebooks/mobi/reader/index.py index aade17312f..70af01b5e0 100644 --- a/src/calibre/ebooks/mobi/reader/index.py +++ b/src/calibre/ebooks/mobi/reader/index.py @@ -100,7 +100,7 @@ class CNCX: # {{{ try: self.records[pos+record_offset] = raw[ pos+consumed:pos+consumed+length].decode(codec) - except: + except Exception: byts = raw[pos:] r = format_bytes(byts) print(f'CNCX entry at offset {pos + record_offset} has unknown format {r}') diff --git a/src/calibre/ebooks/mobi/reader/mobi6.py b/src/calibre/ebooks/mobi/reader/mobi6.py index 0628c5c47b..00aa4a844b 100644 --- a/src/calibre/ebooks/mobi/reader/mobi6.py +++ b/src/calibre/ebooks/mobi/reader/mobi6.py @@ -129,7 +129,7 @@ class MobiReader: elif k8i is not None: # Check for joint mobi 6 and kf 8 file try: raw = self.sections[k8i-1][0] - except: + except Exception: raw = None if raw == b'BOUNDARY': try: @@ -149,14 +149,14 @@ class MobiReader: self.kf8_type = 'joint' self.kf8_boundary = k8i-1 - except: + except Exception: self.book_header = bh def check_for_drm(self): if self.book_header.encryption_type != 0: try: name = self.book_header.exth.mi.title - except: + except Exception: name = self.name if not name: name = self.name @@ -475,14 +475,14 @@ class MobiReader: try: ewidth_val = unit_convert(ewidth, 12, 500, 166) self.text_indents[tag] = ewidth_val - except: + except Exception: pass if width.startswith('-'): styles.append(f'margin-left: {self.ensure_unit(width[1:])}') try: ewidth_val = unit_convert(ewidth[1:], 12, 500, 166) self.left_margins[tag] = ewidth_val - except: + except Exception: pass if 'align' in attrib: @@ -534,7 +534,7 @@ class MobiReader: nval = float(val[:-2]) nval *= 16 * (168.451/72) # Assume this was set using the Kindle profile attrib[attr] = f'{int(nval)}px' - except: + except Exception: del attrib[attr] elif val.lower().endswith('%'): del attrib[attr] @@ -636,11 +636,11 @@ class MobiReader: ti = self.text_indents.get(tag, ti) try: lm = float(lm) - except: + except Exception: lm = 0.0 try: ti = float(ti) - except: + except Exception: ti = 0.0 return lm + ti @@ -718,7 +718,7 @@ class MobiReader: try: text = ' '.join([t.strip() for t in x.xpath('descendant::text()')]) - except: + except Exception: text = '' text = replace_entities(text) item = tocobj.add_item(toc.partition('#')[0], href[1:], diff --git a/src/calibre/ebooks/mobi/reader/mobi8.py b/src/calibre/ebooks/mobi/reader/mobi8.py index db0b943aae..648322134f 100644 --- a/src/calibre/ebooks/mobi/reader/mobi8.py +++ b/src/calibre/ebooks/mobi/reader/mobi8.py @@ -482,7 +482,7 @@ class Mobi8Reader: if os.path.exists(href.replace('/', os.sep)): try: toc = self.read_inline_toc(href, frag) - except: + except Exception: self.log.exception('Failed to read inline ToC') opf = OPFCreator(os.getcwd(), mi) @@ -502,7 +502,7 @@ class Mobi8Reader: if self.for_tweak: try: os.remove('debug-raw.html') - except: + except Exception: pass opf.create_manifest_from_files_in([os.getcwd()], exclude=exclude) diff --git a/src/calibre/ebooks/mobi/tweak.py b/src/calibre/ebooks/mobi/tweak.py index ae9928aafc..0f15b52fbc 100644 --- a/src/calibre/ebooks/mobi/tweak.py +++ b/src/calibre/ebooks/mobi/tweak.py @@ -33,7 +33,7 @@ def do_explode(path, dest): opf = os.path.abspath(mr()) try: os.remove('debug-raw.html') - except: + except Exception: pass return opf diff --git a/src/calibre/ebooks/mobi/utils.py b/src/calibre/ebooks/mobi/utils.py index e4a93ae9b3..09be029b3d 100644 --- a/src/calibre/ebooks/mobi/utils.py +++ b/src/calibre/ebooks/mobi/utils.py @@ -462,7 +462,7 @@ def read_font_record(data, extent=1040): try: usize, flags, dstart, xor_len, xor_start = struct.unpack_from( b'>LLLLL', data, 4) - except: + except Exception: ans['err'] = 'Failed to read font record header fields' return ans font_data = data[dstart:] diff --git a/src/calibre/ebooks/mobi/writer2/indexer.py b/src/calibre/ebooks/mobi/writer2/indexer.py index 3c8eca2f29..408f030188 100644 --- a/src/calibre/ebooks/mobi/writer2/indexer.py +++ b/src/calibre/ebooks/mobi/writer2/indexer.py @@ -368,7 +368,7 @@ class TBS: # {{{ try: next_sec = sections[i+1] - except: + except Exception: next_sec = None extra = {} @@ -635,7 +635,7 @@ class Indexer: # {{{ try: offset = id_offsets[node.href] label = self.cncx[node.title] - except: + except Exception: self.log.warn(f'TOC item {node.title} [{node.href}] not found in document') continue @@ -651,7 +651,7 @@ class Indexer: # {{{ for i, index in enumerate(indices): try: next_offset = indices[i+1].offset - except: + except Exception: next_offset = self.serializer.body_end_offset index.length = next_offset - index.offset @@ -662,7 +662,7 @@ class Indexer: # {{{ for i, index in enumerate(indices): try: next_offset = indices[i+1].offset - except: + except Exception: next_offset = self.serializer.body_end_offset index.length = next_offset - index.offset @@ -700,7 +700,7 @@ class Indexer: # {{{ offset = id_offsets[sec.href] label = self.cncx[sec.title] klass = self.cncx[sec.klass] - except: + except Exception: continue if offset in seen_sec_offsets: continue @@ -714,7 +714,7 @@ class Indexer: # {{{ offset = id_offsets[art.href] label = self.cncx[art.title] klass = self.cncx[art.klass] - except: + except Exception: continue if offset in seen_art_offsets: continue @@ -742,12 +742,12 @@ class Indexer: # {{{ sec, normalized_articles = x try: sec.length = normalized_sections[s+1][0].offset - sec.offset - except: + except Exception: sec.length = self.serializer.body_end_offset - sec.offset for i, art in enumerate(normalized_articles): try: art.length = normalized_articles[i+1].offset - art.offset - except: + except Exception: art.length = sec.offset + sec.length - art.offset # Filter @@ -783,14 +783,14 @@ class Indexer: # {{{ sec, articles = x try: next_offset = normalized_sections[s+1][0].offset - except: + except Exception: next_offset = self.serializer.body_end_offset sec.length = next_offset - sec.offset for a, art in enumerate(articles): try: next_offset = articles[a+1].offset - except: + except Exception: next_offset = sec.next_offset art.length = next_offset - art.offset @@ -799,7 +799,7 @@ class Indexer: # {{{ sec, articles = x try: next_sec = normalized_sections[s+1][0] - except: + except Exception: if (sec.length == 0 or sec.next_offset != self.serializer.body_end_offset): raise ValueError('Invalid section layout') @@ -809,7 +809,7 @@ class Indexer: # {{{ for a, art in enumerate(articles): try: next_art = articles[a+1] - except: + except Exception: if (art.length == 0 or art.next_offset != sec.next_offset): raise ValueError('Invalid article layout') diff --git a/src/calibre/ebooks/mobi/writer2/main.py b/src/calibre/ebooks/mobi/writer2/main.py index 9c8e9ea6d9..b2b8126ff5 100644 --- a/src/calibre/ebooks/mobi/writer2/main.py +++ b/src/calibre/ebooks/mobi/writer2/main.py @@ -100,7 +100,7 @@ class MobiWriter: len(self.records[self.last_text_record_idx]), self.masthead_offset, self.is_periodical, self.opts, self.oeb) - except: + except Exception: self.log.exception('Failed to generate MOBI index:') else: self.primary_index_record_idx = len(self.records) diff --git a/src/calibre/ebooks/mobi/writer2/resources.py b/src/calibre/ebooks/mobi/writer2/resources.py index afe5befe69..dce964ddb3 100644 --- a/src/calibre/ebooks/mobi/writer2/resources.py +++ b/src/calibre/ebooks/mobi/writer2/resources.py @@ -132,7 +132,7 @@ class Resources: self.used_image_indices.add(self.cover_offset) try: tdata = rescale_image(data, dimen=MAX_THUMB_DIMEN, maxsizeb=MAX_THUMB_SIZE) - except: + except Exception: self.log.warn('Failed to generate thumbnail') else: self.image_indices.add(len(self.records)) @@ -168,7 +168,7 @@ class Resources: continue try: data = self.process_image(item.data) - except: + except Exception: self.log.warn(f'Bad image file {item.href!r}') else: self.records.append(data) diff --git a/src/calibre/ebooks/mobi/writer2/serializer.py b/src/calibre/ebooks/mobi/writer2/serializer.py index 7d48491592..a7137a2730 100644 --- a/src/calibre/ebooks/mobi/writer2/serializer.py +++ b/src/calibre/ebooks/mobi/writer2/serializer.py @@ -103,7 +103,7 @@ class Serializer: for i, item in enumerate(items): try: prev_item = items[i-1] - except: + except Exception: prev_item = None if in_art and item.is_article_start is True: prev_item.is_article_end = True diff --git a/src/calibre/ebooks/mobi/writer8/exth.py b/src/calibre/ebooks/mobi/writer8/exth.py index 5421f1fac1..70f33f60dc 100644 --- a/src/calibre/ebooks/mobi/writer8/exth.py +++ b/src/calibre/ebooks/mobi/writer8/exth.py @@ -70,7 +70,7 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False, elif term == 'rights': try: rights = utf8_text(str(metadata.rights[0])) - except: + except Exception: rights = b'Unknown' exth.write(pack(b'>II', EXTH_CODES['rights'], len(rights) + 8)) exth.write(rights) diff --git a/src/calibre/ebooks/odt/input.py b/src/calibre/ebooks/odt/input.py index d2da2e104d..b4323e9f5e 100644 --- a/src/calibre/ebooks/odt/input.py +++ b/src/calibre/ebooks/odt/input.py @@ -259,7 +259,7 @@ class Extract(ODF2XHTML): self.search_page_img(mi, log) try: self.filter_cover(mi, log) - except: + except Exception: pass # parse the modified tree and generate xhtml self._walknode(self.document.topnode) @@ -290,7 +290,7 @@ class Extract(ODF2XHTML): html = html.replace('<title>',f'{mi.title}') try: html = self.fix_markup(html, log) - except: + except Exception: log.exception('Failed to filter CSS, conversion may be slow') with open('index.xhtml', 'wb') as f: f.write(as_bytes(html)) diff --git a/src/calibre/ebooks/oeb/base.py b/src/calibre/ebooks/oeb/base.py index 1192c870d0..a85c77fad4 100644 --- a/src/calibre/ebooks/oeb/base.py +++ b/src/calibre/ebooks/oeb/base.py @@ -802,7 +802,7 @@ class Metadata: elem = element(parent, self.term, attrib=attrib) try: elem.text = self.value - except: + except Exception: elem.text = repr(self.value) else: elem = element(parent, OPF('meta'), attrib=attrib) @@ -1834,7 +1834,7 @@ class OEBBook: for path in self._temp_files: try: os.remove(path) - except: + except Exception: pass @classmethod diff --git a/src/calibre/ebooks/oeb/iterator/book.py b/src/calibre/ebooks/oeb/iterator/book.py index cede2cfc19..987a39b112 100644 --- a/src/calibre/ebooks/oeb/iterator/book.py +++ b/src/calibre/ebooks/oeb/iterator/book.py @@ -172,7 +172,7 @@ class EbookIterator(BookmarksMixin): self.spine.append(Spiny(spath, mime_type=mt)) if is_comic: self.spine[-1].is_single_page = True - except: + except Exception: self.log.warn('Missing spine item:', repr(spath)) cover = self.opf.cover @@ -191,7 +191,7 @@ class EbookIterator(BookmarksMixin): self.opf.path_to_html_toc not in self.spine: try: self.spine.append(Spiny(self.opf.path_to_html_toc)) - except: + except Exception: import traceback traceback.print_exc() @@ -238,5 +238,5 @@ class EbookIterator(BookmarksMixin): for x in self.delete_on_exit: try: os.remove(x) - except: + except Exception: pass diff --git a/src/calibre/ebooks/oeb/parse_utils.py b/src/calibre/ebooks/oeb/parse_utils.py index 55decb1d61..0185bc0be0 100644 --- a/src/calibre/ebooks/oeb/parse_utils.py +++ b/src/calibre/ebooks/oeb/parse_utils.py @@ -239,7 +239,7 @@ def parse_html(data, log=None, decoder=None, preprocessor=None, del x.attrib[key] key = key.lower() x.attrib[key] = val - except: + except Exception: pass if barename(data.tag) != 'html': @@ -272,7 +272,7 @@ def parse_html(data, log=None, decoder=None, preprocessor=None, try: data = safe_xml_fromstring(data, recover=False) - except: + except Exception: data = data.replace(':=', '=').replace(':>', '>') data = data.replace('', '') try: diff --git a/src/calibre/ebooks/oeb/polish/check/base.py b/src/calibre/ebooks/oeb/polish/check/base.py index 21cf8f4ccc..9b04aeec5f 100644 --- a/src/calibre/ebooks/oeb/polish/check/base.py +++ b/src/calibre/ebooks/oeb/polish/check/base.py @@ -36,7 +36,7 @@ def worker(func, args): try: result = func(*args) tb = None - except: + except Exception: result = None import traceback tb = traceback.format_exc() diff --git a/src/calibre/ebooks/oeb/polish/container.py b/src/calibre/ebooks/oeb/polish/container.py index 8955d49f0f..baa08db63c 100644 --- a/src/calibre/ebooks/oeb/polish/container.py +++ b/src/calibre/ebooks/oeb/polish/container.py @@ -81,7 +81,7 @@ def clone_dir(src, dest): else: try: hardlink_file(spath, dpath) - except: + except Exception: shutil.copy2(spath, dpath) @@ -1192,7 +1192,7 @@ class EpubContainer(Container): try: zf = ZipFile(stream) zf.extractall(tdir) - except: + except Exception: log.exception('EPUB appears to be invalid ZIP file, trying a' ' more forgiving ZIP parser') from calibre.utils.localunzip import extractall diff --git a/src/calibre/ebooks/oeb/polish/cover.py b/src/calibre/ebooks/oeb/polish/cover.py index 619a5316ad..379ac3ba11 100644 --- a/src/calibre/ebooks/oeb/polish/cover.py +++ b/src/calibre/ebooks/oeb/polish/cover.py @@ -378,7 +378,7 @@ def create_epub_cover(container, cover_path, existing_image, options=None): else: with open(cover_path, 'rb') as csrc: width, height = identify(csrc)[1:] - except: + except Exception: container.log.exception('Failed to get width and height of cover') ar = 'xMidYMid meet' if keep_aspect else 'none' templ = CoverManager.SVG_TEMPLATE.replace('__ar__', ar) diff --git a/src/calibre/ebooks/oeb/polish/toc.py b/src/calibre/ebooks/oeb/polish/toc.py index b315c65354..0a519a2283 100644 --- a/src/calibre/ebooks/oeb/polish/toc.py +++ b/src/calibre/ebooks/oeb/polish/toc.py @@ -411,7 +411,7 @@ def item_at_top(elem): try: if el.tag.endswith('}img') or (el.text and el.text.strip()): return False - except: + except Exception: return False if not path.startswith(epath): # Only check tail of non-parent elements diff --git a/src/calibre/ebooks/oeb/reader.py b/src/calibre/ebooks/oeb/reader.py index dba0276c27..e3b7de23a7 100644 --- a/src/calibre/ebooks/oeb/reader.py +++ b/src/calibre/ebooks/oeb/reader.py @@ -197,7 +197,7 @@ class OEBReader: item.data except KeyboardInterrupt: raise - except: + except Exception: self.logger.exception(f'Failed to parse content in {item.href}') bad.append(item) self.oeb.manifest.remove(item) @@ -217,7 +217,7 @@ class OEBReader: if (item.media_type in cdoc or item.media_type[-4:] in ('/xml', '+xml')): try: data = item.data - except: + except Exception: self.oeb.log.exception('Failed to read from manifest ' f'entry with id: {item.id}, ignoring') invalid.add(item) @@ -236,7 +236,7 @@ class OEBReader: try: href = item.abshref(urlnormalize(href)) scheme = urlparse(href).scheme - except: + except Exception: self.oeb.log.exception( f'Skipping invalid href: {href!r}') continue @@ -245,7 +245,7 @@ class OEBReader: elif item.media_type in OEB_STYLES: try: urls = list(css_parser.getUrls(data)) - except: + except Exception: urls = [] for url in urls: href, _ = urldefrag(url) @@ -434,7 +434,7 @@ class OEBReader: try: po = int(child.get('playOrder', self.oeb.toc.next_play_order())) - except: + except Exception: po = self.oeb.toc.next_play_order() authorElement = xpath(child, diff --git a/src/calibre/ebooks/oeb/stylizer.py b/src/calibre/ebooks/oeb/stylizer.py index 7e872eeff5..c9b3e53fc1 100644 --- a/src/calibre/ebooks/oeb/stylizer.py +++ b/src/calibre/ebooks/oeb/stylizer.py @@ -381,7 +381,7 @@ class Stylizer: val = elem.get(prop, '').strip() try: del elem.attrib[prop] - except: + except Exception: pass if val: if num_pat.match(val) is not None: @@ -580,7 +580,7 @@ class Style: val = style.getProperty('background').propertyValue try: val = list(val) - except: + except Exception: # val is CSSPrimitiveValue val = [val] for c in val: @@ -590,7 +590,7 @@ class Style: if validate_color(c): col = c break - except: + except Exception: pass if col is None: self._bgcolor = False diff --git a/src/calibre/ebooks/oeb/transforms/cover.py b/src/calibre/ebooks/oeb/transforms/cover.py index 39194b7e0b..a1cfa6746a 100644 --- a/src/calibre/ebooks/oeb/transforms/cover.py +++ b/src/calibre/ebooks/oeb/transforms/cover.py @@ -109,7 +109,7 @@ class CoverManager: m.add('cover', item.id) return item.href - except: + except Exception: self.log.exception('Failed to generate default cover') return None diff --git a/src/calibre/ebooks/oeb/transforms/flatcss.py b/src/calibre/ebooks/oeb/transforms/flatcss.py index ab3b81d281..31368fc3db 100644 --- a/src/calibre/ebooks/oeb/transforms/flatcss.py +++ b/src/calibre/ebooks/oeb/transforms/flatcss.py @@ -179,7 +179,7 @@ class CSSFlattener: try: self.filter_css = {x.strip().lower() for x in self.opts.filter_css.split(',')} - except: + except Exception: self.oeb.log.warning('Failed to parse filter_css, ignoring') else: from calibre.ebooks.oeb.normalize_css import normalize_filter_css @@ -330,7 +330,7 @@ class CSSFlattener: self.baseline_node(body, stylizer, sizes, fsize) try: sbase = max(list(sizes.items()), key=operator.itemgetter(1))[0] - except: + except Exception: sbase = 12.0 self.oeb.logger.info( f'Source base font size is {sbase:0.5f}pt') @@ -354,7 +354,7 @@ class CSSFlattener: else: try: value = round(value / slineh) * dlineh - except: + except Exception: self.oeb.logger.warning( 'Invalid length:', value) value = 0.0 @@ -368,7 +368,7 @@ class CSSFlattener: cssdict = style.cssdict() try: font_size = style['font-size'] - except: + except Exception: font_size = self.sbase if self.sbase is not None else \ self.context.source.fbase if tag == 'body' and isinstance(font_size, numbers.Number): @@ -416,7 +416,7 @@ class CSSFlattener: # Oh, the warcrimes try: esize = 3 + force_int(size) - except: + except Exception: esize = 3 if esize < 1: esize = 1 @@ -426,7 +426,7 @@ class CSSFlattener: else: try: font_size = fnums[force_int(size)] - except: + except Exception: font_size = fnums[3] cssdict['font-size'] = f'{font_size:.1f}pt' del node.attrib['size'] diff --git a/src/calibre/ebooks/oeb/transforms/jacket.py b/src/calibre/ebooks/oeb/transforms/jacket.py index 73e3b244e8..78c25361a0 100644 --- a/src/calibre/ebooks/oeb/transforms/jacket.py +++ b/src/calibre/ebooks/oeb/transforms/jacket.py @@ -112,17 +112,17 @@ class Jacket(Base): try: comments = str(self.oeb.metadata.description[0]) - except: + except Exception: comments = '' try: title = str(self.oeb.metadata.title[0]) - except: + except Exception: title = _('Unknown') try: authors = list(map(str, self.oeb.metadata.creator)) - except: + except Exception: authors = [_('Unknown')] root = render_jacket(mi, self.opts.output_profile, @@ -167,7 +167,7 @@ def get_rating(rating, rchar, e_rchar): ans = '' try: num = float(rating)/2 - except: + except Exception: return ans num = max(0, num) num = min(num, 5) @@ -290,7 +290,7 @@ def render_jacket(mi, output_profile, try: title_str = alt_title if mi.is_null('title') else mi.title - except: + except Exception: title_str = _('Unknown') title_str = escape(title_str) title = f'{title_str}' @@ -298,7 +298,7 @@ def render_jacket(mi, output_profile, series = Series(mi.series, mi.series_index) try: publisher = mi.publisher if not mi.is_null('publisher') else alt_publisher - except: + except Exception: publisher = '' publisher = escape(publisher) @@ -324,7 +324,7 @@ def render_jacket(mi, output_profile, mi.authors = list(alt_authors or (_('Unknown'),)) try: author = mi.format_authors() - except: + except Exception: author = '' mi.authors = orig author = escape(author) diff --git a/src/calibre/ebooks/oeb/transforms/page_margin.py b/src/calibre/ebooks/oeb/transforms/page_margin.py index 736bf82cb1..d41a191e8f 100644 --- a/src/calibre/ebooks/oeb/transforms/page_margin.py +++ b/src/calibre/ebooks/oeb/transforms/page_margin.py @@ -84,7 +84,7 @@ class RemoveFakeMargins: if style: try: ti = style['text-indent'] - except: + except Exception: pass else: if ((hasattr(ti, 'startswith') and ti.startswith('-')) or (isinstance(ti, numbers.Number) and ti < 0)): diff --git a/src/calibre/ebooks/oeb/transforms/rasterize.py b/src/calibre/ebooks/oeb/transforms/rasterize.py index 5843b40723..83c5e44054 100644 --- a/src/calibre/ebooks/oeb/transforms/rasterize.py +++ b/src/calibre/ebooks/oeb/transforms/rasterize.py @@ -114,7 +114,7 @@ class SVGRasterizer: try: h = float(image.get('height').replace('%', ''))/100. image.set('height', str(h*sizes[1])) - except: + except Exception: logger.exception('Failed to convert percentage height:', image.get('height')) diff --git a/src/calibre/ebooks/oeb/transforms/split.py b/src/calibre/ebooks/oeb/transforms/split.py index cae8982825..34263621cb 100644 --- a/src/calibre/ebooks/oeb/transforms/split.py +++ b/src/calibre/ebooks/oeb/transforms/split.py @@ -97,14 +97,14 @@ class Split: self.page_break_selectors.add((rule.selectorText, True)) if self.remove_css_pagebreaks: rule.style.removeProperty('page-break-before') - except: + except Exception: pass try: if after and after not in {'avoid', 'auto', 'inherit'}: self.page_break_selectors.add((rule.selectorText, False)) if self.remove_css_pagebreaks: rule.style.removeProperty('page-break-after') - except: + except Exception: pass page_breaks = set() select = Select(item.data) @@ -138,10 +138,10 @@ class Split: id = x.get('id') try: xp = XPath(f'//*[@id="{id}"]') - except: + except Exception: try: xp = XPath(f"//*[@id='{id}']") - except: + except Exception: # The id has both a quote and an apostrophe or some other # Just replace it since I doubt its going to work anywhere else # either @@ -410,7 +410,7 @@ class FlowSplitter: if elem is not None: try: XPath(elem.getroottree().getpath(elem)) - except: + except Exception: continue return elem, True diff --git a/src/calibre/ebooks/oeb/transforms/structure.py b/src/calibre/ebooks/oeb/transforms/structure.py index 36dcac9ede..b9bcc60239 100644 --- a/src/calibre/ebooks/oeb/transforms/structure.py +++ b/src/calibre/ebooks/oeb/transforms/structure.py @@ -111,7 +111,7 @@ class DetectStructure: expr = self.opts.start_reading_at try: expr = XPath(expr) - except: + except Exception: self.log.warn( f'Invalid start reading at XPath expression, ignoring: {expr}') return @@ -151,7 +151,7 @@ class DetectStructure: ans = XPath(expr)(doc) len(ans) return ans - except: + except Exception: self.log.warn(f'Invalid chapter expression, ignoring: {expr}') return [] @@ -263,7 +263,7 @@ class DetectStructure: ans = XPath(expr)(doc) len(ans) return ans - except: + except Exception: self.log.warn(f'Invalid ToC expression, ignoring: {expr}') return [] diff --git a/src/calibre/ebooks/oeb/transforms/trimmanifest.py b/src/calibre/ebooks/oeb/transforms/trimmanifest.py index b3c1aa6469..1c5eb93e29 100644 --- a/src/calibre/ebooks/oeb/transforms/trimmanifest.py +++ b/src/calibre/ebooks/oeb/transforms/trimmanifest.py @@ -51,7 +51,7 @@ class ManifestTrimmer: href = href.decode('utf-8') try: href = item.abshref(urlnormalize(href)) - except: + except Exception: continue if href in oeb.manifest.hrefs: found = oeb.manifest.hrefs[href] diff --git a/src/calibre/ebooks/pdb/plucker/reader.py b/src/calibre/ebooks/pdb/plucker/reader.py index e156f01de3..a890419030 100644 --- a/src/calibre/ebooks/pdb/plucker/reader.py +++ b/src/calibre/ebooks/pdb/plucker/reader.py @@ -455,7 +455,7 @@ class Reader(FormatReader): home_html = self.header_record.home_html if not home_html: home_html = self.uid_text_secion_number.items()[0][0] - except: + except Exception: raise Exception('Could not determine home.html') # Generate oeb from html conversion. oeb = html_input.convert(open(f'{home_html}.html', 'rb'), self.options, 'html', self.log, {}) diff --git a/src/calibre/ebooks/pdf/pdftohtml.py b/src/calibre/ebooks/pdf/pdftohtml.py index 90e8078c3b..a239bf5e38 100644 --- a/src/calibre/ebooks/pdf/pdftohtml.py +++ b/src/calibre/ebooks/pdf/pdftohtml.py @@ -110,7 +110,7 @@ def pdftohtml(output_dir, pdf_path, no_images, as_xml=False): try: os.remove(pdfsrc) - except: + except Exception: pass diff --git a/src/calibre/ebooks/pml/pmlml.py b/src/calibre/ebooks/pml/pmlml.py index c11651ac5c..584cb3f94d 100644 --- a/src/calibre/ebooks/pml/pmlml.py +++ b/src/calibre/ebooks/pml/pmlml.py @@ -332,7 +332,7 @@ class PMLMLizer: mms = int(float(style['margin-left']) * 100 / style.height) if mms: text.append(rf'\T="{mms}%"') - except: + except Exception: pass # Soft scene breaks. @@ -340,7 +340,7 @@ class PMLMLizer: ems = round((float(style.marginTop) / style.fontSize) - 1) if ems >= 1: text.append('\n\\c \n\\c\n') - except: + except Exception: pass # Process text within this tag. diff --git a/src/calibre/ebooks/rtf2xml/check_brackets.py b/src/calibre/ebooks/rtf2xml/check_brackets.py index b53c3e52d8..2954ab4000 100644 --- a/src/calibre/ebooks/rtf2xml/check_brackets.py +++ b/src/calibre/ebooks/rtf2xml/check_brackets.py @@ -35,7 +35,7 @@ class CheckBrackets: num = line[-5:-1] try: last_num = self.__open_bracket_num.pop() - except: + except Exception: return False if num != last_num: return False diff --git a/src/calibre/ebooks/rtf2xml/colors.py b/src/calibre/ebooks/rtf2xml/colors.py index ef42033eee..9a231e99c2 100644 --- a/src/calibre/ebooks/rtf2xml/colors.py +++ b/src/calibre/ebooks/rtf2xml/colors.py @@ -247,7 +247,7 @@ class Colors: try: sys.stderr.write('no matching state in module fonts.py\n') sys.stderr.write(self.__state + '\n') - except: + except Exception: pass action(line) copy_obj = copy.Copy(bug_handler=self.__bug_handler) diff --git a/src/calibre/ebooks/rtf2xml/configure_txt.py b/src/calibre/ebooks/rtf2xml/configure_txt.py index f0713b3c7b..9395377791 100644 --- a/src/calibre/ebooks/rtf2xml/configure_txt.py +++ b/src/calibre/ebooks/rtf2xml/configure_txt.py @@ -133,7 +133,7 @@ class Configure: try: int_num = int(return_dict[int_option]) return_dict[int_option] = int_num - except: + except Exception: sys.stderr.write(f'"{int_option}" must be a number\n') sys.stderr.write(f'You choose "{return_dict[int_option]}" ') return 1 diff --git a/src/calibre/ebooks/rtf2xml/convert_to_tags.py b/src/calibre/ebooks/rtf2xml/convert_to_tags.py index ac3fedb363..c31a39af62 100644 --- a/src/calibre/ebooks/rtf2xml/convert_to_tags.py +++ b/src/calibre/ebooks/rtf2xml/convert_to_tags.py @@ -128,7 +128,7 @@ class ConvertToTags: self.__write_obj.write( f' {val}="{att}"' ) - except: + except Exception: if self.__run_level > 3: msg = 'index out of range\n' raise self.__bug_handler(msg) diff --git a/src/calibre/ebooks/rtf2xml/old_rtf.py b/src/calibre/ebooks/rtf2xml/old_rtf.py index d63bcda39c..ac0b26f80c 100644 --- a/src/calibre/ebooks/rtf2xml/old_rtf.py +++ b/src/calibre/ebooks/rtf2xml/old_rtf.py @@ -127,7 +127,7 @@ class OldRtf: if action is None: try: sys.stderr.write('No action for this state!\n') - except: + except Exception: pass result = action(line) if result == 'new_rtf': diff --git a/src/calibre/ebooks/rtf2xml/paragraphs.py b/src/calibre/ebooks/rtf2xml/paragraphs.py index 1a4477c54e..d44250939c 100644 --- a/src/calibre/ebooks/rtf2xml/paragraphs.py +++ b/src/calibre/ebooks/rtf2xml/paragraphs.py @@ -254,7 +254,7 @@ class Paragraphs: try: sys.stderr.write('no matching state in module paragraphs.py\n') sys.stderr.write(self.__state + '\n') - except: + except Exception: pass action(line) copy_obj = copy.Copy(bug_handler=self.__bug_handler) diff --git a/src/calibre/ebooks/rtf2xml/pict.py b/src/calibre/ebooks/rtf2xml/pict.py index ca8d022468..0b884a4970 100644 --- a/src/calibre/ebooks/rtf2xml/pict.py +++ b/src/calibre/ebooks/rtf2xml/pict.py @@ -168,7 +168,7 @@ class Pict: copy_obj.copy_file(self.__write_to, 'pict.data') try: copy_obj.copy_file(self.__pict_file, 'pict.rtf') - except: + except Exception: pass copy_obj.rename(self.__write_to, self.__file) os.remove(self.__write_to) diff --git a/src/calibre/ebooks/rtf2xml/process_tokens.py b/src/calibre/ebooks/rtf2xml/process_tokens.py index 0cf65747ca..0a8a849059 100644 --- a/src/calibre/ebooks/rtf2xml/process_tokens.py +++ b/src/calibre/ebooks/rtf2xml/process_tokens.py @@ -757,7 +757,7 @@ class ProcessTokens: try: hex_num = f'{num:X}' return hex_num - except: + except Exception: raise self.__bug_handler def process_cw(self, token): diff --git a/src/calibre/ebooks/txt/txtml.py b/src/calibre/ebooks/txt/txtml.py index 99b25705f4..5051f778ee 100644 --- a/src/calibre/ebooks/txt/txtml.py +++ b/src/calibre/ebooks/txt/txtml.py @@ -236,7 +236,7 @@ class TXTMLizer: ems = round((float(style.marginTop) / style.fontSize) - 1) if ems >= 1: text.append('\n' * ems) - except: + except Exception: pass # Process tags that contain text. diff --git a/src/calibre/ebooks/unihandecode/unidecoder.py b/src/calibre/ebooks/unihandecode/unidecoder.py index 0bac7ed26e..5b4f2c1341 100644 --- a/src/calibre/ebooks/unihandecode/unidecoder.py +++ b/src/calibre/ebooks/unihandecode/unidecoder.py @@ -85,7 +85,7 @@ class Unidecoder: # represents the position in the list of characters for the group. return self.codepoints[self.code_group(codepoint)][self.grouped_point( codepoint)] - except: + except Exception: return '?' def code_group(self, character): diff --git a/src/calibre/gui2/__init__.py b/src/calibre/gui2/__init__.py index a5893d2c39..c039c4d7a9 100644 --- a/src/calibre/gui2/__init__.py +++ b/src/calibre/gui2/__init__.py @@ -667,7 +667,7 @@ def is_widescreen(): if _is_widescreen is None: try: _is_widescreen = available_width()/available_height() > 1.4 - except: + except Exception: _is_widescreen = False return _is_widescreen @@ -844,7 +844,7 @@ class FunctionDispatcher(QObject): def dispatch(self, q, args, kwargs): try: res = self.func(*args, **kwargs) - except: + except Exception: res = None q.put(res) @@ -875,7 +875,7 @@ class GetMetadata(QObject): from calibre.ebooks.metadata.meta import metadata_from_formats try: mi = metadata_from_formats(*args, **kwargs) - except: + except Exception: mi = MetaInformation('', [_('Unknown')]) self.metadataf.emit(id, mi) @@ -883,7 +883,7 @@ class GetMetadata(QObject): from calibre.ebooks.metadata.meta import get_metadata try: mi = get_metadata(*args, **kwargs) - except: + except Exception: mi = MetaInformation('', [_('Unknown')]) self.metadata.emit(id, mi) @@ -1083,7 +1083,7 @@ class Translator(QTranslator): def translate(self, *args, **kwargs): try: src = str(args[1]) - except: + except Exception: return '' t = _ return t(src) diff --git a/src/calibre/gui2/actions/__init__.py b/src/calibre/gui2/actions/__init__.py index 041d0ce011..2bd5aa2cec 100644 --- a/src/calibre/gui2/actions/__init__.py +++ b/src/calibre/gui2/actions/__init__.py @@ -262,7 +262,7 @@ class InterfaceAction(QObject): except NameConflict as e: try: prints(str(e)) - except: + except Exception: pass shortcut_action.setShortcuts([QKeySequence(key, QKeySequence.SequenceFormat.PortableText) for key in keys]) diff --git a/src/calibre/gui2/actions/add.py b/src/calibre/gui2/actions/add.py index 202cef8b2f..dd110886d1 100644 --- a/src/calibre/gui2/actions/add.py +++ b/src/calibre/gui2/actions/add.py @@ -455,7 +455,7 @@ class AddAction(InterfaceAction): self.add_by_isbn_ids.add(db.import_book(mi, fmts)) self.isbn_add_dialog.value += 1 QTimer.singleShot(10, self.do_one_isbn_add) - except: + except Exception: self.isbn_add_dialog.accept() raise diff --git a/src/calibre/gui2/actions/annotate.py b/src/calibre/gui2/actions/annotate.py index ffcd4c32e0..9cf9f28c8b 100644 --- a/src/calibre/gui2/actions/annotate.py +++ b/src/calibre/gui2/actions/annotate.py @@ -50,7 +50,7 @@ class Updater(QThread): # {{{ self.annotation_map[id_][1]) try: self.device.add_annotation_to_library(self.db, id_, bm) - except: + except Exception: import traceback self.errors[id_] = traceback.format_exc() self.update_progress.emit(i) diff --git a/src/calibre/gui2/actions/choose_library.py b/src/calibre/gui2/actions/choose_library.py index e274f835d4..de25d867c3 100644 --- a/src/calibre/gui2/actions/choose_library.py +++ b/src/calibre/gui2/actions/choose_library.py @@ -227,7 +227,7 @@ class BackupStatus(QDialog): # {{{ dirty_text = 'no' try: dirty_text = f'{db.dirty_queue_length()}' - except: + except Exception: dirty_text = _('none') self.msg.setText('

' + _( 'Book metadata files remaining to be written: %s') % dirty_text) @@ -605,7 +605,7 @@ class ChooseLibraryAction(InterfaceAction): self.gui.library_broker.remove_library(loc) try: os.rename(loc, newloc) - except: + except Exception: import traceback det_msg = f'Location: {loc!r} New Location: {newloc!r}\n{traceback.format_exc()}' error_dialog(self.gui, _('Rename failed'), diff --git a/src/calibre/gui2/actions/convert.py b/src/calibre/gui2/actions/convert.py index cfc623e94b..c5dc7a4616 100644 --- a/src/calibre/gui2/actions/convert.py +++ b/src/calibre/gui2/actions/convert.py @@ -264,7 +264,7 @@ class ConvertAction(InterfaceActionWithLibraryDrop): try: if os.path.exists(f.name): os.remove(f.name) - except: + except Exception: pass self.gui.tags_view.recount() if self.gui.current_view() is self.gui.library_view: diff --git a/src/calibre/gui2/actions/copy_to_library.py b/src/calibre/gui2/actions/copy_to_library.py index 2ca99840d7..1dec03ba2e 100644 --- a/src/calibre/gui2/actions/copy_to_library.py +++ b/src/calibre/gui2/actions/copy_to_library.py @@ -153,7 +153,7 @@ class Worker(Thread): # {{{ import traceback try: err = str(err) - except: + except Exception: err = repr(err) self.error = (err, traceback.format_exc()) diff --git a/src/calibre/gui2/actions/delete.py b/src/calibre/gui2/actions/delete.py index e268243f8b..fc820af89f 100644 --- a/src/calibre/gui2/actions/delete.py +++ b/src/calibre/gui2/actions/delete.py @@ -54,7 +54,7 @@ class MultiDeleter(QObject): # {{{ self.model.db.delete_book(id_, notify=False, commit=False, permanent=False) self.deleted_ids.append(id_) - except: + except Exception: import traceback self.failures.append((id_, title, traceback.format_exc())) single_shot(self.delete_one) diff --git a/src/calibre/gui2/actions/edit_metadata.py b/src/calibre/gui2/actions/edit_metadata.py index 4b1da92a46..cde671a23b 100644 --- a/src/calibre/gui2/actions/edit_metadata.py +++ b/src/calibre/gui2/actions/edit_metadata.py @@ -247,7 +247,7 @@ class EditMetadataAction(InterfaceActionWithLibraryDrop): def cleanup_bulk_download(self, tdir, *args): try: shutil.rmtree(tdir, ignore_errors=True) - except: + except Exception: pass def metadata_downloaded(self, job): @@ -819,14 +819,14 @@ class EditMetadataAction(InterfaceActionWithLibraryDrop): db.set_metadata(book_id, mi, commit=False, set_title=set_title, set_authors=set_authors, notify=False) self.applied_ids.add(book_id) - except: + except Exception: import traceback self.apply_failures.append((book_id, traceback.format_exc())) try: if mi.cover: os.remove(mi.cover) - except: + except Exception: pass def finalize_apply(self): diff --git a/src/calibre/gui2/actions/fetch_news.py b/src/calibre/gui2/actions/fetch_news.py index b143987676..9549c49575 100644 --- a/src/calibre/gui2/actions/fetch_news.py +++ b/src/calibre/gui2/actions/fetch_news.py @@ -79,7 +79,7 @@ class FetchNewsAction(InterfaceAction): # delete all but newest x issues. try: keep_issues = int(arg['keep_issues']) - except: + except Exception: keep_issues = 0 if keep_issues > 0: ids_with_tag = list(sorted(self.gui.library_view.model(). diff --git a/src/calibre/gui2/actions/mark_books.py b/src/calibre/gui2/actions/mark_books.py index d2b94308f5..a18a503d47 100644 --- a/src/calibre/gui2/actions/mark_books.py +++ b/src/calibre/gui2/actions/mark_books.py @@ -132,7 +132,7 @@ class MarkBooksAction(InterfaceActionWithLibraryDrop): try: w = x.widgetForAction(self.qaction) w.installEventFilter(self) - except: + except Exception: continue def eventFilter(self, obj, ev): diff --git a/src/calibre/gui2/actions/polish.py b/src/calibre/gui2/actions/polish.py index 8e00177558..649c28f195 100644 --- a/src/calibre/gui2/actions/polish.py +++ b/src/calibre/gui2/actions/polish.py @@ -288,7 +288,7 @@ class Polish(QDialog): # {{{ num, book_id = self.queue.pop(0) try: self.do_book(num, book_id, self.book_id_map[book_id]) - except: + except Exception: self.pd.reject() raise else: @@ -543,7 +543,7 @@ class PolishAction(InterfaceActionWithLibraryDrop): shutil.rmtree(base) parent = os.path.dirname(base) os.rmdir(parent) - except: + except Exception: pass self.to_be_refreshed.add(book_id) self.refresh_debounce_timer.start() diff --git a/src/calibre/gui2/actions/unpack_book.py b/src/calibre/gui2/actions/unpack_book.py index d32f09f4f4..15e116f54f 100644 --- a/src/calibre/gui2/actions/unpack_book.py +++ b/src/calibre/gui2/actions/unpack_book.py @@ -178,7 +178,7 @@ class UnpackBook(QDialog): except Error as e: return error_dialog(self, _('Failed to unpack'), (_('Could not explode the %s file.')%self.current_format) + ' ' + as_unicode(e), show=True) - except: + except Exception: import traceback det_msg = traceback.format_exc() finally: @@ -213,7 +213,7 @@ class UnpackBook(QDialog): rebuilder(src_dir, of) except WorkerError as e: det_msg = e.orig_tb - except: + except Exception: import traceback det_msg = traceback.format_exc() finally: @@ -258,19 +258,19 @@ class UnpackBook(QDialog): import appscript self.finder = appscript.app('Finder') self.finder.Finder_windows[os.path.basename(self._exploded)].close() - except: + except Exception: pass for f in self._cleanup_files: try: os.remove(f) - except: + except Exception: pass for d in self._cleanup_dirs: try: shutil.rmtree(d) - except: + except Exception: pass @property diff --git a/src/calibre/gui2/actions/view.py b/src/calibre/gui2/actions/view.py index f5b16ba0b8..2203853981 100644 --- a/src/calibre/gui2/actions/view.py +++ b/src/calibre/gui2/actions/view.py @@ -341,7 +341,7 @@ class ViewAction(InterfaceAction): for id_ in ids: try: title = db.title(id_, index_is_id=True) - except: + except Exception: error_dialog(self.gui, _('Cannot view'), _('This book no longer exists in your library'), show=True) self.update_history([], remove={id_}) diff --git a/src/calibre/gui2/auto_add.py b/src/calibre/gui2/auto_add.py index 5bf5b7b8af..091278d84a 100644 --- a/src/calibre/gui2/auto_add.py +++ b/src/calibre/gui2/auto_add.py @@ -75,7 +75,7 @@ class Worker(Thread): break try: self.auto_add() - except: + except Exception: import traceback traceback.print_exc() finally: @@ -120,7 +120,7 @@ class Worker(Thread): # QFileSystemWatcher when writing is completed, so ignore for now. try: open(make_long_path_useable(f), 'rb').close() - except: + except Exception: continue tdir = tempfile.mkdtemp(dir=self.tdir) try: @@ -129,7 +129,7 @@ class Worker(Thread): except WorkerError as e: prints('Failed to read metadata from:', fname) prints(e.orig_tb) - except: + except Exception: import traceback traceback.print_exc() @@ -139,7 +139,7 @@ class Worker(Thread): try: with open(szpath, 'rb') as f: int(f.read()) - except: + except Exception: with open(szpath, 'wb') as f: f.write(b'0') @@ -147,7 +147,7 @@ class Worker(Thread): try: if os.stat(opfpath).st_size < 30: raise Exception('metadata reading failed') - except: + except Exception: mi = metadata_from_filename(fname) with open(opfpath, 'wb') as f: f.write(metadata_to_opf(mi)) @@ -186,7 +186,7 @@ class AutoAdder(QObject): try: if os.listdir(self.worker.path): self.dir_changed() - except: + except Exception: pass self.watcher.addPath(self.worker.path) @@ -244,7 +244,7 @@ class AutoAdder(QObject): if sz != os.stat(make_long_path_useable(paths[0])).st_size: raise Exception('Looks like the file was written to after' ' we tried to read metadata') - except: + except Exception: needs_rescan = True try: self.worker.staging.remove(fname) @@ -281,7 +281,7 @@ class AutoAdder(QObject): try: os.remove(make_long_path_useable(path_to_remove)) self.worker.staging.remove(fname) - except: + except Exception: import traceback traceback.print_exc() count += num @@ -310,7 +310,7 @@ class AutoAdder(QObject): for fname, tdir in data: try: shutil.rmtree(tdir) - except: + except Exception: pass if added_ids and gprefs['auto_add_auto_convert']: diff --git a/src/calibre/gui2/book_details.py b/src/calibre/gui2/book_details.py index 45c5d9b0a4..835f566179 100644 --- a/src/calibre/gui2/book_details.py +++ b/src/calibre/gui2/book_details.py @@ -842,7 +842,7 @@ class CoverView(QWidget): # {{{ try: self.pwidth, self.pheight = fit_image(pwidth, pheight, self.rect().width(), self.rect().height())[1:] - except: + except Exception: self.pwidth, self.pheight = self.rect().width()-1, \ self.rect().height()-1 self.current_pixmap_size = QSize(self.pwidth, self.pheight) @@ -1055,7 +1055,7 @@ class CoverView(QWidget): # {{{ def update_tooltip(self, current_path): try: sz = self.pixmap.size() - except: + except Exception: sz = QSize(0, 0) self.setToolTip( '

'+_('Double click to open the Book details window') + @@ -1302,7 +1302,7 @@ class DetailsLayout(QSplitter): # {{{ mh = min(int(r.height()//2), int(4/3 * r.width())+1) try: ph = self._children[0].pixmap.height() - except: + except Exception: ph = 0 if ph > 0: mh = min(mh, ph) @@ -1314,7 +1314,7 @@ class DetailsLayout(QSplitter): # {{{ mw = 1 + int(3/4 * r.height()) try: pw = self._children[0].pixmap.width() - except: + except Exception: pw = 0 if pw > 0: mw = min(mw, pw) diff --git a/src/calibre/gui2/catalog/catalog_epub_mobi.py b/src/calibre/gui2/catalog/catalog_epub_mobi.py index 22887d8aee..f8cc0487b1 100644 --- a/src/calibre/gui2/catalog/catalog_epub_mobi.py +++ b/src/calibre/gui2/catalog/catalog_epub_mobi.py @@ -229,7 +229,7 @@ class PluginWidget(QWidget, Ui_Form): try: pattern = re.compile(regex) - except: + except Exception: results = _('regex error: %s') % sys.exc_info()[1] else: excluded_tags = [] @@ -545,7 +545,7 @@ class PluginWidget(QWidget, Ui_Form): # Append the output profile try: opts_dict['output_profile'] = [load_defaults('page_setup')['output_profile']] - except: + except Exception: opts_dict['output_profile'] = ['default'] if False and self.DEBUG: @@ -732,7 +732,7 @@ class PluginWidget(QWidget, Ui_Form): names.extend(self.preset_field_values) try: dex = names.index(self.preset_search_name) - except: + except Exception: dex = 0 name = '' while not name: @@ -806,7 +806,7 @@ class PluginWidget(QWidget, Ui_Form): # Append the current output profile try: preset['output_profile'] = load_defaults('page_setup')['output_profile'] - except: + except Exception: preset['output_profile'] = 'default' self.presets[name] = preset diff --git a/src/calibre/gui2/convert/__init__.py b/src/calibre/gui2/convert/__init__.py index 13ccdc23bc..7fdf243150 100644 --- a/src/calibre/gui2/convert/__init__.py +++ b/src/calibre/gui2/convert/__init__.py @@ -179,7 +179,7 @@ class Widget(QWidget): ans = str(g.currentText()).strip() try: codecs.lookup(ans) - except: + except Exception: ans = '' if not ans: ans = None @@ -270,7 +270,7 @@ class Widget(QWidget): if msg and getattr(msg, 'strip', lambda:True)(): try: self.set_help_signal.emit(msg) - except: + except Exception: pass def setup_help(self, help_provider): diff --git a/src/calibre/gui2/convert/bulk.py b/src/calibre/gui2/convert/bulk.py index e0e2034524..50a12891f1 100644 --- a/src/calibre/gui2/convert/bulk.py +++ b/src/calibre/gui2/convert/bulk.py @@ -111,7 +111,7 @@ class BulkConfig(Config): self.show_pane(idx) try: shutil.rmtree(self.plumber.archive_input_tdir, ignore_errors=True) - except: + except Exception: pass def setup_output_formats(self, db, preferred_output_format): diff --git a/src/calibre/gui2/convert/debug.py b/src/calibre/gui2/convert/debug.py index 55f5e7fae9..985a116bcd 100644 --- a/src/calibre/gui2/convert/debug.py +++ b/src/calibre/gui2/convert/debug.py @@ -43,7 +43,7 @@ class DebugWidget(Widget, Ui_Form): test = os.path.join(x, 'test') open(test, 'wb').close() os.remove(test) - except: + except Exception: import traceback det_msg = traceback.format_exc() error_dialog(self, _('Invalid debug folder'), diff --git a/src/calibre/gui2/convert/font_key.py b/src/calibre/gui2/convert/font_key.py index a8b44184b1..27725ec16e 100644 --- a/src/calibre/gui2/convert/font_key.py +++ b/src/calibre/gui2/convert/font_key.py @@ -78,7 +78,7 @@ class FontKeyChooser(QDialog, Ui_Dialog): fsize = self.input_font_size.value() try: fsizes = self.fsizes - except: + except Exception: return if dbase == 0.0 or not fsizes: diff --git a/src/calibre/gui2/convert/heuristics.py b/src/calibre/gui2/convert/heuristics.py index 50afe83314..53ac641d84 100644 --- a/src/calibre/gui2/convert/heuristics.py +++ b/src/calibre/gui2/convert/heuristics.py @@ -59,7 +59,7 @@ class HeuristicsWidget(Widget, Ui_Form): try: self.opt_enable_heuristics.stateChanged.disconnect() self.opt_unwrap_lines.stateChanged.disconnect() - except: + except Exception: pass def set_value_handler(self, g, val): diff --git a/src/calibre/gui2/convert/metadata.py b/src/calibre/gui2/convert/metadata.py index b8bb142fc1..697b48e1bf 100644 --- a/src/calibre/gui2/convert/metadata.py +++ b/src/calibre/gui2/convert/metadata.py @@ -103,7 +103,7 @@ class MetadataWidget(Widget, Ui_Form): if mi.series_index is not None: try: self.series_index.setValue(mi.series_index) - except: + except Exception: self.series_index.setValue(1.0) cover = self.db.cover(self.book_id, index_is_id=True) diff --git a/src/calibre/gui2/convert/regex_builder.py b/src/calibre/gui2/convert/regex_builder.py index 55574921b2..0ab0c5e633 100644 --- a/src/calibre/gui2/convert/regex_builder.py +++ b/src/calibre/gui2/convert/regex_builder.py @@ -60,7 +60,7 @@ class RegexBuilder(QDialog, Ui_RegexBuilder): compile_regular_expression(regex) self.regex.setStyleSheet('QLineEdit { color: black; background-color: rgba(0,255,0,20%); }') return True - except: + except Exception: self.regex.setStyleSheet('QLineEdit { color: black; background-color: rgba(255,0,0,20%); }') else: self.regex.setStyleSheet('QLineEdit { color: black; background-color: white; }') @@ -173,7 +173,7 @@ class RegexBuilder(QDialog, Ui_RegexBuilder): finally: try: os.remove(fpath) - except: + except Exception: # Fails on windows if the input plugin for this format keeps the file open # Happens for LIT files pass @@ -189,7 +189,7 @@ class RegexBuilder(QDialog, Ui_RegexBuilder): except WorkerError as e: return error_dialog(self, _('Failed to generate preview'), err_msg, det_msg=str(e) + '\n\n' + e.orig_tb, show=True) - except: + except Exception: import traceback return error_dialog(self, _('Failed to generate preview'), err_msg, det_msg=traceback.format_exc(), show=True) diff --git a/src/calibre/gui2/convert/search_and_replace.py b/src/calibre/gui2/convert/search_and_replace.py index 52b9c6ec52..6fc6c5ec78 100644 --- a/src/calibre/gui2/convert/search_and_replace.py +++ b/src/calibre/gui2/convert/search_and_replace.py @@ -170,7 +170,7 @@ class SearchAndReplaceWidget(Widget, Ui_Form): def d(x): try: x.disconnect() - except: + except Exception: pass d(self.sr_search) @@ -242,7 +242,7 @@ class SearchAndReplaceWidget(Widget, Ui_Form): rowItems = json.loads(val) if not isinstance(rowItems, list): rowItems = [] - except: + except Exception: rowItems = [] if len(rowItems) == 0: diff --git a/src/calibre/gui2/convert/single.py b/src/calibre/gui2/convert/single.py index 4947fea16f..36d2e31ee3 100644 --- a/src/calibre/gui2/convert/single.py +++ b/src/calibre/gui2/convert/single.py @@ -61,7 +61,7 @@ class GroupModel(QAbstractListModel): def data(self, index, role): try: widget = self.widgets[index.row()] - except: + except Exception: return None if role == Qt.ItemDataRole.DisplayRole: return (widget.config_title()) diff --git a/src/calibre/gui2/convert/xpath_wizard.py b/src/calibre/gui2/convert/xpath_wizard.py index e54077ad98..70c9562af2 100644 --- a/src/calibre/gui2/convert/xpath_wizard.py +++ b/src/calibre/gui2/convert/xpath_wizard.py @@ -127,7 +127,7 @@ class XPathEdit(QWidget): try: if self.text.strip(): XPath(self.text) - except: + except Exception: import traceback traceback.print_exc() return False diff --git a/src/calibre/gui2/cover_flow.py b/src/calibre/gui2/cover_flow.py index 9b92e29a80..3914229fe6 100644 --- a/src/calibre/gui2/cover_flow.py +++ b/src/calibre/gui2/cover_flow.py @@ -506,7 +506,7 @@ class CoverFlowMixin: if self.library_view.currentIndex().row() != row and index.isValid(): self.cover_flow_sync_flag = False self.library_view.select_rows([row], using_ids=False) - except: + except Exception: import traceback traceback.print_exc() if self.cover_flow_syncing_enabled: diff --git a/src/calibre/gui2/custom_column_widgets.py b/src/calibre/gui2/custom_column_widgets.py index 9666b72695..35ead3a77a 100644 --- a/src/calibre/gui2/custom_column_widgets.py +++ b/src/calibre/gui2/custom_column_widgets.py @@ -69,7 +69,7 @@ def label_string(txt): try: if txt[0].isalnum(): return '&' + txt - except: + except Exception: pass return txt @@ -95,10 +95,10 @@ class Base: try: self.widgets[0].setToolTip(description) self.widgets[1].setToolTip(description) - except: + except Exception: try: self.widgets[1].setToolTip(description) - except: + except Exception: pass @property diff --git a/src/calibre/gui2/device.py b/src/calibre/gui2/device.py index 220ddd9221..c4013020bf 100644 --- a/src/calibre/gui2/device.py +++ b/src/calibre/gui2/device.py @@ -94,7 +94,7 @@ class DeviceJob(BaseJob): # {{{ try: self.callback_on_done(self) - except: + except Exception: pass if DEBUG: prints('DeviceJob:', self.id, self.description, @@ -255,7 +255,7 @@ class DeviceManager(Thread): # {{{ continue except OpenFailed: raise - except: + except Exception: tb = traceback.format_exc() if DEBUG or tb not in self.reported_errors: self.reported_errors.add(tb) @@ -296,7 +296,7 @@ class DeviceManager(Thread): # {{{ break try: self.connected_device.post_yank_cleanup() - except: + except Exception: pass if self.connected_device in self.ejected_devices: self.ejected_devices.remove(self.connected_device) @@ -345,7 +345,7 @@ class DeviceManager(Thread): # {{{ for dev in self.unmanaged_devices: try: cd = dev.detect_managed_devices(self.scanner.devices) - except: + except Exception: prints(f'Error during device detection for {dev}:') traceback.print_exc() else: @@ -358,7 +358,7 @@ class DeviceManager(Thread): # {{{ if e.only_once_id not in self.open_feedback_only_once_seen: self.open_feedback_only_once_seen.add(e.only_once_id) self.open_feedback_msg(e.device_name, e) - except: + except Exception: prints(f'Error while trying to open {cd} (Driver: {dev})') traceback.print_exc() else: @@ -428,7 +428,7 @@ class DeviceManager(Thread): # {{{ try: name = dev.__class__.__name__ dev.startup() - except: + except Exception: prints(f'Startup method for device {name} threw exception') traceback.print_exc() @@ -502,7 +502,7 @@ class DeviceManager(Thread): # {{{ for p in self.devices: try: p.shutdown() - except: + except Exception: pass def create_job_step(self, func, done, description, to_job, args=[], kwargs={}): @@ -522,7 +522,7 @@ class DeviceManager(Thread): # {{{ def has_card(self): try: return bool(self.device.card_prefix()) - except: + except Exception: return False def _debug_detection(self): @@ -654,7 +654,7 @@ class DeviceManager(Thread): # {{{ if nuke_comments is not None: mi.comments = nuke_comments set_metadata(stream, newmi, stream_type=ext) - except: + except Exception: if DEBUG: prints(traceback.format_exc(), file=sys.__stdout__) @@ -667,7 +667,7 @@ class DeviceManager(Thread): # {{{ try: if mi.cover: os.remove(mi.cover) - except: + except Exception: pass def upload_books(self, done, files, names, on_card=None, titles=None, @@ -758,7 +758,7 @@ class DeviceManager(Thread): # {{{ d = self.dynamic_plugins.get(name, None) if d: return True - except: + except Exception: pass return False @@ -1131,17 +1131,17 @@ class DeviceMixin: # {{{ 'device. Please unplug and reconnect the device ' 'or reboot.')).show() return - except: + except Exception: pass if getattr(job, 'exception', None).__class__.__name__ == 'MTPInvalidSendPathError': try: from calibre.gui2.device_drivers.mtp_config import SendError return SendError(self, job.exception).exec() - except: + except Exception: traceback.print_exc() try: prints(job.details, file=sys.stderr) - except: + except Exception: pass if not self.device_error_dialog.isVisible(): self.device_error_dialog.set_details(job.details) @@ -1316,7 +1316,7 @@ class DeviceMixin: # {{{ if not self.current_view().currentIndex().isValid(): self.current_view().set_current_row() self.current_view().refresh_book_details() - except: + except Exception: traceback.print_exc() def dispatch_sync_event(self, dest, delete, specific): @@ -1399,7 +1399,7 @@ class DeviceMixin: # {{{ self.device_manager.device.THUMBNAIL_WIDTH, self.device_manager.device.THUMBNAIL_HEIGHT, preserve_aspect_ratio=False) - except: + except Exception: pass return ht = self.device_manager.device.THUMBNAIL_HEIGHT \ @@ -1407,7 +1407,7 @@ class DeviceMixin: # {{{ try: return scale_image(data, ht, ht, compression_quality=self.device_manager.device.THUMBNAIL_COMPRESSION_QUALITY) - except: + except Exception: pass def sync_catalogs(self, send_ids=None, do_auto_convert=True): @@ -1472,7 +1472,7 @@ class DeviceMixin: # {{{ try: ans = self.library_view.model().db.new_api.pref('news_to_be_synced', []) - except: + except Exception: import traceback traceback.print_exc() return set(ans) @@ -1482,7 +1482,7 @@ class DeviceMixin: # {{{ try: self.library_view.model().db.new_api.set_pref('news_to_be_synced', list(ids)) - except: + except Exception: import traceback traceback.print_exc() @@ -1539,11 +1539,11 @@ class DeviceMixin: # {{{ on_card = space.get(sorted(space.keys(), reverse=True)[0], None) try: total_size = sum(os.stat(f).st_size for f in files) - except: + except Exception: try: import traceback traceback.print_exc() - except: + except Exception: pass total_size = self.location_manager.free[0] loc = tweaks['send_news_to_device_location'] @@ -1743,7 +1743,7 @@ class DeviceMixin: # {{{ try: self.device_manager.add_books_to_metadata(job.result, metadata, self.booklists()) - except: + except Exception: traceback.print_exc() raise @@ -1776,7 +1776,7 @@ class DeviceMixin: # {{{ 'KEEP_TEMP_FILES_AFTER_UPLOAD', False) if rem and 'caltmpfmt.' in f: os.remove(f) - except: + except Exception: pass def update_metadata_on_device(self): @@ -1861,7 +1861,7 @@ class DeviceMixin: # {{{ # library view. In this case, simply give up try: db = self.library_view.model().db - except: + except Exception: return False # Define the cleaning function @@ -1949,7 +1949,7 @@ class DeviceMixin: # {{{ max(book.thumbnail[0], book.thumbnail[1]) != desired_thumbnail_height ) ) - except: + except Exception: return True def get_by_author(book, d, author): @@ -2066,7 +2066,7 @@ class DeviceMixin: # {{{ len(book_ids_to_refresh), 'books') self.library_view.model().refresh_ids(book_ids_to_refresh, current_row=self.library_view.currentIndex().row()) - except: + except Exception: # This shouldn't ever happen, but just in case ... traceback.print_exc() @@ -2088,7 +2088,7 @@ class DeviceMixin: # {{{ mi = db.new_api.get_metadata(id_, get_cover=True) self.update_thumbnail(mi) metadata.append(mi) - except: + except Exception: prints('Problem creating temporary file for', fmt_name) traceback.print_exc() else: @@ -2096,7 +2096,7 @@ class DeviceMixin: # {{{ prints("DeviceJob: book doesn't have that format") if files: self.upload_books(files, names, metadata) - except: + except Exception: # Shouldn't ever happen, but just in case traceback.print_exc() @@ -2110,7 +2110,7 @@ class DeviceMixin: # {{{ show=False, show_copy_button=True) d.show() - except: + except Exception: traceback.print_exc() debug_print('DeviceJob: set_books_in_library finished: time=', time.time() - start_time) diff --git a/src/calibre/gui2/dialogs/catalog.py b/src/calibre/gui2/dialogs/catalog.py index b84a5a75bf..2fa61641ef 100644 --- a/src/calibre/gui2/dialogs/catalog.py +++ b/src/calibre/gui2/dialogs/catalog.py @@ -227,7 +227,7 @@ class Catalog(QDialog, Ui_Dialog): if self.tabs.count() > 1 and hasattr(self.options_widget,'show_help'): try: self.options_widget.show_help() - except: + except Exception: info_dialog(self, _('No help available'), _('No help available for this output format.'), show_copy_button=False, diff --git a/src/calibre/gui2/dialogs/check_library.py b/src/calibre/gui2/dialogs/check_library.py index 751e1214ad..82228a9d13 100644 --- a/src/calibre/gui2/dialogs/check_library.py +++ b/src/calibre/gui2/dialogs/check_library.py @@ -513,7 +513,7 @@ class CheckLibraryDialog(QDialog): delete_tree(p) else: delete_file(p) - except: + except Exception: prints('failed to delete', os.path.join(self.db.library_path, str(it.text(2)))) diff --git a/src/calibre/gui2/dialogs/confirm_delete_location.py b/src/calibre/gui2/dialogs/confirm_delete_location.py index a15500be10..807503704c 100644 --- a/src/calibre/gui2/dialogs/confirm_delete_location.py +++ b/src/calibre/gui2/dialogs/confirm_delete_location.py @@ -63,7 +63,7 @@ class Dialog(QDialog): b = getattr(self, 'button_'+x) try: b.clicked.disconnect() - except: + except Exception: pass diff --git a/src/calibre/gui2/dialogs/custom_recipes.py b/src/calibre/gui2/dialogs/custom_recipes.py index 93d993f05d..50cf62e853 100644 --- a/src/calibre/gui2/dialogs/custom_recipes.py +++ b/src/calibre/gui2/dialogs/custom_recipes.py @@ -136,7 +136,7 @@ class CustomRecipeModel(QAbstractListModel): # {{{ try: urn = self.recipe_model.custom_recipe_collection[r].get('id') urns.append(urn) - except: + except Exception: pass self.beginResetModel() self.recipe_model.remove_custom_recipes(urns) diff --git a/src/calibre/gui2/dialogs/match_books.py b/src/calibre/gui2/dialogs/match_books.py index fa3db9b776..1e9d045d55 100644 --- a/src/calibre/gui2/dialogs/match_books.py +++ b/src/calibre/gui2/dialogs/match_books.py @@ -58,7 +58,7 @@ class MatchBooks(QDialog, Ui_MatchBooks): self.books_table_column_widths = \ gprefs.get('match_books_dialog_books_table_widths', None) self.restore_geometry(gprefs, 'match_books_dialog_geometry') - except: + except Exception: pass self.search_text.initialize('match_books_dialog') diff --git a/src/calibre/gui2/dialogs/metadata_bulk.py b/src/calibre/gui2/dialogs/metadata_bulk.py index 35b57d8a35..06e5f78231 100644 --- a/src/calibre/gui2/dialogs/metadata_bulk.py +++ b/src/calibre/gui2/dialogs/metadata_bulk.py @@ -202,7 +202,7 @@ class MyBlockingBusy(QDialog): # {{{ import traceback try: err = str(err) - except: + except Exception: err = repr(err) self.error = (err, traceback.format_exc()) @@ -826,7 +826,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog): self.s_r_dst_ident.setCompleter(QCompleter(ident_types)) try: self.s_r_dst_ident.setPlaceholderText(_('Enter an identifier type')) - except: + except Exception: pass self.s_r_src_ident.addItems(ident_types) @@ -1105,7 +1105,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog): v = int(val[0]) if v < 0 or v > 10: ok = False - except: + except Exception: ok = False if not ok: raise Exception(_('The replacement value for a rating column must ' @@ -1232,7 +1232,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog): else: try: val = dict([(t.split(':', maxsplit=1)) for t in val]) - except: + except Exception: import traceback ans = question_dialog(self, _('Invalid identifier string'), _('The identifier string for book "{0}" (id {1}) is ' @@ -1333,7 +1333,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog): return QDialog.accept(self) try: source = self.s_r_sf_itemdata(None) - except: + except Exception: source = '' do_sr = source and self.s_r_obj @@ -1476,7 +1476,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog): names.extend(self.query_field_values) try: dex = names.index(self.saved_search_name) - except: + except Exception: dex = 0 name = '' while not name: @@ -1541,25 +1541,25 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog): def set_text(attr, key): try: attr.setText(item[key]) - except: + except Exception: pass def set_checked(attr, key): try: attr.setChecked(item[key]) - except: + except Exception: attr.setChecked(False) def set_value(attr, key): try: attr.setValue(int(item[key])) - except: + except Exception: attr.setValue(0) def set_index(attr, key): try: attr.setCurrentIndex(attr.findText(item[key])) - except: + except Exception: attr.setCurrentIndex(0) set_index(self.search_mode, 'search_mode') diff --git a/src/calibre/gui2/dialogs/plugin_updater.py b/src/calibre/gui2/dialogs/plugin_updater.py index 6ba69617db..5d7387a951 100644 --- a/src/calibre/gui2/dialogs/plugin_updater.py +++ b/src/calibre/gui2/dialogs/plugin_updater.py @@ -96,7 +96,7 @@ def read_available_plugins(raise_error=False): if not raw: return raw = json.loads(bz2.decompress(raw)) - except: + except Exception: if raise_error: raise traceback.print_exc() @@ -761,7 +761,7 @@ class PluginUpdaterDialog(SizePersistedDialog): display_plugin.plugin = plugin # We cannot read the 'actual' version information as the plugin will not be loaded yet display_plugin.installed_version = display_plugin.available_version - except: + except Exception: if DEBUG: prints(f'ERROR occurred while installing plugin: {display_plugin.name}') traceback.print_exc() diff --git a/src/calibre/gui2/dialogs/quickview.py b/src/calibre/gui2/dialogs/quickview.py index 547e04b80f..f2efa880d1 100644 --- a/src/calibre/gui2/dialogs/quickview.py +++ b/src/calibre/gui2/dialogs/quickview.py @@ -187,7 +187,7 @@ class Quickview(QDialog, Ui_Quickview): gprefs.get('quickview_dialog_books_table_widths', None) if not self.is_pane: self.restore_geometry(gprefs, 'quickview_dialog_geometry') - except: + except Exception: pass self.view = gui.library_view @@ -501,7 +501,7 @@ class Quickview(QDialog, Ui_Quickview): # eventually. try: self.refresh(self.view.model().index(self.db.row(mi.id), self.current_column)) - except: + except Exception: pass # clicks on the items listWidget @@ -539,7 +539,7 @@ class Quickview(QDialog, Ui_Quickview): if self.current_book_id == book_id and self.current_key == key: return self._refresh(book_id, key) - except: + except Exception: traceback.print_exc() self.indicate_no_items() @@ -582,7 +582,7 @@ class Quickview(QDialog, Ui_Quickview): if is_grid_view: key = 'authors' vals = mi.get(key, None) - except: + except Exception: traceback.print_exc() self.current_book_id = book_id @@ -710,7 +710,7 @@ class Quickview(QDialog, Ui_Quickview): else: v = mi.format_field(col)[1] return v, v, 0 - except: + except Exception: traceback.print_exc() return _('Something went wrong while filling in the table'), '', 0 @@ -754,7 +754,7 @@ class Quickview(QDialog, Ui_Quickview): try: self.db.data.index(book_id) return True - except: + except Exception: return False def quickview_item(self, row, column): @@ -768,7 +768,7 @@ class Quickview(QDialog, Ui_Quickview): self.quickview_item(row, column) else: self.quickview_item(row, self.key_to_table_widget_column(self.current_key)) - except: + except Exception: traceback.print_exc() self.book_not_in_view_error() diff --git a/src/calibre/gui2/dialogs/scheduler.py b/src/calibre/gui2/dialogs/scheduler.py index f70b581c21..20b4563426 100644 --- a/src/calibre/gui2/dialogs/scheduler.py +++ b/src/calibre/gui2/dialogs/scheduler.py @@ -193,7 +193,7 @@ class DaysOfMonth(Base): x.strip()] try: days_of_month = tuple(map(int, parts)) - except: + except Exception: days_of_month = (1,) if not days_of_month: days_of_month = (1,) @@ -421,7 +421,7 @@ class SchedulerDialog(QDialog): self.recipe_model.searched.disconnect(self.search.search_done) self.search.search.disconnect() self.download.disconnect() - except: + except Exception: pass self.recipe_model = None @@ -518,7 +518,7 @@ class SchedulerDialog(QDialog): recipe = self.recipe_model.recipe_from_urn(urn) try: schedule_info = self.recipe_model.schedule_info_from_urn(urn) - except: + except Exception: # Happens if user does something stupid like unchecking all the # days of the week schedule_info = None @@ -666,7 +666,7 @@ class Scheduler(QObject): try: ids = list(db.tags_older_than(_('News'), delta, must_have_authors=['calibre'])) - except: + except Exception: # Happens if library is being switched ids = [] if ids: diff --git a/src/calibre/gui2/dialogs/smartdevice.py b/src/calibre/gui2/dialogs/smartdevice.py index b539473a5d..23d1217ccb 100644 --- a/src/calibre/gui2/dialogs/smartdevice.py +++ b/src/calibre/gui2/dialogs/smartdevice.py @@ -113,7 +113,7 @@ class SmartdeviceDialog(QDialog, Ui_Dialog): return try: port = int(port) - except: + except Exception: error_dialog(self, _('Invalid port number'), _('The port must be a number between 8000 and 65535.'), show=True) return diff --git a/src/calibre/gui2/dialogs/template_dialog.py b/src/calibre/gui2/dialogs/template_dialog.py index 4e3f0a37b6..f57320bdbd 100644 --- a/src/calibre/gui2/dialogs/template_dialog.py +++ b/src/calibre/gui2/dialogs/template_dialog.py @@ -596,7 +596,7 @@ class TemplateDialog(QDialog, Ui_TemplateDialog): self.table_column_widths = None try: self.table_column_widths = gprefs.get(self.geometry_string('template_editor_table_widths'), None) - except: + except Exception: pass self.set_mi(mi, fm) @@ -639,7 +639,7 @@ class TemplateDialog(QDialog, Ui_TemplateDialog): try: with open(P('template-functions.json'), 'rb') as f: self.builtin_source_dict = json.load(f, encoding='utf-8') - except: + except Exception: self.builtin_source_dict = {} self.function_names = func_names = sorted(self.all_functions) @@ -997,11 +997,11 @@ def evaluate(book, context): os.makedirs(d) with open(os.path.join(d, icon_name), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) - except: + except Exception: traceback.print_exc() self.icon_files.setCurrentIndex(self.icon_files.findText(icon_name)) self.icon_files.adjustSize() - except: + except Exception: traceback.print_exc() def update_filename_box(self): @@ -1230,7 +1230,7 @@ class BreakReporterBase(QDialog): self.table_column_widths = \ gprefs.get('template_editor_break_table_widths', None) t.setColumnWidth(0, self.table_column_widths[0]) - except: + except Exception: t.setColumnWidth(0, t.fontMetrics().averageCharWidth() * 20) t.horizontalHeader().sectionResized.connect(self.table_column_resized) t.horizontalHeader().setStretchLastSection(True) diff --git a/src/calibre/gui2/dnd.py b/src/calibre/gui2/dnd.py index c203d30962..91998c2ae6 100644 --- a/src/calibre/gui2/dnd.py +++ b/src/calibre/gui2/dnd.py @@ -141,7 +141,7 @@ def data_as_string(f, md): if '/x-moz' in f: try: raw = raw.decode('utf-16') - except: + except Exception: pass return raw @@ -351,7 +351,7 @@ def get_firefox_rurl(md, exts): url, fname = _get_firefox_pair(md, exts, 'application/x-moz-file-promise-url', 'application/x-moz-file-promise-dest-filename') - except: + except Exception: if DEBUG: import traceback traceback.print_exc() @@ -360,7 +360,7 @@ def get_firefox_rurl(md, exts): try: url, fname = _get_firefox_pair(md, exts, 'text/x-moz-url-data', 'text/x-moz-url-desc') - except: + except Exception: if DEBUG: import traceback traceback.print_exc() @@ -375,7 +375,7 @@ def get_firefox_rurl(md, exts): ext = posixpath.splitext(fname)[1][1:].lower() if ext not in exts: fname = url = None - except: + except Exception: if DEBUG: import traceback traceback.print_exc() diff --git a/src/calibre/gui2/ebook_download.py b/src/calibre/gui2/ebook_download.py index ac627556e4..d0288d04e3 100644 --- a/src/calibre/gui2/ebook_download.py +++ b/src/calibre/gui2/ebook_download.py @@ -89,7 +89,7 @@ class EbookDownload: try: if dfilename: os.remove(dfilename) - except: + except Exception: pass def _download(self, cookie_file, url, filename, save_loc, add_to_lib, create_browser): diff --git a/src/calibre/gui2/email.py b/src/calibre/gui2/email.py index 587ddad357..6ba00766e9 100644 --- a/src/calibre/gui2/email.py +++ b/src/calibre/gui2/email.py @@ -511,7 +511,7 @@ class EmailMixin: # {{{ self.library_view.model().delete_books_by_id(remove) self.iactions['Remove Books'].library_ids_deleted2(remove, next_id=next_id) - except: + except Exception: import traceback # Probably the user deleted the files, in any case, failing diff --git a/src/calibre/gui2/font_family_chooser.py b/src/calibre/gui2/font_family_chooser.py index 2a824dd6a1..65e47c3409 100644 --- a/src/calibre/gui2/font_family_chooser.py +++ b/src/calibre/gui2/font_family_chooser.py @@ -113,7 +113,7 @@ class FontFamilyDelegate(QStyledItemDelegate): def sizeHint(self, option, index): try: return self.do_size_hint(option, index) - except: + except Exception: return QSize(300, 50) def do_size_hint(self, option, index): @@ -128,7 +128,7 @@ class FontFamilyDelegate(QStyledItemDelegate): painter.save() try: self.do_paint(painter, option, index) - except: + except Exception: import traceback traceback.print_exc() painter.restore() @@ -308,7 +308,7 @@ class FontFamilyDialog(QDialog): def build_font_list(self): try: self.families = list(self.font_scanner.find_font_families()) - except: + except Exception: self.families = [] print('WARNING: Could not load fonts') import traceback diff --git a/src/calibre/gui2/init.py b/src/calibre/gui2/init.py index 3f98c63a6b..82d373c47b 100644 --- a/src/calibre/gui2/init.py +++ b/src/calibre/gui2/init.py @@ -205,7 +205,7 @@ class StatusBar(QStatusBar): # {{{ def set_label(self): try: self._set_label() - except: + except Exception: import traceback traceback.print_exc() diff --git a/src/calibre/gui2/jobs.py b/src/calibre/gui2/jobs.py index 1bca58d9a1..6af8feebe1 100644 --- a/src/calibre/gui2/jobs.py +++ b/src/calibre/gui2/jobs.py @@ -166,7 +166,7 @@ class JobManager(QAbstractTableModel, AdaptSQP): # {{{ if job.killed or job.failed: return self.error_icon return self.done_icon - except: + except Exception: import traceback traceback.print_exc() return None @@ -229,7 +229,7 @@ class JobManager(QAbstractTableModel, AdaptSQP): # {{{ # Kill parallel jobs that have gone on too long try: wmax_time = gprefs['worker_max_time'] * 60 - except: + except Exception: wmax_time = 0 if wmax_time > 0: @@ -398,7 +398,7 @@ class FilterModel(QSortFilterProxyModel): # {{{ m = self.sourceModel() try: job = m.row_to_job(source_row) - except: + except Exception: return False return not getattr(job, 'hidden_in_gui', False) diff --git a/src/calibre/gui2/keyboard.py b/src/calibre/gui2/keyboard.py index 1c7ebd3f57..c7f8c97777 100644 --- a/src/calibre/gui2/keyboard.py +++ b/src/calibre/gui2/keyboard.py @@ -257,7 +257,7 @@ class ConfigModel(SearchQueryParser, QAbstractItemModel): ip = self.data try: return self.createIndex(row, column, ip[row]) - except: + except Exception: pass return ROOT @@ -350,7 +350,7 @@ class ConfigModel(SearchQueryParser, QAbstractItemModel): else: try: sc = self.data[c].children[p].data - except: + except Exception: continue if query in lower(sc['name']): ans.add((c, p)) diff --git a/src/calibre/gui2/library/alternate_views.py b/src/calibre/gui2/library/alternate_views.py index ea294b7583..f1403e764a 100644 --- a/src/calibre/gui2/library/alternate_views.py +++ b/src/calibre/gui2/library/alternate_views.py @@ -210,7 +210,7 @@ def drag_data(self): def path_for_id(i): try: ans = db.format_path(i, fmt, index_is_id=True) - except: + except Exception: ans = None if ans is None: fmts = db.formats(i, index_is_id=True) @@ -221,7 +221,7 @@ def drag_data(self): for f in fmts: try: ans = db.format_path(i, f, index_is_id=True) - except: + except Exception: ans = None if ans is None: ans = db.abspath(i, index_is_id=True) diff --git a/src/calibre/gui2/library/models.py b/src/calibre/gui2/library/models.py index a0cfb8d06f..7d51ee8247 100644 --- a/src/calibre/gui2/library/models.py +++ b/src/calibre/gui2/library/models.py @@ -91,7 +91,7 @@ class ColumnColor: # {{{ if color.isValid(): self.mi = None return color - except: + except Exception: pass # }}} @@ -178,7 +178,7 @@ class ColumnIcon: # {{{ icon_bitmap_cache[icon_string] = result self.mi = None return result - except: + except Exception: pass # }}} @@ -496,7 +496,7 @@ class BooksModel(QAbstractTableModel): # {{{ return None try: return self.ids_to_highlight[self.current_highlighted_idx] - except: + except Exception: return None def get_next_highlighted_id(self, current_row, forward): @@ -516,7 +516,7 @@ class BooksModel(QAbstractTableModel): # {{{ break try: self.current_highlighted_idx = self.ids_to_highlight.index(self.id(row_)) - except: + except Exception: # This shouldn't happen ... return None return self.get_current_highlighted_id() @@ -636,7 +636,7 @@ class BooksModel(QAbstractTableModel): # {{{ mi.row_number = idx try: mi.marked = self.db.data.get_marked(idx, index_is_id=False) - except: + except Exception: mi.marked = None return mi @@ -755,7 +755,7 @@ class BooksModel(QAbstractTableModel): # {{{ _set_metadata(pt, newmi, format) else: _set_metadata(pt, mi, format) - except: + except Exception: traceback.print_exc() pt.close() @@ -1081,7 +1081,7 @@ class BooksModel(QAbstractTableModel): # {{{ if color.isValid(): self.column_color.mi = None return (color) - except: + except Exception: pass if self.color_row_fmt_cache is None: @@ -1284,7 +1284,7 @@ class BooksModel(QAbstractTableModel): # {{{ error_dialog(get_gui(), _('Failed to set data'), _('Could not set data, click "Show details" to see why.'), det_msg=traceback.format_exc(), show=True) - except: + except Exception: import traceback traceback.print_exc() error_dialog(get_gui(), _('Failed to set data'), @@ -1513,7 +1513,7 @@ class DeviceBooksModel(BooksModel): # {{{ idx = None try: idx = self.db.index(item) - except: + except Exception: path = getattr(item, 'path', None) if path: for i, x in enumerate(self.db): @@ -1622,14 +1622,14 @@ class DeviceBooksModel(BooksModel): # {{{ ax = self.db[x].author_sort if not ax: raise Exception('') - except: + except Exception: try: ax = authors_to_string(self.db[x].authors) - except: + except Exception: ax = '' try: return sort_key(ax) - except: + except Exception: return ax keygen = { diff --git a/src/calibre/gui2/library/views.py b/src/calibre/gui2/library/views.py index 1c04e6158d..5c97651736 100644 --- a/src/calibre/gui2/library/views.py +++ b/src/calibre/gui2/library/views.py @@ -191,7 +191,7 @@ class PreserveViewState: # {{{ self.hscroll = view.horizontalScrollBar().value() ci = self.view.currentIndex() self.row, self.col = ci.row(), ci.column() - except: + except Exception: import traceback traceback.print_exc() @@ -501,7 +501,7 @@ class BooksView(TableView): # {{{ return try: idx = self.column_map.index(column) - except: + except Exception: return h = view.column_header @@ -993,7 +993,7 @@ class BooksView(TableView): # {{{ ans = gprefs.get(name, None) try: del gprefs[name] - except: + except Exception: pass if ans is not None: db.new_api.set_pref(name, ans) @@ -1023,7 +1023,7 @@ class BooksView(TableView): # {{{ if not isinstance(d, bool): d = True if d == 0 else False sh.append((c, d)) - except: + except Exception: # Ignore invalid tweak values as users seem to often get them # wrong print('Ignoring invalid sort_columns_at_startup tweak, with error:') @@ -1473,7 +1473,7 @@ class BooksView(TableView): # {{{ def current_id(self): try: return self.model().id(self.currentIndex()) - except: + except Exception: pass return None @@ -1513,7 +1513,7 @@ class BooksView(TableView): # {{{ continue try: return self.model().id(self.model().index(i, column)) - except: + except Exception: pass # No unselected rows after the current row, look before @@ -1522,7 +1522,7 @@ class BooksView(TableView): # {{{ continue try: return self.model().id(self.model().index(i, column)) - except: + except Exception: pass return None diff --git a/src/calibre/gui2/linux_file_dialogs.py b/src/calibre/gui2/linux_file_dialogs.py index 42b8d36092..c9f018d2a5 100644 --- a/src/calibre/gui2/linux_file_dialogs.py +++ b/src/calibre/gui2/linux_file_dialogs.py @@ -330,7 +330,7 @@ def linux_native_dialog(name): def r(): try: ret[0] = func(window, *args, **kwargs) - except: + except Exception: ret[1] = sys.exc_info() while not loop.isRunning(): time.sleep(0.001) # yield so that loop starts diff --git a/src/calibre/gui2/lrf_renderer/main.py b/src/calibre/gui2/lrf_renderer/main.py index 1cd3b02e76..8f07883c52 100644 --- a/src/calibre/gui2/lrf_renderer/main.py +++ b/src/calibre/gui2/lrf_renderer/main.py @@ -258,7 +258,7 @@ def file_renderer(stream, opts, parent=None, logger=None): try: # Set lrfviewer as the default for LRF files for this user from subprocess import call call('xdg-mime default calibre-lrfviewer.desktop application/lrf', shell=True) - except: + except Exception: pass m = Main(logger, opts, parent=parent) m.set_ebook(stream) diff --git a/src/calibre/gui2/main.py b/src/calibre/gui2/main.py index 19fab1d55f..5b46572a6e 100644 --- a/src/calibre/gui2/main.py +++ b/src/calibre/gui2/main.py @@ -177,7 +177,7 @@ def get_library_path(gui_runner): if not os.path.exists(library_path): try: os.makedirs(library_path) - except: + except Exception: gui_runner.show_error(_('Failed to create library'), _('Failed to create calibre library at: %r.\n' 'You will be asked to choose a new library location.')%library_path, @@ -297,7 +297,7 @@ class GuiRunner(QObject): try: self.library_path = candidate db = LibraryDatabase(candidate) - except: + except Exception: self.show_error(_('Bad database location'), _( 'Bad database location %r. calibre will now quit.')%self.library_path, det_msg=traceback.format_exc()) @@ -343,7 +343,7 @@ class GuiRunner(QObject): return if repair_library(self.library_path): db = LibraryDatabase(self.library_path) - except: + except Exception: self.show_error(_('Bad database location'), _('Bad database location %r. Will start with ' ' a new, empty calibre library')%self.library_path, @@ -423,7 +423,7 @@ def run_gui_(opts, args, app, gui_debug=None): if iswindows: try: runner.main.system_tray_icon.hide() - except: + except Exception: pass if getattr(runner.main, 'gui_debug', None) is not None: debugfile = runner.main.gui_debug diff --git a/src/calibre/gui2/main_window.py b/src/calibre/gui2/main_window.py index 968ae3f274..5502a442a3 100644 --- a/src/calibre/gui2/main_window.py +++ b/src/calibre/gui2/main_window.py @@ -221,7 +221,7 @@ class MainWindow(QMainWindow): try: from calibre.debug import print_basic_debug_info print_basic_debug_info(out=sio) - except: + except Exception: pass traceback.print_exception(exc_type, value, tb, file=sio) if getattr(value, 'locking_debug_msg', None): @@ -238,7 +238,7 @@ class MainWindow(QMainWindow): show=True) except BaseException: pass - except: + except Exception: pass diff --git a/src/calibre/gui2/metadata/basic_widgets.py b/src/calibre/gui2/metadata/basic_widgets.py index 667941cc24..e2ca2dcf23 100644 --- a/src/calibre/gui2/metadata/basic_widgets.py +++ b/src/calibre/gui2/metadata/basic_widgets.py @@ -318,7 +318,7 @@ class TitleSortEdit(TitleEdit, ToMetadataMixin, LineEditIndicators): def book_lang(self): try: book_lang = self.languages_edit.lang_codes[0] - except: + except Exception: book_lang = None return book_lang @@ -344,15 +344,15 @@ class TitleSortEdit(TitleEdit, ToMetadataMixin, LineEditIndicators): def break_cycles(self): try: self.title_edit.textChanged.disconnect() - except: + except Exception: pass try: self.textChanged.disconnect() - except: + except Exception: pass try: self.autogen_button.clicked.disconnect() - except: + except Exception: pass # }}} @@ -470,7 +470,7 @@ class AuthorsEdit(EditWithComplete, ToMetadataMixin): self.db = self.dialog = None try: self.manage_authors_signal.triggered.disconnect() - except: + except Exception: pass @@ -600,23 +600,23 @@ class AuthorSortEdit(EnLineEdit, ToMetadataMixin, LineEditIndicators): self.db = None try: self.authors_edit.editTextChanged.disconnect() - except: + except Exception: pass try: self.textChanged.disconnect() - except: + except Exception: pass try: self.autogen_button.clicked.disconnect() - except: + except Exception: pass try: self.copy_a_to_as_action.triggered.disconnect() - except: + except Exception: pass try: self.copy_as_to_a_action.triggered.disconnect() - except: + except Exception: pass self.authors_edit = None @@ -763,7 +763,7 @@ class SeriesIndexEdit(make_undoable(QDoubleSpinBox), ToMetadataMixin): ns = self.db.get_next_series_num_for(series) self.current_val = ns self.original_series_name = series - except: + except Exception: import traceback traceback.print_exc() @@ -773,15 +773,15 @@ class SeriesIndexEdit(make_undoable(QDoubleSpinBox), ToMetadataMixin): def break_cycles(self): try: self.series_edit.currentIndexChanged.disconnect() - except: + except Exception: pass try: self.series_edit.editTextChanged.disconnect() - except: + except Exception: pass try: self.series_edit.lineEdit().editingFinished.disconnect() - except: + except Exception: pass self.db = self.series_edit = self.dialog = None @@ -1158,7 +1158,7 @@ class FormatsManager(QWidget): with stream: mi = get_metadata(stream, ext) return mi, ext - except: + except Exception: import traceback error_dialog(self, _('Could not read metadata'), _('Could not read metadata from %s format')%ext.upper(), @@ -1174,7 +1174,7 @@ class FormatsManager(QWidget): for name in self.temp_files: try: os.remove(name) - except: + except Exception: pass self.temp_files = [] # }}} @@ -1424,7 +1424,7 @@ class Cover(ImageView): # {{{ def break_cycles(self): try: self.cover_changed.disconnect() - except: + except Exception: pass self.dialog = self._cdata = self.current_val = self.original_val = None diff --git a/src/calibre/gui2/metadata/bulk_download.py b/src/calibre/gui2/metadata/bulk_download.py index c19173eacd..e34fc97eda 100644 --- a/src/calibre/gui2/metadata/bulk_download.py +++ b/src/calibre/gui2/metadata/bulk_download.py @@ -199,14 +199,14 @@ class Notifier(Thread): while self.keep_going: try: names = os.listdir(self.tdir) - except: + except Exception: pass else: for x in names: if x.endswith('.log'): try: book_id = int(x.partition('.')[0]) - except: + except Exception: continue if book_id not in self.seen and book_id in self.title_map: self.seen.add(book_id) diff --git a/src/calibre/gui2/metadata/diff.py b/src/calibre/gui2/metadata/diff.py index 92dca33ebd..b4626f5aee 100644 --- a/src/calibre/gui2/metadata/diff.py +++ b/src/calibre/gui2/metadata/diff.py @@ -250,7 +250,7 @@ class SeriesEdit(LineEdit): val = str(self.text()).strip() try: series_index = float(val.rpartition('[')[-1].rstrip(']').strip()) - except: + except Exception: series_index = 1.0 series = val.rpartition('[')[0].strip() or val.rpartition('[')[-1].strip() or None mi.set(self.field, series) diff --git a/src/calibre/gui2/metadata/single.py b/src/calibre/gui2/metadata/single.py index e309d550bf..ad3e568f97 100644 --- a/src/calibre/gui2/metadata/single.py +++ b/src/calibre/gui2/metadata/single.py @@ -717,7 +717,7 @@ class MetadataSingleDialogBase(QDialog): try: self.save_geometry(gprefs, 'metasingle_window_geometry3') self.save_widget_settings() - except: + except Exception: # Weird failure, see https://bugs.launchpad.net/bugs/995271 import traceback traceback.print_exc() @@ -802,7 +802,7 @@ class MetadataSingleDialogBase(QDialog): def disconnect(signal): try: signal.disconnect() - except: + except Exception: pass # Fails if view format was never connected disconnect(self.view_format) disconnect(self.edit_format) diff --git a/src/calibre/gui2/metadata/single_download.py b/src/calibre/gui2/metadata/single_download.py index 1028ce1e08..852a15bd8b 100644 --- a/src/calibre/gui2/metadata/single_download.py +++ b/src/calibre/gui2/metadata/single_download.py @@ -171,7 +171,7 @@ class ResultsModel(QAbstractTableModel): # {{{ if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole: try: return (self.COLUMNS[section]) - except: + except Exception: return None return None @@ -191,7 +191,7 @@ class ResultsModel(QAbstractTableModel): # {{{ row, col = index.row(), index.column() try: book = self.results[row] - except: + except Exception: return None if role == Qt.ItemDataRole.DisplayRole and col not in self.ICON_COLS: res = self.data_as_text(book, col) @@ -454,7 +454,7 @@ class IdentifyWorker(Thread): # {{{ result.gui_rank = i except WorkerError as e: self.error = force_unicode(e.orig_tb) - except: + except Exception: import traceback self.error = force_unicode(traceback.format_exc()) @@ -601,7 +601,7 @@ class CoverWorker(Thread): # {{{ self.run_fork() except WorkerError as e: self.error = force_unicode(e.orig_tb) - except: + except Exception: import traceback self.error = force_unicode(traceback.format_exc()) @@ -635,7 +635,7 @@ class CoverWorker(Thread): # {{{ width, height = int(width), int(height) with open(os.path.join(tdir, x), 'rb') as f: data = f.read() - except: + except Exception: import traceback traceback.print_exc() else: @@ -693,7 +693,7 @@ class CoversModel(QAbstractListModel): # {{{ def data(self, index, role): try: text, pmap, cover, waiting = self.covers[index.row()] - except: + except Exception: return None if role == Qt.ItemDataRole.DecorationRole: return pmap diff --git a/src/calibre/gui2/preferences/coloring.py b/src/calibre/gui2/preferences/coloring.py index dbdd772421..f58e0cb66c 100644 --- a/src/calibre/gui2/preferences/coloring.py +++ b/src/calibre/gui2/preferences/coloring.py @@ -157,7 +157,7 @@ class ConditionEditor(QWidget): # {{{ texts = _('If the ___ column ___ value') try: one, two, three = texts.split('___') - except: + except Exception: one, two, three = 'If the ', ' column ', ' value ' self.l1 = l1 = QLabel(one) @@ -663,7 +663,7 @@ class RuleEditor(QDialog): # {{{ os.makedirs(d) with open(os.path.join(d, icon_name), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) - except: + except Exception: import traceback traceback.print_exc() self.update_filename_box() @@ -674,7 +674,7 @@ class RuleEditor(QDialog): # {{{ else: self.filename_box.setCurrentIndex(self.filename_box.findText(icon_name)) self.filename_box.adjustSize() - except: + except Exception: import traceback traceback.print_exc() @@ -753,7 +753,7 @@ class RuleEditor(QDialog): # {{{ self.conditions_widget.layout().addWidget(ce) try: ce.condition = c - except: + except Exception: import traceback traceback.print_exc() @@ -820,7 +820,7 @@ class RulesModel(QAbstractListModel): # {{{ return try: rule = rule_from_template(self.fm, template) - except: + except Exception: rule = template return rule @@ -853,7 +853,7 @@ class RulesModel(QAbstractListModel): # {{{ row = index.row() try: kind, col, rule = self.rules[row] - except: + except Exception: return None if role == Qt.ItemDataRole.DisplayRole: if col == color_row_key: @@ -1231,7 +1231,7 @@ class EditRules(QWidget): # {{{ def edit_rule(self, index): try: kind, col, rule = self.model.data(index, Qt.ItemDataRole.UserRole) - except: + except Exception: return if isinstance(rule, Rule): d = RuleEditor(self.model.fm, self.pref_name) diff --git a/src/calibre/gui2/preferences/columns.py b/src/calibre/gui2/preferences/columns.py index 6889c15ed4..f7e2e7a830 100644 --- a/src/calibre/gui2/preferences/columns.py +++ b/src/calibre/gui2/preferences/columns.py @@ -413,7 +413,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): self.setup_row(row, new_key, self.column_order_val(row)) self.opt_columns.scrollTo(self.opt_columns.currentIndex()) self.changed_signal.emit() - except: + except Exception: import traceback traceback.print_exc() diff --git a/src/calibre/gui2/preferences/create_custom_column.py b/src/calibre/gui2/preferences/create_custom_column.py index c07354c59a..390ba80e9b 100644 --- a/src/calibre/gui2/preferences/create_custom_column.py +++ b/src/calibre/gui2/preferences/create_custom_column.py @@ -613,7 +613,7 @@ class CreateCustomColumn(QDialog): def datatype_changed(self, *args): try: col_type = self.column_types[self.column_type_box.currentIndex()]['datatype'] - except: + except Exception: col_type = None needs_format = col_type in ('datetime', 'int', 'float') for x in ('box', 'default_label', 'label'): @@ -758,7 +758,7 @@ class CreateCustomColumn(QDialog): else: try: tv = parse_date(default_val) - except: + except Exception: tv = UNDEFINED_DATE if tv == UNDEFINED_DATE: return self.simple_error(_('Invalid default value'), @@ -829,7 +829,7 @@ class CreateCustomColumn(QDialog): msg = _('The default value must be a real number') tv = float(default_val) display_dict['default_value'] = tv - except: + except Exception: return self.simple_error(_('Invalid default value'), msg) elif col_type == 'comments': display_dict['heading_position'] = str(self.comments_heading_position.currentData()) @@ -840,7 +840,7 @@ class CreateCustomColumn(QDialog): if default_val: try: tv = int((float(default_val) if half_stars else int(default_val)) * 2) - except: + except Exception: tv = -1 if tv < 0 or tv > 10: if half_stars: diff --git a/src/calibre/gui2/preferences/look_feel_tabs/__init__.py b/src/calibre/gui2/preferences/look_feel_tabs/__init__.py index 0bc448ee22..5a26182ef8 100644 --- a/src/calibre/gui2/preferences/look_feel_tabs/__init__.py +++ b/src/calibre/gui2/preferences/look_feel_tabs/__init__.py @@ -152,13 +152,13 @@ class DisplayedFields(QAbstractListModel): def data(self, index, role): try: field, visible = self.fields[index.row()] - except: + except Exception: return None if role == Qt.ItemDataRole.DisplayRole: name = field try: name = self.db.field_metadata[field]['name'] - except: + except Exception: pass if field == 'path': name = _('Folders/path') @@ -322,6 +322,6 @@ def selected_rows_metadatas(): for row in rows: if row.isValid(): rslt.append(db.new_api.get_proxy_metadata(db.data.index_to_id(row.row()))) - except: + except Exception: pass return rslt diff --git a/src/calibre/gui2/preferences/look_feel_tabs/tb_icon_rules.py b/src/calibre/gui2/preferences/look_feel_tabs/tb_icon_rules.py index 0a718f1ec2..40d1b7c105 100644 --- a/src/calibre/gui2/preferences/look_feel_tabs/tb_icon_rules.py +++ b/src/calibre/gui2/preferences/look_feel_tabs/tb_icon_rules.py @@ -782,7 +782,7 @@ class TbIconRulesTab(LazyConfigWidgetBase, Ui_Form): path = os.path.join(config_dir, 'tb_icons', icon_file) try: os.remove(path) - except: + except Exception: pass tbvip[cat_item.lookup_name].pop(value_text, None) continue diff --git a/src/calibre/gui2/preferences/metadata_sources.py b/src/calibre/gui2/preferences/metadata_sources.py index 65d3683d82..c3c6a94bec 100644 --- a/src/calibre/gui2/preferences/metadata_sources.py +++ b/src/calibre/gui2/preferences/metadata_sources.py @@ -68,7 +68,7 @@ class SourcesModel(QAbstractTableModel): # {{{ def data(self, index, role): try: plugin = self.plugins[index.row()] - except: + except Exception: return None col = index.column() @@ -96,7 +96,7 @@ class SourcesModel(QAbstractTableModel): # {{{ def setData(self, index, val, role): try: plugin = self.plugins[index.row()] - except: + except Exception: return False col = index.column() ret = False @@ -206,7 +206,7 @@ class FieldsModel(QAbstractListModel): # {{{ def data(self, index, role): try: field = self.fields[index.row()] - except: + except Exception: return None if role == Qt.ItemDataRole.DisplayRole: return self.descs.get(field, field) @@ -236,7 +236,7 @@ class FieldsModel(QAbstractListModel): # {{{ def setData(self, index, val, role): try: field = self.fields[index.row()] - except: + except Exception: return False ret = False if role == Qt.ItemDataRole.CheckStateRole: @@ -378,7 +378,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): def pc_finished(self): try: self.pc.finished.disconnect() - except: + except Exception: pass self.stack.setCurrentIndex(0) self.stack.removeWidget(self.pc) diff --git a/src/calibre/gui2/preferences/plugins.py b/src/calibre/gui2/preferences/plugins.py index 26bd9a4957..6b6a50f458 100644 --- a/src/calibre/gui2/preferences/plugins.py +++ b/src/calibre/gui2/preferences/plugins.py @@ -84,7 +84,7 @@ class PluginModel(QAbstractItemModel, AdaptSQP): # {{{ else: try: plugin = self._data[self.categories[c]][p] - except: + except Exception: continue if query in lower(plugin.name) or query in lower(plugin.author) or \ query in lower(plugin.description): @@ -428,7 +428,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): all_locations = OrderedDict(ConfigWidget.LOCATIONS) try: plugin_action = plugin.load_actual_plugin(self.gui) - except: + except Exception: # Broken plugin, fails to initialize. Given that, it's probably # already configured, so we can just quit. return diff --git a/src/calibre/gui2/preferences/template_functions.py b/src/calibre/gui2/preferences/template_functions.py index 15c03e71c6..c402b4d381 100644 --- a/src/calibre/gui2/preferences/template_functions.py +++ b/src/calibre/gui2/preferences/template_functions.py @@ -155,7 +155,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): try: self.builtin_source_dict = json.loads(P('template-functions.json', data=True, allow_user_override=False).decode('utf-8')) - except: + except Exception: traceback.print_exc() self.builtin_source_dict = {} @@ -169,7 +169,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): for v in self.db.prefs.get('user_template_functions', []): if function_object_type(v) is not StoredObjectType.PythonFunction: self.st_funcs.update({function_pref_name(v):compile_user_function(*v)}) - except: + except Exception: if question_dialog(self, _('Template functions'), _('The template functions saved in the library are corrupt. ' "Do you want to delete them? Answering 'Yes' will delete all " @@ -339,7 +339,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): prog = str(self.program.toPlainText()) compile_user_function(name, str(self.documentation.toPlainText()), self.argument_count.value(), prog) - except: + except Exception: error_dialog(self.gui, _('Template functions'), _('Exception while compiling function'), show=True, det_msg=traceback.format_exc()) @@ -358,7 +358,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): self.argument_count.value(), prog) self.funcs[name] = cls self.build_function_names_box(scroll_to=name) - except: + except Exception: error_dialog(self.gui, _('Template functions'), _('Exception while compiling function'), show=True, det_msg=traceback.format_exc()) @@ -540,7 +540,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form): 0, prog) self.st_funcs[name] = cls self.st_build_function_names_box(scroll_to=name) - except: + except Exception: error_dialog(self.gui, _('Stored templates'), _('Exception while storing template'), show=True, det_msg=traceback.format_exc()) diff --git a/src/calibre/gui2/preferences/toolbar.py b/src/calibre/gui2/preferences/toolbar.py index 97ff2dee9f..aa677ad2cd 100644 --- a/src/calibre/gui2/preferences/toolbar.py +++ b/src/calibre/gui2/preferences/toolbar.py @@ -53,7 +53,7 @@ class BaseModel(QAbstractListModel): dont_add_to=frozenset(['menubar', 'menubar-device'])) try: return gui.iactions[name] - except: + except Exception: return None def rowCount(self, parent): diff --git a/src/calibre/gui2/preferences/tweaks.py b/src/calibre/gui2/preferences/tweaks.py index 269b2cb2ee..a959d48a08 100644 --- a/src/calibre/gui2/preferences/tweaks.py +++ b/src/calibre/gui2/preferences/tweaks.py @@ -152,7 +152,7 @@ class Tweaks(QAbstractListModel, AdaptSQP): # {{{ row = index.row() try: tweak = self.tweaks[row] - except: + except Exception: return None if role == Qt.ItemDataRole.DisplayRole: return tweak.name @@ -175,7 +175,7 @@ class Tweaks(QAbstractListModel, AdaptSQP): # {{{ def parse_tweaks(self): try: custom_tweaks = read_custom_tweaks() - except: + except Exception: print('Failed to load custom tweaks file') import traceback traceback.print_exc() @@ -494,7 +494,7 @@ class ConfigWidget(ConfigWidgetBase): g, l = {}, {} try: exec(str(d.edit.toPlainText()), g, l) - except: + except Exception: import traceback return error_dialog(self, _('Failed'), _('There was a syntax error in your tweak. Click ' @@ -538,7 +538,7 @@ class ConfigWidget(ConfigWidgetBase): l, g = {}, {} try: exec(str(self.edit_tweak.toPlainText()), g, l) - except: + except Exception: import traceback error_dialog(self.gui, _('Failed'), _('There was a syntax error in your tweak. Click ' @@ -554,7 +554,7 @@ class ConfigWidget(ConfigWidgetBase): raw = raw.encode('utf-8') try: custom_tweaks = exec_tweaks(raw) - except: + except Exception: import traceback error_dialog(self, _('Invalid tweaks'), _('The tweaks you entered are invalid, try resetting the' diff --git a/src/calibre/gui2/search_box.py b/src/calibre/gui2/search_box.py index b4c5e9d1b9..9b7fbd7e4c 100644 --- a/src/calibre/gui2/search_box.py +++ b/src/calibre/gui2/search_box.py @@ -185,7 +185,7 @@ class SearchBox2(QComboBox): # {{{ def hide_completer_popup(self): try: self.lineEdit().completer().popup().setVisible(False) - except: + except Exception: pass def normalize_state(self): @@ -537,7 +537,7 @@ class SavedSearchBoxMixin: # {{{ if not current_search: raise ValueError() self.search.set_search_string(current_search) - except: + except Exception: from calibre.gui2.ui import get_gui get_gui().status_bar.show_message(_('Current search is not a saved search'), 3000) # }}} diff --git a/src/calibre/gui2/store/config/chooser/models.py b/src/calibre/gui2/store/config/chooser/models.py index 11e23f0048..b9341f3cd4 100644 --- a/src/calibre/gui2/store/config/chooser/models.py +++ b/src/calibre/gui2/store/config/chooser/models.py @@ -67,7 +67,7 @@ class Matches(QAbstractItemModel): else: try: self.matches = list(self.search_filter.parse(self.filter)) - except: + except Exception: self.matches = self.all_matches self.layoutChanged.emit() self.sort(self.sort_col, self.sort_order) diff --git a/src/calibre/gui2/store/loader.py b/src/calibre/gui2/store/loader.py index 152a14d68f..0ddf1dac78 100644 --- a/src/calibre/gui2/store/loader.py +++ b/src/calibre/gui2/store/loader.py @@ -94,7 +94,7 @@ class Stores(OrderedDict): except VersionMismatch as e: self.cached_version_map[name] = e.ver continue - except: + except Exception: import traceback prints('Failed to load cached store:', name) traceback.print_exc() @@ -128,7 +128,7 @@ class Stores(OrderedDict): for name, ver in iteritems(self.version_map)} try: updates = download_updates(ver_map) - except: + except Exception: import traceback traceback.print_exc() else: @@ -150,7 +150,7 @@ class Stores(OrderedDict): self.cached_version_map[name] = e.ver replacements[name] = src continue - except: + except Exception: import traceback prints('Failed to load downloaded store:', name) traceback.print_exc() diff --git a/src/calibre/gui2/store/search/download_thread.py b/src/calibre/gui2/store/search/download_thread.py index d34d889459..297372c9c5 100644 --- a/src/calibre/gui2/store/search/download_thread.py +++ b/src/calibre/gui2/store/search/download_thread.py @@ -123,7 +123,7 @@ class SearchThread(Thread): res.create_browser = store_plugin.create_browser self.results.put((res, store_plugin)) self.tasks.task_done() - except: + except Exception: if DEBUG: traceback.print_exc() @@ -169,7 +169,7 @@ class CoverThread(Thread): result.cover_data = scale_image(result.cover_data, 256, 256)[2] callback() self.tasks.task_done() - except: + except Exception: if DEBUG: traceback.print_exc() @@ -204,7 +204,7 @@ class DetailsThread(Thread): store_plugin.get_details(result, timeout) callback(result) self.tasks.task_done() - except: + except Exception: if DEBUG: traceback.print_exc() @@ -235,6 +235,6 @@ class CacheUpdateThread(Thread): try: store_plugin, timeout = self.tasks.get() store_plugin.update_cache(timeout=timeout, suppress_progress=True) - except: + except Exception: if DEBUG: traceback.print_exc() diff --git a/src/calibre/gui2/store/search/models.py b/src/calibre/gui2/store/search/models.py index 416c003769..f7e75ed583 100644 --- a/src/calibre/gui2/store/search/models.py +++ b/src/calibre/gui2/store/search/models.py @@ -303,7 +303,7 @@ class Matches(QAbstractItemModel): def keygen(x): try: return self.all_matches.index(x) - except: + except Exception: return 100000 self.matches = sorted(self.matches, key=keygen) diff --git a/src/calibre/gui2/store/stores/amazon_es_plugin.py b/src/calibre/gui2/store/stores/amazon_es_plugin.py index 607d5723d3..92f7cbdc8d 100644 --- a/src/calibre/gui2/store/stores/amazon_es_plugin.py +++ b/src/calibre/gui2/store/stores/amazon_es_plugin.py @@ -101,7 +101,7 @@ def search_amazon(query, max_results=10, timeout=60, author = ''.join(data.xpath(author_xpath)) try: author = author.split('by ', 1)[1].split(' (')[0] - except: + except Exception: pass price = ''.join(data.xpath(price_xpath)) diff --git a/src/calibre/gui2/store/stores/amazon_it_plugin.py b/src/calibre/gui2/store/stores/amazon_it_plugin.py index 895c825d81..ce1b1092d2 100644 --- a/src/calibre/gui2/store/stores/amazon_it_plugin.py +++ b/src/calibre/gui2/store/stores/amazon_it_plugin.py @@ -101,7 +101,7 @@ def search_amazon(query, max_results=10, timeout=60, author = ''.join(data.xpath(author_xpath)) try: author = author.split('by ', 1)[1].split(' (')[0] - except: + except Exception: pass price = ''.join(data.xpath(price_xpath)) diff --git a/src/calibre/gui2/store/stores/litres_plugin.py b/src/calibre/gui2/store/stores/litres_plugin.py index c98c11b108..a15e26be79 100644 --- a/src/calibre/gui2/store/stores/litres_plugin.py +++ b/src/calibre/gui2/store/stores/litres_plugin.py @@ -115,7 +115,7 @@ def format_price_in_RUR(price): try: price = u'{:,.2F} \u20bd'.format(float(price)) # \u20bd => руб. price = price.replace(',', ' ').replace('.', ',', 1) - except: + except Exception: pass return price diff --git a/src/calibre/gui2/store/stores/mobileread/cache_update_thread.py b/src/calibre/gui2/store/stores/mobileread/cache_update_thread.py index e696e9da85..f8bce52433 100644 --- a/src/calibre/gui2/store/stores/mobileread/cache_update_thread.py +++ b/src/calibre/gui2/store/stores/mobileread/cache_update_thread.py @@ -51,7 +51,7 @@ class CacheUpdateThread(Thread, QObject): try: with closing(br.open(url, timeout=self.timeout)) as f: raw_data = f.read() - except: + except Exception: return if not raw_data or not self._run: @@ -86,7 +86,7 @@ class CacheUpdateThread(Thread, QObject): break else: self.update_progress.emit(i) - except: + except Exception: pass # Save the book list and it's create time. diff --git a/src/calibre/gui2/store/stores/mobileread/models.py b/src/calibre/gui2/store/stores/mobileread/models.py index 94f1af96df..ff6fe1be96 100644 --- a/src/calibre/gui2/store/stores/mobileread/models.py +++ b/src/calibre/gui2/store/stores/mobileread/models.py @@ -44,7 +44,7 @@ class BooksModel(QAbstractItemModel): else: try: self.books = list(self.search_filter.parse(self.filter)) - except: + except Exception: self.books = self.all_books self.layoutChanged.emit() self.sort(self.sort_col, self.sort_order) diff --git a/src/calibre/gui2/tag_browser/model.py b/src/calibre/gui2/tag_browser/model.py index 93a0e9c49d..f5c04d383f 100644 --- a/src/calibre/gui2/tag_browser/model.py +++ b/src/calibre/gui2/tag_browser/model.py @@ -472,7 +472,7 @@ class TagsModel(QAbstractItemModel): # {{{ path = os.path.join(self.icon_config_dir, file_name) try: os.remove(path) - except: + except Exception: pass def remove_value_icon(self, key, value, file_name): @@ -1460,7 +1460,7 @@ class TagsModel(QAbstractItemModel): # {{{ order = tweaks.get('tag_browser_category_order', {'*':1}) if not isinstance(order, dict): raise TypeError() - except: + except Exception: print('Tweak tag_browser_category_order is not valid. Ignored') order = {'*': 1000} defvalue = order.get('*', 1000) diff --git a/src/calibre/gui2/tag_browser/view.py b/src/calibre/gui2/tag_browser/view.py index d35540af51..8b0eabee06 100644 --- a/src/calibre/gui2/tag_browser/view.py +++ b/src/calibre/gui2/tag_browser/view.py @@ -370,7 +370,7 @@ class TagsView(QTreeView): # {{{ try: from calibre.gui2.ui import get_gui get_gui().shift_esc() - except: + except Exception: traceback.print_exc() @property @@ -521,7 +521,7 @@ class TagsView(QTreeView): # {{{ for i, ac in enumerate(self.alter_tb.match_menu.actions()): if ac is action: config.set('match_tags_type', self.db.MATCH_TYPE[i]) - except: + except Exception: pass def mousePressEvent(self, event): @@ -732,7 +732,7 @@ class TagsView(QTreeView): # {{{ os.makedirs(d) with open(os.path.join(d, icon_file_name), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) - except: + except Exception: traceback.print_exc() return else: diff --git a/src/calibre/gui2/threaded_jobs.py b/src/calibre/gui2/threaded_jobs.py index a8c4d1970c..e9ce2b2585 100644 --- a/src/calibre/gui2/threaded_jobs.py +++ b/src/calibre/gui2/threaded_jobs.py @@ -92,7 +92,7 @@ class ThreadedJob(BaseJob): self.duration = time.time() - self.start_time try: self.callback(self) - except: + except Exception: import traceback traceback.print_exc() self._cleanup() @@ -101,7 +101,7 @@ class ThreadedJob(BaseJob): try: self.consolidate_log() - except: + except Exception: if self.log is not None: self.log.exception('Log consolidation failed') @@ -165,7 +165,7 @@ class ThreadedJobWorker(Thread): def run(self): try: self.job.start_work() - except: + except Exception: import traceback from calibre import prints @@ -199,7 +199,7 @@ class ThreadedJobServer(Thread): while self.keep_going: try: self.run_once() - except: + except Exception: import traceback traceback.print_exc() time.sleep(0.1) diff --git a/src/calibre/gui2/toc/main.py b/src/calibre/gui2/toc/main.py index eedc161ddf..ca002b8887 100644 --- a/src/calibre/gui2/toc/main.py +++ b/src/calibre/gui2/toc/main.py @@ -1309,7 +1309,7 @@ class TOCEditor(QDialog): # {{{ commit_toc(self.ebook, toc, lang=self.toc_view.toc_lang, uid=self.toc_view.toc_uid) self.ebook.commit() - except: + except Exception: import traceback tb = traceback.format_exc() self.writing_done.emit(tb) diff --git a/src/calibre/gui2/tools.py b/src/calibre/gui2/tools.py index ca6b2f31f9..743d78857a 100644 --- a/src/calibre/gui2/tools.py +++ b/src/calibre/gui2/tools.py @@ -73,7 +73,7 @@ def convert_single_ebook(parent, db, book_ids, auto_conversion=False, # {{{ try: dtitle = str(mi.title) - except: + except Exception: dtitle = repr(mi.title) desc = _('Convert book %(num)d of %(total)d (%(title)s)') % \ {'num':i + 1, 'total':total, 'title':dtitle} @@ -234,7 +234,7 @@ class QueueBulk(QProgressDialog): lrecs.remove(x) try: dtitle = str(mi.title) - except: + except Exception: dtitle = repr(mi.title) if len(dtitle) > 50: dtitle = dtitle[:50].rpartition(' ')[0]+'...' @@ -368,7 +368,7 @@ def generate_catalog(parent, dbspec, ids, device_manager, db): # {{{ connected_device['serial'] = device.detected_device.serial if \ hasattr(device.detected_device,'serial') else None connected_device['save_template'] = device.save_template() - except: + except Exception: pass # Create a temporary copy of the databases to pass into the generation diff --git a/src/calibre/gui2/tweak_book/boss.py b/src/calibre/gui2/tweak_book/boss.py index 637bfa3795..59a55ba72e 100644 --- a/src/calibre/gui2/tweak_book/boss.py +++ b/src/calibre/gui2/tweak_book/boss.py @@ -549,7 +549,7 @@ class Boss(QObject): spine_index += 1 try: added_name = c.add_file(file_name, adata, spine_index=spine_index) - except: + except Exception: self.rewind_savepoint() raise self.gui.file_list.build(c) @@ -589,7 +589,7 @@ class Boss(QObject): try: with open(path, 'rb') as f: c.add_file(name, f.read()) - except: + except Exception: self.rewind_savepoint() raise if name.rpartition('.')[2].lower() in ('ttf', 'otf', 'woff'): @@ -672,7 +672,7 @@ class Boss(QObject): self.add_savepoint(_('Before: %s') % name) try: report, changed = tweak_polish(current_container(), {action:True}, customization=customization) - except: + except Exception: self.rewind_savepoint() raise if changed: @@ -716,7 +716,7 @@ class Boss(QObject): self.add_savepoint(_('Before HTML transformation')) try: changed = transform_container(current_container(), last_used_html_transform_rules, names) - except: + except Exception: self.rewind_savepoint() raise if changed: @@ -742,7 +742,7 @@ class Boss(QObject): self.add_savepoint(_('Before style transformation')) try: changed = transform_container(current_container(), last_used_transform_rules) - except: + except Exception: self.rewind_savepoint() raise if changed: diff --git a/src/calibre/gui2/tweak_book/completion/worker.py b/src/calibre/gui2/tweak_book/completion/worker.py index 3d407c86d4..4406132b24 100644 --- a/src/calibre/gui2/tweak_book/completion/worker.py +++ b/src/calibre/gui2/tweak_book/completion/worker.py @@ -58,7 +58,7 @@ class CompletionWorker(Thread): conn = conn or self.control_conn try: eintr_retry_call(conn.send, data) - except: + except Exception: if not self.shutting_down: raise @@ -66,7 +66,7 @@ class CompletionWorker(Thread): conn = conn or self.control_conn try: return eintr_retry_call(conn.recv) - except: + except Exception: if not self.shutting_down: raise diff --git a/src/calibre/gui2/tweak_book/diff/main.py b/src/calibre/gui2/tweak_book/diff/main.py index 5224f99049..9ccd6acee8 100644 --- a/src/calibre/gui2/tweak_book/diff/main.py +++ b/src/calibre/gui2/tweak_book/diff/main.py @@ -344,7 +344,7 @@ class Diff(Dialog): for x in ('revert_requested', 'line_activated'): try: getattr(self, x).disconnect() - except: + except Exception: pass def do_search(self, reverse): @@ -500,7 +500,7 @@ def compare_books(path1, path2, revert_msg=None, revert_callback=None, parent=No d.exec() try: d.revert_requested.disconnect() - except: + except Exception: pass d.break_cycles() diff --git a/src/calibre/gui2/tweak_book/diff/view.py b/src/calibre/gui2/tweak_book/diff/view.py index 59c688a401..43cfb6d316 100644 --- a/src/calibre/gui2/tweak_book/diff/view.py +++ b/src/calibre/gui2/tweak_book/diff/view.py @@ -215,7 +215,7 @@ class TextBrowser(PlainTextEdit): # {{{ return try: lnum = int(self.line_number_map.get(block_number, '')) - except: + except Exception: lnum = 1 for i, (num, text) in enumerate(self.headers): if num > block_number: diff --git a/src/calibre/gui2/tweak_book/editor/insert_resource.py b/src/calibre/gui2/tweak_book/editor/insert_resource.py index 02a4fcc20c..ba403fc761 100644 --- a/src/calibre/gui2/tweak_book/editor/insert_resource.py +++ b/src/calibre/gui2/tweak_book/editor/insert_resource.py @@ -141,7 +141,7 @@ class ImageDelegate(QStyledItemDelegate): cover = self.cover_cache[name] = QPixmap() try: raw = current_container().raw_data(name, decode=False) - except: + except Exception: pass else: try: diff --git a/src/calibre/gui2/tweak_book/job.py b/src/calibre/gui2/tweak_book/job.py index b7c32b0da7..e57c710558 100644 --- a/src/calibre/gui2/tweak_book/job.py +++ b/src/calibre/gui2/tweak_book/job.py @@ -31,7 +31,7 @@ class LongJob(Thread): st = time.time() try: self.result = self.function(*self.args, **self.kwargs) - except: + except Exception: import traceback self.traceback = traceback.format_exc() self.time_taken = time.time() - st diff --git a/src/calibre/gui2/tweak_book/preview.py b/src/calibre/gui2/tweak_book/preview.py index b8687b4a9d..d1b06cfb6e 100644 --- a/src/calibre/gui2/tweak_book/preview.py +++ b/src/calibre/gui2/tweak_book/preview.py @@ -110,7 +110,7 @@ class ParseWorker(Thread): # Connect to the worker and send a dummy job to initialize it self.worker = offload_worker(priority='low') self.worker(mod, func, '

') - except: + except Exception: import traceback traceback.print_exc() self.launch_error = traceback.format_exc() @@ -133,7 +133,7 @@ class ParseWorker(Thread): pi, data = request[1:] try: res = self.worker(mod, func, data) - except: + except Exception: import traceback traceback.print_exc() else: diff --git a/src/calibre/gui2/tweak_book/save.py b/src/calibre/gui2/tweak_book/save.py index 469459983f..1eb62d852f 100644 --- a/src/calibre/gui2/tweak_book/save.py +++ b/src/calibre/gui2/tweak_book/save.py @@ -157,7 +157,7 @@ class SaveManager(QObject): try: count, tdir, container = x error_occurred = self.process_save(count, tdir, container) - except: + except Exception: import traceback traceback.print_exc() finally: @@ -193,7 +193,7 @@ class SaveManager(QObject): error_occurred = False try: self.do_save(tdir, container) - except: + except Exception: import traceback self.report_error.emit(traceback.format_exc()) error_occurred = True diff --git a/src/calibre/gui2/tweak_book/spell.py b/src/calibre/gui2/tweak_book/spell.py index 5273ebc940..10b0b2e105 100644 --- a/src/calibre/gui2/tweak_book/spell.py +++ b/src/calibre/gui2/tweak_book/spell.py @@ -222,7 +222,7 @@ class AddDictionary(QDialog): # {{{ oxt = str(self.path.text()) try: num = import_from_oxt(oxt, nick) - except: + except Exception: import traceback return error_dialog(self, _('Failed to import dictionaries'), _( 'Failed to import dictionaries from %s. Click "Show details" for more information') % oxt, @@ -240,7 +240,7 @@ class AddDictionary(QDialog): # {{{ 'A dictionary with the nick name "%s" already exists.') % nick, show=True) try: num = import_from_online(directory, nick) - except: + except Exception: import traceback return error_dialog(self, _('Failed to download dictionaries'), _( 'Failed to download dictionaries for "{}". Click "Show details" for more information').format(data['text']), @@ -1553,7 +1553,7 @@ class SpellCheck(Dialog): try: words = get_all_words(current_container(), dictionaries.default_locale, excluded_files=self.excluded_files) spell_map = {w:dictionaries.recognized(*w) for w in words} - except: + except Exception: import traceback traceback.print_exc() words = traceback.format_exc() diff --git a/src/calibre/gui2/tweak_book/undo.py b/src/calibre/gui2/tweak_book/undo.py index 5dac2ba431..4a56a5a4a7 100644 --- a/src/calibre/gui2/tweak_book/undo.py +++ b/src/calibre/gui2/tweak_book/undo.py @@ -32,7 +32,7 @@ def cleanup(containers): for container in containers: try: shutil.rmtree(container.root, ignore_errors=True) - except: + except Exception: pass diff --git a/src/calibre/gui2/ui.py b/src/calibre/gui2/ui.py index ba5b366302..28fe857a6a 100644 --- a/src/calibre/gui2/ui.py +++ b/src/calibre/gui2/ui.py @@ -188,7 +188,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ try: st = self.init_istore(store) self.add_istore(st) - except: + except Exception: # Ignore errors in loading user supplied plugins import traceback traceback.print_exc() @@ -364,7 +364,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ if not gprefs.get('quick_start_guide_added', False): try: add_quick_start_guide(self.library_view) - except: + except Exception: import traceback traceback.print_exc() for view in ('library', 'memory', 'card_a', 'card_b'): @@ -399,7 +399,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ for ac in self.iactions.values(): try: ac.gui_layout_complete() - except: + except Exception: import traceback traceback.print_exc() if ac.installation_type is PluginInstallationType.BUILTIN: @@ -429,7 +429,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ for ac in self.iactions.values(): try: ac.initialization_complete() - except: + except Exception: import traceback traceback.print_exc() if ac.installation_type is PluginInstallationType.BUILTIN: @@ -964,7 +964,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ olddb = self.library_view.model().db if copy_structure: default_prefs = dict(olddb.prefs) - except: + except Exception: olddb = None if copy_structure and olddb is not None and default_prefs is not None: default_prefs['field_metadata'] = olddb.new_api.field_metadata.all_metadata() @@ -1164,13 +1164,13 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ d.show() self._modeless_dialogs.append(d) return - except: + except Exception: pass if job.killed: return try: prints(job.details, file=sys.stderr) - except: + except Exception: pass if not minz: self.job_error_dialog.show_error(dialog_title, @@ -1213,7 +1213,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ self.restart_after_quit = restart try: self.shutdown() - except: + except Exception: import traceback traceback.print_exc() self.debug_on_restart = debug_on_restart @@ -1270,7 +1270,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ try: db = self.library_view.model().db cf = db.clean - except: + except Exception: pass else: cf() @@ -1298,7 +1298,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ def eh(t, v, tb): try: traceback.print_exception(t, v, tb, file=sys.stderr) - except: + except Exception: pass sys.excepthook = eh @@ -1347,7 +1347,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ self.restart_after_quit = True try: self.shutdown(write_settings=False) - except: + except Exception: pass QApplication.instance().quit() @@ -1368,7 +1368,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin, # {{{ if self.confirm_quit(): try: self.shutdown(write_settings=False) - except: + except Exception: import traceback traceback.print_exc() e.accept() diff --git a/src/calibre/gui2/wizard/__init__.py b/src/calibre/gui2/wizard/__init__.py index 07f79ddb4e..bad4eb5149 100644 --- a/src/calibre/gui2/wizard/__init__.py +++ b/src/calibre/gui2/wizard/__init__.py @@ -612,7 +612,7 @@ class StanzaPage(QWizardPage, StanzaUI): t = re.sub(r':\d+', ':'+str(p), t) self.instructions.setText(t) return p - except: + except Exception: continue @@ -758,7 +758,7 @@ class LibraryPage(QWizardPage, LibraryUI): from calibre.customize.ui import enable_plugin for name in metadata_plugins: enable_plugin(name) - except: + except Exception: pass lp = self.location.text() if lp == self.initial_library_location: @@ -771,7 +771,7 @@ class LibraryPage(QWizardPage, LibraryUI): from calibre.db.legacy import LibraryDatabase try: return LibraryDatabase.exists_at(x) or not os.listdir(x) - except: + except Exception: return False def validatePage(self): @@ -794,7 +794,7 @@ class LibraryPage(QWizardPage, LibraryUI): if not os.path.exists(x): try: self.makedirs(x) - except: + except Exception: return error_dialog(self, _('Bad location'), _('Failed to create a folder at %s')%x, det_msg=traceback.format_exc(), show=True) @@ -808,7 +808,7 @@ class LibraryPage(QWizardPage, LibraryUI): if not isinstance(x, str): try: x = x.decode(filesystem_encoding) - except: + except Exception: x = str(repr(x)) error_dialog(self, _('Bad location'), _('You must choose an empty folder for ' @@ -829,7 +829,7 @@ class LibraryPage(QWizardPage, LibraryUI): if not os.path.exists(lp): try: self.makedirs(lp) - except: + except Exception: traceback.print_exc() try: lp = os.path.expanduser('~') @@ -850,7 +850,7 @@ class LibraryPage(QWizardPage, LibraryUI): lp = str(self.location.text()) ans = bool(lp) and os.path.exists(lp) and os.path.isdir(lp) and os.access(lp, os.W_OK) - except: + except Exception: ans = False return ans diff --git a/src/calibre/gui2/wizard/send_email.py b/src/calibre/gui2/wizard/send_email.py index 81fa130e5a..5f9058f5d7 100644 --- a/src/calibre/gui2/wizard/send_email.py +++ b/src/calibre/gui2/wizard/send_email.py @@ -238,7 +238,7 @@ class SendEmail(QWidget, Ui_Form): username=opts.relay_username, debug_output=debug_out, password=from_hex_unicode(opts.relay_password), encryption=opts.encryption, port=opts.relay_port) - except: + except Exception: import traceback tb = traceback.format_exc() tb += '\n\nLog:\n' + buf.getvalue() diff --git a/src/calibre/library/caches.py b/src/calibre/library/caches.py index 3b9405bbc5..7c57b168f9 100644 --- a/src/calibre/library/caches.py +++ b/src/calibre/library/caches.py @@ -60,7 +60,7 @@ class MetadataBackup(Thread): # {{{ if id_ is None: continue # print('writer thread', id_, sequence) - except: + except Exception: # Happens during interpreter shutdown break if not self.keep_running: @@ -68,13 +68,13 @@ class MetadataBackup(Thread): # {{{ try: path, mi, sequence = self.get_metadata_for_dump(id_) - except: + except Exception: prints('Failed to get backup metadata for id:', id_, 'once') traceback.print_exc() time.sleep(2) try: path, mi, sequence = self.get_metadata_for_dump(id_) - except: + except Exception: prints('Failed to get backup metadata for id:', id_, 'again, giving up') traceback.print_exc() continue @@ -91,7 +91,7 @@ class MetadataBackup(Thread): # {{{ time.sleep(0.1) try: raw = metadata_to_opf(mi) - except: + except Exception: prints('Failed to convert to opf for id:', id_) traceback.print_exc() continue @@ -102,12 +102,12 @@ class MetadataBackup(Thread): # {{{ time.sleep(0.1) # Give the GUI thread a chance to do something try: self.do_write(path, raw) - except: + except Exception: prints('Failed to write backup metadata for id:', id_, 'once') time.sleep(2) try: self.do_write(path, raw) - except: + except Exception: prints('Failed to write backup metadata for id:', id_, 'again, giving up') continue @@ -152,7 +152,7 @@ def force_to_bool(val): val = False else: val = bool(int(val)) - except: + except Exception: val = None return val @@ -399,13 +399,13 @@ class ResultCache(SearchQueryParser): # {{{ num = query[0:-(self.untrans_daysago_len if query.endswith(self.untrans_daysago) else self.local_daysago_len)] try: qd = now() - timedelta(int(num)) - except: + except Exception: raise ParseException(_('Number conversion error: {0}').format(num)) field_count = 3 else: try: qd = parse_date(query, as_utc=False) - except: + except Exception: raise ParseException(_('Date conversion error: {0}').format(query)) if '-' in query: field_count = query.count('-') + 1 @@ -494,7 +494,7 @@ class ResultCache(SearchQueryParser): # {{{ mult = 1.0 try: q = cast(query) * mult - except: + except Exception: raise ParseException(_('Non-numeric value in query: {0}').format(query)) for id_ in candidates: @@ -503,7 +503,7 @@ class ResultCache(SearchQueryParser): # {{{ continue try: v = cast(val_func(item)) - except: + except Exception: v = None if v: v = adjust(v) @@ -709,7 +709,7 @@ class ResultCache(SearchQueryParser): # {{{ c -= m if len(c) == 0: break - except: + except Exception: pass return matches @@ -777,7 +777,7 @@ class ResultCache(SearchQueryParser): # {{{ try: rating_query = int(query) * 2 - except: + except Exception: rating_query = None location = [location] if location != 'all' else list(db_col.keys()) @@ -836,7 +836,7 @@ class ResultCache(SearchQueryParser): # {{{ if int(query) == item[loc]: matches.add(item[0]) continue - except: + except Exception: # A conversion threw an exception. Because of the type, # no further match is possible continue @@ -1075,7 +1075,7 @@ class ResultCache(SearchQueryParser): # {{{ for id_,val in iteritems(self.marked_ids_dict): try: self._data[id_][marked_col] = val - except: + except Exception: pass in_tag_browser_col = self.FIELD_MAP['in_tag_browser'] @@ -1188,7 +1188,7 @@ class SortKeyGenerator: if sb == 'date': try: val = parse_date(val) - except: + except Exception: val = UNDEFINED_DATE dt = 'datetime' elif sb == 'number': @@ -1201,7 +1201,7 @@ class SortKeyGenerator: val = val[:-len(candidate)].strip() break val = locale.atof(val) * p - except: + except Exception: val = 0.0 dt = 'float' elif sb == 'bool': diff --git a/src/calibre/library/catalogs/bibtex.py b/src/calibre/library/catalogs/bibtex.py index 49edd025e7..bec49e87cf 100644 --- a/src/calibre/library/catalogs/bibtex.py +++ b/src/calibre/library/catalogs/bibtex.py @@ -190,7 +190,7 @@ class BIBTEX(CatalogPlugin): # html to text try: item = html2text(item) - except: + except Exception: log.warn('Failed to convert comments to text') bibtex_entry.append(f'note = "{bibtexdict.utf8ToBibtex(item)}"') @@ -289,7 +289,7 @@ class BIBTEX(CatalogPlugin): bibfile_enc = bibfile_enc[opts.bibfile_enc] bibfile_enctag = bibfile_enctag[opts.bibfile_enctag] bib_entry = bib_entry[opts.bib_entry] - except: + except Exception: if opts.bibfile_enc in bibfile_enc: bibfile_enc = opts.bibfile_enc else: diff --git a/src/calibre/library/catalogs/epub_mobi.py b/src/calibre/library/catalogs/epub_mobi.py index 3e56266ac1..d4ae3ace1e 100644 --- a/src/calibre/library/catalogs/epub_mobi.py +++ b/src/calibre/library/catalogs/epub_mobi.py @@ -293,7 +293,7 @@ class EPUB_MOBI(CatalogPlugin): for storage in opts.connected_device['storage']: if storage: build_log.append(f' mount point: {storage}') - except: + except Exception: build_log.append(' (no mount points)') else: build_log.append(" connected_device: '{}'".format(opts.connected_device['name'])) @@ -355,7 +355,7 @@ class EPUB_MOBI(CatalogPlugin): if type(opts.prefix_rules) is not tuple: try: opts.prefix_rules = eval(opts.prefix_rules) - except: + except Exception: log.error(f'malformed --prefix-rules: {opts.prefix_rules}') raise for rule in opts.prefix_rules: @@ -366,7 +366,7 @@ class EPUB_MOBI(CatalogPlugin): if type(opts.exclusion_rules) is not tuple: try: opts.exclusion_rules = eval(opts.exclusion_rules) - except: + except Exception: log.error(f'malformed --exclusion-rules: {opts.exclusion_rules}') raise for rule in opts.exclusion_rules: @@ -405,7 +405,7 @@ class EPUB_MOBI(CatalogPlugin): log.info(f' Completed catalog source generation ({datetime.timedelta(seconds=int(time.time() - opts.start_time))!s})\n') except (AuthorSortMismatchException, EmptyCatalogException) as e: log.error(f' *** Terminated catalog generation: {e} ***') - except: + except Exception: log.error(' unhandled exception in catalog generator') raise @@ -448,7 +448,7 @@ class EPUB_MOBI(CatalogPlugin): cpath = db.cover(matches[0], index_is_id=True, as_path=True) if cpath and os.path.exists(cpath): existing_cover = True - except: + except Exception: pass if self.opts.use_existing_cover and not existing_cover: @@ -476,7 +476,7 @@ class EPUB_MOBI(CatalogPlugin): try: os.remove(cpath) - except: + except Exception: pass if GENERATE_DEBUG_EPUB: diff --git a/src/calibre/library/catalogs/epub_mobi_builder.py b/src/calibre/library/catalogs/epub_mobi_builder.py index 124660e9be..90e4e1aa02 100644 --- a/src/calibre/library/catalogs/epub_mobi_builder.py +++ b/src/calibre/library/catalogs/epub_mobi_builder.py @@ -441,9 +441,9 @@ class CatalogBuilder: with ZipFile(self.thumbs_path, mode='r') as zfr: try: cached_thumb_width = zfr.read('thumb_width') - except: + except Exception: cached_thumb_width = '-1' - except: + except Exception: os.remove(self.thumbs_path) cached_thumb_width = '-1' @@ -502,7 +502,7 @@ class CatalogBuilder: try: self.generate_masthead_image(os.path.join(self.catalog_path, 'images/mastheadImage.gif')) - except: + except Exception: pass def create_catalog_directory_structure(self): @@ -635,7 +635,7 @@ class CatalogBuilder: if self.DEBUG: _log_prefix_rule_match_info(rule, record, field_contents) return rule['prefix'] - except: + except Exception: if self.opts.verbose: self.opts.log.error('pattern failed to compile: {}'.format(rule['pattern'])) elif field_contents is None and rule['pattern'] == 'None': @@ -1166,7 +1166,7 @@ class CatalogBuilder: myBookmark = Bookmark(path_map[id], id, book_ext[id], bookmark_ext) try: book['percent_read'] = min(float(100 * myBookmark.last_read / myBookmark.book_length), 100) - except: + except Exception: book['percent_read'] = 0 dots = int((book['percent_read'] + 5) // 10) dot_string = self.SYMBOL_PROGRESS_READ * dots @@ -1271,7 +1271,7 @@ class CatalogBuilder: if re.search(self.opts.exclude_genre, tag): excluded_tags.append(tag) continue - except: + except Exception: self.opts.log.error(f'\tfilterDbTags(): malformed --exclude-genre regex pattern: {self.opts.exclude_genre}') if tag == ' ': @@ -1317,7 +1317,7 @@ class CatalogBuilder: continue else: tag_list.append(tag) - except: + except Exception: self.opts.log.error(f'\tfilter_excluded_genres(): malformed --exclude-genre regex pattern: {regex}') return tags @@ -2026,7 +2026,7 @@ class CatalogBuilder: book[1]['bookmark_timestamp'] = book[0].timestamp try: book[1]['percent_read'] = min(float(100 * book[0].last_read / book[0].book_length), 100) - except: + except Exception: book[1]['percent_read'] = 0 bookmarked_books.append(book[1]) @@ -2928,7 +2928,7 @@ class CatalogBuilder: draw = ImageDraw.Draw(img) try: font = ImageFont.truetype(font_path, 48) - except: + except Exception: self.opts.log.error(f" Failed to load user-specifed font '{font_path}'") font = ImageFont.truetype(default_font, 48) text = self.opts.catalog_title.encode('utf-8') @@ -3705,7 +3705,7 @@ class CatalogBuilder: star_string = self.SYMBOL_FULL_RATING * stars empty_stars = self.SYMBOL_EMPTY_RATING * (5 - stars) rating = f'{star_string}{empty_stars}' - except: + except Exception: # Rating could be None pass return rating @@ -3851,7 +3851,7 @@ class CatalogBuilder: def _open_archive(mode='r'): try: return ZipFile(self.thumbs_path, mode=mode, allowZip64=True) - except: + except Exception: # occurs under windows if the file is opened by another # process pass @@ -3869,7 +3869,7 @@ class CatalogBuilder: with zf: try: zf.getinfo(uuid + cover_crc) - except: + except Exception: pass else: # uuid found in cache with matching crc @@ -3922,7 +3922,7 @@ class CatalogBuilder: try: self.generate_thumbnail(title, image_dir, thumb_file) thumbs.append('thumbnail_{}.jpg'.format(int(title['id']))) - except: + except Exception: if 'cover' in title and os.path.exists(title['cover']): valid_cover = False self.opts.log.warn(" *** Invalid cover file for '{}'***".format(title['title'])) @@ -4072,7 +4072,7 @@ class CatalogBuilder: prefix_rule['pattern'] = rule[2] prefix_rule['prefix'] = rule[3] pr.append(prefix_rule) - except: + except Exception: self.opts.log.error(f'malformed prefix_rules: {self.opts.prefix_rules!r}') raise return pr diff --git a/src/calibre/library/catalogs/utils.py b/src/calibre/library/catalogs/utils.py index 4db3b1f967..c4fc3e16c7 100644 --- a/src/calibre/library/catalogs/utils.py +++ b/src/calibre/library/catalogs/utils.py @@ -171,7 +171,7 @@ class NumberToText: # {{{ try: self.float_as_number = float(self.number) number = int(self.number) - except: + except Exception: return if number > 10**9: diff --git a/src/calibre/library/check_library.py b/src/calibre/library/check_library.py index ef990d963d..aedd40e7fa 100644 --- a/src/calibre/library/check_library.py +++ b/src/calibre/library/check_library.py @@ -142,7 +142,7 @@ class CheckLibrary: # Record the book to check its formats self.book_dirs.append((db_path, title_dir, id_)) found_titles = True - except: + except Exception: traceback.print_exc() # Sort-of check: exception processing directory self.failed_folders.append((auth_dir, traceback.format_exc(), [])) @@ -154,7 +154,7 @@ class CheckLibrary: for x in self.book_dirs: try: self.process_book(lib, x) - except: + except Exception: traceback.print_exc() # Sort-of check: exception processing directory self.failed_folders.append((title_path, traceback.format_exc(), [])) diff --git a/src/calibre/library/coloring.py b/src/calibre/library/coloring.py index dcf8497c87..2e58552af3 100644 --- a/src/calibre/library/coloring.py +++ b/src/calibre/library/coloring.py @@ -39,14 +39,14 @@ class Rule: # {{{ if (dt in ('int', 'float', 'rating') and action in ('lt', 'eq', 'gt')): try: int(val) if dt == 'int' else float(val) - except: + except Exception: return f'{val!r} is not a valid numerical value' if (dt in ('comments', 'series', 'text', 'enumeration') and 'pattern' in action): try: re.compile(val) - except: + except Exception: return f'{val!r} is not a valid regular expression' @property @@ -228,14 +228,14 @@ def rule_from_template(fm, template): raw = line[len(Rule.SIGNATURE):].strip() try: color, conditions = json.loads(from_hex_bytes(raw)) - except: + except Exception: continue r = Rule(fm) r.color = color for c in conditions: try: r.add_condition(*c) - except: + except Exception: continue if r.color and r.conditions: return r diff --git a/src/calibre/library/comments.py b/src/calibre/library/comments.py index 8b792ed71a..dc464fa51f 100644 --- a/src/calibre/library/comments.py +++ b/src/calibre/library/comments.py @@ -60,7 +60,7 @@ def comments_to_html(comments): if sanitize_pat.search(comments) is not None: try: return sanitize_comments_html(comments) - except: + except Exception: import traceback traceback.print_exc() return '

' diff --git a/src/calibre/library/database.py b/src/calibre/library/database.py index 225ae9eec6..7ce86d3133 100644 --- a/src/calibre/library/database.py +++ b/src/calibre/library/database.py @@ -924,7 +924,7 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE; return self.data[index][1] try: return self.conn.get('SELECT title FROM meta WHERE id=?',(index,), all=False) - except: + except Exception: return _('Unknown') def authors(self, index, index_is_id=False): @@ -936,7 +936,7 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE; return self.data[index][2] try: return self.conn.get('SELECT authors FROM meta WHERE id=?',(index,), all=False) - except: + except Exception: pass def author_id(self, index, index_is_id=False): @@ -1008,7 +1008,7 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE; ans = self.conn.get('SELECT series_index FROM books WHERE id=?', (index,), all=False) try: return float(ans) - except: + except Exception: return 1.0 def books_in_series(self, series_id): diff --git a/src/calibre/library/database2.py b/src/calibre/library/database2.py index ff0d30e293..fe8f3676fe 100644 --- a/src/calibre/library/database2.py +++ b/src/calibre/library/database2.py @@ -160,7 +160,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): try: if isbytestring(library_path): library_path = library_path.decode(filesystem_encoding) - except: + except Exception: traceback.print_exc() self.field_metadata = FieldMetadata() self.format_filename_cache = defaultdict(dict) @@ -276,7 +276,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): rules = migrate_old_rule(self.field_metadata, templ) for templ in rules: old_rules.append((col, templ)) - except: + except Exception: pass if old_rules: self.prefs['column_color_rules'] += old_rules @@ -303,7 +303,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): for t in ogst: ngst[icu_lower(t)] = ogst[t] self.prefs.set('grouped_search_terms', ngst) - except: + except Exception: pass # migrate the gui_restriction preference to a virtual library @@ -502,7 +502,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): # user category. Print the exception and continue. try: self.field_metadata.add_user_category(label='@' + cat, name=cat) - except: + except Exception: traceback.print_exc() if len(saved_searches().names()): @@ -731,7 +731,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): try: os.rename(os.path.join(curpath, oldseg), os.path.join(curpath, newseg)) - except: + except Exception: break # Fail silently since nothing catastrophic has happened curpath = os.path.join(curpath, newseg) @@ -747,7 +747,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): for listener in self.listeners: try: listener(event, ids) - except: + except Exception: traceback.print_exc() continue @@ -795,7 +795,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): path = os.path.join(self.library_path, self.path(id, index_is_id=True), 'cover.jpg') try: return utcfromtimestamp(os.stat(path).st_mtime) - except: + except Exception: # Cover doesn't exist pass return self.last_modified() @@ -850,7 +850,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): self.conn.commit() try: del self.dirtied_cache[book_id] - except: + except Exception: pass elif dc_sequence is not None: # print('book needs to be done again') @@ -888,7 +888,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): f.write(raw) if remove_from_dirtied: self.clear_dirtied(book_id, sequence) - except: + except Exception: pass if callback is not None: callback(book_id, mi, True) @@ -978,7 +978,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): # no harm done. This way no need to call dirtied when # cover is set/removed mi.cover = 'cover.jpg' - except: + except Exception: # This almost certainly means that the book has been deleted while # the backup operation sat in the queue. pass @@ -993,7 +993,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): idx = idx if index_is_id else self.id(idx) try: row = self.data._data[idx] - except: + except Exception: row = None if row is None: @@ -1148,7 +1148,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): return identical_book_ids try: book_ids = self.data.parse(query) - except: + except Exception: traceback.print_exc() return identical_book_ids if qauthors and book_ids: @@ -1361,7 +1361,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): id = index if index_is_id else self.id(index) try: name = self.format_filename_cache[id][format.upper()] - except: + except Exception: return None if name: path = os.path.join(self.library_path, self.path(id, index_is_id=True)) @@ -1371,12 +1371,12 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): return fmt_path try: candidates = glob.glob(os.path.join(path, '*'+format)) - except: # If path contains strange characters this throws an exc + except Exception: # If path contains strange characters this throws an exc candidates = [] if format and candidates and os.path.exists(candidates[0]): try: shutil.copyfile(candidates[0], fmt_path) - except: + except Exception: # This can happen if candidates[0] or fmt_path is too long, # which can happen if the user copied the library from a # non windows machine to a windows machine. @@ -1413,7 +1413,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): try: if path != dest: os.rename(path, dest) - except: + except Exception: pass # Nothing too catastrophic happened, the cases mismatch, that's all else: windows_atomic_move.copy_path_to(path, dest) @@ -1429,14 +1429,14 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): # Ensure that the file has the same case as dest try: os.rename(path, dest) - except: + except Exception: pass # Nothing too catastrophic happened, the cases mismatch, that's all else: if use_hardlink: try: hardlink_file(path, dest) return - except: + except Exception: pass with open(path, 'rb') as f, open(dest, 'wb') as d: shutil.copyfileobj(f, d) @@ -1484,7 +1484,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): try: hardlink_file(path, dest) return True - except: + except Exception: pass with open(dest, 'wb') as d: shutil.copyfileobj(f, d) @@ -1518,7 +1518,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): d = os.path.join(bd, 'format_abspath') try: os.makedirs(d) - except: + except Exception: pass fname = os.path.basename(path) ret = os.path.join(d, fname) @@ -1625,7 +1625,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): ''' try: path = os.path.join(self.library_path, self.path(id, index_is_id=True)) - except: + except Exception: path = None if path and os.path.exists(path): self.rmtree(path, permanent=permanent) @@ -1654,7 +1654,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): path = self.format_abspath(id, format, index_is_id=True) if path: delete_file(path) - except: + except Exception: traceback.print_exc() self.format_filename_cache[id].pop(format.upper(), None) self.conn.execute('DELETE FROM data WHERE book=? AND format=?', (id, format.upper())) @@ -1782,7 +1782,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): try: if new_cats != user_cats: self.prefs.set('user_categories', new_cats) - except: + except Exception: pass return new_cats @@ -1909,7 +1909,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): if rating > 0: item.rt += rating item.rc += 1 - except: + except Exception: prints('get_categories: item', val, 'is not in', cat, 'list!') else: vals = book[dex].split(mult) @@ -1931,7 +1931,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): if rating > 0: item.rt += rating item.rc += 1 - except: + except Exception: prints('get_categories: item', val, 'is not in', cat, 'list!') # print('end phase "books":', time.clock() - last, 'seconds') @@ -2301,7 +2301,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): def doit(func, *args, **kwargs): try: func(*args, **kwargs) - except: + except Exception: if ignore_errors: traceback.print_exc() else: @@ -3231,7 +3231,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): idx = 1.0 try: idx = float(idx) - except: + except Exception: idx = 1.0 self.conn.execute('UPDATE books SET series_index=? WHERE id=?', (idx, id)) self.dirtied([id], commit=False) @@ -3384,7 +3384,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): self.conn.commit() try: mi = get_metadata(stream, format) - except: + except Exception: mi = Metadata(title, ['calibre']) stream.seek(0) mi.title, mi.authors = title, ['calibre'] @@ -3493,7 +3493,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): if cover is not None: try: self.set_cover(id, cover) - except: + except Exception: traceback.print_exc() return id @@ -3644,12 +3644,12 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): self.connect() try: os.unlink(opath) - except: + except Exception: pass for dir in old_dirs: try: shutil.rmtree(dir) - except: + except Exception: pass def __iter__(self): @@ -3702,7 +3702,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): if s is None: return default return json.loads(s, object_hook=from_json) - except: + except Exception: pass return default @@ -3716,7 +3716,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): for r in s: res[r[0]] = json.loads(r[1], object_hook=from_json) return res - except: + except Exception: pass return default diff --git a/src/calibre/library/prefs.py b/src/calibre/library/prefs.py index f75a021c62..7cca5224df 100644 --- a/src/calibre/library/prefs.py +++ b/src/calibre/library/prefs.py @@ -24,7 +24,7 @@ class DBPrefs(dict): for key, val in self.db.conn.get('SELECT key,val FROM preferences'): try: val = self.raw_to_object(val) - except: + except Exception: prints('Failed to read value for:', key, 'from db') continue dict.__setitem__(self, key, val) @@ -87,7 +87,7 @@ class DBPrefs(dict): data = data.encode('utf-8') with open(to_filename, 'wb') as f: f.write(data) - except: + except Exception: import traceback traceback.print_exc() @@ -110,7 +110,7 @@ class DBPrefs(dict): cls.clear() cls.update(d) return d - except: + except Exception: import traceback traceback.print_exc() raise diff --git a/src/calibre/library/restore.py b/src/calibre/library/restore.py index 9c8029c5d0..f0eece6a3f 100644 --- a/src/calibre/library/restore.py +++ b/src/calibre/library/restore.py @@ -115,7 +115,7 @@ class Restore(Thread): if self.successes == 0 and len(self.dirs) > 0: raise Exception('Something bad happened') self.replace_db() - except: + except Exception: self.tb = traceback.format_exc() def load_preferences(self): @@ -138,7 +138,7 @@ class Restore(Thread): return True self.progress_callback(_('Finished restoring preferences'), 1) return False - except: + except Exception: traceback.print_exc() self.progress_callback(None, 1) self.progress_callback(_('Restoring preferences and column metadata failed'), 0) @@ -158,7 +158,7 @@ class Restore(Thread): dirpath, filenames, book_id = x try: self.process_dir(dirpath, filenames, book_id) - except: + except Exception: self.failed_dirs.append((dirpath, traceback.format_exc())) self.progress_callback(_('Processed') + ' ' + dirpath, i+1) @@ -244,7 +244,7 @@ class Restore(Thread): for i, book in enumerate(self.books): try: self.restore_book(book, db) - except: + except Exception: self.failed_restores.append((book, traceback.format_exc())) self.progress_callback(book['mi'].title, i+1) diff --git a/src/calibre/library/save_to_disk.py b/src/calibre/library/save_to_disk.py index b2d9e40c7c..98b555c247 100644 --- a/src/calibre/library/save_to_disk.py +++ b/src/calibre/library/save_to_disk.py @@ -151,7 +151,7 @@ class Formatter(TemplateFormatter): key = key.lower() try: b = self.book.get_user_metadata(key, False) - except: + except Exception: traceback.print_exc() b = None if b is not None and b['datatype'] == 'composite': @@ -167,7 +167,7 @@ class Formatter(TemplateFormatter): val = ','.join(val) return val.replace('/', '_').replace('\\', '_') return '' - except: + except Exception: traceback.print_exc() return key @@ -317,7 +317,7 @@ def update_metadata(mi, fmt, stream, plugboards, cdata, error_report=None, plugb if cdata: newmi.cover_data = ('jpg', cdata) set_metadata(stream, newmi, fmt, report_error=None if error_report is None else report_error) - except: + except Exception: if error_report is None: prints('Failed to set metadata for the', fmt, 'format of', mi.title) traceback.print_exc() @@ -414,7 +414,7 @@ def save_to_disk(db, ids, root, opts=None, callback=None): try: failed, id, title = save_book_to_disk(x, db, root, opts, length) tb = _('Requested formats not available') - except: + except Exception: failed, id, title = True, x, db.title(x, index_is_id=True) tb = traceback.format_exc() if failed: @@ -431,7 +431,7 @@ def read_serialized_metadata(data): mi = OPF(data['opf'], try_to_guess_cover=False, populate_spine=False, basedir=os.path.dirname(data['opf'])).to_book_metadata() try: mi.last_modified = parse_date(data['last_modified']) - except: + except Exception: pass mi.cover, mi.cover_data = None, (None, None) cdata = None diff --git a/src/calibre/library/sqlite.py b/src/calibre/library/sqlite.py index d72ecc073e..96e396b251 100644 --- a/src/calibre/library/sqlite.py +++ b/src/calibre/library/sqlite.py @@ -35,7 +35,7 @@ def _c_convert_timestamp(val): return None try: ret = _c_speedup.parse_date(val.strip()) - except: + except Exception: ret = None if ret is None: return parse_date(val, as_utc=False) @@ -62,7 +62,7 @@ def _py_convert_timestamp(val): sec = int(val[17:19]) return datetime(year, month, day, hour, min, sec, tzinfo=timezone(tzsecs)) - except: + except Exception: pass return parse_date(val, as_utc=False) return None @@ -219,12 +219,12 @@ def pynocase(one, two, encoding='utf-8'): if isbytestring(one): try: one = one.decode(encoding, 'replace') - except: + except Exception: pass if isbytestring(two): try: two = two.decode(encoding, 'replace') - except: + except Exception: pass return cmp(one.lower(), two.lower()) @@ -340,7 +340,7 @@ class DatabaseException(Exception): tb = '\n\t'.join(('\tRemote'+tb).splitlines()) try: msg = str(err) +'\n' + tb - except: + except Exception: msg = repr(err) + '\n' + tb Exception.__init__(self, msg) self.orig_err = err diff --git a/src/calibre/linux.py b/src/calibre/linux.py index c81188de5f..9ca87f1bd5 100644 --- a/src/calibre/linux.py +++ b/src/calibre/linux.py @@ -81,7 +81,7 @@ class PreserveMIMEDefaults: # {{{ try: with open(x, 'rb') as f: self.initial_values[x] = f.read() - except: + except Exception: self.initial_values[x] = None def __exit__(self, *args): @@ -89,7 +89,7 @@ class PreserveMIMEDefaults: # {{{ if val is None: try: os.remove(path) - except: + except Exception: pass elif os.path.exists(path): try: @@ -820,7 +820,7 @@ class PostInstall: os.chmod(dest, stat.S_IRWXU|stat.S_IRGRP|stat.S_IROTH) if os.geteuid() == 0: os.chown(dest, 0, 0) - except: + except Exception: if self.opts.fatal_errors: raise self.task_failed('Creating uninstaller failed') @@ -847,7 +847,7 @@ class PostInstall: if self.opts.fatal_errors: raise self.task_failed('Setting up completion failed') - except: + except Exception: if self.opts.fatal_errors: raise self.task_failed('Setting up completion failed') @@ -947,7 +947,7 @@ class PostInstall: if not os.path.exists(appdata): try: os.mkdir(appdata) - except: + except Exception: self.warning(f'Failed to create {appdata} not installing appdata files') if os.path.exists(appdata) and not os.access(appdata, os.W_OK): self.warning(f'Do not have write permissions for {appdata} not installing appdata files') diff --git a/src/calibre/ptempfile.py b/src/calibre/ptempfile.py index 5bd18388b0..a6544dfa0d 100644 --- a/src/calibre/ptempfile.py +++ b/src/calibre/ptempfile.py @@ -156,7 +156,7 @@ class PersistentTemporaryFile: def __del__(self): try: self.close() - except: + except Exception: pass diff --git a/src/calibre/spell/dictionary.py b/src/calibre/spell/dictionary.py index 09966958e6..cf6081d8d9 100644 --- a/src/calibre/spell/dictionary.py +++ b/src/calibre/spell/dictionary.py @@ -66,7 +66,7 @@ def catalog_online_dictionaries(): loaded = json.loads(P('dictionaries/online-catalog.json', allow_user_override=False, data=True)) try: loaded.update(json.loads(P('dictionaries/online-catalog.json', data=True))) - except: + except Exception: pass rslt = [] for lang, directory in loaded.items(): diff --git a/src/calibre/srv/ajax.py b/src/calibre/srv/ajax.py index 46c8ba1809..4f7f6ddc31 100644 --- a/src/calibre/srv/ajax.py +++ b/src/calibre/srv/ajax.py @@ -33,11 +33,11 @@ def ensure_val(x, *allowed): def get_pagination(query, num=100, offset=0): try: num = int(query.get('num', num)) - except: + except Exception: raise HTTPNotFound('Invalid num') try: offset = int(query.get('offset', offset)) - except: + except Exception: raise HTTPNotFound('Invalid offset') return num, offset @@ -88,7 +88,7 @@ def book_to_json(ctx, rd, db, book_id, other_fmts = list(fmts) try: fmt = pf if pf in fmts else other_fmts[0] - except: + except Exception: fmt = None if fmts and fmt: other_fmts = [x for x in fmts if x != fmt] @@ -349,7 +349,7 @@ def category(ctx, rd, encoded_name, library_id): sort_order = ensure_val(sort_order, 'asc', 'desc') try: dname = decode_name(encoded_name) - except: + except Exception: raise HTTPNotFound(f'Invalid encoding of category name {encoded_name!r}') base_url = ctx.url_for(globals()['category'], encoded_name=encoded_name, library_id=db.server_library_id) @@ -382,7 +382,7 @@ def category(ctx, rd, encoded_name, library_id): # User categories cannot be applied to books, so this is the # complete set of items, no need to consider sub categories items = categories[fullname] - except: + except Exception: raise HTTPNotFound(f'User category {fullname!r} not found') parts = fullname.split('.') @@ -475,7 +475,7 @@ def books_in(ctx, rd, encoded_category, encoded_item, library_id): with db.safe_read_lock: try: dname, ditem = map(decode_name, (encoded_category, encoded_item)) - except: + except Exception: raise HTTPNotFound(f'Invalid encoded param: {encoded_category!r} ({encoded_item!r})') num, offset = get_pagination(rd.query) sort, sort_order = rd.query.get('sort', 'title'), rd.query.get('sort_order') diff --git a/src/calibre/srv/loop.py b/src/calibre/srv/loop.py index 8d4f4e677e..15f1f24277 100644 --- a/src/calibre/srv/loop.py +++ b/src/calibre/srv/loop.py @@ -550,7 +550,7 @@ class ServerLoop: raise except KeyboardInterrupt: break - except: + except Exception: self.log.exception('Error in ServerLoop.tick') self.shutdown() diff --git a/src/calibre/srv/manage_users_cli.py b/src/calibre/srv/manage_users_cli.py index f3d233166c..c8464f560a 100644 --- a/src/calibre/srv/manage_users_cli.py +++ b/src/calibre/srv/manage_users_cli.py @@ -402,7 +402,7 @@ def manage_users_cli(path=None, args=()): names = list(filter(None, [x.strip() for x in names.split(',')])) w = 'allowed_library_names' if c == 1 else 'blocked_library_names' t = _('Allowing access only to libraries: {}') if c == 1 else _( - 'Allowing access to all libraries, except: {}') + 'Allowing access to all libraries, except Exception: {}') prints(t.format(', '.join(names))) m.update_user_restrictions(username, {w: names}) diff --git a/src/calibre/srv/opds.py b/src/calibre/srv/opds.py index 23cdd364ab..46dc62f7a2 100644 --- a/src/calibre/srv/opds.py +++ b/src/calibre/srv/opds.py @@ -125,7 +125,7 @@ def html_to_lxml(raw): raw = etree.tostring(root, encoding='unicode') try: return safe_xml_fromstring(raw, recover=False) - except: + except Exception: for x in root.iterdescendants(): remove = [] for attr in x.attrib: @@ -136,7 +136,7 @@ def html_to_lxml(raw): raw = etree.tostring(root, encoding='unicode') try: return safe_xml_fromstring(raw, recover=False) - except: + except Exception: from calibre.ebooks.oeb.parse_utils import _html4_parse return _html4_parse(raw) diff --git a/src/calibre/utils/complete.py b/src/calibre/utils/complete.py index 74f4f722d5..9e6be6855c 100644 --- a/src/calibre/utils/complete.py +++ b/src/calibre/utils/complete.py @@ -107,7 +107,7 @@ class EbookConvert: try: parser, _ = create_option_parser(self.words[:3], log) ans += list(get_opts_from_parser(parser, self.prefix)) - except: + except Exception: pass if self.previous.startswith('-'): ans += list(files_and_dirs(self.prefix, None)) diff --git a/src/calibre/utils/config.py b/src/calibre/utils/config.py index 58856666c8..8b9ff5b041 100644 --- a/src/calibre/utils/config.py +++ b/src/calibre/utils/config.py @@ -354,7 +354,7 @@ class XMLConfig(dict): d = self.raw_to_object(raw) if raw.strip() else {} except SystemError: pass - except: + except Exception: import traceback traceback.print_exc() d = {} diff --git a/src/calibre/utils/date.py b/src/calibre/utils/date.py index a3b815b865..c10808b36b 100644 --- a/src/calibre/utils/date.py +++ b/src/calibre/utils/date.py @@ -28,7 +28,7 @@ if iswindows: try: ctypes.windll.kernel32.GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, buf, 255) parse_date_day_first = buf.value.index(b'd') < buf.value.index(b'M') - except: + except Exception: parse_date_day_first = False del ctypes, LOCALE_SSHORTDATE, buf, LOCALE_USER_DEFAULT elif ismacos: @@ -36,7 +36,7 @@ elif ismacos: from calibre_extensions.usbobserver import date_format date_fmt = date_format() parse_date_day_first = date_fmt.index('d') < date_fmt.index('M') - except: + except Exception: parse_date_day_first = False else: try: @@ -52,7 +52,7 @@ else: raw = locale.nl_langinfo(locale.D_FMT) parse_date_day_first = first_index(raw, ('%d', '%a', '%A')) < first_index(raw, ('%m', '%b', '%B')) del raw, first_index - except: + except Exception: parse_date_day_first = False DEFAULT_DATE = datetime(2000,1,1, tzinfo=utc_tz) diff --git a/src/calibre/utils/filenames.py b/src/calibre/utils/filenames.py index 5182f75ea6..7a62a9fdc0 100644 --- a/src/calibre/utils/filenames.py +++ b/src/calibre/utils/filenames.py @@ -221,7 +221,7 @@ def case_preserving_open_file(path, mode='wb', mkdir_mode=0o777): cl = comp.lower() try: candidates = [c for c in os.listdir(cpath) if c.lower() == cl] - except: + except Exception: # Don't have permission to do the listdir, assume the case is # correct as we have no way to check it. pass @@ -421,7 +421,7 @@ class WindowsAtomicFolderMove: raise err prints(f'CreateFile failed for: {f!r}') raise - except: + except Exception: self.close_handles() prints(f'CreateFile failed for: {f!r}') raise diff --git a/src/calibre/utils/fonts/scanner.py b/src/calibre/utils/fonts/scanner.py index 8ec3c1585d..b50c4b4de2 100644 --- a/src/calibre/utils/fonts/scanner.py +++ b/src/calibre/utils/fonts/scanner.py @@ -43,7 +43,7 @@ def fc_list(): return default_font_dirs() try: lib = ctypes.CDLL(lib) - except: + except Exception: return default_font_dirs() prototype = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p) @@ -278,7 +278,7 @@ class FontScanner(Thread): try: raw = self.get_font_data(font) return supports_text(raw, text) - except: + except Exception: pass return False diff --git a/src/calibre/utils/fonts/utils.py b/src/calibre/utils/fonts/utils.py index fc15fc4032..4e5612f59a 100644 --- a/src/calibre/utils/fonts/utils.py +++ b/src/calibre/utils/fonts/utils.py @@ -481,7 +481,7 @@ def supports_text(raw, text, has_only_printable_chars=False): for glyph_id in get_glyph_ids(raw, text): if glyph_id == 0: return False - except: + except Exception: return False return True diff --git a/src/calibre/utils/fonts/win_fonts.py b/src/calibre/utils/fonts/win_fonts.py index 8db1d23bb2..c6d293212a 100644 --- a/src/calibre/utils/fonts/win_fonts.py +++ b/src/calibre/utils/fonts/win_fonts.py @@ -90,7 +90,7 @@ class WinFonts: try: family_name, sub_family_name, full_name = get_font_names(data) - except: + except Exception: pass if normalize: @@ -112,7 +112,7 @@ class WinFonts: try: sub_family_name.encode('ascii') subf = sub_family_name - except: + except Exception: subf = '' name = family + ((' ' + subf) if subf else '') diff --git a/src/calibre/utils/formatter.py b/src/calibre/utils/formatter.py index 042f2369e9..8d9874f17b 100644 --- a/src/calibre/utils/formatter.py +++ b/src/calibre/utils/formatter.py @@ -378,7 +378,7 @@ class _Parser: token = self.prog[self.lex_pos][1] self.lex_pos += 1 return token - except: + except Exception: return None def consume(self): @@ -389,21 +389,21 @@ class _Parser: try: token = self.prog[self.lex_pos] return token[1] == op and token[0] == self.LEX_OP - except: + except Exception: return False def token_op_is_string_infix_compare(self): self.check_eol() try: return self.prog[self.lex_pos][0] == self.LEX_STRING_INFIX - except: + except Exception: return False def token_op_is_numeric_infix_compare(self): self.check_eol() try: return self.prog[self.lex_pos][0] == self.LEX_NUMERIC_INFIX - except: + except Exception: return False def token_is_newline(self): @@ -413,7 +413,7 @@ class _Parser: self.check_eol() try: return self.prog[self.lex_pos][0] == self.LEX_ID - except: + except Exception: return False def token_is(self, candidate): @@ -421,35 +421,35 @@ class _Parser: try: token = self.prog[self.lex_pos] return token[1] == candidate and token[0] == self.LEX_KEYWORD - except: + except Exception: return False def token_is_keyword(self): self.check_eol() try: return self.prog[self.lex_pos][0] == self.LEX_KEYWORD - except: + except Exception: return False def token_is_constant(self): self.check_eol() try: return self.prog[self.lex_pos][0] == self.LEX_CONST - except: + except Exception: return False def token_is_eof(self): self.check_eol() try: return self.prog[self.lex_pos][0] == self.LEX_EOF - except: + except Exception: return True def token_text(self): self.check_eol() try: return self.prog[self.lex_pos][1] - except: + except Exception: return _("'End of program'") def program(self, parent, funcs, prog): @@ -1124,7 +1124,7 @@ class _Interpreter: if (self.break_reporter): self.break_reporter(prog.node_name, self.locals[prog.name], prog.line_number) return self.locals[prog.name] - except: + except Exception: self.error(_("Unknown identifier '{0}'").format(prog.name), prog.line_number) def do_node_func(self, prog): @@ -1256,11 +1256,11 @@ class _Interpreter: return res except StopException: raise - except: + except Exception: self.error(_("Unknown field '{0}'").format(name), prog.line_number) except (StopException, ValueError): raise - except: + except Exception: self.error(_("Unknown field '{0}'").format('internal parse error'), prog.line_number) @@ -1290,7 +1290,7 @@ class _Interpreter: return res except (StopException, ValueError) as e: raise e - except: + except Exception: self.error(_("Unknown field '{0}'").format('internal parse error'), prog.line_number) @@ -1429,7 +1429,7 @@ class _Interpreter: return res except (StopException, ValueError) as e: raise e - except: + except Exception: self.error(_("Error during string comparison: " "operator '{0}'").format(prog.operator), prog.line_number) @@ -1457,7 +1457,7 @@ class _Interpreter: return res except (StopException, ValueError) as e: raise e - except: + except Exception: self.error(_("Value used in comparison is not a number: " "operator '{0}'").format(prog.operator), prog.line_number) @@ -1474,7 +1474,7 @@ class _Interpreter: return res except (StopException, ValueError) as e: raise e - except: + except Exception: self.error(_("Error during operator evaluation: " "operator '{0}'").format(prog.operator), prog.line_number) @@ -1491,7 +1491,7 @@ class _Interpreter: return res except (StopException, ValueError) as e: raise e - except: + except Exception: self.error(_("Error during operator evaluation: " "operator '{0}'").format(prog.operator), prog.line_number) @@ -1513,7 +1513,7 @@ class _Interpreter: return res except (StopException, ValueError) as e: raise e - except: + except Exception: self.error(_("Error during operator evaluation: " "operator '{0}'").format(prog.operator), prog.line_number) @@ -1531,7 +1531,7 @@ class _Interpreter: return res except (StopException, ValueError) as e: raise e - except: + except Exception: self.error(_("Error during operator evaluation: " "operator '{0}'").format(prog.operator), prog.line_number) @@ -1543,7 +1543,7 @@ class _Interpreter: return res except (StopException, ValueError) as e: raise e - except: + except Exception: self.error(_("Error during operator evaluation: " "operator '{0}'").format(prog.operator), prog.line_number) @@ -1670,7 +1670,7 @@ class TemplateFormatter(string.Formatter): elif 'eEfFgGn%'.find(typ) >= 0: try: val = float(val) - except: + except Exception: raise ValueError( _('format: type {0} requires a decimal (float) value, got {1}').format(typ, val)) return str(('{0:'+fmt+'}').format(val)) @@ -1681,7 +1681,7 @@ class TemplateFormatter(string.Formatter): if matches is None or matches.lastindex != 3: return fmt, '', '' return matches.groups() - except: + except Exception: if DEBUG: traceback.print_exc() return fmt, '', '' diff --git a/src/calibre/utils/formatter_functions.py b/src/calibre/utils/formatter_functions.py index 69fb3b5436..2ee6ff011b 100644 --- a/src/calibre/utils/formatter_functions.py +++ b/src/calibre/utils/formatter_functions.py @@ -274,7 +274,7 @@ class BuiltinFormatterFunction(FormatterFunction): lambda x: inspect.isfunction(x) and x.__name__ == 'evaluate') try: lines = [l[4:] for l in inspect.getsourcelines(eval_func[0][1])[0]] - except: + except Exception: lines = [] self.program_text = ''.join(lines) @@ -407,7 +407,7 @@ r''' def evaluate(self, formatter, kwargs, mi, locals, a): try: return len(a) - except: + except Exception: return -1 @@ -883,7 +883,7 @@ many ``prefix, string`` pairs as you wish. raise ValueError(_('strcat_max requires an even number of arguments')) try: max = int(args[0]) - except: + except Exception: raise ValueError(_('first argument to strcat_max must be an integer')) i = 2 @@ -894,7 +894,7 @@ many ``prefix, string`` pairs as you wish. break result = result + args[i] + args[i+1] i += 2 - except: + except Exception: pass return result.strip() @@ -1198,7 +1198,7 @@ usually comma but is ampersand for author-like lists. val = val.split(sep) try: return val[index].strip() - except: + except Exception: return '' @@ -1275,7 +1275,7 @@ that format names are always uppercase, as in EPUB. data = sorted(fmt_data.items(), key=lambda x:x[1]['mtime'], reverse=True) return ','.join(k.upper()+':'+format_date(v['mtime'], fmt) for k,v in data) - except: + except Exception: return '' @@ -1296,7 +1296,7 @@ format names are always uppercase, as in EPUB. fmt_data = mi.get('format_metadata', {}) try: return ','.join(k.upper()+':'+str(v['size']) for k,v in iteritems(fmt_data)) - except: + except Exception: return '' @@ -1318,7 +1318,7 @@ format names are always uppercase, as in EPUB. fmt_data = mi.get('format_metadata', {}) try: return sep.join(k.upper()+':'+str(v['path']) for k,v in iteritems(fmt_data)) - except: + except Exception: return '' @@ -1400,7 +1400,7 @@ representing that number in KB, MB, GB, etc. def evaluate(self, formatter, kwargs, mi, locals, val): try: return human_readable(round(float(val))) - except: + except Exception: return '' @@ -1428,17 +1428,17 @@ Python[/URL] documentation for more examples. Returns the empty string if format template = '{0:' + template + '}' try: v1 = float(val) - except: + except Exception: return '' try: # Try formatting the value as a float return template.format(v1) - except: + except Exception: pass try: # Try formatting the value as an int v2 = trunc(v1) if v2 == v1: return template.format(v2) - except: + except Exception: pass return '' @@ -1478,7 +1478,7 @@ Examples assuming that the tags column (which is comma-separated) contains "A, B return sep.join(val[si:]) else: return sep.join(val[si:ei]) - except: + except Exception: return '' @@ -1535,7 +1535,7 @@ Examples: t = '.'.join(components[si:ei]).strip() if t: rv.add(t) - except: + except Exception: pass return ', '.join(sorted(rv, key=sort_key)) @@ -1601,7 +1601,7 @@ contain ``MMMM``. Using ``format_date_field()`` avoids this problem. else: s = format_date(parse_date(val), format_string) return s - except: + except Exception: s = 'BAD DATE' return s @@ -1725,7 +1725,7 @@ column's value in your save/send templates if v is not None: return str(mi._proxy_metadata.book_size) return '' - except: + except Exception: pass return '' self.only_in_gui_error() @@ -2242,7 +2242,7 @@ returns the empty string. d2 = parse_date(date2) if d2 == UNDEFINED_DATE: return '' - except: + except Exception: return '' i = d1 - d2 return f'{i.days+(i.seconds/(24.0*60.0*60.0)):.1f}' @@ -2322,7 +2322,7 @@ return the strings in the language of the current locale. ``lang_codes`` is a co n = calibre_langcode_to_name(c, localize != '0') if n: retval.append(n) - except: + except Exception: pass return ', '.join(retval) @@ -2346,7 +2346,7 @@ current locale. ``lang_strings`` is a comma-separated list. cv = canonicalize_lang(c) if cv: retval.append(canonicalize_lang(cv)) - except: + except Exception: pass return ', '.join(retval) @@ -2719,7 +2719,7 @@ available with custom ratings columns. err_msg = _('The rating must be a number between 0 and 5') try: v = float(value) * 2 - except: + except Exception: raise ValueError(err_msg) if v < 0 or v > 10: raise ValueError(err_msg) @@ -2750,7 +2750,7 @@ the ``title_sort``. try: for v in [x.strip() for x in val.split(separator)]: result.append(title_sort(v).replace(',', ';')) - except: + except Exception: traceback.print_exc() return separator.join(sorted(result, key=sort_key)) diff --git a/src/calibre/utils/icu.py b/src/calibre/utils/icu.py index e545b967eb..d3011c0b4a 100644 --- a/src/calibre/utils/icu.py +++ b/src/calibre/utils/icu.py @@ -35,14 +35,14 @@ def is_ascii(name): try: if is_ascii(sys.getdefaultencoding()): _icu.set_default_encoding(b'utf-8') -except: +except Exception: import traceback traceback.print_exc() try: if is_ascii(sys.getfilesystemencoding()): _icu.set_filesystem_encoding(b'utf-8') -except: +except Exception: import traceback traceback.print_exc() del is_ascii diff --git a/src/calibre/utils/ipc/job.py b/src/calibre/utils/ipc/job.py index b1795e12ac..fdaa94587d 100644 --- a/src/calibre/utils/ipc/job.py +++ b/src/calibre/utils/ipc/job.py @@ -62,18 +62,18 @@ class BaseJob: try: prints('Job:', self.id, self.description, 'finished') prints('\t'.join(self.details.splitlines(True))) - except: + except Exception: pass if not self._done_called: self._done_called = True try: self.done(self) - except: + except Exception: pass try: if callable(self.done2): self.done2(self) - except: + except Exception: pass elif self.start_time is not None: self._run_state = self.RUNNING diff --git a/src/calibre/utils/ipc/launch.py b/src/calibre/utils/ipc/launch.py index df73c4da48..53465ac97a 100644 --- a/src/calibre/utils/ipc/launch.py +++ b/src/calibre/utils/ipc/launch.py @@ -19,7 +19,7 @@ from polyglot.builtins import environ_item, native_string_type, string_or_bytes if iswindows: try: windows_null_file = open(os.devnull, 'wb') - except: + except Exception: raise RuntimeError('NUL file missing in windows. This indicates a' ' corrupted windows. You should contact Microsoft' ' for assistance and/or follow the steps described here: https://bytes.com/topic/net/answers/264804-compile-error-null-device-missing') @@ -28,7 +28,7 @@ if iswindows: def renice(niceness): try: os.nice(niceness) - except: + except Exception: pass @@ -143,7 +143,7 @@ class Worker: def close_log_file(self): try: self._file.close() - except: + except Exception: pass def kill(self): @@ -160,7 +160,7 @@ class Worker: finally: if self.is_alive: self.child.kill() - except: + except Exception: pass def __init__(self, env=None, gui=False, job_name=None): diff --git a/src/calibre/utils/ipc/server.py b/src/calibre/utils/ipc/server.py index 61b39aa566..808a392718 100644 --- a/src/calibre/utils/ipc/server.py +++ b/src/calibre/utils/ipc/server.py @@ -145,7 +145,7 @@ class Server(Thread): except BaseException: try: w.kill() - except: + except Exception: pass b.close() import traceback @@ -184,7 +184,7 @@ class Server(Thread): for worker in [w for w in self.workers if not w.is_alive]: try: worker.close_log_file() - except: + except Exception: pass self.workers.remove(worker) job = worker.job @@ -196,7 +196,7 @@ class Server(Thread): with open(worker.rfile, 'rb') as f: job.result = pickle_loads(f.read()) os.remove(worker.rfile) - except: + except Exception: pass job.duration = time.time() - job.start_time self.changed_jobs_queue.put(job) @@ -281,17 +281,17 @@ class Server(Thread): def close(self): try: self.add_jobs_queue.put(None) - except: + except Exception: pass try: self.listener.close() - except: + except Exception: pass time.sleep(0.2) for worker in list(self.workers): try: worker.kill() - except: + except Exception: pass def __enter__(self): diff --git a/src/calibre/utils/ipc/simple_worker.py b/src/calibre/utils/ipc/simple_worker.py index bbe8c8a4d9..5a336979e7 100644 --- a/src/calibre/utils/ipc/simple_worker.py +++ b/src/calibre/utils/ipc/simple_worker.py @@ -72,14 +72,14 @@ class OffloadWorker: eintr_retry_call(self.conn.send, None) except OSError: pass - except: + except Exception: import traceback traceback.print_exc() finally: self.conn = None try: os.remove(self.worker.log_path) - except: + except Exception: pass self.kill_thread.start() @@ -187,7 +187,7 @@ def two_part_fork_job(env=None, priority='normal', cwd=None): if no_output: try: os.remove(w.log_path) - except: + except Exception: pass if not no_output: ans['stdout_stderr'] = w.log_path @@ -297,12 +297,12 @@ def main(): mod = importlib.import_module(mod) func = getattr(mod, func) res = {'result':func(*args, **kwargs)} - except: + except Exception: res = {'tb': traceback.format_exc()} try: conn.send(res) - except: + except Exception: # Maybe EINTR conn.send(res) @@ -330,7 +330,7 @@ def offload(): m = importlib.import_module(mod) func_cache[(mod, func)] = f = getattr(m, func) res['result'] = f(*args, **kwargs) - except: + except Exception: import traceback res['tb'] = traceback.format_exc() diff --git a/src/calibre/utils/ipc/worker.py b/src/calibre/utils/ipc/worker.py index 1dce85410b..573b6249d6 100644 --- a/src/calibre/utils/ipc/worker.py +++ b/src/calibre/utils/ipc/worker.py @@ -86,7 +86,7 @@ class Progress(Thread): break try: eintr_retry_call(self.conn.send, x) - except: + except Exception: break diff --git a/src/calibre/utils/localization.py b/src/calibre/utils/localization.py index 9cd67fdc08..a3f926a5b6 100644 --- a/src/calibre/utils/localization.py +++ b/src/calibre/utils/localization.py @@ -54,7 +54,7 @@ def get_system_locale(): lang = lang.strip() if not lang: lang = None - except: + except Exception: pass # Windows XP does not have the GetUserDefaultLocaleName fn elif ismacos: from calibre_extensions.usbobserver import user_locale @@ -75,12 +75,12 @@ def get_system_locale(): if os.environ.get(var) == 'C': lang = 'en_US' break - except: + except Exception: pass # This happens on Ubuntu apparently if lang is None and 'LANG' in os.environ: # Needed for OS X try: lang = os.environ['LANG'] - except: + except Exception: pass if lang: lang = lang.replace('-', '_') @@ -109,7 +109,7 @@ def get_lang(): return lang try: lang = get_system_locale() - except: + except Exception: import traceback traceback.print_exc() lang = None @@ -244,18 +244,18 @@ def translator_for_lang(lang): isof = mpath + '/iso639.mo' try: iso639 = io.BytesIO(zf.read(isof)) - except: + except Exception: pass # No iso639 translations for this lang isof = mpath + '/iso3166.mo' try: iso3166 = io.BytesIO(zf.read(isof)) - except: + except Exception: pass # No iso3166 translations for this lang if buf is not None: from calibre.utils.serialize import msgpack_loads try: lcdata = msgpack_loads(zf.read(mpath + '/lcdata.calibre_msgpack')) - except: + except Exception: pass # No lcdata if buf is not None: @@ -432,7 +432,7 @@ def calibre_langcode_to_name(lc, localize=True): translate = _ if localize else lambda x: x try: return translate(iso639['by_3'][lc]) - except: + except Exception: pass return lc diff --git a/src/calibre/utils/localunzip.py b/src/calibre/utils/localunzip.py index a8828c0eaf..3c3970d1d5 100644 --- a/src/calibre/utils/localunzip.py +++ b/src/calibre/utils/localunzip.py @@ -54,12 +54,12 @@ def decode_arcname(name): from calibre.ebooks.chardet import detect try: name = name.decode('utf-8') - except: + except Exception: res = detect(name) encoding = res['encoding'] try: name = name.decode(encoding) - except: + except Exception: name = name.decode('utf-8', 'replace') return name diff --git a/src/calibre/utils/mdns.py b/src/calibre/utils/mdns.py index dd7b426677..9ec753a71a 100644 --- a/src/calibre/utils/mdns.py +++ b/src/calibre/utils/mdns.py @@ -72,7 +72,7 @@ def _get_external_ip(): ipaddr = s.getsockname()[0] if not ipaddr.startswith('127.'): break - except: + except Exception: time.sleep(0.3) # print('ipaddr: %s' % ipaddr) return ipaddr @@ -128,7 +128,7 @@ def start_server(): def inet_aton(addr): try: return socket.inet_pton(socket.AF_INET6, addr) - except: + except Exception: return socket.inet_pton(socket.AF_INET, addr) @@ -136,16 +136,16 @@ def create_service(desc, service_type, port, properties, add_hostname, use_ip_ad port = int(port) try: hostname = ascii_text(force_unicode(socket.gethostname())).partition('.')[0] - except: + except Exception: hostname = 'Unknown' if add_hostname: try: desc += f' (on {hostname} port {port})' - except: + except Exception: try: desc += f' (on {hostname})' - except: + except Exception: pass if use_ip_address: diff --git a/src/calibre/utils/recycle_bin.py b/src/calibre/utils/recycle_bin.py index 304a4bc608..f598d2b6f9 100644 --- a/src/calibre/utils/recycle_bin.py +++ b/src/calibre/utils/recycle_bin.py @@ -45,7 +45,7 @@ if iswindows: break try: recycle_path(path) - except: + except Exception: eintr_retry_call(stdout.write, b'KO\n') stdout.flush() try: @@ -123,7 +123,7 @@ def delete_file(path, permanent=False): try: recycle(path) return - except: + except Exception: import traceback traceback.print_exc() os.remove(path) @@ -136,7 +136,7 @@ def delete_tree(path, permanent=False): # leading to access errors. If we get an exception, wait and hope # that whatever has the file (Antivirus, DropBox?) lets go of it. shutil.rmtree(path) - except: + except Exception: import traceback traceback.print_exc() time.sleep(1) @@ -146,7 +146,7 @@ def delete_tree(path, permanent=False): try: recycle(path) return - except: + except Exception: import traceback traceback.print_exc() delete_tree(path, permanent=True) diff --git a/src/calibre/utils/resources.py b/src/calibre/utils/resources.py index 42132815cc..e8d64f9a2d 100644 --- a/src/calibre/utils/resources.py +++ b/src/calibre/utils/resources.py @@ -25,7 +25,7 @@ class PathResolver: try: return os.path.exists(path) and os.path.isdir(path) and \ os.listdir(path) - except: + except Exception: pass return False diff --git a/src/calibre/utils/search_query_parser.py b/src/calibre/utils/search_query_parser.py index 22d013a750..221dd87759 100644 --- a/src/calibre/utils/search_query_parser.py +++ b/src/calibre/utils/search_query_parser.py @@ -445,7 +445,7 @@ class SearchQueryParser: return ss except ParseException as e: raise e - except: # convert all exceptions (e.g., missing key) to a parse error + except Exception: # convert all exceptions (e.g., missing key) to a parse error import traceback traceback.print_exc() raise ParseException(_('Unknown error in saved search: {0}').format(query)) diff --git a/src/calibre/utils/smtp.py b/src/calibre/utils/smtp.py index e3cc638a5a..af79026dae 100644 --- a/src/calibre/utils/smtp.py +++ b/src/calibre/utils/smtp.py @@ -194,7 +194,7 @@ def sendmail(msg, from_, to, localhost=None, verbose=0, timeout=None, finally: try: ret = s.quit() - except: + except Exception: pass # Ignore so as to not hide original error return ret @@ -329,7 +329,7 @@ def main(args=sys.argv): timeout=opts.timeout, relay=opts.relay, username=opts.username, password=opts.password, port=opts.port, encryption=opts.encryption_method, verify_server_cert=not opts.dont_verify_server_certificate, cafile=opts.cafile) - except: + except Exception: if outbox is not None: outbox.add(msg) outbox.close() diff --git a/src/calibre/utils/terminal.py b/src/calibre/utils/terminal.py index 047b457528..448932cb6d 100644 --- a/src/calibre/utils/terminal.py +++ b/src/calibre/utils/terminal.py @@ -265,7 +265,7 @@ def geometry(): ti = windows_terminfo() return (ti.dwSize.X or 80, ti.dwSize.Y or 25) - except: + except Exception: return 80, 25 else: try: diff --git a/src/calibre/utils/threadpool.py b/src/calibre/utils/threadpool.py index 5db19d17bc..0c63852c97 100644 --- a/src/calibre/utils/threadpool.py +++ b/src/calibre/utils/threadpool.py @@ -99,7 +99,7 @@ class WorkerThread(threading.Thread): self.resultQueue.put( (request, request.callable(*request.args, **request.kwds)) ) - except: + except Exception: request.exception = True import traceback self.resultQueue.put((request, traceback.format_exc())) diff --git a/src/calibre/web/__init__.py b/src/calibre/web/__init__.py index 03905d2ffd..22709f44b4 100644 --- a/src/calibre/web/__init__.py +++ b/src/calibre/web/__init__.py @@ -55,7 +55,7 @@ def get_download_filename(url, cookie_file=None): try: with closing(br.open(url)) as r: filename = get_download_filename_from_response(r) - except: + except Exception: import traceback traceback.print_exc() diff --git a/src/calibre/web/feeds/__init__.py b/src/calibre/web/feeds/__init__.py index 11b0b67f46..266ded702a 100644 --- a/src/calibre/web/feeds/__init__.py +++ b/src/calibre/web/feeds/__init__.py @@ -48,7 +48,7 @@ class Article: try: s = html.fragment_fromstring(summary, create_parent=True) summary = html.tostring(s, method='text', encoding='unicode') - except: + except Exception: print('Failed to process article summary, deleting:') print(summary.encode('utf-8')) traceback.print_exc() @@ -210,7 +210,7 @@ class Feed: title = re.sub(r'<.+?>', '', title) try: link = self.get_article_url(item) - except: + except Exception: self.logger.warning(f'Failed to get link for {title}') self.logger.debug(traceback.format_exc()) link = None diff --git a/src/calibre/web/feeds/news.py b/src/calibre/web/feeds/news.py index 32b4a7fa87..05d669424d 100644 --- a/src/calibre/web/feeds/news.py +++ b/src/calibre/web/feeds/news.py @@ -671,7 +671,7 @@ class BasicNewsRecipe(Recipe): if self.auto_cleanup: try: raw_html = self.extract_readable_article(raw_html, url) - except: + except Exception: self.log.exception(f'Auto cleanup of URL: {url!r} failed') return raw_html @@ -793,7 +793,7 @@ class BasicNewsRecipe(Recipe): try: frag = fragment_fromstring(article_html) - except: + except Exception: doc = document_fromstring(article_html) frag = doc.xpath('//body')[-1] if frag.tag == 'html': @@ -1104,7 +1104,7 @@ class BasicNewsRecipe(Recipe): url, f, a, feed_len = job_info try: article = self.feed_objects[f].articles[a] - except: + except Exception: self.log.exception('Failed to get article object for postprocessing') else: self.populate_article_metadata(article, ans, first_fetch) @@ -1145,7 +1145,7 @@ class BasicNewsRecipe(Recipe): lang = self.language.replace('_', '-').partition('-')[0].lower() if lang == 'und': lang = None - except: + except Exception: lang = None return lang @@ -1203,7 +1203,7 @@ class BasicNewsRecipe(Recipe): self.image_counter += 1 feed.image_url = img self.image_map[feed.image_url] = img - except: + except Exception: pass if isinstance(feed.image_url, bytes): feed.image_url = feed.image_url.decode(sys.getfilesystemencoding(), 'strict') @@ -1350,7 +1350,7 @@ class BasicNewsRecipe(Recipe): url = self.print_version(article.url) except NotImplementedError: url = article.url - except: + except Exception: self.log.exception('Failed to find print version for: '+article.url) url = None if not url: @@ -1440,7 +1440,7 @@ class BasicNewsRecipe(Recipe): self.cover_path = None try: self._download_cover() - except: + except Exception: self.log.exception('Failed to download cover') self.cover_path = None @@ -1472,14 +1472,14 @@ class BasicNewsRecipe(Recipe): def download_masthead(self, url): try: self._download_masthead(url) - except: + except Exception: self.log.exception('Failed to download supplied masthead_url') def resolve_masthead(self): self.masthead_path = None try: murl = self.get_masthead_url() - except: + except Exception: self.log.exception('Failed to get masthead url') murl = None @@ -1492,7 +1492,7 @@ class BasicNewsRecipe(Recipe): self.masthead_path = os.path.join(self.output_dir, 'mastheadImage.jpg') try: self.default_masthead_image(self.masthead_path) - except: + except Exception: self.log.exception('Failed to generate default masthead image') self.masthead_path = None @@ -1508,7 +1508,7 @@ class BasicNewsRecipe(Recipe): img_data = create_cover(title, [date]) cover_file.write(img_data) cover_file.flush() - except: + except Exception: self.log.exception('Failed to generate default cover') return False return True @@ -1984,6 +1984,6 @@ class CalibrePeriodical(BasicNewsRecipe): recipe = compile_recipe(open(glob('*.recipe')[0], 'rb').read()) self.conversion_options = recipe.conversion_options - except: + except Exception: self.log.exception('Failed to compile downloaded recipe') return os.path.abspath('index.html') diff --git a/src/calibre/web/feeds/recipes/collection.py b/src/calibre/web/feeds/recipes/collection.py index 0435b466fe..7066fe584f 100644 --- a/src/calibre/web/feeds/recipes/collection.py +++ b/src/calibre/web/feeds/recipes/collection.py @@ -94,7 +94,7 @@ def serialize_collection(mapping_of_recipe_classes): 'utf-8')): try: recipe = serialize_recipe(urn, mapping_of_recipe_classes[urn]) - except: + except Exception: import traceback traceback.print_exc() continue @@ -113,7 +113,7 @@ def serialize_builtin_recipes(): with open(f, 'rb') as stream: try: recipe_class = compile_recipe(stream.read()) - except: + except Exception: print(f'Failed to compile: {f}') raise if recipe_class is not None: @@ -139,7 +139,7 @@ def get_custom_recipe_collection(*args): recipe_class = compile_recipe(recipe) if recipe_class is not None: rmap[f'custom:{id_}'] = recipe_class - except: + except Exception: print(f'Failed to load recipe from: {fname!r}') import traceback traceback.print_exc() @@ -215,7 +215,7 @@ def remove_custom_recipe(id_): del custom_recipes[id_] try: delete_file(os.path.join(bdir, fname)) - except: + except Exception: pass @@ -265,7 +265,7 @@ def get_builtin_recipe_by_title(title, log=None, download_recipe=False): if log is not None: log('Trying to get latest version of recipe:', urn) return download_builtin_recipe(urn) - except: + except Exception: if log is None: import traceback traceback.print_exc() @@ -284,7 +284,7 @@ def get_builtin_recipe_by_id(id_, log=None, download_recipe=False): if log is not None: log('Trying to get latest version of recipe:', urn) return download_builtin_recipe(urn) - except: + except Exception: if log is None: import traceback traceback.print_exc() @@ -314,7 +314,7 @@ class SchedulerConfig: with ExclusiveFile(self.conf_path) as f: try: self.root = safe_xml_fromstring(f.read(), recover=False) - except: + except Exception: print('Failed to read recipe scheduler config') import traceback traceback.print_exc() @@ -458,7 +458,7 @@ class SchedulerConfig: def recipe_needs_to_be_downloaded(self, recipe): try: typ, sch, ld = self.un_serialize_schedule(recipe) - except: + except Exception: return False def is_time(now, hour, minute): @@ -565,7 +565,7 @@ class SchedulerConfig: for r in c.get('scheduled_recipes', []): try: self.add_old_recipe(r) - except: + except Exception: continue for k in c.keys(): if k.startswith('recipe_account_info'): @@ -577,17 +577,17 @@ class SchedulerConfig: urn = f'custom:{int(urn)}' try: username, password = c[k] - except: + except Exception: username = password = '' self.set_account_info(urn, str(username), str(password)) - except: + except Exception: continue del c self.write_scheduler_file() try: os.remove(old_conf_path) - except: + except Exception: pass def add_old_recipe(self, r): @@ -597,7 +597,7 @@ class SchedulerConfig: elif not r['builtin']: try: urn = 'custom:{}'.format(int(r['id'])) - except: + except Exception: return schedule = r['schedule'] typ = 'interval' diff --git a/src/calibre/web/feeds/recipes/model.py b/src/calibre/web/feeds/recipes/model.py index f9ed0b06f6..c8615b2bea 100644 --- a/src/calibre/web/feeds/recipes/model.py +++ b/src/calibre/web/feeds/recipes/model.py @@ -180,7 +180,7 @@ class RecipeModel(QAbstractItemModel, AdaptSQP): allow_user_override=False), 'r') as zf: self.favicons = {x.filename: x for x in zf.infolist() if x.filename.endswith('.png')} - except: + except Exception: self.favicons = {} self.do_refresh() @@ -188,7 +188,7 @@ class RecipeModel(QAbstractItemModel, AdaptSQP): if download: try: return download_builtin_recipe(urn) - except: + except Exception: import traceback traceback.print_exc() return get_builtin_recipe(urn) diff --git a/src/calibre/web/fetch/simple.py b/src/calibre/web/fetch/simple.py index 45dc1ecece..a828cda882 100644 --- a/src/calibre/web/fetch/simple.py +++ b/src/calibre/web/fetch/simple.py @@ -76,7 +76,7 @@ def basename(url): parts = urlsplit(url) path = url2pathname(parts.path) res = os.path.basename(path) - except: + except Exception: global bad_url_counter bad_url_counter += 1 return f'bad_url_{bad_url_counter}.html' @@ -325,7 +325,7 @@ class RecursiveFetcher: return self._is_link_wanted(url, tag) except NotImplementedError: pass - except: + except Exception: return False if self.filter_regexps: for f in self.filter_regexps: diff --git a/src/odf/attrconverters.py b/src/odf/attrconverters.py index 8351863a50..3ed1d85128 100644 --- a/src/odf/attrconverters.py +++ b/src/odf/attrconverters.py @@ -175,11 +175,11 @@ def cnv_lengthorpercent(attribute, arg, element): failed = False try: return cnv_length(attribute, arg, element) - except: + except Exception: failed = True try: return cnv_percent(attribute, arg, element) - except: + except Exception: failed = True if failed: raise ValueError(f"'{arg}' is not a valid length or percent") @@ -226,7 +226,7 @@ def cnv_NCName(attribute, arg, element): def cnv_StyleNameRef(attribute, arg, element): try: return arg.getAttrNS(STYLENS, 'name') - except: + except Exception: return arg # This function takes either an instance of a style (preferred) @@ -238,7 +238,7 @@ def cnv_StyleNameRef(attribute, arg, element): def cnv_DrawNameRef(attribute, arg, element): try: return arg.getAttrNS(DRAWNS, 'name') - except: + except Exception: return arg @@ -276,7 +276,7 @@ def cnv_points(attribute, arg, element): else: try: strarg = ' '.join(['{},{}'.format(*p) for p in arg]) - except: + except Exception: raise ValueError(f'Points must be string or [(0,0),(1,1)] - not {arg}') return strarg diff --git a/src/odf/load.py b/src/odf/load.py index f476e45c52..3cace4678c 100644 --- a/src/odf/load.py +++ b/src/odf/load.py @@ -107,7 +107,7 @@ class LoadParser(handler.ContentHandler): tn = getattr(self.curr, 'tagName', '') try: do_strip = not tn.startswith('text:') - except: + except Exception: do_strip = True if do_strip: q = q.strip() diff --git a/src/odf/odf2moinmoin.py b/src/odf/odf2moinmoin.py index e4cb5a5887..14753f5a9f 100644 --- a/src/odf/odf2moinmoin.py +++ b/src/odf/odf2moinmoin.py @@ -217,7 +217,7 @@ class ODF2MoinMoin: try: level = int(level) paraProps.setHeading(level) - except: + except Exception: level = 0 if name == 'Title': @@ -232,7 +232,7 @@ class ODF2MoinMoin: leftMargin = float(leftMargin[:-2]) if leftMargin > 0.01: paraProps.setIndented(True) - except: + except Exception: pass textProps = self.extractTextProperties(style) @@ -350,7 +350,7 @@ class ODF2MoinMoin: try: num = int(node.getAttribute('text:c')) return ' '*num - except: + except Exception: return ' ' def text_tab(self, node): diff --git a/src/odf/odf2xhtml.py b/src/odf/odf2xhtml.py index 141b791d6f..d1c3c65c23 100644 --- a/src/odf/odf2xhtml.py +++ b/src/odf/odf2xhtml.py @@ -1525,7 +1525,7 @@ dl.notes dd:last-of-type { page-break-after: avoid } ''' try: c = int(attrs.get((TEXTNS, 'c'), 1)) - except: + except Exception: c = 0 if c > 0: self.data.append('\u00a0'*c) diff --git a/src/odf/opendocument.py b/src/odf/opendocument.py index 5bb7a7432b..d89e462806 100644 --- a/src/odf/opendocument.py +++ b/src/odf/opendocument.py @@ -325,7 +325,7 @@ class OpenDocument: mediatype = '' try: ext = filename[filename.rindex('.'):] - except: + except Exception: ext='' else: ext = mimetypes.guess_extension(mediatype)