From 0889ee85ec8b0716347c8d2bc40f2f2dc01eda8c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 4 Sep 2018 10:49:18 -0400 Subject: [PATCH] Fix syntax errors Command used: futurize --no-diffs -f libfuturize.fixes.fix_print_with_import -f lib2to3.fixes.fix_throw -f lib2to3.fixes.fix_numliterals -f lib2to3.fixes.fix_except -f lib2to3.fixes.fix_exec -f lib2to3.fixes.fix_raise -f lib2to3.fixes.fix_tuple_params -f lib2to3.fixes.fix_ne -j20 -w -n setup recipes src manual setup.py recipes/*.recipe And manual adjustments of print((...)) -> print(...) --- manual/custom.py | 5 +- recipes/DrawAndCook.recipe | 7 +- recipes/al_monitor.recipe | 1 + recipes/am730.recipe | 9 +- recipes/auto_prove.recipe | 3 +- recipes/birmingham_post.recipe | 9 +- recipes/brewiarz.recipe | 3 +- recipes/calgary_herald.recipe | 1 + recipes/cio_magazine.recipe | 7 +- recipes/daily_express.recipe | 3 +- recipes/dilemaveche.recipe | 1 + recipes/dnevnik_mk.recipe | 3 +- recipes/edmonton_journal.recipe | 1 + recipes/el_cultural.recipe | 3 +- recipes/elmundo.recipe | 3 +- recipes/estadao.recipe | 5 +- recipes/gry_online_pl.recipe | 5 +- recipes/houston_chronicle.recipe | 1 + recipes/huffingtonpost.recipe | 1 + recipes/hurriyet_daily_news.recipe | 1 + recipes/klip_me.recipe | 3 +- recipes/la_gazzeta_dello_sport.recipe | 3 +- recipes/la_republica.recipe | 3 +- recipes/le_temps.recipe | 3 +- recipes/lenta_ru.recipe | 2 +- recipes/lwn_weekly.recipe | 5 +- recipes/metro_news_nl.recipe | 7 +- recipes/metro_uk.recipe | 3 +- recipes/ming_pao.recipe | 5 +- recipes/ming_pao_toronto.recipe | 5 +- recipes/ming_pao_vancouver.recipe | 5 +- recipes/montreal_gazette.recipe | 1 + recipes/newsweek_polska.recipe | 3 +- recipes/nikkei_news.recipe | 17 +- recipes/nuus24.recipe | 3 +- recipes/observa_digital.recipe | 3 +- recipes/observatorul_cultural.recipe | 5 +- recipes/oreilly_premium.recipe | 1 + recipes/ottawa_citizen.recipe | 1 + recipes/pagina_12_print_ed.recipe | 3 +- recipes/pravo.recipe | 3 +- recipes/real_clear.recipe | 1 + recipes/todays_zaman.recipe | 9 +- recipes/vancouver_province.recipe | 1 + recipes/vancouver_sun.recipe | 1 + recipes/vedomosti.recipe | 2 +- recipes/vic_times.recipe | 1 + setup/__init__.py | 9 +- setup/build.py | 3 +- setup/build_environment.py | 3 +- setup/git_pre_commit_hook.py | 1 + setup/linux-installer.py | 5 +- setup/mathjax.py | 2 +- setup/publish.py | 1 + setup/pypi.py | 13 +- setup/resources.py | 5 +- setup/translations.py | 1 + setup/upload.py | 3 +- setup/vcvars.py | 1 + src/calibre/constants.py | 5 +- src/calibre/customize/__init__.py | 3 +- src/calibre/customize/ui.py | 29 ++-- src/calibre/customize/zipplugin.py | 7 +- src/calibre/db/backend.py | 2 +- src/calibre/db/tests/profiling.py | 3 +- src/calibre/debug.py | 5 +- src/calibre/devices/__init__.py | 3 +- src/calibre/devices/cli.py | 53 +++---- src/calibre/devices/kindle/bookmark.py | 5 +- src/calibre/devices/kindle/driver.py | 3 +- src/calibre/devices/kobo/driver.py | 7 +- src/calibre/devices/misc.py | 2 +- src/calibre/devices/mtp/driver.py | 3 +- src/calibre/devices/mtp/unix/driver.py | 1 + src/calibre/devices/mtp/windows/remote.py | 11 +- src/calibre/devices/paladin/driver.py | 4 +- src/calibre/devices/prs505/driver.py | 4 +- src/calibre/devices/prst1/driver.py | 5 +- src/calibre/devices/scanner.py | 5 +- src/calibre/devices/udisks.py | 11 +- src/calibre/devices/usbms/cli.py | 3 +- src/calibre/devices/usbms/device.py | 47 +++--- src/calibre/devices/usbobserver/test.py | 5 +- src/calibre/devices/winusb.py | 5 +- src/calibre/ebooks/BeautifulSoup.py | 21 +-- src/calibre/ebooks/chardet.py | 1 + src/calibre/ebooks/compression/palmdoc.py | 15 +- src/calibre/ebooks/covers.py | 3 +- src/calibre/ebooks/djvu/djvubzzdec.py | 1 + src/calibre/ebooks/docx/container.py | 1 + src/calibre/ebooks/docx/dump.py | 3 +- src/calibre/ebooks/docx/writer/container.py | 1 + src/calibre/ebooks/epub/__init__.py | 2 +- src/calibre/ebooks/html/input.py | 3 +- src/calibre/ebooks/hyphenate.py | 3 +- src/calibre/ebooks/lit/from_any.py | 3 +- src/calibre/ebooks/lit/mssha1.py | 53 +++---- src/calibre/ebooks/lit/reader.py | 5 +- src/calibre/ebooks/lit/writer.py | 3 +- src/calibre/ebooks/lrf/html/convert_from.py | 5 +- src/calibre/ebooks/lrf/html/convert_to.py | 3 +- src/calibre/ebooks/lrf/html/table.py | 3 +- src/calibre/ebooks/lrf/lrs/convert_from.py | 3 +- src/calibre/ebooks/lrf/meta.py | 13 +- src/calibre/ebooks/lrf/objects.py | 5 +- src/calibre/ebooks/lrf/pylrs/pylrs.py | 3 +- .../ebooks/metadata/book/json_codec.py | 5 +- src/calibre/ebooks/metadata/docx.py | 1 + src/calibre/ebooks/metadata/epub.py | 5 +- src/calibre/ebooks/metadata/imp.py | 5 +- src/calibre/ebooks/metadata/kdl.py | 3 +- src/calibre/ebooks/metadata/mobi.py | 9 +- src/calibre/ebooks/metadata/opf2.py | 11 +- src/calibre/ebooks/metadata/rb.py | 7 +- .../ebooks/metadata/sources/google_images.py | 3 +- .../ebooks/metadata/sources/overdrive.py | 2 +- src/calibre/ebooks/metadata/sources/update.py | 4 +- src/calibre/ebooks/metadata/toc.py | 5 +- src/calibre/ebooks/metadata/topaz.py | 15 +- src/calibre/ebooks/metadata/xisbn.py | 7 +- src/calibre/ebooks/metadata/xmp.py | 1 + src/calibre/ebooks/mobi/debug/headers.py | 1 + src/calibre/ebooks/mobi/debug/main.py | 3 +- src/calibre/ebooks/mobi/mobiml.py | 3 +- src/calibre/ebooks/mobi/reader/index.py | 1 + .../oeb/display/test-cfi/run_rapydscript.py | 1 + src/calibre/ebooks/oeb/polish/create.py | 5 +- src/calibre/ebooks/oeb/polish/embed.py | 1 + src/calibre/ebooks/oeb/polish/parsing.py | 1 + src/calibre/ebooks/oeb/polish/subset.py | 1 + .../ebooks/oeb/polish/tests/parsing.py | 1 + src/calibre/ebooks/oeb/reader.py | 5 +- src/calibre/ebooks/oeb/transforms/jacket.py | 1 + src/calibre/ebooks/pdb/ereader/inspector.py | 145 +++++++++--------- src/calibre/ebooks/pdf/pdftohtml.py | 5 +- src/calibre/ebooks/pdf/render/test.py | 5 +- src/calibre/ebooks/readability/readability.py | 5 +- src/calibre/ebooks/rtf/preprocess.py | 1 + src/calibre/ebooks/rtf2xml/ParseRtf.py | 2 +- src/calibre/ebooks/rtf2xml/body_styles.py | 2 +- src/calibre/ebooks/rtf2xml/check_encoding.py | 2 +- src/calibre/ebooks/rtf2xml/colors.py | 4 +- src/calibre/ebooks/rtf2xml/configure_txt.py | 4 +- src/calibre/ebooks/rtf2xml/convert_to_tags.py | 2 +- src/calibre/ebooks/rtf2xml/copy.py | 4 +- .../ebooks/rtf2xml/default_encoding.py | 3 +- src/calibre/ebooks/rtf2xml/delete_info.py | 4 +- src/calibre/ebooks/rtf2xml/field_strings.py | 2 +- src/calibre/ebooks/rtf2xml/fonts.py | 2 +- src/calibre/ebooks/rtf2xml/get_char_map.py | 2 +- src/calibre/ebooks/rtf2xml/group_borders.py | 2 +- src/calibre/ebooks/rtf2xml/group_styles.py | 2 +- src/calibre/ebooks/rtf2xml/hex_2_utf8.py | 6 +- src/calibre/ebooks/rtf2xml/info.py | 2 +- src/calibre/ebooks/rtf2xml/inline.py | 2 +- src/calibre/ebooks/rtf2xml/list_table.py | 3 +- src/calibre/ebooks/rtf2xml/options_trem.py | 3 +- src/calibre/ebooks/rtf2xml/override_table.py | 9 +- src/calibre/ebooks/rtf2xml/paragraph_def.py | 4 +- src/calibre/ebooks/rtf2xml/pict.py | 2 +- src/calibre/ebooks/rtf2xml/preamble_div.py | 5 +- src/calibre/ebooks/rtf2xml/process_tokens.py | 26 ++-- src/calibre/ebooks/rtf2xml/sections.py | 2 +- src/calibre/ebooks/rtf2xml/styles.py | 10 +- src/calibre/ebooks/rtf2xml/table_info.py | 2 +- src/calibre/ebooks/sgmllib.py | 29 ++-- src/calibre/ebooks/snb/snbfile.py | 51 +++--- src/calibre/ebooks/tweak.py | 1 + src/calibre/gui2/actions/choose_library.py | 13 +- src/calibre/gui2/actions/copy_to_library.py | 2 +- src/calibre/gui2/catalog/catalog_epub_mobi.py | 5 +- src/calibre/gui2/complete2.py | 5 +- src/calibre/gui2/convert/xpath_wizard.py | 3 +- src/calibre/gui2/cover_flow.py | 3 +- src/calibre/gui2/dbus_export/demo.py | 3 +- .../gui2/device_drivers/mtp_folder_browser.py | 1 + src/calibre/gui2/dialogs/authors_edit.py | 1 + src/calibre/gui2/dialogs/choose_format.py | 1 + src/calibre/gui2/dialogs/duplicates.py | 1 + src/calibre/gui2/dialogs/message_box.py | 1 + src/calibre/gui2/dialogs/metadata_bulk.py | 1 + src/calibre/gui2/dialogs/opml.py | 1 + src/calibre/gui2/dialogs/search.py | 3 +- src/calibre/gui2/dialogs/select_formats.py | 3 +- src/calibre/gui2/dialogs/tag_editor.py | 1 + src/calibre/gui2/dialogs/template_dialog.py | 2 +- src/calibre/gui2/dialogs/trim_image.py | 3 +- src/calibre/gui2/dnd.py | 1 + src/calibre/gui2/font_family_chooser.py | 1 + src/calibre/gui2/icon_theme.py | 2 +- src/calibre/gui2/library/alternate_views.py | 3 +- src/calibre/gui2/library/models.py | 2 +- src/calibre/gui2/library/views.py | 3 +- src/calibre/gui2/linux_file_dialogs.py | 2 +- src/calibre/gui2/lrf_renderer/document.py | 9 +- src/calibre/gui2/lrf_renderer/main.py | 11 +- src/calibre/gui2/lrf_renderer/text.py | 3 +- src/calibre/gui2/main.py | 3 +- src/calibre/gui2/main_window.py | 10 +- src/calibre/gui2/metadata/config.py | 2 +- src/calibre/gui2/metadata/diff.py | 1 + src/calibre/gui2/metadata/pdf_covers.py | 1 + src/calibre/gui2/open_with.py | 1 + src/calibre/gui2/preferences/coloring.py | 7 +- src/calibre/gui2/preferences/plugboard.py | 7 +- .../gui2/preferences/texture_chooser.py | 1 + src/calibre/gui2/preferences/tweaks.py | 3 +- .../gui2/store/stores/amazon_au_plugin.py | 1 + .../gui2/store/stores/amazon_ca_plugin.py | 1 + .../gui2/store/stores/amazon_de_plugin.py | 1 + .../gui2/store/stores/amazon_es_plugin.py | 1 + .../gui2/store/stores/amazon_fr_plugin.py | 1 + .../gui2/store/stores/amazon_in_plugin.py | 1 + .../gui2/store/stores/amazon_it_plugin.py | 1 + .../gui2/store/stores/amazon_plugin.py | 1 + .../gui2/store/stores/amazon_uk_plugin.py | 1 + .../gui2/store/stores/chitanka_plugin.py | 2 +- src/calibre/gui2/tag_browser/model.py | 1 + .../gui2/tweak_book/completion/worker.py | 1 + src/calibre/gui2/tweak_book/diff/view.py | 2 +- src/calibre/gui2/tweak_book/download.py | 1 + .../gui2/tweak_book/editor/snippets.py | 2 +- .../gui2/tweak_book/editor/syntax/base.py | 3 +- .../gui2/tweak_book/editor/syntax/html.py | 5 +- .../gui2/tweak_book/function_replace.py | 2 +- src/calibre/gui2/tweak_book/reports.py | 1 + src/calibre/gui2/tweak_book/widgets.py | 3 +- src/calibre/gui2/ui.py | 3 +- src/calibre/gui2/viewer/config.py | 2 +- src/calibre/gui2/viewer/javascript.py | 1 + src/calibre/gui2/viewer/main.py | 1 + src/calibre/gui2/viewer/position.py | 1 + src/calibre/gui2/widgets.py | 5 +- src/calibre/gui2/wizard/__init__.py | 2 +- src/calibre/library/__init__.py | 15 +- src/calibre/library/catalogs/epub_mobi.py | 3 +- .../library/catalogs/epub_mobi_builder.py | 3 +- src/calibre/library/catalogs/utils.py | 3 +- src/calibre/library/comments.py | 9 +- src/calibre/library/database.py | 3 +- src/calibre/library/save_to_disk.py | 2 +- src/calibre/library/schema_upgrades.py | 3 +- src/calibre/library/sqlite.py | 7 +- src/calibre/libunzip.py | 3 +- src/calibre/linux.py | 11 +- src/calibre/srv/code.py | 2 +- src/calibre/srv/http_response.py | 2 +- src/calibre/srv/metadata.py | 1 + src/calibre/srv/pre_activated.py | 3 +- src/calibre/startup.py | 9 +- src/calibre/translations/__init__.py | 9 +- src/calibre/translations/msgfmt.py | 39 ++--- src/calibre/utils/Zeroconf.py | 25 +-- src/calibre/utils/chm/chm.py | 14 +- src/calibre/utils/config.py | 3 +- src/calibre/utils/config_base.py | 17 +- src/calibre/utils/fonts/sfnt/loca.py | 3 +- src/calibre/utils/fonts/sfnt/metrics.py | 15 +- src/calibre/utils/fonts/utils.py | 5 +- src/calibre/utils/fonts/win_fonts.py | 1 + src/calibre/utils/formatter_functions.py | 7 +- src/calibre/utils/https.py | 1 + src/calibre/utils/icu.py | 3 +- src/calibre/utils/inotify.py | 5 +- src/calibre/utils/ip_routing.py | 1 + src/calibre/utils/ipc/pool.py | 1 + src/calibre/utils/ipc/server.py | 3 +- src/calibre/utils/ipc/simple_worker.py | 2 +- src/calibre/utils/ipc/worker.py | 3 +- src/calibre/utils/ipython.py | 1 + src/calibre/utils/iso8601.py | 1 + src/calibre/utils/localization.py | 1 + src/calibre/utils/mem.py | 5 +- src/calibre/utils/podofo/__init__.py | 5 +- src/calibre/utils/resources.py | 1 + src/calibre/utils/search_query_parser.py | 5 +- src/calibre/utils/sftp.py | 11 +- src/calibre/utils/shared_file.py | 4 +- src/calibre/utils/smtp.py | 7 +- src/calibre/utils/socket_inheritance.py | 1 + src/calibre/utils/threadpool.py | 17 +- src/calibre/utils/wmf/emf.py | 3 +- src/calibre/utils/zipfile.py | 69 +++++---- src/calibre/web/feeds/__init__.py | 13 +- src/calibre/web/feeds/feedparser.py | 30 ++-- src/calibre/web/feeds/recipes/__init__.py | 2 +- src/calibre/web/feeds/recipes/collection.py | 5 +- src/calibre/web/fetch/simple.py | 5 +- src/css_selectors/select.py | 3 +- src/css_selectors/tests.py | 1 + src/lzma/xz.py | 2 +- src/odf/attrconverters.py | 30 ++-- src/odf/draw.py | 4 +- src/odf/element.py | 22 +-- src/odf/load.py | 5 +- src/odf/odfmanifest.py | 3 +- src/odf/opendocument.py | 4 +- src/tinycss/tests/main.py | 1 + 298 files changed, 987 insertions(+), 747 deletions(-) diff --git a/manual/custom.py b/manual/custom.py index 9de4c4f60f..c59ef07d81 100644 --- a/manual/custom.py +++ b/manual/custom.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal ' import os, re, textwrap from functools import partial @@ -198,12 +199,12 @@ def update_cli_doc(name, raw, app): old_raw = open(path, 'rb').read() if os.path.exists(path) else '' if not os.path.exists(path) or old_raw != raw: import difflib - print path, 'has changed' + print(path, 'has changed') if old_raw: lines = difflib.unified_diff(old_raw.splitlines(), raw.splitlines(), path, path) for line in lines: - print line + print(line) app.builder.info('creating '+os.path.splitext(os.path.basename(path))[0]) p = os.path.dirname(path) if p and not os.path.exists(p): diff --git a/recipes/DrawAndCook.recipe b/recipes/DrawAndCook.recipe index 976b7c5393..2f795703a3 100644 --- a/recipes/DrawAndCook.recipe +++ b/recipes/DrawAndCook.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function from calibre.web.feeds.news import BasicNewsRecipe import re @@ -30,7 +31,7 @@ class DrawAndCook(BasicNewsRecipe): articles = self.make_links(url) if articles: feeds.append((title, articles)) - print 'feeds are: ', feeds + print('feeds are: ', feeds) return feeds def make_links(self, url): @@ -45,9 +46,9 @@ class DrawAndCook(BasicNewsRecipe): 'li', attrs={'data-id': re.compile(r'artwork_entry_\d+', re.DOTALL)}) for recipe in recipes: page_url = self.INDEX + recipe.a['href'] - print 'page_url is: ', page_url + print('page_url is: ', page_url) title = recipe.find('strong').string - print 'title is: ', title + print('title is: ', title) current_articles.append( {'title': title, 'url': page_url, 'description': '', 'date': date}) return current_articles diff --git a/recipes/al_monitor.recipe b/recipes/al_monitor.recipe index 3a773c1d6a..a6dd54aae8 100644 --- a/recipes/al_monitor.recipe +++ b/recipes/al_monitor.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # -*- coding: utf-8 -*- __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2014, spswerling' ''' http://www.al-monitor.com/ diff --git a/recipes/am730.recipe b/recipes/am730.recipe index 5208125a22..b670aa6a92 100644 --- a/recipes/am730.recipe +++ b/recipes/am730.recipe @@ -1,5 +1,6 @@ # vim:fileencoding=UTF-8 from __future__ import unicode_literals +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Eddie Lau' __Date__ = '' @@ -60,7 +61,7 @@ class AM730(BasicNewsRecipe): title = href.split('/')[-1].split('-')[0] title = urllib.unquote(title.encode('ASCII')) # .decode('utf-8') if self.debug: - print title + print(title) try: if articles.index({'title':title,'url':href})>=0: # print 'already added' @@ -73,7 +74,7 @@ class AM730(BasicNewsRecipe): if (len(articles) >= self.max_articles_per_feed): break if self.debug: - print articles + print(articles) return (sectionName,articles) def parse_index(self): @@ -89,8 +90,8 @@ class AM730(BasicNewsRecipe): SectionsArticles=[] for (title, url) in Sections: if self.debug: - print title - print url + print(title) + print(url) SectionsArticles.append(self.getAMSectionArticles(title,url)) # feeds.append(articles[0]['url']) return SectionsArticles diff --git a/recipes/auto_prove.recipe b/recipes/auto_prove.recipe index 1bd7f6e7ad..37db0e6896 100644 --- a/recipes/auto_prove.recipe +++ b/recipes/auto_prove.recipe @@ -1,5 +1,6 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __author__ = 'GabrieleMarini, based on Darko Miletic' __copyright__ = '2009, Darko Miletic , Gabriele Marini' __version__ = 'v1.02 Marini Gabriele ' @@ -56,7 +57,7 @@ class AutoPR(BasicNewsRecipe): ]: soup = self.index_to_soup(url) soup = soup.find('channel') - print soup + print(soup) for article in soup.findAllNext('item'): title = self.tag_to_string(article.title) diff --git a/recipes/birmingham_post.recipe b/recipes/birmingham_post.recipe index 4a30855402..4ccf2d23c7 100644 --- a/recipes/birmingham_post.recipe +++ b/recipes/birmingham_post.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function from calibre.web.feeds.news import BasicNewsRecipe import re import mechanize @@ -26,11 +27,11 @@ class AdvancedUserRecipe1306097511(BasicNewsRecipe): # look for the block containing the sun button and url cov = soup.find(attrs={'height': re.compile( '3'), 'alt': re.compile('Post')}) - print - print '%%%%%%%%%%%%%%%', cov - print + print() + print('%%%%%%%%%%%%%%%', cov) + print() cov2 = str(cov['src']) - print '88888888 ', cov2, ' 888888888888' + print('88888888 ', cov2, ' 888888888888') # cover_url=cov2 # return cover_url diff --git a/recipes/brewiarz.recipe b/recipes/brewiarz.recipe index 1f9020b974..1abd0e5179 100644 --- a/recipes/brewiarz.recipe +++ b/recipes/brewiarz.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function from calibre.web.feeds.news import BasicNewsRecipe import datetime @@ -142,7 +143,7 @@ class brewiarz(BasicNewsRecipe): if x == tag: break else: - print "Can't find", tag, "in", tag.parent + print("Can't find", tag, "in", tag.parent) continue for r in reversed(tag.contents): tag.parent.insert(i, r) diff --git a/recipes/calgary_herald.recipe b/recipes/calgary_herald.recipe index 224d3ffd89..63a6073585 100644 --- a/recipes/calgary_herald.recipe +++ b/recipes/calgary_herald.recipe @@ -5,6 +5,7 @@ __license__ = 'GPL v3' ''' www.canada.com ''' +from __future__ import print_function import re from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag diff --git a/recipes/cio_magazine.recipe b/recipes/cio_magazine.recipe index a14ac7fb23..5e8c9b39b2 100644 --- a/recipes/cio_magazine.recipe +++ b/recipes/cio_magazine.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function # Los primeros comentarios son las dificultades que he tenido con el Piton # Cuando da error UTF8 revisa los comentarios (acentos). En notepad++ Search, Goto, posicion y lo ves. # Editar con Notepad++ Si pone - donde no debe es que ha indentado mal... Edit - Blank operations - tab to space @@ -87,7 +88,7 @@ class CIO_Magazine(BasicNewsRecipe): if INDEX.startswith('/'): # protegiendonos de que dejen de usarlos INDEX = 'http://www.cio.com' + INDEX # Y nos aseguramos en los logs que lo estamos haciendo bien - print ("INDEX en parse_index: ", INDEX) + print("INDEX en parse_index: ", INDEX) # Ya sabemos cual es la revista... procesemosla. soup = self.index_to_soup(INDEX) @@ -103,7 +104,7 @@ class CIO_Magazine(BasicNewsRecipe): if div['class'] == 'heading': key = string.capwords(self.tag_to_string(div.span)) - print ("Key: ", key) # Esto es para depurar + print("Key: ", key) # Esto es para depurar articles[key] = [] feeds.append(key) @@ -126,7 +127,7 @@ class CIO_Magazine(BasicNewsRecipe): if summary: description = self.tag_to_string(summary, use_alt=False) - print ("Description = ", description) + print("Description = ", description) # Esto esta copiado del NY times feed = key if key is not None else 'Uncategorized' diff --git a/recipes/daily_express.recipe b/recipes/daily_express.recipe index 85294b6a1a..cf19676b53 100644 --- a/recipes/daily_express.recipe +++ b/recipes/daily_express.recipe @@ -1,5 +1,6 @@ # vim:fileencoding=UTF-8 from __future__ import unicode_literals +from __future__ import print_function import re @@ -65,7 +66,7 @@ class AdvancedUserRecipe1390132023(BasicNewsRecipe): feeds = BasicNewsRecipe.parse_feeds(self) for feed in feeds: for article in feed.articles[:]: - print 'article.title is: ', article.title + print('article.title is: ', article.title) if 'WATCH:' in article.title.upper(): feed.articles.remove(article) diff --git a/recipes/dilemaveche.recipe b/recipes/dilemaveche.recipe index d116fa0d2b..0d96e7b1ab 100644 --- a/recipes/dilemaveche.recipe +++ b/recipes/dilemaveche.recipe @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = u'2014-01-09, Silviu Cotoar\u0103, Marius Popescu' ''' dilemaveche.ro diff --git a/recipes/dnevnik_mk.recipe b/recipes/dnevnik_mk.recipe index 8b88f93dc9..f969651b62 100644 --- a/recipes/dnevnik_mk.recipe +++ b/recipes/dnevnik_mk.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 __author__ = 'Darko Spasovski' +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2011, Darko Spasovski ' ''' @@ -64,7 +65,7 @@ class Dnevnik(BasicNewsRecipe): containerTable = section.findPrevious( name='table').findNextSibling(name='table') if containerTable is None: - print 'No container table found - page layout may have been changed.' + print('No container table found - page layout may have been changed.') continue articles = [] for article in containerTable.findAll('a', attrs={'class': 'WB_DNEVNIK_ArhivaFormText'}): diff --git a/recipes/edmonton_journal.recipe b/recipes/edmonton_journal.recipe index de998607e9..38c6b23810 100644 --- a/recipes/edmonton_journal.recipe +++ b/recipes/edmonton_journal.recipe @@ -5,6 +5,7 @@ __license__ = 'GPL v3' ''' www.canada.com ''' +from __future__ import print_function import re from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag diff --git a/recipes/el_cultural.recipe b/recipes/el_cultural.recipe index e3bacaa8ed..aa024cca4b 100644 --- a/recipes/el_cultural.recipe +++ b/recipes/el_cultural.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function from calibre.web.feeds.recipes import BasicNewsRecipe @@ -31,7 +32,7 @@ class RevistaElCultural(BasicNewsRecipe): # TO GET ARTICLES IN SECTION def ec_parse_section(self, url, titleSection): - print 'Section: ' + titleSection + print('Section: ' + titleSection) soup = self.index_to_soup(url) div = soup.find(attrs={'id': 'gallery'}) current_articles = [] diff --git a/recipes/elmundo.recipe b/recipes/elmundo.recipe index 1241482367..baeea6f14a 100644 --- a/recipes/elmundo.recipe +++ b/recipes/elmundo.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function # -*- mode: python -*- # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 @@ -100,7 +101,7 @@ class ElMundo(BasicNewsRecipe): html = response.read() count = tries except: - print "Retrying download..." + print("Retrying download...") count += 1 if html is not None: tfile = PersistentTemporaryFile('_fa.html') diff --git a/recipes/estadao.recipe b/recipes/estadao.recipe index 31b0d285d1..cbb06247fe 100644 --- a/recipes/estadao.recipe +++ b/recipes/estadao.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function from calibre.web.feeds.news import BasicNewsRecipe from datetime import datetime, timedelta from calibre.ebooks.BeautifulSoup import Tag, BeautifulSoup @@ -92,12 +93,12 @@ class Estadao(BasicNewsRecipe): img = Image() img.open(iurl) width, height = img.size - print 'img is: ', iurl, 'width is: ', width, 'height is: ', height + print('img is: ', iurl, 'width is: ', width, 'height is: ', height) if img < 0: raise RuntimeError('Out of memory') pw = PixelWand() if(width > height and width > 590): - print 'Rotate image' + print('Rotate image') img.rotate(pw, -90) img.save(iurl) return soup diff --git a/recipes/gry_online_pl.recipe b/recipes/gry_online_pl.recipe index 56f1e44cb1..c804c573f4 100644 --- a/recipes/gry_online_pl.recipe +++ b/recipes/gry_online_pl.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function import time from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.ebooks.BeautifulSoup import Comment @@ -37,7 +38,7 @@ class GryOnlinePl(BasicNewsRecipe): soup2 = self.index_to_soup(finalurl) break except: - print 'retrying in 0.5s' + print('retrying in 0.5s') time.sleep(0.5) pagetext = soup2.find(attrs={'class': 'gc660'}) for r in pagetext.findAll(name='header'): @@ -73,7 +74,7 @@ class GryOnlinePl(BasicNewsRecipe): soup2 = self.index_to_soup(finalurl) break except: - print 'retrying in 0.5s' + print('retrying in 0.5s') time.sleep(0.5) tag = soup2.find('div', attrs={'class': 'S018stronyr'}) pagetext = soup2.find(attrs={'class': 'gc660'}) diff --git a/recipes/houston_chronicle.recipe b/recipes/houston_chronicle.recipe index a6545ca4ca..c0b5f155fb 100644 --- a/recipes/houston_chronicle.recipe +++ b/recipes/houston_chronicle.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # -*- coding: utf-8 -*- __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2018, Dale Furrow dkfurrow@gmail.com' ''' chron.com diff --git a/recipes/huffingtonpost.recipe b/recipes/huffingtonpost.recipe index 100d2f9ab1..82fcd3d2ba 100644 --- a/recipes/huffingtonpost.recipe +++ b/recipes/huffingtonpost.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function from calibre.web.feeds.news import BasicNewsRecipe import re diff --git a/recipes/hurriyet_daily_news.recipe b/recipes/hurriyet_daily_news.recipe index de8823b890..ef9eec3d13 100644 --- a/recipes/hurriyet_daily_news.recipe +++ b/recipes/hurriyet_daily_news.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # -*- coding: utf-8 -*- __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2014, spswerling' ''' www.hurriyetdailynews.com diff --git a/recipes/klip_me.recipe b/recipes/klip_me.recipe index cfa1c33038..20d73ac23c 100644 --- a/recipes/klip_me.recipe +++ b/recipes/klip_me.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function from calibre.web.feeds.news import BasicNewsRecipe @@ -64,6 +65,6 @@ class AdvancedUserRecipe1299694372(BasicNewsRecipe): for link_tag in soup.findAll(attrs={"id": "story"}): link_tag.insert( 0, '

' + soup.find('title').contents[0].strip() + '

') - print link_tag + print(link_tag) return soup diff --git a/recipes/la_gazzeta_dello_sport.recipe b/recipes/la_gazzeta_dello_sport.recipe index c51954a068..d502801adc 100644 --- a/recipes/la_gazzeta_dello_sport.recipe +++ b/recipes/la_gazzeta_dello_sport.recipe @@ -1,5 +1,6 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __author__ = 'Lorenzo Vigentini' __copyright__ = '2009, Lorenzo Vigentini ' __version__ = 'v1.02' @@ -77,5 +78,5 @@ class laGazzetta(BasicNewsRecipe): myArticle = myArticleSegs[0] printVerString = myArticle + '_print.html' myURL = basename + subPath + printVerString - print 'this is the url: ' + myURL + print('this is the url: ' + myURL) return basename + subPath + printVerString diff --git a/recipes/la_republica.recipe b/recipes/la_republica.recipe index e0db47dd60..5659e64f1f 100644 --- a/recipes/la_republica.recipe +++ b/recipes/la_republica.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __author__ = 'Lorenzo Vigentini, based on Darko Miletic, Gabriele Marini; minor fixes by faber1971' __copyright__ = '2009-2012, Darko Miletic , Lorenzo Vigentini , faber1971' @@ -48,7 +49,7 @@ class LaRepubblica(BasicNewsRecipe): html = response.read() count = 10 except: - print "Retrying download..." + print("Retrying download...") count += 1 self.temp_files.append(PersistentTemporaryFile('_fa.html')) self.temp_files[-1].write(html) diff --git a/recipes/le_temps.recipe b/recipes/le_temps.recipe index a300df9479..29b0e16249 100644 --- a/recipes/le_temps.recipe +++ b/recipes/le_temps.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -60,7 +61,7 @@ class LeTemps(BasicNewsRecipe): if key.endswith('_origlink'): url = article[key] if url and url.startswith('https://'): - print ('Url is :', url) + print('Url is :', url) return url ans = article.get('link', None) if not ans and getattr(article, 'links', None): diff --git a/recipes/lenta_ru.recipe b/recipes/lenta_ru.recipe index aa4dac49a7..7a1a28652c 100644 --- a/recipes/lenta_ru.recipe +++ b/recipes/lenta_ru.recipe @@ -109,7 +109,7 @@ class LentaRURecipe(BasicNewsRecipe): return result - except Exception, err: + except Exception as err: self.log(err) raise NotImplementedError diff --git a/recipes/lwn_weekly.recipe b/recipes/lwn_weekly.recipe index 73acd60a36..f16be3cf2f 100644 --- a/recipes/lwn_weekly.recipe +++ b/recipes/lwn_weekly.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2011, Davide Cavalca ' ''' lwn.net @@ -120,8 +121,8 @@ class WeeklyLWN(BasicNewsRecipe): if article_anchor: article_url = article_anchor.get('href') if not article_url: - print >>sys.stderr, 'article_url is None for article_anchor "%s": "%s"' \ - % (str(article_anchor), article_title) + print('article_url is None for article_anchor "%s": "%s"' \ + % (str(article_anchor), article_title), file=sys.stderr) continue else: diff --git a/recipes/metro_news_nl.recipe b/recipes/metro_news_nl.recipe index 8881e17fe7..942cdc520d 100644 --- a/recipes/metro_news_nl.recipe +++ b/recipes/metro_news_nl.recipe @@ -1,5 +1,6 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from calibre.web.feeds.news import BasicNewsRecipe +from __future__ import print_function import re from calibre.utils.magick import Image from calibre.ebooks.BeautifulSoup import BeautifulSoup @@ -140,7 +141,7 @@ class MerryPreProcess(): img.trim(0) img.save(iurl) except: - print '\n!!image optimize failed!!\n' + print('\n!!image optimize failed!!\n') continue return soup @@ -198,7 +199,7 @@ class MerryProcess(BeautifulSoup): try: pubdate.parent.insert(0, moveitem) except: - print '\n!!error in moving title!!\n' + print('\n!!error in moving title!!\n') pass moveitem = None moveitem = soup.find('div', {'class': 'byline'}) @@ -206,7 +207,7 @@ class MerryProcess(BeautifulSoup): try: moveitem.parent.parent.insert(-1, moveitem) except: - print '\n!!error in moving byline!!\n' + print('\n!!error in moving byline!!\n') pass return soup diff --git a/recipes/metro_uk.recipe b/recipes/metro_uk.recipe index 865651f2ca..5a420fc126 100644 --- a/recipes/metro_uk.recipe +++ b/recipes/metro_uk.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function import re from calibre.web.feeds.news import BasicNewsRecipe @@ -41,7 +42,7 @@ class AdvancedUserRecipe1390146870(BasicNewsRecipe): feeds = BasicNewsRecipe.parse_feeds(self) for feed in feeds: for article in feed.articles[:]: - print 'article.title is: ', article.title + print('article.title is: ', article.title) if 'VIDEO:' in article.title.upper(): feed.articles.remove(article) diff --git a/recipes/ming_pao.recipe b/recipes/ming_pao.recipe index cdb705fd2b..3af15cdfeb 100644 --- a/recipes/ming_pao.recipe +++ b/recipes/ming_pao.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2010-2013, Eddie Lau' @@ -630,7 +631,7 @@ class MPRecipe(BasicNewsRecipe): {'title': title, 'url': url, 'description': ''}) included_urls.append(url) except: - print 'skipping a premium article' + print('skipping a premium article') current_articles.reverse() return current_articles @@ -822,7 +823,7 @@ class MPRecipe(BasicNewsRecipe): else: if next_is_img_txt is False: if item.startswith("=@"): - print 'skip movie link' + print('skip movie link') elif item.startswith("=?"): next_is_img_txt = True new_raw_html += '(.*)', source, re.DOTALL) if matches is None: - print "no article tag found, returning..." + print("no article tag found, returning...") return main_section = BeautifulSoup(matches.group(0)) diff --git a/recipes/nikkei_news.recipe b/recipes/nikkei_news.recipe index 80ac8c5c63..473407db07 100644 --- a/recipes/nikkei_news.recipe +++ b/recipes/nikkei_news.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=utf-8 from calibre.web.feeds.recipes import BasicNewsRecipe +from __future__ import print_function import re import unicodedata @@ -40,39 +41,39 @@ class NikkeiNet_paper_subscription(BasicNewsRecipe): br = BasicNewsRecipe.get_browser(self) if self.username is not None and self.password is not None: - print "-------------------------open top page-------------------------------------" + print("-------------------------open top page-------------------------------------") br.open('http://www.nikkei.com/') - print "-------------------------open first login form-----------------------------" + print("-------------------------open first login form-----------------------------") try: url = list(br.links( url_regex="www.nikkei.com/etc/accounts/login"))[0].url except IndexError: - print "Found IndexError" + print("Found IndexError") url = 'http://www.nikkei.com/etc/accounts/login?dps=3&pageflag=top&url=http%3A%2F%2Fwww.nikkei.com%2F' except StopIteration: url = 'http://www.nikkei.com/etc/accounts/login?dps=3&pageflag=top&url=http%3A%2F%2Fwww.nikkei.com%2F' br.open(url) - print "-------------------------JS redirect(send autoPostForm)--------------------" + print("-------------------------JS redirect(send autoPostForm)--------------------") br.select_form(name='autoPostForm') br.submit() # response = br.response() - print "-------------------------got login form------------------------------------" + print("-------------------------got login form------------------------------------") br.select_form(name='LA7010Form01') br['LA7010Form01:LA7010Email'] = self.username br['LA7010Form01:LA7010Password'] = self.password br.submit(id='LA7010Form01:submitBtn') - print "-------------------------JS redirect---------------------------------------" + print("-------------------------JS redirect---------------------------------------") br.select_form(nr=0) br.submit() return br def cleanup(self): - print "-------------------------logout--------------------------------------------" + print("-------------------------logout--------------------------------------------") self.browser.open('https://regist.nikkei.com/ds/etc/accounts/logout') def parse_index(self): - print "-------------------------get index of paper--------------------------------" + print("-------------------------get index of paper--------------------------------") result = [] soup = self.index_to_soup('http://www.nikkei.com/paper/') sections = soup.findAll(attrs={'class': re.compile(".*cmn-article_title.*")}) diff --git a/recipes/nuus24.recipe b/recipes/nuus24.recipe index 76e94ce1df..d54c49f5f5 100644 --- a/recipes/nuus24.recipe +++ b/recipes/nuus24.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function import re from calibre import strftime from calibre.web.feeds.recipes import BasicNewsRecipe @@ -48,7 +49,7 @@ class Nuus24(BasicNewsRecipe): attrs={'id': ['lnkLink']}): url = re.sub(r'\?.*', '', anchor['href']) title = self.tag_to_string(anchor, use_alt=True).strip() - print title + print(title) description = '' pubdate = strftime('%a, %d %b') articles[key].append( diff --git a/recipes/observa_digital.recipe b/recipes/observa_digital.recipe index 760e2319e6..78dcfa40ee 100644 --- a/recipes/observa_digital.recipe +++ b/recipes/observa_digital.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __author__ = '2010, Gustavo Azambuja ' ''' observa.com.uy @@ -54,7 +55,7 @@ class Noticias(BasicNewsRecipe): cover_url = 'http://www.elobservador.com.uy' + \ link_item['src'].strip() - print cover_url + print(cover_url) return cover_url diff --git a/recipes/observatorul_cultural.recipe b/recipes/observatorul_cultural.recipe index b8a344848e..34b7ebe8f3 100644 --- a/recipes/observatorul_cultural.recipe +++ b/recipes/observatorul_cultural.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function import re from calibre.web.feeds.news import BasicNewsRecipe coverpage = None @@ -30,7 +31,7 @@ class ObservatorulCultural(BasicNewsRecipe): issueTag = soup.find('a', href=re.compile( "observatorcultural.ro\/Numarul")) issueURL = issueTag['href'] - print issueURL + print(issueURL) issueSoup = self.index_to_soup(issueURL) feeds = [] stories = [] @@ -59,7 +60,7 @@ class ObservatorulCultural(BasicNewsRecipe): coverpage = title[1]['href'] feeds.append((categ, stories)) stories = [] - print feeds + print(feeds) return feeds # procedura de luat coperta diff --git a/recipes/oreilly_premium.recipe b/recipes/oreilly_premium.recipe index d7b11419e1..9649274fd0 100644 --- a/recipes/oreilly_premium.recipe +++ b/recipes/oreilly_premium.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function import time import traceback # above for debugging via stack diff --git a/recipes/ottawa_citizen.recipe b/recipes/ottawa_citizen.recipe index 70b5f40c42..333e52dfd0 100644 --- a/recipes/ottawa_citizen.recipe +++ b/recipes/ottawa_citizen.recipe @@ -5,6 +5,7 @@ __license__ = 'GPL v3' ''' www.canada.com ''' +from __future__ import print_function import re from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag diff --git a/recipes/pagina_12_print_ed.recipe b/recipes/pagina_12_print_ed.recipe index 413a1e4a4f..494be08b19 100644 --- a/recipes/pagina_12_print_ed.recipe +++ b/recipes/pagina_12_print_ed.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal ' ''' pagina12.com.ar @@ -34,7 +35,7 @@ class Pagina12(BasicNewsRecipe): for image in soup.findAll('img', alt=True): if image['alt'].startswith('Tapa de la fecha'): return image['src'] - print image + print(image) return None def parse_index(self): diff --git a/recipes/pravo.recipe b/recipes/pravo.recipe index c3dba65b0f..07bd562852 100644 --- a/recipes/pravo.recipe +++ b/recipes/pravo.recipe @@ -38,7 +38,8 @@ class pravo(BasicNewsRecipe): articles.append(self.parse_page(feed)) return articles - def parse_page(self, (feed_title, url)): + def parse_page(self, xxx_todo_changeme): + (feed_title, url) = xxx_todo_changeme articles = [] soup = self.index_to_soup(url) diff --git a/recipes/real_clear.recipe b/recipes/real_clear.recipe index 787252a8b6..9cc3e10cbc 100644 --- a/recipes/real_clear.recipe +++ b/recipes/real_clear.recipe @@ -1,3 +1,4 @@ +from __future__ import print_function # Test with "\Program Files\Calibre2\ebook-convert.exe" RealClear.recipe # .epub --test -vv --debug-pipeline debug import re diff --git a/recipes/todays_zaman.recipe b/recipes/todays_zaman.recipe index e1d56acde2..e7ed5ec53d 100644 --- a/recipes/todays_zaman.recipe +++ b/recipes/todays_zaman.recipe @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # -*- coding: utf-8 -*- __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2014, spswerling' ''' www.todayszaman.com @@ -73,7 +74,7 @@ class TodaysZaman(BasicNewsRecipe): def parse_section(self, sect_title, sect_uri): url = 'http://www.todayszaman.com/' + sect_uri - print 'Start section ' + sect_title + ', ' + url + print('Start section ' + sect_title + ', ' + url) try: soup = self.index_to_soup(url) except: @@ -89,11 +90,11 @@ class TodaysZaman(BasicNewsRecipe): for link in div.findAll('a', href=True): self.process_link(sect_title, div_class, link) - print 'Finished section: ' + sect_title + print('Finished section: ' + sect_title) def process_link(self, section_title, layout, link): def p(s): - print '[PROCESS LINK] ' + s[0:80] + print('[PROCESS LINK] ' + s[0:80]) href = link['href'] full_href = urljoin('http://www.todayszaman.com/', href) @@ -137,7 +138,7 @@ class TodaysZaman(BasicNewsRecipe): def populate_article_metadata(self, article, soup, first): def p(s): - print '[POPULATE METADATA] ' + s[0:80] + print('[POPULATE METADATA] ' + s[0:80]) tnode = soup.find('title') if tnode: diff --git a/recipes/vancouver_province.recipe b/recipes/vancouver_province.recipe index d478462ca6..23b9e85059 100644 --- a/recipes/vancouver_province.recipe +++ b/recipes/vancouver_province.recipe @@ -5,6 +5,7 @@ __license__ = 'GPL v3' ''' www.canada.com ''' +from __future__ import print_function import re from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag diff --git a/recipes/vancouver_sun.recipe b/recipes/vancouver_sun.recipe index 411df014cf..1b7b5e57ab 100644 --- a/recipes/vancouver_sun.recipe +++ b/recipes/vancouver_sun.recipe @@ -5,6 +5,7 @@ __license__ = 'GPL v3' ''' www.canada.com ''' +from __future__ import print_function import re from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag diff --git a/recipes/vedomosti.recipe b/recipes/vedomosti.recipe index c76578b15b..8133588a1e 100644 --- a/recipes/vedomosti.recipe +++ b/recipes/vedomosti.recipe @@ -113,7 +113,7 @@ class VedomostiRecipe(BasicNewsRecipe): return result - except Exception, err: + except Exception as err: self.log(err) raise NotImplementedError diff --git a/recipes/vic_times.recipe b/recipes/vic_times.recipe index 92aa1c8ff7..0cc0431da8 100644 --- a/recipes/vic_times.recipe +++ b/recipes/vic_times.recipe @@ -5,6 +5,7 @@ __license__ = 'GPL v3' ''' www.canada.com ''' +from __future__ import print_function import re from calibre.web.feeds.news import BasicNewsRecipe diff --git a/setup/__init__.py b/setup/__init__.py index cada8130c8..ccc353a936 100644 --- a/setup/__init__.py +++ b/setup/__init__.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -75,10 +76,10 @@ def require_clean_git(): c('git rev-parse --verify HEAD'.split(), stdout=null) c('git update-index -q --ignore-submodules --refresh'.split()) if p('git diff-files --quiet --ignore-submodules'.split()).wait() != 0: - print >>sys.stderr, 'You have unstaged changes in your working tree' + print('You have unstaged changes in your working tree', file=sys.stderr) raise SystemExit(1) if p('git diff-index --cached --quiet --ignore-submodules HEAD --'.split()).wait() != 0: - print >>sys.stderr, 'Your git index contains uncommitted changes' + print('Your git index contains uncommitted changes', file=sys.stderr) raise SystemExit(1) @@ -269,9 +270,9 @@ class Command(object): sys.stdout.flush() def warn(self, *args, **kwargs): - print '\n'+'_'*20, 'WARNING','_'*20 + print('\n'+'_'*20, 'WARNING','_'*20) prints(*args, **kwargs) - print '_'*50 + print('_'*50) warnings.append((args, kwargs)) sys.stdout.flush() diff --git a/setup/build.py b/setup/build.py index 3042f7ae15..18bf304d21 100644 --- a/setup/build.py +++ b/setup/build.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -343,7 +344,7 @@ class Build(Command): subprocess.check_call(*args, **kwargs) except: cmdline = ' '.join(['"%s"' % (arg) if ' ' in arg else arg for arg in args[0]]) - print "Error while executing: %s\n" % (cmdline) + print("Error while executing: %s\n" % (cmdline)) raise def build_headless(self): diff --git a/setup/build_environment.py b/setup/build_environment.py index 04b6d5f052..42e5206236 100644 --- a/setup/build_environment.py +++ b/setup/build_environment.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -51,7 +52,7 @@ def run_pkgconfig(name, envvar, default, flag, prefix): 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: - print 'Failed to run pkg-config:', PKGCONFIG, 'for:', name + 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 cdcfe1f633..2d199bd29f 100755 --- a/setup/git_pre_commit_hook.py +++ b/setup/git_pre_commit_hook.py @@ -4,6 +4,7 @@ import importlib +from __future__ import print_function import json import re import socket diff --git a/setup/linux-installer.py b/setup/linux-installer.py index cc127d825b..272607c025 100644 --- a/setup/linux-installer.py +++ b/setup/linux-installer.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -319,7 +320,7 @@ def download_tarball(): dest = os.path.join(cache, fname) raw = check_signature(dest, signature) if raw is not None: - print ('Using previously downloaded', fname) + print('Using previously downloaded', fname) return raw cached_sigf = dest +'.signature' cached_sig = None @@ -671,7 +672,7 @@ def run_installer(install_dir, isolated, bin_dir, share_dir): if not os.path.isdir(destdir): prints(destdir, 'exists and is not a directory. Choose a location like /opt or /usr/local') return 1 - print ('Installing to', destdir) + print('Installing to', destdir) download_and_extract(destdir) diff --git a/setup/mathjax.py b/setup/mathjax.py index 991461c8c5..23f28dcbd2 100644 --- a/setup/mathjax.py +++ b/setup/mathjax.py @@ -40,7 +40,7 @@ class MathJax(Command): raw = f.read() self.h.update(raw) zi = ZipInfo(name) - zi.external_attr = 0o444 << 16L + zi.external_attr = 0o444 << 16 zf.writestr(zi, raw) def add_tree(self, zf, base, prefix, ignore=lambda n:False): diff --git a/setup/publish.py b/setup/publish.py index 0ed176eae0..fef57a0d4e 100644 --- a/setup/publish.py +++ b/setup/publish.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' diff --git a/setup/pypi.py b/setup/pypi.py index 59697dd688..92cf97d97c 100644 --- a/setup/pypi.py +++ b/setup/pypi.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -129,7 +130,7 @@ class PyPIRegister(Command): ''' # send the info to the server and report the result (code, result) = self.post_to_server(self.build_post_data('verify')) - print 'Server response (%s): %s'%(code, result) + print('Server response (%s): %s'%(code, result)) def build_post_data(self, action): # figure the data to send - the metadata plus some additional @@ -199,18 +200,18 @@ class PyPIRegister(Command): data = '' try: result = opener.open(req) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if self.show_response: data = e.fp.read() result = e.code, e.msg - except urllib2.URLError, e: + except urllib2.URLError as e: result = 500, str(e) else: if self.show_response: data = result.read() result = 200, 'OK' if self.show_response: - print '-'*75, data, '-'*75 + print('-'*75, data, '-'*75) return result class PyPIUpload(PyPIRegister): @@ -341,7 +342,7 @@ class PyPIUpload(PyPIRegister): http.putheader('Authorization', auth) http.endheaders() http.send(body) - except socket.error, e: + except socket.error as e: self.warn(str(e)) raise SystemExit(1) @@ -352,4 +353,4 @@ class PyPIUpload(PyPIRegister): self.info('Upload failed (%s): %s' % (r.status, r.reason)) raise SystemExit(1) if self.show_response: - print '-'*75, r.read(), '-'*75 + print('-'*75, r.read(), '-'*75) diff --git a/setup/resources.py b/setup/resources.py index 7fb34bd89d..783e6e7f75 100644 --- a/setup/resources.py +++ b/setup/resources.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -55,7 +56,7 @@ class Coffee(Command): # {{{ from pygments.lexers import JavascriptLexer from pygments.formatters import TerminalFormatter from pygments import highlight - print highlight(raw, JavascriptLexer(), TerminalFormatter()) + print(highlight(raw, JavascriptLexer(), TerminalFormatter())) def do_coffee_compile(self, opts, timestamp=False, ignore_errors=False): from calibre.utils.serve_coffee import compile_coffeescript @@ -96,7 +97,7 @@ class Coffee(Command): # {{{ if errors: print ('\n\tCompilation of %s failed'%name) for line in errors: - print >>sys.stderr, line + print(line, file=sys.stderr) if ignore_errors: js = u'# Compilation from coffeescript failed' else: diff --git a/setup/translations.py b/setup/translations.py index 426972dc8d..bea99b2e8a 100644 --- a/setup/translations.py +++ b/setup/translations.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' diff --git a/setup/upload.py b/setup/upload.py index be292787e1..8796d530b1 100644 --- a/setup/upload.py +++ b/setup/upload.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2009, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -143,7 +144,7 @@ def calibre_cmdline(ver): def run_remote_upload(args): - print 'Running remotely:', ' '.join(args) + print('Running remotely:', ' '.join(args)) subprocess.check_call([ 'ssh', '-x', '%s@%s' % (STAGING_USER, STAGING_HOST), 'cd', STAGING_DIR, '&&', 'python2', 'hosting.py' diff --git a/setup/vcvars.py b/setup/vcvars.py index 4641ec06fd..649d9131f4 100644 --- a/setup/vcvars.py +++ b/setup/vcvars.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/constants.py b/src/calibre/constants.py index 62b933c110..db13ad52e7 100644 --- a/src/calibre/constants.py +++ b/src/calibre/constants.py @@ -3,6 +3,7 @@ # License: GPLv3 Copyright: 2015, Kovid Goyal from future_builtins import map +from __future__ import print_function import sys, locale, codecs, os, importlib, collections __appname__ = u'calibre' @@ -231,7 +232,7 @@ if plugins is None: # config_dir {{{ -CONFIG_DIR_MODE = 0700 +CONFIG_DIR_MODE = 0o700 if 'CALIBRE_CONFIG_DIRECTORY' in os.environ: config_dir = os.path.abspath(os.environ['CALIBRE_CONFIG_DIRECTORY']) @@ -257,7 +258,7 @@ else: if not os.path.exists(config_dir) or \ not os.access(config_dir, os.W_OK) or not \ os.access(config_dir, os.X_OK): - print 'No write acces to', config_dir, 'using a temporary dir instead' + print('No write acces to', config_dir, 'using a temporary dir instead') import tempfile, atexit config_dir = tempfile.mkdtemp(prefix='calibre-config-') diff --git a/src/calibre/customize/__init__.py b/src/calibre/customize/__init__.py index a23196dac7..c432de8502 100644 --- a/src/calibre/customize/__init__.py +++ b/src/calibre/customize/__init__.py @@ -1,4 +1,5 @@ from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' @@ -563,7 +564,7 @@ class CatalogPlugin(Plugin): # {{{ try: resources.extract(file, self.resources_path) except: - print " customize:__init__.initialize(): %s not found in %s" % (file, os.path.basename(self.plugin_path)) + print(" customize:__init__.initialize(): %s not found in %s" % (file, os.path.basename(self.plugin_path))) continue resources.close() diff --git a/src/calibre/customize/ui.py b/src/calibre/customize/ui.py index 3ca5efd633..09e98d97c8 100644 --- a/src/calibre/customize/ui.py +++ b/src/calibre/customize/ui.py @@ -1,4 +1,5 @@ from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' @@ -170,7 +171,7 @@ def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'): try: nfp = plugin.run(nfp) or nfp except: - print >>oe, 'Running file type plugin %s failed with traceback:'%plugin.name + print('Running file type plugin %s failed with traceback:'%plugin.name, file=oe) traceback.print_exc(file=oe) sys.stdout, sys.stderr = oo, oe x = lambda j: os.path.normpath(os.path.normcase(j)) @@ -673,7 +674,7 @@ def initialize_plugin(plugin, path_to_zip_file): p.initialize() return p except Exception: - print 'Failed to initialize plugin:', plugin.name, plugin.version + print('Failed to initialize plugin:', plugin.name, plugin.version) tb = traceback.format_exc() raise InvalidPlugin((_('Initialization of plugin %s failed with traceback:') %tb) + '\n'+tb) @@ -718,7 +719,7 @@ def initialize_plugins(perf=False): times[plugin.name] = time.time() - st _initialized_plugins.append(plugin) except: - print 'Failed to initialize plugin:', repr(zfp) + print('Failed to initialize plugin:', repr(zfp)) if DEBUG: traceback.print_exc() # Prevent a custom plugin from overriding stdout/stderr as this breaks @@ -795,19 +796,19 @@ def main(args=sys.argv): opts, args = parser.parse_args(args) if opts.add_plugin is not None: plugin = add_plugin(opts.add_plugin) - print 'Plugin added:', plugin.name, plugin.version + print('Plugin added:', plugin.name, plugin.version) if opts.build_plugin is not None: build_plugin(opts.build_plugin) if opts.remove_plugin is not None: if remove_plugin(opts.remove_plugin): - print 'Plugin removed' + print('Plugin removed') else: - print 'No custom plugin named', opts.remove_plugin + print('No custom plugin named', opts.remove_plugin) if opts.customize_plugin is not None: name, custom = opts.customize_plugin.split(',') plugin = find_plugin(name.strip()) if plugin is None: - print 'No plugin with the name %s exists'%name + print('No plugin with the name %s exists'%name) return 1 customize_plugin(plugin, custom) if opts.enable_plugin is not None: @@ -819,21 +820,21 @@ def main(args=sys.argv): for plugin in initialized_plugins(): type_len, name_len = max(type_len, len(plugin.type)), max(name_len, len(plugin.name)) fmt = '%-{}s%-{}s%-15s%-15s%s'.format(type_len+1, name_len+1) - print fmt%tuple(('Type|Name|Version|Disabled|Site Customization'.split('|'))) - print + print(fmt%tuple(('Type|Name|Version|Disabled|Site Customization'.split('|')))) + print() for plugin in initialized_plugins(): - print fmt%( + print(fmt%( plugin.type, plugin.name, plugin.version, is_disabled(plugin), plugin_customization(plugin) - ) - print '\t', plugin.description + )) + print('\t', plugin.description) if plugin.is_customizable(): try: - print '\t', plugin.customization_help() + print('\t', plugin.customization_help()) except NotImplementedError: pass - print + print() return 0 diff --git a/src/calibre/customize/zipplugin.py b/src/calibre/customize/zipplugin.py index 4c79d3bea4..b9b6096875 100644 --- a/src/calibre/customize/zipplugin.py +++ b/src/calibre/customize/zipplugin.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function from future_builtins import map __license__ = 'GPL v3' @@ -180,7 +181,7 @@ class PluginLoader(object): mod.__dict__['get_resources'] = partial(get_resources, zfp) mod.__dict__['get_icons'] = partial(get_icons, zfp) mod.__dict__['load_translations'] = partial(load_translations, mod.__dict__, zfp) - exec compiled in mod.__dict__ + exec(compiled, mod.__dict__) return mod @@ -309,11 +310,11 @@ if __name__ == '__main__': with CurrentDir(path): for x in os.listdir('.'): if x[0] != '.': - print ('Adding', x) + print('Adding', x) zf.write(x) if os.path.isdir(x): for y in os.listdir(x): zf.write(os.path.join(x, y)) add_plugin(f.name) - print ('Added plugin from', sys.argv[-1]) + print('Added plugin from', sys.argv[-1]) diff --git a/src/calibre/db/backend.py b/src/calibre/db/backend.py index fd83e3aaf6..32a69c81d9 100644 --- a/src/calibre/db/backend.py +++ b/src/calibre/db/backend.py @@ -1626,7 +1626,7 @@ class DB(object): except EnvironmentError as err: if err.errno == errno.EEXIST: # Parent directory already exists, re-raise original exception - raise exc_info[0], exc_info[1], exc_info[2] + raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) raise finally: del exc_info diff --git a/src/calibre/db/tests/profiling.py b/src/calibre/db/tests/profiling.py index b0c35ffdbe..7d5afe8ec2 100644 --- a/src/calibre/db/tests/profiling.py +++ b/src/calibre/db/tests/profiling.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' @@ -38,7 +39,7 @@ def main(): pr.disable() pr.dump_stats(stats) show_stats(stats) - print ('Stats saved to', stats) + print('Stats saved to', stats) if __name__ == '__main__': main() diff --git a/src/calibre/debug.py b/src/calibre/debug.py index 55137ccd10..dbf720722a 100644 --- a/src/calibre/debug.py +++ b/src/calibre/debug.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal ' ''' Embedded console for debugging. @@ -254,7 +255,7 @@ def inspect_mobi(path): from calibre.ebooks.mobi.debug.main import inspect_mobi prints('Inspecting:', path) inspect_mobi(path) - print + print() def main(args=sys.argv): @@ -325,7 +326,7 @@ def main(args=sys.argv): from calibre.utils.winreg.default_programs import register as func else: from calibre.utils.winreg.default_programs import unregister as func - print 'Running', func.__name__, '...' + print('Running', func.__name__, '...') func() elif opts.export_all_calibre_data: args = args[1:] diff --git a/src/calibre/devices/__init__.py b/src/calibre/devices/__init__.py index 723e875a4b..d3ee2b0f19 100644 --- a/src/calibre/devices/__init__.py +++ b/src/calibre/devices/__init__.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' @@ -45,7 +46,7 @@ def get_connected_device(): connected_devices.append((det, dev)) if dev is None: - print >>sys.stderr, 'Unable to find a connected ebook reader.' + print('Unable to find a connected ebook reader.', file=sys.stderr) return for det, d in connected_devices: diff --git a/src/calibre/devices/cli.py b/src/calibre/devices/cli.py index c2181933e9..d9182d0c94 100755 --- a/src/calibre/devices/cli.py +++ b/src/calibre/devices/cli.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' """ @@ -100,10 +101,10 @@ class FileFormatter(object): def info(dev): info = dev.get_device_information() - print "Device name: ", info[0] - print "Device version: ", info[1] - print "Software version:", info[2] - print "Mime type: ", info[3] + print("Device name: ", info[0]) + print("Device version: ", info[1]) + print("Software version:", info[2]) + print("Mime type: ", info[3]) def ls(dev, path, recurse=False, human_readable_size=False, ll=False, cols=0): @@ -132,7 +133,7 @@ def ls(dev, path, recurse=False, human_readable_size=False, ll=False, cols=0): dirs = dev.list(path, recurse) for dir in dirs: if recurse: - print >>output, dir[0] + ":" + print(dir[0] + ":", file=output) lsoutput, lscoloutput = [], [] files = dir[1] maxlen = 0 @@ -153,7 +154,7 @@ def ls(dev, path, recurse=False, human_readable_size=False, ll=False, cols=0): size = str(file.size) if human_readable_size: size = file.human_readable_size - print >>output, file.mode_string, ("%"+str(maxlen)+"s")%size, file.modification_time, name + print(file.mode_string, ("%"+str(maxlen)+"s")%size, file.modification_time, name, file=output) if not ll and len(lsoutput) > 0: trytable = [] for colwidth in range(MINIMUM_COL_WIDTH, cols): @@ -175,9 +176,9 @@ def ls(dev, path, recurse=False, human_readable_size=False, ll=False, cols=0): for r in range(len(trytable)): for c in range(len(trytable[r])): padding = rowwidths[c] - len(trytable[r][c]) - print >>output, trytablecol[r][c], "".ljust(padding), - print >>output - print >>output + print(trytablecol[r][c], "".ljust(padding), end=' ', file=output) + print(file=output) + print(file=output) listing = output.getvalue().rstrip()+ "\n" output.close() return listing @@ -235,7 +236,7 @@ def main(): connected_devices.append((det, dev)) if dev is None: - print >>sys.stderr, 'Unable to find a connected ebook reader.' + print('Unable to find a connected ebook reader.', file=sys.stderr) shutdown_plugins() return 1 @@ -254,22 +255,22 @@ def main(): total = dev.total_space(end_session=False) free = dev.free_space() where = ("Memory", "Card A", "Card B") - print "Filesystem\tSize \tUsed \tAvail \tUse%" + print("Filesystem\tSize \tUsed \tAvail \tUse%") for i in range(3): - print "%-10s\t%s\t%s\t%s\t%s"%(where[i], human_readable(total[i]), human_readable(total[i]-free[i]), human_readable(free[i]), - str(0 if total[i]==0 else int(100*(total[i]-free[i])/(total[i]*1.)))+"%") + print("%-10s\t%s\t%s\t%s\t%s"%(where[i], human_readable(total[i]), human_readable(total[i]-free[i]), human_readable(free[i]), + str(0 if total[i]==0 else int(100*(total[i]-free[i])/(total[i]*1.)))+"%")) elif command == 'eject': dev.eject() elif command == "books": - print "Books in main memory:" + print("Books in main memory:") for book in dev.books(): - print book - print "\nBooks on storage carda:" + print(book) + print("\nBooks on storage carda:") for book in dev.books(oncard='carda'): - print book - print "\nBooks on storage cardb:" + print(book) + print("\nBooks on storage cardb:") for book in dev.books(oncard='cardb'): - print book + print(book) elif command == "mkdir": parser = OptionParser(usage="usage: %prog mkdir [options] path\nCreate a directory on the device\n\npath must begin with / or card:/") if len(args) != 1: @@ -289,7 +290,7 @@ def main(): if len(args) != 1: parser.print_help() return 1 - print ls(dev, args[0], recurse=options.recurse, ll=options.ll, human_readable_size=options.hrs, cols=cols), + print(ls(dev, args[0], recurse=options.recurse, ll=options.ll, human_readable_size=options.hrs, cols=cols), end=' ') elif command == "info": info(dev) elif command == "cp": @@ -316,7 +317,7 @@ def main(): try: outfile = lopen(outfile, "wb") except IOError as e: - print >> sys.stderr, e + print(e, file=sys.stderr) parser.print_help() return 1 dev.get_file(path, outfile) @@ -326,7 +327,7 @@ def main(): try: infile = lopen(args[0], "rb") except IOError as e: - print >> sys.stderr, e + print(e, file=sys.stderr) parser.print_help() return 1 dev.put_file(infile, args[1][4:], replace_file=options.force) @@ -376,8 +377,8 @@ def main(): path = args[0] from calibre.ebooks.metadata.meta import get_metadata mi = get_metadata(lopen(path, 'rb'), path.rpartition('.')[-1].lower()) - print dev.upload_books([args[0]], [os.path.basename(args[0])], - end_session=False, metadata=[mi]) + print(dev.upload_books([args[0]], [os.path.basename(args[0])], + end_session=False, metadata=[mi])) dev.eject() else: parser.print_help() @@ -385,9 +386,9 @@ def main(): dev.close() return 1 except DeviceLocked: - print >> sys.stderr, "The device is locked. Use the --unlock option" + print("The device is locked. Use the --unlock option", file=sys.stderr) except (ArgumentError, DeviceError) as e: - print >>sys.stderr, e + print(e, file=sys.stderr) return 1 finally: shutdown_plugins() diff --git a/src/calibre/devices/kindle/bookmark.py b/src/calibre/devices/kindle/bookmark.py index b122bb7691..2e64a14e4c 100644 --- a/src/calibre/devices/kindle/bookmark.py +++ b/src/calibre/devices/kindle/bookmark.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- __license__ = 'GPL v3' +from __future__ import print_function __docformat__ = 'restructuredtext en' import os @@ -276,7 +277,7 @@ class Bookmark(): # {{{ self.last_read_location = self.last_read - self.pdf_page_offset else: - print "unsupported bookmark_extension: %s" % self.bookmark_extension + print("unsupported bookmark_extension: %s" % self.bookmark_extension) self.user_notes = user_notes def get_book_length(self): @@ -312,6 +313,6 @@ class Bookmark(): # {{{ pass else: - print "unsupported bookmark_extension: %s" % self.bookmark_extension + print("unsupported bookmark_extension: %s" % self.bookmark_extension) # }}} diff --git a/src/calibre/devices/kindle/driver.py b/src/calibre/devices/kindle/driver.py index 7e25f88dc9..aba5c8d994 100644 --- a/src/calibre/devices/kindle/driver.py +++ b/src/calibre/devices/kindle/driver.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2009, John Schember ' __docformat__ = 'restructuredtext en' @@ -555,7 +556,7 @@ class KINDLE2(KINDLE): print('Could not retrieve override method choice, using default.') apnx_builder.write_apnx(filepath, apnx_path, method=method, page_count=custom_page_count) except: - print 'Failed to generate APNX' + print('Failed to generate APNX') import traceback traceback.print_exc() diff --git a/src/calibre/devices/kobo/driver.py b/src/calibre/devices/kobo/driver.py index 507ca475c4..b77ab1a829 100644 --- a/src/calibre/devices/kobo/driver.py +++ b/src/calibre/devices/kobo/driver.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import division +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2010-2012, Timothy Legge , Kovid Goyal and David Forrester ' @@ -646,7 +647,7 @@ class KOBO(USBMS): path = ContentID if oncard == 'cardb': - print 'path from_contentid cardb' + print('path from_contentid cardb') elif oncard == 'carda': path = path.replace("file:///mnt/sd/", self._card_a_prefix) # print "SD Card: " + path @@ -1929,7 +1930,7 @@ class KOBOTOUCH(KOBO): return super(KOBOTOUCH, self).path_from_contentid(ContentID, ContentType, MimeType, oncard) if oncard == 'cardb': - print 'path from_contentid cardb' + print('path from_contentid cardb') else: if (ContentType == "6" or ContentType == "10"): # and MimeType == 'application/x-kobo-epub+zip': if path.startswith("file:///mnt/onboard/"): @@ -3399,6 +3400,6 @@ if __name__ == '__main__': dev.set_progress_reporter(prints) # dev.open(cd, None) # dev.filesystem_cache.dump() - print ('Prefix for main memory:', dev.dbversion) + print('Prefix for main memory:', dev.dbversion) finally: dev.shutdown() diff --git a/src/calibre/devices/misc.py b/src/calibre/devices/misc.py index d27348a1c6..f6fd6f940b 100644 --- a/src/calibre/devices/misc.py +++ b/src/calibre/devices/misc.py @@ -238,7 +238,7 @@ class TREKSTOR(USBMS): 0x0067, # This is for the Pyrus Mini 0x006f, # This is for the Pyrus Maxi 0x003e, # This is for the EBOOK_PLAYER_5M https://bugs.launchpad.net/bugs/792091 - 0x05cL, # This is for the 4ink https://www.mobileread.com/forums/showthread.php?t=191318 + 0x05c, # This is for the 4ink https://www.mobileread.com/forums/showthread.php?t=191318 0x006c, # This is for the 4ink https://www.mobileread.com/forums/showthread.php?t=218273 0x006d, # Another Pyrus? https://www.mobileread.com/forums/showthread.php?t=231982 0x73, # This is for the Pyrus 2 LED https://bugs.launchpad.net/bugs/1376018 diff --git a/src/calibre/devices/mtp/driver.py b/src/calibre/devices/mtp/driver.py index 7870ef3c30..ef13575369 100644 --- a/src/calibre/devices/mtp/driver.py +++ b/src/calibre/devices/mtp/driver.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' @@ -572,6 +573,6 @@ if __name__ == '__main__': dev.set_progress_reporter(prints) dev.open(cd, None) dev.filesystem_cache.dump() - print ('Prefix for main mem:', dev.prefix_for_location(None)) + print('Prefix for main mem:', dev.prefix_for_location(None)) finally: dev.shutdown() diff --git a/src/calibre/devices/mtp/unix/driver.py b/src/calibre/devices/mtp/unix/driver.py index e023ac00d2..ea5ba52e89 100644 --- a/src/calibre/devices/mtp/unix/driver.py +++ b/src/calibre/devices/mtp/unix/driver.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/devices/mtp/windows/remote.py b/src/calibre/devices/mtp/windows/remote.py index 37b8f08cdf..769058266c 100644 --- a/src/calibre/devices/mtp/windows/remote.py +++ b/src/calibre/devices/mtp/windows/remote.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' @@ -64,7 +65,7 @@ def main(): from calibre.devices.mtp.driver import MTP_DEVICE dev = MTP_DEVICE(None) dev.startup() - print (dev.wpd, dev.wpd_error) + print(dev.wpd, dev.wpd_error) try: devices = scan_usb_devices() @@ -72,12 +73,12 @@ def main(): if not pnp_id: raise ValueError('Failed to detect device') # pprint.pprint(dev.detected_devices) - print ('Trying to connect to:', pnp_id) + print('Trying to connect to:', pnp_id) dev.open(pnp_id, '') pprint.pprint(dev.dev.data) - print ('Connected to:', dev.get_gui_name()) - print ('Total space', dev.total_space()) - print ('Free space', dev.free_space()) + print('Connected to:', dev.get_gui_name()) + print('Total space', dev.total_space()) + print('Free space', dev.free_space()) # pprint.pprint(dev.dev.create_folder(dev.filesystem_cache.entries[0].object_id, # 'zzz')) # print ('Fetching file: oFF (198214 bytes)') diff --git a/src/calibre/devices/paladin/driver.py b/src/calibre/devices/paladin/driver.py index 5dd100349e..e7d90b4294 100644 --- a/src/calibre/devices/paladin/driver.py +++ b/src/calibre/devices/paladin/driver.py @@ -221,9 +221,9 @@ class PALADIN(USBMS): '\n'+tb) def get_database_min_id(self, source_id): - sequence_min = 0L + sequence_min = 0 if source_id == 1: - sequence_min = 4294967296L + sequence_min = 4294967296 return sequence_min diff --git a/src/calibre/devices/prs505/driver.py b/src/calibre/devices/prs505/driver.py index 8ccbb2a38b..f816754722 100644 --- a/src/calibre/devices/prs505/driver.py +++ b/src/calibre/devices/prs505/driver.py @@ -130,10 +130,10 @@ class PRS505(USBMS): dname = os.path.dirname(cachep) if not os.path.exists(dname): try: - os.makedirs(dname, mode=0777) + os.makedirs(dname, mode=0o777) except: time.sleep(5) - os.makedirs(dname, mode=0777) + os.makedirs(dname, mode=0o777) with lopen(cachep, 'wb') as f: f.write(u''' diff --git a/src/calibre/devices/prst1/driver.py b/src/calibre/devices/prst1/driver.py index 083991d1a6..b72882c9ce 100644 --- a/src/calibre/devices/prst1/driver.py +++ b/src/calibre/devices/prst1/driver.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal ' @@ -332,9 +333,9 @@ class PRST1(USBMS): return long(row[0]) def get_database_min_id(self, source_id): - sequence_min = 0L + sequence_min = 0 if source_id == 1: - sequence_min = 4294967296L + sequence_min = 4294967296 return sequence_min diff --git a/src/calibre/devices/scanner.py b/src/calibre/devices/scanner.py index 080dd1c5b5..7ac97b3f84 100644 --- a/src/calibre/devices/scanner.py +++ b/src/calibre/devices/scanner.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' ''' @@ -90,8 +91,8 @@ class LibUSBScanner(object): self() for i in xrange(3): gc.collect() - print 'Mem consumption increased by:', memory() - start, 'MB', - print 'after', num, 'repeats' + print('Mem consumption increased by:', memory() - start, 'MB', end=' ') + print('after', num, 'repeats') class LinuxScanner(object): diff --git a/src/calibre/devices/udisks.py b/src/calibre/devices/udisks.py index 3781dc8b62..7792a86521 100644 --- a/src/calibre/devices/udisks.py +++ b/src/calibre/devices/udisks.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2010, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -201,13 +202,13 @@ def umount(node_path): def test_udisks(ver=None): import sys dev = sys.argv[1] - print 'Testing with node', dev + print('Testing with node', dev) u = get_udisks(ver=ver) - print 'Using Udisks:', u.__class__.__name__ - print 'Mounted at:', u.mount(dev) - print 'Unmounting' + print('Using Udisks:', u.__class__.__name__) + print('Mounted at:', u.mount(dev)) + print('Unmounting') u.unmount(dev) - print 'Ejecting:' + print('Ejecting:') u.eject(dev) if __name__ == '__main__': diff --git a/src/calibre/devices/usbms/cli.py b/src/calibre/devices/usbms/cli.py index e424787ff6..c577e4a387 100644 --- a/src/calibre/devices/usbms/cli.py +++ b/src/calibre/devices/usbms/cli.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- __license__ = 'GPL 3' +from __future__ import print_function __copyright__ = '2009, John Schember ' __docformat__ = 'restructuredtext en' @@ -54,7 +55,7 @@ class CLI(object): try: shutil.copyfileobj(infile, dest) except IOError: - print 'WARNING: First attempt to send file to device failed' + print('WARNING: First attempt to send file to device failed') time.sleep(0.2) infile.seek(0) dest.seek(0) diff --git a/src/calibre/devices/usbms/device.py b/src/calibre/devices/usbms/device.py index e0ba32a2a1..8d3085f5b5 100644 --- a/src/calibre/devices/usbms/device.py +++ b/src/calibre/devices/usbms/device.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2009, John Schember ' \ '2009, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -404,7 +405,7 @@ class Device(DeviceConfig, DevicePlugin): mount_map = usbobserver.get_mounted_filesystems() drives = {k: mount_map.get(v) for k, v in drives.iteritems()} if DEBUG: - print + print() from pprint import pprint pprint({'bsd_drives': bsd_drives, 'mount_map': mount_map, 'drives': drives}) if drives.get('carda') is None and drives.get('cardb') is not None: @@ -504,7 +505,7 @@ class Device(DeviceConfig, DevicePlugin): except: ok[node] = False if DEBUG and not ok[node]: - print '\nIgnoring the node: %s as could not read size from: %s' % (node, sz) + print('\nIgnoring the node: %s as could not read size from: %s' % (node, sz)) devnodes.append(node) @@ -553,7 +554,7 @@ class Device(DeviceConfig, DevicePlugin): mount(node) return 0 except: - print 'Udisks mount call failed:' + print('Udisks mount call failed:') import traceback traceback.print_exc() return 1 @@ -570,7 +571,7 @@ class Device(DeviceConfig, DevicePlugin): 'kernel is exporting a deprecated version of SYSFS.') %self.__class__.__name__) if DEBUG: - print '\nFound device nodes:', main, carda, cardb + print('\nFound device nodes:', main, carda, cardb) self._linux_mount_map = {} mp, ret = mount(main, 'main') @@ -589,7 +590,7 @@ class Device(DeviceConfig, DevicePlugin): continue mp, ret = mount(card, typ) if mp is None: - print >>sys.stderr, 'Unable to mount card (Error code: %d)'%ret + print('Unable to mount card (Error code: %d)'%ret, file=sys.stderr) else: if not mp.endswith('/'): mp += '/' @@ -616,7 +617,7 @@ class Device(DeviceConfig, DevicePlugin): except: pass if DEBUG and ro: - print '\nThe mountpoint', mp, 'is readonly, ignoring it' + print('\nThe mountpoint', mp, 'is readonly, ignoring it') return ro for mp in ('_main_prefix', '_card_a_prefix', '_card_b_prefix'): @@ -701,10 +702,10 @@ class Device(DeviceConfig, DevicePlugin): 'label': vdevif.GetProperty('volume.label')} vols.append(vol) except dbus.exceptions.DBusException as e: - print e + print(e) continue except dbus.exceptions.DBusException as e: - print e + print(e) continue except dbus.exceptions.DBusException as e: continue @@ -719,7 +720,7 @@ class Device(DeviceConfig, DevicePlugin): vols.sort(cmp=ocmp) if verbose: - print "FBSD: ", vols + print("FBSD: ", vols) mtd=0 @@ -736,33 +737,33 @@ class Device(DeviceConfig, DevicePlugin): time.sleep(1) loops += 1 if loops > 100: - print "ERROR: Timeout waiting for mount to complete" + print("ERROR: Timeout waiting for mount to complete") continue mp = vol['dev'].GetProperty('volume.mount_point') except dbus.exceptions.DBusException as e: - print "Failed to mount ", e + print("Failed to mount ", e) continue # Mount Point becomes Mount Path mp += '/' if verbose: - print "FBSD: mounted", vol['label'], "on", mp + print("FBSD: mounted", vol['label'], "on", mp) if mtd == 0: self._main_prefix = mp self._main_vol = vol['vol'] if verbose: - print "FBSD: main = ", self._main_prefix + print("FBSD: main = ", self._main_prefix) if mtd == 1: self._card_a_prefix = mp self._card_a_vol = vol['vol'] if verbose: - print "FBSD: card a = ", self._card_a_prefix + print("FBSD: card a = ", self._card_a_prefix) if mtd == 2: self._card_b_prefix = mp self._card_b_vol = vol['vol'] if verbose: - print "FBSD: card b = ", self._card_b_prefix + print("FBSD: card b = ", self._card_b_prefix) # Note that mtd is used as a bool... not incrementing is fine. break mtd += 1 @@ -785,27 +786,27 @@ class Device(DeviceConfig, DevicePlugin): if self._main_prefix: if verbose: - print "FBSD: umount main:", self._main_prefix + print("FBSD: umount main:", self._main_prefix) try: self._main_vol.Unmount([]) except dbus.exceptions.DBusException as e: - print 'Unable to eject ', e + print('Unable to eject ', e) if self._card_a_prefix: if verbose: - print "FBSD: umount card a:", self._card_a_prefix + print("FBSD: umount card a:", self._card_a_prefix) try: self._card_a_vol.Unmount([]) except dbus.exceptions.DBusException as e: - print 'Unable to eject ', e + print('Unable to eject ', e) if self._card_b_prefix: if verbose: - print "FBSD: umount card b:", self._card_b_prefix + print("FBSD: umount card b:", self._card_b_prefix) try: self._card_b_vol.Unmount([]) except dbus.exceptions.DBusException as e: - print 'Unable to eject ', e + print('Unable to eject ', e) self._main_prefix = None self._card_a_prefix = None @@ -885,8 +886,8 @@ class Device(DeviceConfig, DevicePlugin): try: eject(d) except Exception as e: - print 'Udisks eject call for:', d, 'failed:' - print '\t', e + print('Udisks eject call for:', d, 'failed:') + print('\t', e) def eject(self): if islinux: diff --git a/src/calibre/devices/usbobserver/test.py b/src/calibre/devices/usbobserver/test.py index e78aaff299..010bd9e06c 100644 --- a/src/calibre/devices/usbobserver/test.py +++ b/src/calibre/devices/usbobserver/test.py @@ -1,7 +1,8 @@ +from __future__ import print_function import gc, usbobserver a = None -print len(gc.get_objects()) +print(len(gc.get_objects())) usbobserver.get_devices() gc.collect() -print len(gc.get_objects()) +print(len(gc.get_objects())) diff --git a/src/calibre/devices/winusb.py b/src/calibre/devices/winusb.py index ab6e359b56..840291683d 100644 --- a/src/calibre/devices/winusb.py +++ b/src/calibre/devices/winusb.py @@ -4,6 +4,7 @@ from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function import os, string, _winreg as winreg, re, sys from collections import namedtuple, defaultdict @@ -220,8 +221,8 @@ PUSB_DESCRIPTOR_REQUEST = POINTER(USB_DESCRIPTOR_REQUEST) PSP_DEVICE_INTERFACE_DETAIL_DATA = POINTER(SP_DEVICE_INTERFACE_DETAIL_DATA) PSP_DEVICE_INTERFACE_DATA = POINTER(SP_DEVICE_INTERFACE_DATA) INVALID_HANDLE_VALUE = c_void_p(-1).value -GENERIC_READ = 0x80000000L -GENERIC_WRITE = 0x40000000L +GENERIC_READ = 0x80000000 +GENERIC_WRITE = 0x40000000 FILE_SHARE_READ = 0x1 FILE_SHARE_WRITE = 0x2 OPEN_EXISTING = 0x3 diff --git a/src/calibre/ebooks/BeautifulSoup.py b/src/calibre/ebooks/BeautifulSoup.py index 5bf9574735..5ca831444c 100644 --- a/src/calibre/ebooks/BeautifulSoup.py +++ b/src/calibre/ebooks/BeautifulSoup.py @@ -77,6 +77,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT. """ from __future__ import generators +from __future__ import print_function __author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.0.5" @@ -419,7 +420,7 @@ class NavigableString(unicode, PageElement): if attr == 'string': return self else: - raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr) + raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)) def __unicode__(self): return unicode(str(self), DEFAULT_OUTPUT_ENCODING) # Changed by Kovid @@ -517,10 +518,10 @@ class Tag(PageElement): self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities # Convert any HTML, XML, or numeric entities in the attribute values. - convert = lambda(k, val): (k, + convert = lambda k_val: (k_val[0], re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);", self._convertEntities, - val)) + k_val[1])) self.attrs = map(convert, self.attrs) def get(self, key, default=None): @@ -589,7 +590,7 @@ class Tag(PageElement): return self.find(tag[:-3]) elif tag.find('__') != 0: return self.find(tag) - raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag) + raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__, tag)) def __eq__(self, other): """Returns true iff this tag has the same name, the same attributes, @@ -881,8 +882,8 @@ class SoupStrainer: if self._matches(markup, self.text): found = markup else: - raise Exception, "I don't know how to match against a %s" \ - % markup.__class__ + raise Exception("I don't know how to match against a %s" \ + % markup.__class__) return found def _matches(self, markup, matchAgainst): @@ -1261,7 +1262,7 @@ class BeautifulStoneSoup(Tag, SGMLParser): if self.quoteStack: #This is not a real tag. #print "<%s> is not real!" % name - attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs)) + attrs = ''.join(map(lambda x_y: ' %s="%s"' % (x_y[0], x_y[1]), attrs)) self.handle_data('<%s%s>' % (name, attrs)) return self.endData() @@ -1535,7 +1536,7 @@ class BeautifulSoup(BeautifulStoneSoup): # else an encoding was specified explicitly and it # worked. Rewrite the meta tag. newAttr = self.CHARSET_RE.sub\ - (lambda(match):match.group(1) + + (lambda match:match.group(1) + "%SOUP-ENCODING%", value) attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], newAttr) @@ -1738,7 +1739,7 @@ class UnicodeDammit: "iso-8859-1", "iso-8859-2"): markup = re.compile("([\x80-\x9f])").sub \ - (lambda(x): self._subMSChar(x.group(1)), + (lambda x: self._subMSChar(x.group(1)), markup) try: @@ -1934,4 +1935,4 @@ class UnicodeDammit: if __name__ == '__main__': import sys soup = BeautifulSoup(sys.stdin.read()) - print soup.prettify() + print(soup.prettify()) diff --git a/src/calibre/ebooks/chardet.py b/src/calibre/ebooks/chardet.py index fd919d3c01..42c2142537 100644 --- a/src/calibre/ebooks/chardet.py +++ b/src/calibre/ebooks/chardet.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' diff --git a/src/calibre/ebooks/compression/palmdoc.py b/src/calibre/ebooks/compression/palmdoc.py index e12978a11b..d329a72cdf 100644 --- a/src/calibre/ebooks/compression/palmdoc.py +++ b/src/calibre/ebooks/compression/palmdoc.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal ' from cStringIO import StringIO @@ -34,17 +35,17 @@ def test(): 'owaic jociowapjcivcjpoivjporeivjpoavca; p9aw8743y6r74%$^$^%8 ') ] for test in TESTS: - print 'Test:', repr(test) - print '\tTesting compression...' + print('Test:', repr(test)) + print('\tTesting compression...') good = py_compress_doc(test) x = compress_doc(test) - print '\t\tgood:', repr(good) - print '\t\tx :', repr(x) + print('\t\tgood:', repr(good)) + print('\t\tx :', repr(x)) assert x == good - print '\tTesting decompression...' - print '\t\t', repr(decompress_doc(x)) + print('\tTesting decompression...') + print('\t\t', repr(decompress_doc(x))) assert decompress_doc(x) == test - print + print() def py_compress_doc(data): diff --git a/src/calibre/ebooks/covers.py b/src/calibre/ebooks/covers.py index 6bf63cd6e6..8eb9013a2f 100644 --- a/src/calibre/ebooks/covers.py +++ b/src/calibre/ebooks/covers.py @@ -174,7 +174,8 @@ class Block(object): def fget(self): return self._position - def fset(self, (x, y)): + def fset(self, xxx_todo_changeme): + (x, y) = xxx_todo_changeme self._position = Point(x, y) if self.layouts: self.layouts[0].setPosition(QPointF(x, y)) diff --git a/src/calibre/ebooks/djvu/djvubzzdec.py b/src/calibre/ebooks/djvu/djvubzzdec.py index 407794520c..1457b8dbb2 100644 --- a/src/calibre/ebooks/djvu/djvubzzdec.py +++ b/src/calibre/ebooks/djvu/djvubzzdec.py @@ -2,6 +2,7 @@ # coding: utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2011, Anthon van der Neut ' diff --git a/src/calibre/ebooks/docx/container.py b/src/calibre/ebooks/docx/container.py index 448ceb97c7..9da70d997a 100644 --- a/src/calibre/ebooks/docx/container.py +++ b/src/calibre/ebooks/docx/container.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' diff --git a/src/calibre/ebooks/docx/dump.py b/src/calibre/ebooks/docx/dump.py index c1edfeccf4..d3be7fd75e 100644 --- a/src/calibre/ebooks/docx/dump.py +++ b/src/calibre/ebooks/docx/dump.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' @@ -39,7 +40,7 @@ def dump(path): dest += '-dumped' do_dump(path, dest) - print (path, 'dumped to', dest) + print(path, 'dumped to', dest) if __name__ == '__main__': dump(sys.argv[-1]) diff --git a/src/calibre/ebooks/docx/writer/container.py b/src/calibre/ebooks/docx/writer/container.py index 4d45910bc7..01b27ed8ed 100644 --- a/src/calibre/ebooks/docx/writer/container.py +++ b/src/calibre/ebooks/docx/writer/container.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' diff --git a/src/calibre/ebooks/epub/__init__.py b/src/calibre/ebooks/epub/__init__.py index b7c54e0edc..dc85db1e36 100644 --- a/src/calibre/ebooks/epub/__init__.py +++ b/src/calibre/ebooks/epub/__init__.py @@ -41,7 +41,7 @@ def initialize_container(path_to_container, opf_name='metadata.opf', CONTAINER = simple_container_xml(opf_name, rootfiles).encode('utf-8') zf = ZipFile(path_to_container, 'w') zf.writestr('mimetype', 'application/epub+zip', compression=ZIP_STORED) - zf.writestr('META-INF/', '', 0755) + zf.writestr('META-INF/', '', 0o755) zf.writestr('META-INF/container.xml', CONTAINER) for path, _, data in extra_entries: zf.writestr(path, data) diff --git a/src/calibre/ebooks/html/input.py b/src/calibre/ebooks/html/input.py index fe200ec01b..3ee912cf0e 100644 --- a/src/calibre/ebooks/html/input.py +++ b/src/calibre/ebooks/html/input.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -220,7 +221,7 @@ def traverse(path_to_html_file, max_levels=sys.maxint, verbose=0, encoding=None) except IgnoreFile as err: rejects.append(link) if not err.doesnt_exist or verbose > 1: - print repr(err) + print(repr(err)) for link in rejects: hf.links.remove(link) diff --git a/src/calibre/ebooks/hyphenate.py b/src/calibre/ebooks/hyphenate.py index 6ae0b55886..1dfc08ad68 100644 --- a/src/calibre/ebooks/hyphenate.py +++ b/src/calibre/ebooks/hyphenate.py @@ -13,6 +13,7 @@ Ned Batchelder, July 2007. This Python code is in the public domain. """ +from __future__ import print_function import re @@ -520,7 +521,7 @@ if __name__ == '__main__': import sys if len(sys.argv) > 1: for word in sys.argv[1:]: - print '-'.join(hyphenate_word(word)) + print('-'.join(hyphenate_word(word))) else: import doctest doctest.testmod(verbose=True) diff --git a/src/calibre/ebooks/lit/from_any.py b/src/calibre/ebooks/lit/from_any.py index 93eb4e75ff..4e242b06f0 100644 --- a/src/calibre/ebooks/lit/from_any.py +++ b/src/calibre/ebooks/lit/from_any.py @@ -1,4 +1,5 @@ from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' @@ -56,7 +57,7 @@ def main(args=sys.argv): opts, args = parser.parse_args(args) if len(args) < 2: parser.print_help() - print 'No input file specified.' + print('No input file specified.') return 1 any2lit(opts, args[1]) return 0 diff --git a/src/calibre/ebooks/lit/mssha1.py b/src/calibre/ebooks/lit/mssha1.py index 3ccf2b10e8..bc3d44e318 100644 --- a/src/calibre/ebooks/lit/mssha1.py +++ b/src/calibre/ebooks/lit/mssha1.py @@ -3,6 +3,7 @@ Modified version of SHA-1 used in Microsoft LIT files. Adapted from the PyPy pure-Python SHA-1 implementation. """ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Marshall T. Vandegrift ' @@ -29,7 +30,7 @@ def _long2bytesBigEndian(n, blocksize=0): s = '' pack = struct.pack while n > 0: - s = pack('>I', n & 0xffffffffL) + s + s = pack('>I', n & 0xffffffff) + s n = n >> 32 # Strip off leading zeros. @@ -55,7 +56,7 @@ def _bytelist2longBigEndian(list): "Transform a list of characters into a list of longs." imax = len(list)/4 - hl = [0L] * imax + hl = [0] * imax j = 0 i = 0 @@ -119,10 +120,10 @@ f[68] = f0_19 # Constants to be used K = [ - 0x5A827999L, # ( 0 <= t <= 19) - 0x6ED9EBA1L, # (20 <= t <= 39) - 0x8F1BBCDCL, # (40 <= t <= 59) - 0xCA62C1D6L # (60 <= t <= 79) + 0x5A827999, # ( 0 <= t <= 19) + 0x6ED9EBA1, # (20 <= t <= 39) + 0x8F1BBCDC, # (40 <= t <= 59) + 0xCA62C1D6 # (60 <= t <= 79) ] @@ -133,7 +134,7 @@ class mssha1(object): "Initialisation." # Initial message length in bits(!). - self.length = 0L + self.length = 0 self.count = [0, 0] # Initial empty message as a sequence of bytes (8 bit characters). @@ -146,21 +147,21 @@ class mssha1(object): def init(self): "Initialize the message-digest and set all fields to zero." - self.length = 0L + self.length = 0 self.input = [] # Initial 160 bit message digest (5 times 32 bit). # Also changed by Microsoft from standard. - self.H0 = 0x32107654L - self.H1 = 0x23016745L - self.H2 = 0xC4E680A2L - self.H3 = 0xDC679823L - self.H4 = 0xD0857A34L + self.H0 = 0x32107654 + self.H1 = 0x23016745 + self.H2 = 0xC4E680A2 + self.H3 = 0xDC679823 + self.H4 = 0xD0857A34 def _transform(self, W): for t in range(16, 80): W.append(_rotateLeft( - W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1) & 0xffffffffL) + W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1) & 0xffffffff) A = self.H0 B = self.H1 @@ -172,15 +173,15 @@ class mssha1(object): TEMP = _rotateLeft(A, 5) + f[t](B, C, D) + E + W[t] + K[t/20] E = D D = C - C = _rotateLeft(B, 30) & 0xffffffffL + C = _rotateLeft(B, 30) & 0xffffffff B = A - A = TEMP & 0xffffffffL + A = TEMP & 0xffffffff - self.H0 = (self.H0 + A) & 0xffffffffL - self.H1 = (self.H1 + B) & 0xffffffffL - self.H2 = (self.H2 + C) & 0xffffffffL - self.H3 = (self.H3 + D) & 0xffffffffL - self.H4 = (self.H4 + E) & 0xffffffffL + self.H0 = (self.H0 + A) & 0xffffffff + self.H1 = (self.H1 + B) & 0xffffffff + self.H2 = (self.H2 + C) & 0xffffffff + self.H3 = (self.H3 + D) & 0xffffffff + self.H4 = (self.H4 + E) & 0xffffffff # Down from here all methods follow the Python Standard Library # API of the sha module. @@ -204,7 +205,7 @@ class mssha1(object): leninBuf = long(len(inBuf)) # Compute number of bytes mod 64. - index = (self.count[1] >> 3) & 0x3FL + index = (self.count[1] >> 3) & 0x3F # Update number of bits. self.count[1] = self.count[1] + (leninBuf << 3) @@ -243,7 +244,7 @@ class mssha1(object): input = [] + self.input count = [] + self.count - index = (self.count[1] >> 3) & 0x3fL + index = (self.count[1] >> 3) & 0x3f if index < 56: padLen = 56 - index @@ -325,7 +326,7 @@ if __name__ == '__main__': import sys file = None if len(sys.argv) > 2: - print "usage: %s [FILE]" % sys.argv[0] + print("usage: %s [FILE]" % sys.argv[0]) return elif len(sys.argv) < 2: file = sys.stdin @@ -339,6 +340,6 @@ if __name__ == '__main__': file.close() digest = context.hexdigest().upper() for i in xrange(0, 40, 8): - print digest[i:i+8], - print + print(digest[i:i+8], end=' ') + print() main() diff --git a/src/calibre/ebooks/lit/reader.py b/src/calibre/ebooks/lit/reader.py index 17e3f2ddbf..adb3c7de72 100644 --- a/src/calibre/ebooks/lit/reader.py +++ b/src/calibre/ebooks/lit/reader.py @@ -2,6 +2,7 @@ Support for reading LIT files. ''' from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' \ @@ -244,7 +245,7 @@ class UnBinary(object): errors += 1 tag_name = '?'+unichr(tag)+'?' current_map = self.tag_to_attr_map[tag] - print 'WARNING: tag %s unknown' % unichr(tag) + print('WARNING: tag %s unknown' % unichr(tag)) buf.write(encode(tag_name)) elif flags & FLAG_CLOSING: if depth == 0: @@ -920,7 +921,7 @@ class LitContainer(object): except LitError: if 'PENGUIN group' not in raw: raise - print "WARNING: attempting PENGUIN malformed OPF fix" + print("WARNING: attempting PENGUIN malformed OPF fix") raw = raw.replace( 'PENGUIN group', '\x00\x01\x18\x00PENGUIN group', 1) unbin = UnBinary(raw, path, self._litfile.manifest, OPF_MAP) diff --git a/src/calibre/ebooks/lit/writer.py b/src/calibre/ebooks/lit/writer.py index b895072ed9..c983e75a4e 100644 --- a/src/calibre/ebooks/lit/writer.py +++ b/src/calibre/ebooks/lit/writer.py @@ -2,6 +2,7 @@ Basic support for writing LIT files. ''' from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Marshall T. Vandegrift ' @@ -135,7 +136,7 @@ def randbytes(n): def warn(x): - print x + print(x) class ReBinary(object): diff --git a/src/calibre/ebooks/lrf/html/convert_from.py b/src/calibre/ebooks/lrf/html/convert_from.py index 53d1a20fa4..bea112c559 100644 --- a/src/calibre/ebooks/lrf/html/convert_from.py +++ b/src/calibre/ebooks/lrf/html/convert_from.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' """ @@ -731,7 +732,7 @@ class HTMLConverter(object): if self.minimize_memory_usage: ptag.extract() except AttributeError: - print ptag, type(ptag) + print(ptag, type(ptag)) def get_alignment(self, css): val = css['text-align'].lower() if css.has_key('text-align') else None # noqa @@ -1727,7 +1728,7 @@ class HTMLConverter(object): self.process_children(tag, tag_css, tag_pseudo_css) elif tagname == 'table' and not self.ignore_tables and not self.in_table: if self.render_tables_as_images: - print 'Rendering table...' + print('Rendering table...') from calibre.ebooks.lrf.html.table_as_image import render_table pheight = int(self.current_page.pageStyle.attrs['textheight']) pwidth = int(self.current_page.pageStyle.attrs['textwidth']) diff --git a/src/calibre/ebooks/lrf/html/convert_to.py b/src/calibre/ebooks/lrf/html/convert_to.py index ad780b90bf..8ae9224d2c 100644 --- a/src/calibre/ebooks/lrf/html/convert_to.py +++ b/src/calibre/ebooks/lrf/html/convert_to.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' import sys, logging, os @@ -78,7 +79,7 @@ class LRFConverter(object): for obj in self.lrf.objects.values(): if isinstance(obj, TextAttr): self.text_css += str(TextStyle(obj)) - print self.text_css + print(self.text_css) def create_styles(self): self.logger.info('Creating CSS stylesheet...') diff --git a/src/calibre/ebooks/lrf/html/table.py b/src/calibre/ebooks/lrf/html/table.py index ac0b15d372..e2cb0d1b9f 100644 --- a/src/calibre/ebooks/lrf/html/table.py +++ b/src/calibre/ebooks/lrf/html/table.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' import math, sys, re @@ -17,7 +18,7 @@ def print_xml(elem): elem = elem.toElement('utf8') ew = ElementWriter(elem, sourceEncoding='utf8') ew.write(sys.stdout) - print + print() def cattrs(base, extra): diff --git a/src/calibre/ebooks/lrf/lrs/convert_from.py b/src/calibre/ebooks/lrf/lrs/convert_from.py index fb8f289209..44e3425b56 100644 --- a/src/calibre/ebooks/lrf/lrs/convert_from.py +++ b/src/calibre/ebooks/lrf/lrs/convert_from.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' ''' @@ -259,7 +260,7 @@ class LrsParser(object): if os.access(f, os.R_OK): settings['thumbnail'] = f else: - print _('Could not read from thumbnail file:'), f + print(_('Could not read from thumbnail file:'), f) self.book = Book(title=title, author=author, publisher=publisher, category=category, classification=classification, diff --git a/src/calibre/ebooks/lrf/meta.py b/src/calibre/ebooks/lrf/meta.py index 6a3a9a226c..4f890c7c73 100644 --- a/src/calibre/ebooks/lrf/meta.py +++ b/src/calibre/ebooks/lrf/meta.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' @@ -685,8 +686,8 @@ def main(args=sys.argv): options, args = parser.parse_args(args) if len(args) != 2: parser.print_help() - print - print 'No lrf file specified' + print() + print('No lrf file specified') return 1 lrf = LRFMetaFile(open(args[1], "r+b")) @@ -731,9 +732,9 @@ def main(args=sys.argv): fields.sort() for f in fields: if "XML" in str(f): - print str(f[1]) + ":", lrf.__getattribute__(f[0]).encode('utf-8') + print(str(f[1]) + ":", lrf.__getattribute__(f[0]).encode('utf-8')) if options.get_thumbnail: - print "Thumbnail:", td + print("Thumbnail:", td) if options.get_cover: try: ext, data = lrf.get_cover() @@ -742,9 +743,9 @@ def main(args=sys.argv): if data: cover = os.path.splitext(os.path.basename(args[1]))[0]+"_cover."+ext open(cover, 'wb').write(data) - print 'Cover:', cover + print('Cover:', cover) else: - print 'Could not find cover in the LRF file' + print('Could not find cover in the LRF file') if __name__ == '__main__': diff --git a/src/calibre/ebooks/lrf/objects.py b/src/calibre/ebooks/lrf/objects.py index f3cfc88ab7..887effe837 100644 --- a/src/calibre/ebooks/lrf/objects.py +++ b/src/calibre/ebooks/lrf/objects.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' import struct, array, zlib, cStringIO, collections, re @@ -177,7 +178,7 @@ class LRFStream(LRFObject): if len(self.stream) != decomp_size: raise LRFParseError("Stream decompressed size is wrong!") if stream.read(2) != '\x06\xF5': - print "Warning: corrupted end-of-stream tag at %08X; skipping it"%(stream.tell()-2) + print("Warning: corrupted end-of-stream tag at %08X; skipping it"%(stream.tell()-2)) self.end_stream(None, None) @@ -992,7 +993,7 @@ class Canvas(LRFStream): PutObj(self._document.objects, *struct.unpack(" @@ -561,7 +562,7 @@ class Book(Delegator): length = len(text.text) fonts[fs] = fonts.get(fs, 0) + length if not fonts: - print 'WARNING: LRF seems to have no textual content. Cannot rationalize font sizes.' + print('WARNING: LRF seems to have no textual content. Cannot rationalize font sizes.') return old_base_font_size = float(max(fonts.items(), key=operator.itemgetter(1))[0]) diff --git a/src/calibre/ebooks/metadata/book/json_codec.py b/src/calibre/ebooks/metadata/book/json_codec.py index c730dd71ef..6d15eb5031 100644 --- a/src/calibre/ebooks/metadata/book/json_codec.py +++ b/src/calibre/ebooks/metadata/book/json_codec.py @@ -3,6 +3,7 @@ Created on 4 Jun 2010 @author: charles ''' +from __future__ import print_function from base64 import b64encode, b64decode import json, traceback @@ -177,7 +178,7 @@ class JsonCodec(object): if entry is not None: booklist.append(entry) except: - print 'exception during JSON decode_from_file' + print('exception during JSON decode_from_file') traceback.print_exc() def raw_to_book(self, json_book, book_class, prefix): @@ -193,7 +194,7 @@ class JsonCodec(object): setattr(book, key, meta) return book except: - print 'exception during JSON decoding' + print('exception during JSON decoding') traceback.print_exc() def decode_metadata(self, key, value): diff --git a/src/calibre/ebooks/metadata/docx.py b/src/calibre/ebooks/metadata/docx.py index ceba4b7708..94b76beecc 100644 --- a/src/calibre/ebooks/metadata/docx.py +++ b/src/calibre/ebooks/metadata/docx.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/ebooks/metadata/epub.py b/src/calibre/ebooks/metadata/epub.py index 245ee2cef3..ae0f672f17 100644 --- a/src/calibre/ebooks/metadata/epub.py +++ b/src/calibre/ebooks/metadata/epub.py @@ -1,5 +1,6 @@ #!/usr/bin/env python2 from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' @@ -90,9 +91,9 @@ class OCFReader(OCF): try: mimetype = self.open('mimetype').read().rstrip() if mimetype != OCF.MIMETYPE: - print 'WARNING: Invalid mimetype declaration', mimetype + print('WARNING: Invalid mimetype declaration', mimetype) except: - print 'WARNING: Epub doesn\'t contain a mimetype declaration' + print('WARNING: Epub doesn\'t contain a mimetype declaration') try: with closing(self.open(OCF.CONTAINER_PATH)) as f: diff --git a/src/calibre/ebooks/metadata/imp.py b/src/calibre/ebooks/metadata/imp.py index c02deff161..4e8c87c93a 100644 --- a/src/calibre/ebooks/metadata/imp.py +++ b/src/calibre/ebooks/metadata/imp.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Ashish Kulkarni ' '''Read meta information from IMP files''' @@ -16,7 +17,7 @@ def get_metadata(stream): stream.seek(0) try: if stream.read(10) not in MAGIC: - print >>sys.stderr, u'Couldn\'t read IMP header from file' + print(u'Couldn\'t read IMP header from file', file=sys.stderr) return mi def cString(skip=0): @@ -43,5 +44,5 @@ def get_metadata(stream): mi.category = category except Exception as err: msg = u'Couldn\'t read metadata from imp: %s with error %s'%(mi.title, unicode(err)) - print >>sys.stderr, msg.encode('utf8') + print(msg.encode('utf8'), file=sys.stderr) return mi diff --git a/src/calibre/ebooks/metadata/kdl.py b/src/calibre/ebooks/metadata/kdl.py index 1567f53b73..31c08f06a0 100644 --- a/src/calibre/ebooks/metadata/kdl.py +++ b/src/calibre/ebooks/metadata/kdl.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2011, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -83,5 +84,5 @@ def get_series(title, authors, timeout=60): if __name__ == '__main__': import sys - print get_series(sys.argv[-2], [sys.argv[-1]]) + print(get_series(sys.argv[-2], [sys.argv[-1]])) diff --git a/src/calibre/ebooks/metadata/mobi.py b/src/calibre/ebooks/metadata/mobi.py index 7def78a886..71e1b3bfc6 100644 --- a/src/calibre/ebooks/metadata/mobi.py +++ b/src/calibre/ebooks/metadata/mobi.py @@ -3,6 +3,7 @@ Retrieve and modify in-place Mobipocket book metadata. ''' from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal kovid@kovidgoyal.net and ' \ @@ -289,7 +290,7 @@ class MetadataUpdater(object): s = s.translate(FILTER) result += "%04X %-*s %s\n" % (N, length*3, hexa, s) N+=length - print result + print(result) def get_pdbrecords(self): pdbrecords = [] @@ -308,11 +309,11 @@ class MetadataUpdater(object): def dump_pdbrecords(self): # Diagnostic - print "MetadataUpdater.dump_pdbrecords()" - print "%10s %10s %10s" % ("offset","flags","val") + print("MetadataUpdater.dump_pdbrecords()") + print("%10s %10s %10s" % ("offset","flags","val")) for i in xrange(len(self.pdbrecords)): pdbrecord = self.pdbrecords[i] - print "%10X %10X %10X" % (pdbrecord[0], pdbrecord[1], pdbrecord[2]) + print("%10X %10X %10X" % (pdbrecord[0], pdbrecord[1], pdbrecord[2])) def record(self, n): if n >= self.nrecs: diff --git a/src/calibre/ebooks/metadata/opf2.py b/src/calibre/ebooks/metadata/opf2.py index c5957d1d23..93ab56599e 100644 --- a/src/calibre/ebooks/metadata/opf2.py +++ b/src/calibre/ebooks/metadata/opf2.py @@ -1,5 +1,6 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' @@ -1734,7 +1735,7 @@ def test_m2o(): mi.rights = 'yes' mi.cover = os.path.abspath('asd.jpg') opf = metadata_to_opf(mi) - print opf + print(opf) newmi = MetaInformation(OPF(StringIO(opf))) for attr in ('author_sort', 'title_sort', 'comments', 'publisher', 'series', 'series_index', 'rating', @@ -1744,10 +1745,10 @@ def test_m2o(): 'pubdate', 'rights', 'publication_type'): o, n = getattr(mi, attr), getattr(newmi, attr) if o != n and o.strip() != n.strip(): - print 'FAILED:', attr, getattr(mi, attr), '!=', getattr(newmi, attr) + print('FAILED:', attr, getattr(mi, attr), '!=', getattr(newmi, attr)) if mi.get_identifiers() != newmi.get_identifiers(): - print 'FAILED:', 'identifiers', mi.get_identifiers(), - print '!=', newmi.get_identifiers() + print('FAILED:', 'identifiers', mi.get_identifiers(), end=' ') + print('!=', newmi.get_identifiers()) class OPFTest(unittest.TestCase): @@ -1848,7 +1849,7 @@ def test_user_metadata(): opf2 = OPF(f2) assert um == opf._user_metadata_ assert um == opf2._user_metadata_ - print opf.render() + print(opf.render()) if __name__ == '__main__': diff --git a/src/calibre/ebooks/metadata/rb.py b/src/calibre/ebooks/metadata/rb.py index 65b92781e5..f16bad1de9 100644 --- a/src/calibre/ebooks/metadata/rb.py +++ b/src/calibre/ebooks/metadata/rb.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Ashish Kulkarni ' '''Read meta information from RB files''' @@ -16,7 +17,7 @@ def get_metadata(stream): stream.seek(0) try: if not stream.read(14) == MAGIC: - print >>sys.stderr, u'Couldn\'t read RB header from file' + print(u'Couldn\'t read RB header from file', file=sys.stderr) return mi stream.read(10) @@ -31,7 +32,7 @@ def get_metadata(stream): if flag == 2: break else: - print >>sys.stderr, u'Couldn\'t find INFO from RB file' + print(u'Couldn\'t find INFO from RB file', file=sys.stderr) return mi stream.seek(offset) @@ -47,7 +48,7 @@ def get_metadata(stream): mi.authors = string_to_authors(value) except Exception as err: msg = u'Couldn\'t read metadata from rb: %s with error %s'%(mi.title, unicode(err)) - print >>sys.stderr, msg.encode('utf8') + print(msg.encode('utf8'), file=sys.stderr) raise return mi diff --git a/src/calibre/ebooks/metadata/sources/google_images.py b/src/calibre/ebooks/metadata/sources/google_images.py index 843a5d4107..f2cf06b953 100644 --- a/src/calibre/ebooks/metadata/sources/google_images.py +++ b/src/calibre/ebooks/metadata/sources/google_images.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' @@ -103,7 +104,7 @@ def test(): rq = Queue() p.download_cover(default_log, rq, Event(), title='The Heroes', authors=('Joe Abercrombie',)) - print ('Downloaded', rq.qsize(), 'covers') + print('Downloaded', rq.qsize(), 'covers') if __name__ == '__main__': diff --git a/src/calibre/ebooks/metadata/sources/overdrive.py b/src/calibre/ebooks/metadata/sources/overdrive.py index 326b1e005d..c10dec79ff 100755 --- a/src/calibre/ebooks/metadata/sources/overdrive.py +++ b/src/calibre/ebooks/metadata/sources/overdrive.py @@ -408,7 +408,7 @@ class OverDrive(Source): try: raw = br.open_novisit(metadata_url).read() - except Exception, e: + except Exception as e: if callable(getattr(e, 'getcode', None)) and \ e.getcode() == 404: return False diff --git a/src/calibre/ebooks/metadata/sources/update.py b/src/calibre/ebooks/metadata/sources/update.py index 7fd4e54228..c6b7292fd9 100644 --- a/src/calibre/ebooks/metadata/sources/update.py +++ b/src/calibre/ebooks/metadata/sources/update.py @@ -37,7 +37,7 @@ def debug_print(*args, **k): def load_plugin(src): src = src.encode('utf-8') ns = {} - exec src in ns + exec(src, ns) for x in ns.itervalues(): if isinstance(x, type) and issubclass(x, Source) and x is not Source: return x @@ -59,7 +59,7 @@ def patch_search_engines(src): global current_search_engines src = src.encode('utf-8') ns = {} - exec src in ns + exec(src, ns) mcv = ns.get('minimum_calibre_version') if mcv is None or mcv > numeric_version: return diff --git a/src/calibre/ebooks/metadata/toc.py b/src/calibre/ebooks/metadata/toc.py index dae06f0265..bf665a171e 100644 --- a/src/calibre/ebooks/metadata/toc.py +++ b/src/calibre/ebooks/metadata/toc.py @@ -1,5 +1,6 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2010, Kovid Goyal ' import os, glob, re, functools @@ -143,7 +144,7 @@ class TOC(list): self.read_html_toc(toc) except: - print 'WARNING: Could not read Table of Contents. Continuing anyway.' + print('WARNING: Could not read Table of Contents. Continuing anyway.') else: path = opfreader.manifest.item(toc.lower()) path = getattr(path, 'path', path) @@ -151,7 +152,7 @@ class TOC(list): try: self.read_ncx_toc(path) except Exception as err: - print 'WARNING: Invalid NCX file:', err + print('WARNING: Invalid NCX file:', err) return cwd = os.path.abspath(self.base_path) m = glob.glob(os.path.join(cwd, '*.ncx')) diff --git a/src/calibre/ebooks/metadata/topaz.py b/src/calibre/ebooks/metadata/topaz.py index ab86d7ea27..15ac2f9509 100644 --- a/src/calibre/ebooks/metadata/topaz.py +++ b/src/calibre/ebooks/metadata/topaz.py @@ -1,4 +1,5 @@ from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL 3' __copyright__ = '2010, Greg Riker ' __docformat__ = 'restructuredtext en' @@ -129,13 +130,13 @@ class MetadataUpdater(object): def dump_headers(self): ''' Diagnostic ''' - print "\ndump_headers():" + print("\ndump_headers():") for tag in self.topaz_headers: - print "%s: " % (tag) + print("%s: " % (tag)) num_recs = len(self.topaz_headers[tag]['blocks']) - print " num_recs: %d" % num_recs + print(" num_recs: %d" % num_recs) if num_recs: - print " starting offset: 0x%x" % self.topaz_headers[tag]['blocks'][0]['offset'] + print(" starting offset: 0x%x" % self.topaz_headers[tag]['blocks'][0]['offset']) def dump_hex(self, src, length=16): ''' Diagnostic ''' @@ -148,12 +149,12 @@ class MetadataUpdater(object): s = s.translate(FILTER) result += "%04X %-*s %s\n" % (N, length*3, hexa, s) N+=length - print result + print(result) def dump_metadata(self): ''' Diagnostic ''' for tag in self.metadata: - print '%s: %s' % (tag, repr(self.metadata[tag])) + print('%s: %s' % (tag, repr(self.metadata[tag]))) def encode_vwi(self,value): bytes = [] @@ -372,7 +373,7 @@ def set_metadata(stream, mi): if __name__ == '__main__': if False: # Test get_metadata() - print get_metadata(open(sys.argv[1], 'rb')) + print(get_metadata(open(sys.argv[1], 'rb'))) else: # Test set_metadata() import cStringIO diff --git a/src/calibre/ebooks/metadata/xisbn.py b/src/calibre/ebooks/metadata/xisbn.py index f7c456822c..304f965c0d 100644 --- a/src/calibre/ebooks/metadata/xisbn.py +++ b/src/calibre/ebooks/metadata/xisbn.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2010, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -104,6 +105,6 @@ xisbn = xISBN() if __name__ == '__main__': import sys, pprint isbn = sys.argv[-1] - print pprint.pprint(xisbn.get_data(isbn)) - print - print xisbn.get_associated_isbns(isbn) + print(pprint.pprint(xisbn.get_data(isbn))) + print() + print(xisbn.get_associated_isbns(isbn)) diff --git a/src/calibre/ebooks/metadata/xmp.py b/src/calibre/ebooks/metadata/xmp.py index 9e01e8106c..dd51c4095a 100644 --- a/src/calibre/ebooks/metadata/xmp.py +++ b/src/calibre/ebooks/metadata/xmp.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal ' diff --git a/src/calibre/ebooks/mobi/debug/headers.py b/src/calibre/ebooks/mobi/debug/headers.py index 5651f67966..4e3508c137 100644 --- a/src/calibre/ebooks/mobi/debug/headers.py +++ b/src/calibre/ebooks/mobi/debug/headers.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/ebooks/mobi/debug/main.py b/src/calibre/ebooks/mobi/debug/main.py index d2c4c437af..78171385db 100644 --- a/src/calibre/ebooks/mobi/debug/main.py +++ b/src/calibre/ebooks/mobi/debug/main.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' @@ -37,7 +38,7 @@ def inspect_mobi(path_or_stream, ddir=None): # {{{ else: inspect_mobi8(f, ddir) - print ('Debug data saved to:', ddir) + print('Debug data saved to:', ddir) # }}} diff --git a/src/calibre/ebooks/mobi/mobiml.py b/src/calibre/ebooks/mobi/mobiml.py index 4ba9243269..b8de6d2b31 100644 --- a/src/calibre/ebooks/mobi/mobiml.py +++ b/src/calibre/ebooks/mobi/mobiml.py @@ -2,6 +2,7 @@ Transform XHTML/OPS-ish content into Mobipocket HTML 3.2. ''' from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Marshall T. Vandegrift ' @@ -237,7 +238,7 @@ class MobiMLizer(object): try: etree.SubElement(para, XHTML(tag), attrib=istate.attrib) except: - print 'Invalid subelement:', para, tag, istate.attrib + print('Invalid subelement:', para, tag, istate.attrib) raise elif tag in TABLE_TAGS: para.attrib['valign'] = 'top' diff --git a/src/calibre/ebooks/mobi/reader/index.py b/src/calibre/ebooks/mobi/reader/index.py index 1e9dcebc92..389b013fb2 100644 --- a/src/calibre/ebooks/mobi/reader/index.py +++ b/src/calibre/ebooks/mobi/reader/index.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/ebooks/oeb/display/test-cfi/run_rapydscript.py b/src/calibre/ebooks/oeb/display/test-cfi/run_rapydscript.py index 887708f454..59c854d3d9 100644 --- a/src/calibre/ebooks/oeb/display/test-cfi/run_rapydscript.py +++ b/src/calibre/ebooks/oeb/display/test-cfi/run_rapydscript.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal ' diff --git a/src/calibre/ebooks/oeb/polish/create.py b/src/calibre/ebooks/oeb/polish/create.py index e91ab88652..ff3879390a 100644 --- a/src/calibre/ebooks/oeb/polish/create.py +++ b/src/calibre/ebooks/oeb/polish/create.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' @@ -109,7 +110,7 @@ def create_book(mi, path, fmt='epub', opf_name='metadata.opf', html_name='start. else: with ZipFile(path, 'w', compression=ZIP_STORED) as zf: zf.writestr('mimetype', b'application/epub+zip', compression=ZIP_STORED) - zf.writestr('META-INF/', b'', 0755) + zf.writestr('META-INF/', b'', 0o755) zf.writestr('META-INF/container.xml', CONTAINER) zf.writestr(opf_name, opf) zf.writestr(html_name, HTML) @@ -121,6 +122,6 @@ if __name__ == '__main__': path = sys.argv[-1] ext = path.rpartition('.')[-1].lower() if ext not in valid_empty_formats: - print ('Unsupported format:', ext) + print('Unsupported format:', ext) raise SystemExit(1) create_book(mi, path, fmt=ext) diff --git a/src/calibre/ebooks/oeb/polish/embed.py b/src/calibre/ebooks/oeb/polish/embed.py index 5e2dbe7a6b..dba76e6c41 100644 --- a/src/calibre/ebooks/oeb/polish/embed.py +++ b/src/calibre/ebooks/oeb/polish/embed.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' diff --git a/src/calibre/ebooks/oeb/polish/parsing.py b/src/calibre/ebooks/oeb/polish/parsing.py index e89275393c..5487156166 100644 --- a/src/calibre/ebooks/oeb/polish/parsing.py +++ b/src/calibre/ebooks/oeb/polish/parsing.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' diff --git a/src/calibre/ebooks/oeb/polish/subset.py b/src/calibre/ebooks/oeb/polish/subset.py index 888e6d169c..32621f685f 100644 --- a/src/calibre/ebooks/oeb/polish/subset.py +++ b/src/calibre/ebooks/oeb/polish/subset.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' diff --git a/src/calibre/ebooks/oeb/polish/tests/parsing.py b/src/calibre/ebooks/oeb/polish/tests/parsing.py index 43c81550dc..750bb27c6c 100644 --- a/src/calibre/ebooks/oeb/polish/tests/parsing.py +++ b/src/calibre/ebooks/oeb/polish/tests/parsing.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' diff --git a/src/calibre/ebooks/oeb/reader.py b/src/calibre/ebooks/oeb/reader.py index dd145049d6..736e110bb8 100644 --- a/src/calibre/ebooks/oeb/reader.py +++ b/src/calibre/ebooks/oeb/reader.py @@ -2,6 +2,7 @@ Container-/OPF-based input OEBBook reader. """ from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Marshall T. Vandegrift ' @@ -715,9 +716,9 @@ def main(argv=sys.argv): for arg in argv[1:]: oeb = reader(OEBBook(), arg) for name, doc in oeb.to_opf1().values(): - print etree.tostring(doc, pretty_print=True) + print(etree.tostring(doc, pretty_print=True)) for name, doc in oeb.to_opf2(page_map=True).values(): - print etree.tostring(doc, pretty_print=True) + print(etree.tostring(doc, pretty_print=True)) return 0 diff --git a/src/calibre/ebooks/oeb/transforms/jacket.py b/src/calibre/ebooks/oeb/transforms/jacket.py index 3c6ba2621f..9cc91b7179 100644 --- a/src/calibre/ebooks/oeb/transforms/jacket.py +++ b/src/calibre/ebooks/oeb/transforms/jacket.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' diff --git a/src/calibre/ebooks/pdb/ereader/inspector.py b/src/calibre/ebooks/pdb/ereader/inspector.py index 4f0c957d3e..73c1ad8894 100644 --- a/src/calibre/ebooks/pdb/ereader/inspector.py +++ b/src/calibre/ebooks/pdb/ereader/inspector.py @@ -2,6 +2,7 @@ ''' Inspect the header of ereader files. This is primarily used for debugging. ''' +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, John Schember ' @@ -17,102 +18,102 @@ from calibre.ebooks.pdb.header import PdbHeaderReader def ereader_header_info(header): h0 = header.section_data(0) - print 'Header Size: %s' % len(h0) + print('Header Size: %s' % len(h0)) if len(h0) == 132: - print 'Header Type: Dropbook compatible' - print '' + print('Header Type: Dropbook compatible') + print('') ereader_header_info132(h0) elif len(h0) == 202: - print 'Header Type: Makebook compatible' - print '' + print('Header Type: Makebook compatible') + print('') ereader_header_info202(h0) else: raise EreaderError('Size mismatch. eReader header record size %i KB is not supported.' % len(h0)) def pdb_header_info(header): - print 'PDB Header Info:' - print '' - print 'Identity: %s' % header.ident - print 'Total Sectons: %s' % header.num_sections - print 'Title: %s' % header.title - print '' + print('PDB Header Info:') + print('') + print('Identity: %s' % header.ident) + print('Total Sectons: %s' % header.num_sections) + print('Title: %s' % header.title) + print('') def ereader_header_info132(h0): - print 'Ereader Record 0 (Header) Info:' - print '' - print '0-2 Version: %i' % struct.unpack('>H', h0[0:2])[0] - print '2-4: %i' % struct.unpack('>H', h0[2:4])[0] - print '4-6: %i' % struct.unpack('>H', h0[4:6])[0] - print '6-8 Codepage: %i' % struct.unpack('>H', h0[6:8])[0] - print '8-10: %i' % struct.unpack('>H', h0[8:10])[0] - print '10-12: %i' % struct.unpack('>H', h0[10:12])[0] - print '12-14 Non-Text offset: %i' % struct.unpack('>H', h0[12:14])[0] - print '14-16: %i' % struct.unpack('>H', h0[14:16])[0] - print '16-18: %i' % struct.unpack('>H', h0[16:18])[0] - print '18-20: %i' % struct.unpack('>H', h0[18:20])[0] - print '20-22 Image Count: %i' % struct.unpack('>H', h0[20:22])[0] - print '22-24: %i' % struct.unpack('>H', h0[22:24])[0] - print '24-26 Has Metadata?: %i' % struct.unpack('>H', h0[24:26])[0] - print '26-28: %i' % struct.unpack('>H', h0[26:28])[0] - print '28-30 Footnote Count: %i' % struct.unpack('>H', h0[28:30])[0] - print '30-32 Sidebar Count: %i' % struct.unpack('>H', h0[30:32])[0] - print '32-34 Bookmark Offset: %i' % struct.unpack('>H', h0[32:34])[0] - print '34-36 MAGIC: %i' % struct.unpack('>H', h0[34:36])[0] - print '36-38: %i' % struct.unpack('>H', h0[36:38])[0] - print '38-40: %i' % struct.unpack('>H', h0[38:40])[0] - print '40-42 Image Data Offset: %i' % struct.unpack('>H', h0[40:42])[0] - print '42-44: %i' % struct.unpack('>H', h0[42:44])[0] - print '44-46 Metadata Offset: %i' % struct.unpack('>H', h0[44:46])[0] - print '46-48: %i' % struct.unpack('>H', h0[46:48])[0] - print '48-50 Footnote Offset: %i' % struct.unpack('>H', h0[48:50])[0] - print '50-52 Sidebar Offset: %i' % struct.unpack('>H', h0[50:52])[0] - print '52-54 Last Data Offset: %i' % struct.unpack('>H', h0[52:54])[0] + print('Ereader Record 0 (Header) Info:') + print('') + print('0-2 Version: %i' % struct.unpack('>H', h0[0:2])[0]) + print('2-4: %i' % struct.unpack('>H', h0[2:4])[0]) + print('4-6: %i' % struct.unpack('>H', h0[4:6])[0]) + print('6-8 Codepage: %i' % struct.unpack('>H', h0[6:8])[0]) + print('8-10: %i' % struct.unpack('>H', h0[8:10])[0]) + print('10-12: %i' % struct.unpack('>H', h0[10:12])[0]) + print('12-14 Non-Text offset: %i' % struct.unpack('>H', h0[12:14])[0]) + print('14-16: %i' % struct.unpack('>H', h0[14:16])[0]) + print('16-18: %i' % struct.unpack('>H', h0[16:18])[0]) + print('18-20: %i' % struct.unpack('>H', h0[18:20])[0]) + print('20-22 Image Count: %i' % struct.unpack('>H', h0[20:22])[0]) + print('22-24: %i' % struct.unpack('>H', h0[22:24])[0]) + print('24-26 Has Metadata?: %i' % struct.unpack('>H', h0[24:26])[0]) + print('26-28: %i' % struct.unpack('>H', h0[26:28])[0]) + print('28-30 Footnote Count: %i' % struct.unpack('>H', h0[28:30])[0]) + print('30-32 Sidebar Count: %i' % struct.unpack('>H', h0[30:32])[0]) + print('32-34 Bookmark Offset: %i' % struct.unpack('>H', h0[32:34])[0]) + print('34-36 MAGIC: %i' % struct.unpack('>H', h0[34:36])[0]) + print('36-38: %i' % struct.unpack('>H', h0[36:38])[0]) + print('38-40: %i' % struct.unpack('>H', h0[38:40])[0]) + print('40-42 Image Data Offset: %i' % struct.unpack('>H', h0[40:42])[0]) + print('42-44: %i' % struct.unpack('>H', h0[42:44])[0]) + print('44-46 Metadata Offset: %i' % struct.unpack('>H', h0[44:46])[0]) + print('46-48: %i' % struct.unpack('>H', h0[46:48])[0]) + print('48-50 Footnote Offset: %i' % struct.unpack('>H', h0[48:50])[0]) + print('50-52 Sidebar Offset: %i' % struct.unpack('>H', h0[50:52])[0]) + print('52-54 Last Data Offset: %i' % struct.unpack('>H', h0[52:54])[0]) for i in range(54, 131, 2): - print '%i-%i: %i' % (i, i+2, struct.unpack('>H', h0[i:i+2])[0]) + print('%i-%i: %i' % (i, i+2, struct.unpack('>H', h0[i:i+2])[0])) - print '' + print('') def ereader_header_info202(h0): - print 'Ereader Record 0 (Header) Info:' - print '' - print '0-2 Version: %i' % struct.unpack('>H', h0[0:2])[0] - print '2-4 Garbage: %i' % struct.unpack('>H', h0[2:4])[0] - print '4-6 Garbage: %i' % struct.unpack('>H', h0[4:6])[0] - print '6-8 Garbage: %i' % struct.unpack('>H', h0[6:8])[0] - print '8-10 Non-Text Offset: %i' % struct.unpack('>H', h0[8:10])[0] - print '10-12: %i' % struct.unpack('>H', h0[10:12])[0] - print '12-14: %i' % struct.unpack('>H', h0[12:14])[0] - print '14-16 Garbage: %i' % struct.unpack('>H', h0[14:16])[0] - print '16-18 Garbage: %i' % struct.unpack('>H', h0[16:18])[0] - print '18-20 Garbage: %i' % struct.unpack('>H', h0[18:20])[0] - print '20-22 Garbage: %i' % struct.unpack('>H', h0[20:22])[0] - print '22-24 Garbage: %i' % struct.unpack('>H', h0[22:24])[0] - print '24-26: %i' % struct.unpack('>H', h0[24:26])[0] - print '26-28: %i' % struct.unpack('>H', h0[26:28])[0] + print('Ereader Record 0 (Header) Info:') + print('') + print('0-2 Version: %i' % struct.unpack('>H', h0[0:2])[0]) + print('2-4 Garbage: %i' % struct.unpack('>H', h0[2:4])[0]) + print('4-6 Garbage: %i' % struct.unpack('>H', h0[4:6])[0]) + print('6-8 Garbage: %i' % struct.unpack('>H', h0[6:8])[0]) + print('8-10 Non-Text Offset: %i' % struct.unpack('>H', h0[8:10])[0]) + print('10-12: %i' % struct.unpack('>H', h0[10:12])[0]) + print('12-14: %i' % struct.unpack('>H', h0[12:14])[0]) + print('14-16 Garbage: %i' % struct.unpack('>H', h0[14:16])[0]) + print('16-18 Garbage: %i' % struct.unpack('>H', h0[16:18])[0]) + print('18-20 Garbage: %i' % struct.unpack('>H', h0[18:20])[0]) + print('20-22 Garbage: %i' % struct.unpack('>H', h0[20:22])[0]) + print('22-24 Garbage: %i' % struct.unpack('>H', h0[22:24])[0]) + print('24-26: %i' % struct.unpack('>H', h0[24:26])[0]) + print('26-28: %i' % struct.unpack('>H', h0[26:28])[0]) for i in range(28, 98, 2): - print '%i-%i Garbage: %i' % (i, i+2, struct.unpack('>H', h0[i:i+2])[0]) - print '98-100: %i' % struct.unpack('>H', h0[98:100])[0] + print('%i-%i Garbage: %i' % (i, i+2, struct.unpack('>H', h0[i:i+2])[0])) + print('98-100: %i' % struct.unpack('>H', h0[98:100])[0]) for i in range(100, 110, 2): - print '%i-%i Garbage: %i' % (i, i+2, struct.unpack('>H', h0[i:i+2])[0]) - print '110-112: %i' % struct.unpack('>H', h0[110:112])[0] - print '112-114: %i' % struct.unpack('>H', h0[112:114])[0] - print '114-116 Garbage: %i' % struct.unpack('>H', h0[114:116])[0] + print('%i-%i Garbage: %i' % (i, i+2, struct.unpack('>H', h0[i:i+2])[0])) + print('110-112: %i' % struct.unpack('>H', h0[110:112])[0]) + print('112-114: %i' % struct.unpack('>H', h0[112:114])[0]) + print('114-116 Garbage: %i' % struct.unpack('>H', h0[114:116])[0]) for i in range(116, 202, 2): - print '%i-%i: %i' % (i, i+2, struct.unpack('>H', h0[i:i+2])[0]) + print('%i-%i: %i' % (i, i+2, struct.unpack('>H', h0[i:i+2])[0])) - print '' - print '* Garbage: Random values.' - print '' + print('') + print('* Garbage: Random values.') + print('') def section_lengths(header): - print 'Section Sizes' - print '' + print('Section Sizes') + print('') for i in range(0, header.section_count()): size = len(header.section_data(i)) @@ -121,12 +122,12 @@ def section_lengths(header): else: message = '' - print 'Section %i: %i %s' % (i, size, message) + print('Section %i: %i %s' % (i, size, message)) def main(args=sys.argv): if len(args) < 2: - print 'Error: requires input file.' + print('Error: requires input file.') return 1 f = open(sys.argv[1], 'rb') diff --git a/src/calibre/ebooks/pdf/pdftohtml.py b/src/calibre/ebooks/pdf/pdftohtml.py index b4f073312c..61520181d3 100644 --- a/src/calibre/ebooks/pdf/pdftohtml.py +++ b/src/calibre/ebooks/pdf/pdftohtml.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- __license__ = 'GPL 3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal , ' \ '2009, John Schember ' __docformat__ = 'restructuredtext en' @@ -91,8 +92,8 @@ def pdftohtml(output_dir, pdf_path, no_images, as_xml=False): if ret != 0: raise ConversionError(b'pdftohtml failed with return code: %d\n%s' % (ret, out)) if out: - print "pdftohtml log:" - print out + print("pdftohtml log:") + print(out) if not os.path.exists(index) or os.stat(index).st_size < 100: raise DRMError() diff --git a/src/calibre/ebooks/pdf/render/test.py b/src/calibre/ebooks/pdf/render/test.py index 809a782160..94469a55a1 100644 --- a/src/calibre/ebooks/pdf/render/test.py +++ b/src/calibre/ebooks/pdf/render/test.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' @@ -131,8 +132,8 @@ def main(): run(img, func) path = os.path.join(tdir, 'painter.png') img.save(path) - print ('PDF written to:', pdf) - print ('Image written to:', path) + print('PDF written to:', pdf) + print('Image written to:', path) if __name__ == '__main__': main() diff --git a/src/calibre/ebooks/readability/readability.py b/src/calibre/ebooks/readability/readability.py index 6614ebcf5e..95615ed76b 100644 --- a/src/calibre/ebooks/readability/readability.py +++ b/src/calibre/ebooks/readability/readability.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function import re, sys from collections import defaultdict @@ -154,9 +155,9 @@ class Document: continue # try again else: return cleaned_article - except StandardError, e: + except StandardError as e: self.log.exception('error getting summary: ') - raise Unparseable(str(e)), None, sys.exc_info()[2] + raise Unparseable(str(e)).with_traceback(sys.exc_info()[2]) def get_article(self, candidates, best_candidate): # Now that we have the top candidate, look through its siblings for content that might also be related. diff --git a/src/calibre/ebooks/rtf/preprocess.py b/src/calibre/ebooks/rtf/preprocess.py index 42ffa3b57e..ecbacddcb1 100644 --- a/src/calibre/ebooks/rtf/preprocess.py +++ b/src/calibre/ebooks/rtf/preprocess.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2010, Gerendi Sandor Attila' diff --git a/src/calibre/ebooks/rtf2xml/ParseRtf.py b/src/calibre/ebooks/rtf2xml/ParseRtf.py index dfb385f91f..be979c733b 100755 --- a/src/calibre/ebooks/rtf2xml/ParseRtf.py +++ b/src/calibre/ebooks/rtf2xml/ParseRtf.py @@ -230,7 +230,7 @@ class ParseRtf: ) try: return_value = process_tokens_obj.process_tokens() - except InvalidRtfException, msg: + except InvalidRtfException as msg: # Check to see if the file is correctly encoded encode_obj = default_encoding.DefaultEncoding( in_file=self.__temp_file, diff --git a/src/calibre/ebooks/rtf2xml/body_styles.py b/src/calibre/ebooks/rtf2xml/body_styles.py index 7e439517d5..439d990f07 100755 --- a/src/calibre/ebooks/rtf2xml/body_styles.py +++ b/src/calibre/ebooks/rtf2xml/body_styles.py @@ -69,7 +69,7 @@ class BodyStyles: # this shouldn't happen! if self.__run_level > 3: msg = 'Not enough data for each table\n' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) # why was this line even here? # self.__write_obj.write('mi 3: msg = 'can\'t make integer from string\n' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) else: return 'bdr-color_:no-value' hex_num = self.__figure_num(num) @@ -211,7 +211,7 @@ class Colors: if self.__run_level > 3: msg = 'no value in self.__color_dict' \ 'for key %s at line %d\n' % (num, self.__line) - raise self.__bug_handler, msg + raise self.__bug_handler(msg) return hex_num def __do_nothing_func(self, line): diff --git a/src/calibre/ebooks/rtf2xml/configure_txt.py b/src/calibre/ebooks/rtf2xml/configure_txt.py index b2100400e0..7fe92975af 100755 --- a/src/calibre/ebooks/rtf2xml/configure_txt.py +++ b/src/calibre/ebooks/rtf2xml/configure_txt.py @@ -50,7 +50,7 @@ class Configure: msg += ('Options take the form of option = value.\n') msg += ('Please correct the configuration file "%s" before continuing\n' % self.__configuration_file) - raise self.__bug_handler, msg + raise self.__bug_handler(msg) att = fields[0] value = fields[1] att = att.strip() @@ -60,7 +60,7 @@ class Configure: if return_dict == 1: msg = ('Please correct the configuration file "%s" before continuing\n' % self.__configuration_file) - raise self.__bug_handler, msg + raise self.__bug_handler(msg) return return_dict def __get_file_name(self): diff --git a/src/calibre/ebooks/rtf2xml/convert_to_tags.py b/src/calibre/ebooks/rtf2xml/convert_to_tags.py index 3fa48888a8..a8be373693 100755 --- a/src/calibre/ebooks/rtf2xml/convert_to_tags.py +++ b/src/calibre/ebooks/rtf2xml/convert_to_tags.py @@ -129,7 +129,7 @@ class ConvertToTags: except: if self.__run_level > 3: msg = 'index out of range\n' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) self.__write_obj.write('>') self.__new_line = 0 if element_name in self.__block: diff --git a/src/calibre/ebooks/rtf2xml/copy.py b/src/calibre/ebooks/rtf2xml/copy.py index edfd2957b2..e89d24c002 100755 --- a/src/calibre/ebooks/rtf2xml/copy.py +++ b/src/calibre/ebooks/rtf2xml/copy.py @@ -25,11 +25,11 @@ class Copy: """Set the temporary directory to write files to""" if deb_dir is None: message = "No directory has been provided to write to in the copy.py" - raise self.__bug_handler, message + raise self.__bug_handler(message) check = os.path.isdir(deb_dir) if not check: message = "%(deb_dir)s is not a directory" % vars() - raise self.__bug_handler , message + raise self.__bug_handler(message) Copy.__dir = deb_dir def remove_files(self): diff --git a/src/calibre/ebooks/rtf2xml/default_encoding.py b/src/calibre/ebooks/rtf2xml/default_encoding.py index 32e2e3b26f..1dde71d464 100755 --- a/src/calibre/ebooks/rtf2xml/default_encoding.py +++ b/src/calibre/ebooks/rtf2xml/default_encoding.py @@ -55,6 +55,7 @@ Codepages as to RTF 1.9.1: 57010 Gujarati 57011 Punjabi ''' +from __future__ import print_function import re @@ -182,4 +183,4 @@ if __name__ == '__main__': bug_handler=Exception, check_raw=True, ) - print encode_obj.get_codepage() + print(encode_obj.get_codepage()) diff --git a/src/calibre/ebooks/rtf2xml/delete_info.py b/src/calibre/ebooks/rtf2xml/delete_info.py index fdfce2be6c..1544d0f2fe 100755 --- a/src/calibre/ebooks/rtf2xml/delete_info.py +++ b/src/calibre/ebooks/rtf2xml/delete_info.py @@ -126,7 +126,7 @@ class DeleteInfo: # believe I have a '{\*} if self.__run_level > 3: msg = 'Flag problem\n' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) return True elif self.__token_info in self.__allowable : if self.__ob: @@ -150,7 +150,7 @@ class DeleteInfo: if self.__run_level > 5: msg = ('After an asterisk, and found neither an allowable or non-allowable token\n\ token is "%s"\n') % self.__token_info - raise self.__bug_handler, msg + raise self.__bug_handler(msg) if not self.__ob: self.__write_cb = True self.__ob = 0 diff --git a/src/calibre/ebooks/rtf2xml/field_strings.py b/src/calibre/ebooks/rtf2xml/field_strings.py index c32301afec..6691e2f449 100755 --- a/src/calibre/ebooks/rtf2xml/field_strings.py +++ b/src/calibre/ebooks/rtf2xml/field_strings.py @@ -219,7 +219,7 @@ class FieldStrings: sys.stderr.write(msg) if self.__run_level > 3: msg = 'no key for "%s" "%s"\n' % (field_name, changed_string) - raise self.__bug_handler, msg + raise self.__bug_handler(msg) the_list = self.__fall_back_func(field_name, line) return the_list return the_list diff --git a/src/calibre/ebooks/rtf2xml/fonts.py b/src/calibre/ebooks/rtf2xml/fonts.py index 148e58cb51..bd53fdf8ec 100755 --- a/src/calibre/ebooks/rtf2xml/fonts.py +++ b/src/calibre/ebooks/rtf2xml/fonts.py @@ -178,7 +178,7 @@ class Fonts: if font_name is None: if self.__run_level > 3: msg = 'no value for %s in self.__font_table\n' % font_num - raise self.__bug_handler, msg + raise self.__bug_handler(msg) else: # self.__special_font_dict if font_name in self.__special_font_list: diff --git a/src/calibre/ebooks/rtf2xml/get_char_map.py b/src/calibre/ebooks/rtf2xml/get_char_map.py index 55a7d41647..07ba40b981 100755 --- a/src/calibre/ebooks/rtf2xml/get_char_map.py +++ b/src/calibre/ebooks/rtf2xml/get_char_map.py @@ -57,6 +57,6 @@ class GetCharMap: if not found_map: msg = 'no map found\nmap is "%s"\n'%(map,) - raise self.__bug_handler, msg + raise self.__bug_handler(msg) return map_dict diff --git a/src/calibre/ebooks/rtf2xml/group_borders.py b/src/calibre/ebooks/rtf2xml/group_borders.py index ce290f4ae6..2d34f79c0d 100755 --- a/src/calibre/ebooks/rtf2xml/group_borders.py +++ b/src/calibre/ebooks/rtf2xml/group_borders.py @@ -150,7 +150,7 @@ class GroupBorders: sys.stderr.write('Wrong flag in __after_pard_func\n') if self.__run_level > 2: msg = 'wrong flag' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) elif self.__token_info in self.__end_list: self.__write_obj.write('mi 2: msg = 'wrong flag' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) elif self.__token_info in self.__end_list: self.__write_obj.write('mi 3: msg = 'No dictionary match for %s\n' % att - raise self.__bug_handler, msg + raise self.__bug_handler(msg) else: self.__text_string += '<%s>%s' % (att_changed, value) diff --git a/src/calibre/ebooks/rtf2xml/inline.py b/src/calibre/ebooks/rtf2xml/inline.py index 59d1efe8af..8e6beb9a35 100755 --- a/src/calibre/ebooks/rtf2xml/inline.py +++ b/src/calibre/ebooks/rtf2xml/inline.py @@ -302,7 +302,7 @@ class Inline: if len(inline_list) <= 0: if self.__run_level > 3: msg = 'self.__inline_list is %s\n' % self.__inline_list - raise self.__bug_handler, msg + raise self.__bug_handler(msg) self.__write_obj.write('error\n') self.__groups_in_waiting[0] = 0 return diff --git a/src/calibre/ebooks/rtf2xml/list_table.py b/src/calibre/ebooks/rtf2xml/list_table.py index 41605ce403..aeb6b6f62f 100755 --- a/src/calibre/ebooks/rtf2xml/list_table.py +++ b/src/calibre/ebooks/rtf2xml/list_table.py @@ -1,3 +1,4 @@ +from __future__ import print_function ######################################################################### # # # # @@ -98,7 +99,7 @@ class ListTable: self.__ob_group -= 1 action = self.__state_dict.get(self.__state) if action is None: - print self.__state + print(self.__state) action(line) self.__write_final_string() # self.__add_to_final_line() diff --git a/src/calibre/ebooks/rtf2xml/options_trem.py b/src/calibre/ebooks/rtf2xml/options_trem.py index 2aacbc26a9..d768b8b232 100755 --- a/src/calibre/ebooks/rtf2xml/options_trem.py +++ b/src/calibre/ebooks/rtf2xml/options_trem.py @@ -1,3 +1,4 @@ +from __future__ import print_function import sys @@ -279,7 +280,7 @@ if __name__ == '__main__': options_dict=this_dict ) options, the_args = test_obj.parse_options() - print options, the_args + print(options, the_args) """ this_options = ['--foo', '-o'] this_opt_with_args = ['--foo'] diff --git a/src/calibre/ebooks/rtf2xml/override_table.py b/src/calibre/ebooks/rtf2xml/override_table.py index 5296f6e8cc..6eb5e24d88 100755 --- a/src/calibre/ebooks/rtf2xml/override_table.py +++ b/src/calibre/ebooks/rtf2xml/override_table.py @@ -1,3 +1,4 @@ +from __future__ import print_function ######################################################################### # # # # @@ -89,11 +90,11 @@ class OverrideTable: list_id = override_dict.get('list-id') if list_id is None and self.__level > 3: msg = 'This override does not appear to have a list-id\n' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) current_table_id = override_dict.get('list-table-id') if current_table_id is None and self.__run_level > 3: msg = 'This override does not appear to have a list-table-id\n' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) counter = 0 for list in self.__list_of_lists: info_dict = list[0] @@ -126,7 +127,7 @@ class OverrideTable: self.__ob_group -= 1 action = self.__state_dict.get(self.__state) if action is None: - print self.__state + print(self.__state) action(line) self.__write_final_string() # self.__add_to_final_line() @@ -165,7 +166,7 @@ class OverrideTable: elif self.__run_level > 3: msg = 'No matching token after open bracket\n' msg += 'token is "%s\n"' % (line) - raise self.__bug_handler, msg + raise self.__bug_handler(msg) def __write_final_string(self): """ diff --git a/src/calibre/ebooks/rtf2xml/paragraph_def.py b/src/calibre/ebooks/rtf2xml/paragraph_def.py index 683be7d18c..8b062e524b 100755 --- a/src/calibre/ebooks/rtf2xml/paragraph_def.py +++ b/src/calibre/ebooks/rtf2xml/paragraph_def.py @@ -373,7 +373,7 @@ if another paragraph_def is found, the state changes to collect_tokens. else: if self.__run_level > 3: msg = 'no entry for %s\n' % self.__token_info - raise self.__bug_handler, msg + raise self.__bug_handler(msg) def __tab_leader_func(self, line): """ @@ -384,7 +384,7 @@ if another paragraph_def is found, the state changes to collect_tokens. else: if self.__run_level > 3: msg = 'no entry for %s\n' % self.__token_info - raise self.__bug_handler, msg + raise self.__bug_handler(msg) def __tab_bar_func(self, line): """ diff --git a/src/calibre/ebooks/rtf2xml/pict.py b/src/calibre/ebooks/rtf2xml/pict.py index 3580946b94..5db214393d 100755 --- a/src/calibre/ebooks/rtf2xml/pict.py +++ b/src/calibre/ebooks/rtf2xml/pict.py @@ -73,7 +73,7 @@ class Pict: if not os.path.isdir(self.__dir_name): try: os.mkdir(self.__dir_name) - except OSError, msg: + except OSError as msg: msg = "%sCouldn't make directory '%s':\n" % (str(msg), self.__dir_name) raise self.__bug_handler else: diff --git a/src/calibre/ebooks/rtf2xml/preamble_div.py b/src/calibre/ebooks/rtf2xml/preamble_div.py index 94d17e14a6..c33e718179 100755 --- a/src/calibre/ebooks/rtf2xml/preamble_div.py +++ b/src/calibre/ebooks/rtf2xml/preamble_div.py @@ -1,3 +1,4 @@ +from __future__ import print_function ######################################################################### # # # # @@ -411,7 +412,7 @@ cw 3: msg = 'Number "%s" cannot be converted to integer\n' % num - raise self.__bug_handler, msg + raise self.__bug_handler(msg) type = self.__number_type_dict.get(num) if type is None: if self.__run_level > 3: @@ -654,7 +654,7 @@ class ProcessTokens: lang_name = "not defined" if self.__run_level > 3: msg = 'No entry for number "%s"' % num - raise self.__bug_handler, msg + raise self.__bug_handler(msg) return 'cw<%s<%sfalse<%s\n' % (token, token) else: msg = "boolean should have some value module process tokens\ntoken is %s\n'%s'\n" % (token, num) - raise self.__bug_handler, msg + raise self.__bug_handler(msg) def __no_sup_sub_func(self, pre, token, num): the_string = 'cw 3: msg = ('No number to process?\nthis indicates that the token \(\\li\) \ should have a number and does not\nnumerator is \ "%s"\ndenominator is "%s"\n') % (numerator, denominator) - raise self.__bug_handler, msg + raise self.__bug_handler(msg) if 5 > self.__return_code: self.__return_code = 5 return 0 @@ -741,7 +741,7 @@ class ProcessTokens: if not second: if self.__run_level > 3: msg = "token is '%s' \n" % token - raise self.__bug_handler, msg + raise self.__bug_handler(msg) return first, 0 else: if self.__run_level > 3: @@ -791,23 +791,23 @@ class ProcessTokens: line_count += 1 if line_count == 1 and token != '\\{': msg = '\nInvalid RTF: document doesn\'t start with {\n' - raise self.__exception_handler, msg + raise self.__exception_handler(msg) elif line_count == 2 and token[0:4] != '\\rtf': msg = '\nInvalid RTF: document doesn\'t start with \\rtf \n' - raise self.__exception_handler, msg + raise self.__exception_handler(msg) the_index = token.find('\\ ') if token is not None and the_index > -1: msg = '\nInvalid RTF: token "\\ " not valid.\nError at line %d'\ % line_count - raise self.__exception_handler, msg + raise self.__exception_handler(msg) elif token[:1] == "\\": try: token.decode('us-ascii') - except UnicodeError, msg: + except UnicodeError as msg: msg = '\nInvalid RTF: Tokens not ascii encoded.\n%s\nError at line %d'\ % (str(msg), line_count) - raise self.__exception_handler, msg + raise self.__exception_handler(msg) line = self.process_cw(token) if line is not None: write_obj.write(line) @@ -823,7 +823,7 @@ class ProcessTokens: if not line_count: msg = '\nInvalid RTF: file appears to be empty.\n' - raise self.__exception_handler, msg + raise self.__exception_handler(msg) copy_obj = copy.Copy(bug_handler=self.__bug_handler) if self.__copy: @@ -834,6 +834,6 @@ class ProcessTokens: bad_brackets = self.__check_brackets(self.__file) if bad_brackets: msg = '\nInvalid RTF: document does not have matching brackets.\n' - raise self.__exception_handler, msg + raise self.__exception_handler(msg) else: return self.__return_code diff --git a/src/calibre/ebooks/rtf2xml/sections.py b/src/calibre/ebooks/rtf2xml/sections.py index be794ceed7..3bdebb6838 100755 --- a/src/calibre/ebooks/rtf2xml/sections.py +++ b/src/calibre/ebooks/rtf2xml/sections.py @@ -289,7 +289,7 @@ class Sections: self.__handle_sec_def(my_string) elif self.__run_level > 3: msg = 'missed a flag\n' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) def __handle_sec_def(self, my_string): """ diff --git a/src/calibre/ebooks/rtf2xml/styles.py b/src/calibre/ebooks/rtf2xml/styles.py index 1b72a7feb5..6f0b48ae3d 100755 --- a/src/calibre/ebooks/rtf2xml/styles.py +++ b/src/calibre/ebooks/rtf2xml/styles.py @@ -301,7 +301,7 @@ class Styles: if info not in self.__ignore_list: if self.__run_level > 3: msg = 'no value for key %s\n' % info - raise self.__bug_handler, msg + raise self.__bug_handler(msg) else: value = line[20:-1] self.__enter_dict_entry(att, value) @@ -346,7 +346,7 @@ class Styles: else: if self.__run_level > 3: msg = 'no entry for %s\n' % self.__token_info - raise self.__bug_handler, msg + raise self.__bug_handler(msg) def __tab_leader_func(self, line): """ @@ -371,7 +371,7 @@ class Styles: else: if self.__run_level > 3: msg = 'no entry for %s\n' % self.__token_info - raise self.__bug_handler, msg + raise self.__bug_handler(msg) def __tab_bar_func(self, line): """ @@ -438,7 +438,7 @@ class Styles: else: if self.__run_level > 3: msg = self.__type_of_style + 'error\n' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) smallest_dict = {} smallest_dict[att] = value type_dict[self.__styles_num] = smallest_dict @@ -550,7 +550,7 @@ class Styles: if self.__run_level > 4: msg = '%s %s is based on %s\n' % (type, key, value) msg = 'There is no style with %s\n' % value - raise self.__bug_handler, msg + raise self.__bug_handler(msg) del self.__styles_dict[type][key][style] def __print_style_table(self): diff --git a/src/calibre/ebooks/rtf2xml/table_info.py b/src/calibre/ebooks/rtf2xml/table_info.py index a7490a8d9e..ddf66a1e37 100755 --- a/src/calibre/ebooks/rtf2xml/table_info.py +++ b/src/calibre/ebooks/rtf2xml/table_info.py @@ -72,7 +72,7 @@ class TableInfo: # this shouldn't happen! if self.__run_level > 3: msg = 'Not enough data for each table\n' - raise self.__bug_handler, msg + raise self.__bug_handler(msg) self.__write_obj.write('mi tag. def report_unbalanced(self, tag): if self.verbose: - print '*** Unbalanced ' - print '*** Stack:', self.stack + print('*** Unbalanced ') + print('*** Stack:', self.stack) def convert_charref(self, name): """Convert character reference, may be overridden.""" @@ -487,40 +488,40 @@ class TestSGMLParser(SGMLParser): data = self.testdata if data: self.testdata = "" - print 'data:', repr(data) + print('data:', repr(data)) def handle_comment(self, data): self.flush() r = repr(data) if len(r) > 68: r = r[:32] + '...' + r[-32:] - print 'comment:', r + print('comment:', r) def unknown_starttag(self, tag, attrs): self.flush() if not attrs: - print 'start tag: <' + tag + '>' + print('start tag: <' + tag + '>') else: - print 'start tag: <' + tag, + print('start tag: <' + tag, end=' ') for name, value in attrs: - print name + '=' + '"' + value + '"', - print '>' + print(name + '=' + '"' + value + '"', end=' ') + print('>') def unknown_endtag(self, tag): self.flush() - print 'end tag: ' + print('end tag: ') def unknown_entityref(self, ref): self.flush() - print '*** unknown entity ref: &' + ref + ';' + print('*** unknown entity ref: &' + ref + ';') def unknown_charref(self, ref): self.flush() - print '*** unknown char ref: &#' + ref + ';' + print('*** unknown char ref: &#' + ref + ';') def unknown_decl(self, data): self.flush() - print '*** unknown decl: [' + data + ']' + print('*** unknown decl: [' + data + ']') def close(self): SGMLParser.close(self) @@ -549,8 +550,8 @@ def test(args=None): else: try: f = open(file, 'r') - except IOError, msg: - print file, ":", msg + except IOError as msg: + print(file, ":", msg) sys.exit(1) data = f.read() diff --git a/src/calibre/ebooks/snb/snbfile.py b/src/calibre/ebooks/snb/snbfile.py index 6189314350..2b8d7a3c05 100644 --- a/src/calibre/ebooks/snb/snbfile.py +++ b/src/calibre/ebooks/snb/snbfile.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- __license__ = 'GPL 3' +from __future__ import print_function __copyright__ = '2010, Li Fanxi ' __docformat__ = 'restructuredtext en' @@ -92,7 +93,7 @@ class SNBFile: else: uncompressedData += data except Exception as e: - print e + print(e) if len(uncompressedData) != self.plainStreamSizeUncompressed: raise Exception() f.fileBody = uncompressedData[plainPos:plainPos+f.fileSize] @@ -103,7 +104,7 @@ class SNBFile: f.fileBody = snbFile.read(f.fileSize) binPos += f.fileSize else: - print f.attr, f.fileName + print(f.attr, f.fileName) raise Exception("Invalid file") def ParseFile(self, vfat, fileCount): @@ -143,7 +144,7 @@ class SNBFile: if (self.binBlock + self.plainBlock) * 4 + self.fileCount * 8 != self.tailSizeUncompressed: return False if self.tailMagic != SNBFile.MAGIC: - print self.tailMagic + print(self.tailMagic) return False return True @@ -222,7 +223,7 @@ class SNBFile: f.contentOffset = len(binStream) binStream += f.fileBody else: - print f.attr, f.fileName + print(f.attr, f.fileName) raise Exception("Unknown file type") vfatCompressed = zlib.compress(vfat+fileNameTable) @@ -285,32 +286,32 @@ class SNBFile: def Dump(self): if self.fileName: - print "File Name:\t", self.fileName - print "File Count:\t", self.fileCount - print "VFAT Size(Compressed):\t%d(%d)" % (self.vfatSize, self.vfatCompressed) - print "Binary Stream Size:\t", self.binStreamSize - print "Plain Stream Uncompressed Size:\t", self.plainStreamSizeUncompressed - print "Binary Block Count:\t", self.binBlock - print "Plain Block Count:\t", self.plainBlock + print("File Name:\t", self.fileName) + print("File Count:\t", self.fileCount) + print("VFAT Size(Compressed):\t%d(%d)" % (self.vfatSize, self.vfatCompressed)) + print("Binary Stream Size:\t", self.binStreamSize) + print("Plain Stream Uncompressed Size:\t", self.plainStreamSizeUncompressed) + print("Binary Block Count:\t", self.binBlock) + print("Plain Block Count:\t", self.plainBlock) for i in range(self.fileCount): - print "File ", i + print("File ", i) f = self.files[i] - print "File Name: ", f.fileName - print "File Attr: ", f.attr - print "File Size: ", f.fileSize - print "Block Index: ", f.blockIndex - print "Content Offset: ", f.contentOffset + print("File Name: ", f.fileName) + print("File Attr: ", f.attr) + print("File Size: ", f.fileSize) + print("Block Index: ", f.blockIndex) + print("Content Offset: ", f.contentOffset) tempFile = open("/tmp/" + f.fileName, 'wb') tempFile.write(f.fileBody) tempFile.close() def usage(): - print "This unit test is for INTERNAL usage only!" - print "This unit test accept two parameters." - print "python snbfile.py " - print "The input file will be extracted and write to dest file. " - print "Meta data of the file will be shown during this process." + print("This unit test is for INTERNAL usage only!") + print("This unit test accept two parameters.") + print("python snbfile.py ") + print("The input file will be extracted and write to dest file. ") + print("Meta data of the file will be shown during this process.") def main(): @@ -320,15 +321,15 @@ def main(): inputFile = sys.argv[1] outputFile = sys.argv[2] - print "Input file: ", inputFile - print "Output file: ", outputFile + print("Input file: ", inputFile) + print("Output file: ", outputFile) snbFile = SNBFile(inputFile) if snbFile.IsValid(): snbFile.Dump() snbFile.Output(outputFile) else: - print "The input file is invalid." + print("The input file is invalid.") return 1 return 0 diff --git a/src/calibre/ebooks/tweak.py b/src/calibre/ebooks/tweak.py index b4464e7020..9cee103f2e 100644 --- a/src/calibre/ebooks/tweak.py +++ b/src/calibre/ebooks/tweak.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/gui2/actions/choose_library.py b/src/calibre/gui2/actions/choose_library.py index a03b3c42de..6fe946958e 100644 --- a/src/calibre/gui2/actions/choose_library.py +++ b/src/calibre/gui2/actions/choose_library.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2010, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -591,13 +592,13 @@ class ChooseLibraryAction(InterfaceAction): for i in xrange(3): gc.collect() if ref() is not None: - print 'DB object alive:', ref() + print('DB object alive:', ref()) for r in gc.get_referrers(ref())[:10]: - print r - print - print 'before:', self.before_mem - print 'after:', memory() - print + print(r) + print() + print('before:', self.before_mem) + print('after:', memory()) + print() self.dbref = self.before_mem = None def count_changed(self, new_count): diff --git a/src/calibre/gui2/actions/copy_to_library.py b/src/calibre/gui2/actions/copy_to_library.py index 23b6e9e36c..c9f6091dfd 100644 --- a/src/calibre/gui2/actions/copy_to_library.py +++ b/src/calibre/gui2/actions/copy_to_library.py @@ -277,7 +277,7 @@ class ChooseLibrary(Dialog): # {{{ def resort(self): if self.sort_alphabetically.isChecked(): - sorted_locations = sorted(self.locations, key=lambda (name, loc): numeric_sort_key(name)) + sorted_locations = sorted(self.locations, key=lambda name_loc: numeric_sort_key(name_loc[0])) else: sorted_locations = self.locations self.items.clear() diff --git a/src/calibre/gui2/catalog/catalog_epub_mobi.py b/src/calibre/gui2/catalog/catalog_epub_mobi.py index ef1122cc09..cef67c660c 100644 --- a/src/calibre/gui2/catalog/catalog_epub_mobi.py +++ b/src/calibre/gui2/catalog/catalog_epub_mobi.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -521,9 +522,9 @@ class PluginWidget(QWidget,Ui_Form): opts_dict['output_profile'] = ['default'] if False and self.DEBUG: - print "opts_dict" + print("opts_dict") for opt in sorted(opts_dict.keys(), key=sort_key): - print " %s: %s" % (opt, repr(opts_dict[opt])) + print(" %s: %s" % (opt, repr(opts_dict[opt]))) return opts_dict def populate_combo_boxes(self): diff --git a/src/calibre/gui2/complete2.py b/src/calibre/gui2/complete2.py index c0fb7f1cb5..50630148dd 100644 --- a/src/calibre/gui2/complete2.py +++ b/src/calibre/gui2/complete2.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' @@ -200,9 +201,9 @@ class Completer(QListView): # {{{ def debug_event(self, ev): from calibre.gui2 import event_type_name - print ('Event:', event_type_name(ev)) + print('Event:', event_type_name(ev)) if ev.type() in (ev.KeyPress, ev.ShortcutOverride, ev.KeyRelease): - print ('\tkey:', QKeySequence(ev.key()).toString()) + print('\tkey:', QKeySequence(ev.key()).toString()) def eventFilter(self, obj, e): 'Redirect key presses from the popup to the widget' diff --git a/src/calibre/gui2/convert/xpath_wizard.py b/src/calibre/gui2/convert/xpath_wizard.py index 99bcbc4b7a..6014f80cf8 100644 --- a/src/calibre/gui2/convert/xpath_wizard.py +++ b/src/calibre/gui2/convert/xpath_wizard.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -113,4 +114,4 @@ if __name__ == '__main__': w.setObjectName('test') w.show() app.exec_() - print w.xpath + print(w.xpath) diff --git a/src/calibre/gui2/cover_flow.py b/src/calibre/gui2/cover_flow.py index fa632d97ff..926a6640ef 100644 --- a/src/calibre/gui2/cover_flow.py +++ b/src/calibre/gui2/cover_flow.py @@ -1,5 +1,6 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' @@ -55,7 +56,7 @@ if pictureflow is not None: return self.subtitles[index] def currentChanged(self, index): - print 'current changed:', index + print('current changed:', index) class DummyImageList(pictureflow.FlowImages): diff --git a/src/calibre/gui2/dbus_export/demo.py b/src/calibre/gui2/dbus_export/demo.py index 0efc6ded9a..65f8f057ad 100644 --- a/src/calibre/gui2/dbus_export/demo.py +++ b/src/calibre/gui2/dbus_export/demo.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal ' @@ -90,7 +91,7 @@ class MainWindow(QMainWindow): b.clicked.connect(self.remove_menu), l.addWidget(b) self.sd = b = QPushButton('Show modal dialog') b.clicked.connect(self.show_dialog), l.addWidget(b) - print ('DBUS connection unique name:', f.bus.get_unique_name()) + print('DBUS connection unique name:', f.bus.get_unique_name()) def update_tooltip(self): self.systray.setToolTip(time.strftime('A dynamically updated tooltip [%H:%M:%S]')) diff --git a/src/calibre/gui2/device_drivers/mtp_folder_browser.py b/src/calibre/gui2/device_drivers/mtp_folder_browser.py index b054977e82..c1e85557e9 100644 --- a/src/calibre/gui2/device_drivers/mtp_folder_browser.py +++ b/src/calibre/gui2/device_drivers/mtp_folder_browser.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/gui2/dialogs/authors_edit.py b/src/calibre/gui2/dialogs/authors_edit.py index 34ce34722c..d125c66db0 100644 --- a/src/calibre/gui2/dialogs/authors_edit.py +++ b/src/calibre/gui2/dialogs/authors_edit.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' diff --git a/src/calibre/gui2/dialogs/choose_format.py b/src/calibre/gui2/dialogs/choose_format.py index e90232b281..231c77d75f 100644 --- a/src/calibre/gui2/dialogs/choose_format.py +++ b/src/calibre/gui2/dialogs/choose_format.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' diff --git a/src/calibre/gui2/dialogs/duplicates.py b/src/calibre/gui2/dialogs/duplicates.py index 5154058095..67e7c4f534 100644 --- a/src/calibre/gui2/dialogs/duplicates.py +++ b/src/calibre/gui2/dialogs/duplicates.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' diff --git a/src/calibre/gui2/dialogs/message_box.py b/src/calibre/gui2/dialogs/message_box.py index 689a722910..bb1c5b4586 100644 --- a/src/calibre/gui2/dialogs/message_box.py +++ b/src/calibre/gui2/dialogs/message_box.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2011, Kovid Goyal ' __docformat__ = 'restructuredtext en' diff --git a/src/calibre/gui2/dialogs/metadata_bulk.py b/src/calibre/gui2/dialogs/metadata_bulk.py index 01726101e6..729bf70ed6 100644 --- a/src/calibre/gui2/dialogs/metadata_bulk.py +++ b/src/calibre/gui2/dialogs/metadata_bulk.py @@ -3,6 +3,7 @@ # License: GPLv3 Copyright: 2008, Kovid Goyal import re +from __future__ import print_function from collections import defaultdict, namedtuple from io import BytesIO from threading import Thread diff --git a/src/calibre/gui2/dialogs/opml.py b/src/calibre/gui2/dialogs/opml.py index 9235eea48d..0313ae06e4 100644 --- a/src/calibre/gui2/dialogs/opml.py +++ b/src/calibre/gui2/dialogs/opml.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal ' diff --git a/src/calibre/gui2/dialogs/search.py b/src/calibre/gui2/dialogs/search.py index e47da7fbd1..d929ebf6b4 100644 --- a/src/calibre/gui2/dialogs/search.py +++ b/src/calibre/gui2/dialogs/search.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' @@ -173,7 +174,7 @@ def create_date_tab(self, db): l.addLayout(h) self.date_field = df = add(_("&Search the"), QComboBox(w)) vals = [((v['search_terms'] or [k])[0], v['name'] or k) for k, v in db.field_metadata.iteritems() if v.get('datatype', None) == 'datetime'] - for k, v in sorted(vals, key=lambda (k, v): sort_key(v)): + for k, v in sorted(vals, key=lambda k_v: sort_key(k_v[1])): df.addItem(v, k) h.addWidget(df) self.dateop_date = dd = add(_("date column for books whose &date is "), QComboBox(w)) diff --git a/src/calibre/gui2/dialogs/select_formats.py b/src/calibre/gui2/dialogs/select_formats.py index d1de9b5202..62ace67c3e 100644 --- a/src/calibre/gui2/dialogs/select_formats.py +++ b/src/calibre/gui2/dialogs/select_formats.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -97,4 +98,4 @@ if __name__ == '__main__': app = QApplication([]) d = SelectFormats(['epub', 'lrf', 'lit', 'mobi'], 'Choose a format') d.exec_() - print d.selected_formats + print(d.selected_formats) diff --git a/src/calibre/gui2/dialogs/tag_editor.py b/src/calibre/gui2/dialogs/tag_editor.py index 7368f59398..822f898e24 100644 --- a/src/calibre/gui2/dialogs/tag_editor.py +++ b/src/calibre/gui2/dialogs/tag_editor.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' diff --git a/src/calibre/gui2/dialogs/template_dialog.py b/src/calibre/gui2/dialogs/template_dialog.py index 57dfd40676..4bfa3280ed 100644 --- a/src/calibre/gui2/dialogs/template_dialog.py +++ b/src/calibre/gui2/dialogs/template_dialog.py @@ -219,7 +219,7 @@ class TemplateDialog(QDialog, Ui_TemplateDialog): cols = [] if fm is not None: for key in sorted(displayable_columns(fm), - key=lambda(k): sort_key(fm[k]['name']) if k != color_row_key else 0): + key=lambda k: sort_key(fm[k]['name']) if k != color_row_key else 0): if key == color_row_key and not self.coloring: continue from calibre.gui2.preferences.coloring import all_columns_string diff --git a/src/calibre/gui2/dialogs/trim_image.py b/src/calibre/gui2/dialogs/trim_image.py index 4230b2daa1..1457be4fa1 100644 --- a/src/calibre/gui2/dialogs/trim_image.py +++ b/src/calibre/gui2/dialogs/trim_image.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' @@ -106,4 +107,4 @@ if __name__ == '__main__': fname = b + '-trimmed' + ext with open(fname, 'wb') as f: f.write(d.image_data) - print ('Trimmed image written to', fname) + print('Trimmed image written to', fname) diff --git a/src/calibre/gui2/dnd.py b/src/calibre/gui2/dnd.py index a46190351a..243c57e93e 100644 --- a/src/calibre/gui2/dnd.py +++ b/src/calibre/gui2/dnd.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal ' diff --git a/src/calibre/gui2/font_family_chooser.py b/src/calibre/gui2/font_family_chooser.py index 7fb0197866..b649df4093 100644 --- a/src/calibre/gui2/font_family_chooser.py +++ b/src/calibre/gui2/font_family_chooser.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/gui2/icon_theme.py b/src/calibre/gui2/icon_theme.py index 7083df3901..d0995b2f1e 100644 --- a/src/calibre/gui2/icon_theme.py +++ b/src/calibre/gui2/icon_theme.py @@ -368,7 +368,7 @@ def create_themeball(report, progress=None, abort=None): return if errors: e = errors[0] - raise e[0], e[1], e[2] + raise e[0](e[1]).with_traceback(e[2]) if progress is not None: progress(next(num), _('Creating theme file')) diff --git a/src/calibre/gui2/library/alternate_views.py b/src/calibre/gui2/library/alternate_views.py index 1acccf8b72..93a8e10fc6 100644 --- a/src/calibre/gui2/library/alternate_views.py +++ b/src/calibre/gui2/library/alternate_views.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' @@ -969,7 +970,7 @@ class GridView(QListView): # Create a range based selector for each set of contiguous rows # as supplying selectors for each individual row causes very poor # performance if a large number of rows has to be selected. - for k, g in itertools.groupby(enumerate(rows), lambda (i,x):i-x): + for k, g in itertools.groupby(enumerate(rows), lambda i_x:i_x[0]-i_x[1]): group = list(map(operator.itemgetter(1), g)) sel.merge(QItemSelection(m.index(min(group), 0), m.index(max(group), 0)), sm.Select) sm.select(sel, sm.ClearAndSelect) diff --git a/src/calibre/gui2/library/models.py b/src/calibre/gui2/library/models.py index abaafa368f..1eb8405e6d 100644 --- a/src/calibre/gui2/library/models.py +++ b/src/calibre/gui2/library/models.py @@ -55,7 +55,7 @@ def default_image(): def group_numbers(numbers): - for k, g in groupby(enumerate(sorted(numbers)), lambda (i, x):i - x): + for k, g in groupby(enumerate(sorted(numbers)), lambda i_x:i_x[0] - i_x[1]): first = None for last in g: if first is None: diff --git a/src/calibre/gui2/library/views.py b/src/calibre/gui2/library/views.py index d6b38bac7b..3186436433 100644 --- a/src/calibre/gui2/library/views.py +++ b/src/calibre/gui2/library/views.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2010, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -1136,7 +1137,7 @@ class BooksView(QTableView): # {{{ # Create a range based selector for each set of contiguous rows # as supplying selectors for each individual row causes very poor # performance if a large number of rows has to be selected. - for k, g in itertools.groupby(enumerate(rows), lambda (i,x):i-x): + for k, g in itertools.groupby(enumerate(rows), lambda i_x:i_x[0]-i_x[1]): group = list(map(operator.itemgetter(1), g)) sel.merge(QItemSelection(m.index(min(group), 0), m.index(max(group), max_col)), sm.Select) diff --git a/src/calibre/gui2/linux_file_dialogs.py b/src/calibre/gui2/linux_file_dialogs.py index 656c4c10f1..8ee09193f4 100644 --- a/src/calibre/gui2/linux_file_dialogs.py +++ b/src/calibre/gui2/linux_file_dialogs.py @@ -314,7 +314,7 @@ def linux_native_dialog(name): t.start() loop.exec_(QEventLoop.ExcludeUserInputEvents) if ret[1] is not None: - raise ret[1][0], ret[1][1], ret[1][2] + raise ret[1][0](ret[1][1]).with_traceback(ret[1][2]) return ret[0] except Exception: linux_native_dialog.native_failed = True diff --git a/src/calibre/gui2/lrf_renderer/document.py b/src/calibre/gui2/lrf_renderer/document.py index 81983e7bc3..6611eb3bc3 100644 --- a/src/calibre/gui2/lrf_renderer/document.py +++ b/src/calibre/gui2/lrf_renderer/document.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' import collections, itertools, glob @@ -163,10 +164,10 @@ class _Canvas(QGraphicsRectItem): self.is_full = y > self.max_y-5 ib.has_content = False if ib.block_id == 54: - print - print ib.block_id, ib.has_content, self.is_full - print self.current_y, self.max_y, y, br.height() - print + print() + print(ib.block_id, ib.has_content, self.is_full) + print(self.current_y, self.max_y, y, br.height()) + print() def search(self, phrase): matches = [] diff --git a/src/calibre/gui2/lrf_renderer/main.py b/src/calibre/gui2/lrf_renderer/main.py index 6107cb0714..f1c62bc417 100644 --- a/src/calibre/gui2/lrf_renderer/main.py +++ b/src/calibre/gui2/lrf_renderer/main.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' import sys, logging, os, traceback, time @@ -179,11 +180,11 @@ class Main(MainWindow, Ui_MainWindow): import cProfile lrf = self.renderer.lrf cProfile.runctx('self.document.render(lrf)', globals(), locals(), lrf.metadata.title+'.stats') - print 'Stats written to', self.renderer.lrf.metadata.title+'.stats' + print('Stats written to', self.renderer.lrf.metadata.title+'.stats') else: start = time.time() self.document.render(self.renderer.lrf) - print 'Layout time:', time.time()-start, 'seconds' + print('Layout time:', time.time()-start, 'seconds') self.renderer.lrf = None self.graphics_view.setScene(self.document) @@ -196,9 +197,9 @@ class Main(MainWindow, Ui_MainWindow): self.graphics_view.setFocus(Qt.OtherFocusReason) elif self.renderer.exception is not None: exception = self.renderer.exception - print >>sys.stderr, 'Error rendering document' - print >>sys.stderr, exception - print >>sys.stderr, self.renderer.formatted_traceback + print('Error rendering document', file=sys.stderr) + print(exception, file=sys.stderr) + print(self.renderer.formatted_traceback, file=sys.stderr) msg = u'

%s: '%(exception.__class__.__name__,) + unicode(str(exception), 'utf8', 'replace') + u'

' msg += u'

Failed to render document

' msg += u'

Detailed traceback:

'
diff --git a/src/calibre/gui2/lrf_renderer/text.py b/src/calibre/gui2/lrf_renderer/text.py
index 42b0f65616..8ab88fd5a8 100644
--- a/src/calibre/gui2/lrf_renderer/text.py
+++ b/src/calibre/gui2/lrf_renderer/text.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
 __license__   = 'GPL v3'
 __copyright__ = '2008, Kovid Goyal '
 import sys, collections, operator, copy, re
@@ -536,7 +537,7 @@ class Line(QGraphicsItem):
                     matches.append(word)
                     for c in range(1, len(tokens)):
                         word = words.next()
-                        print tokens[c], word.string
+                        print(tokens[c], word.string)
                         if tokens[c] not in unicode(word.string):
                             return None
                         matches.append(word)
diff --git a/src/calibre/gui2/main.py b/src/calibre/gui2/main.py
index 91154d1e9a..903a0ca2cb 100644
--- a/src/calibre/gui2/main.py
+++ b/src/calibre/gui2/main.py
@@ -3,6 +3,7 @@
 # License: GPLv3 Copyright: 2015, Kovid Goyal 
 
 import os
+from __future__ import print_function
 import re
 import socket
 import sys
@@ -257,7 +258,7 @@ class GuiRunner(QObject):
             error_dialog(self.splash_screen, title, msg, det_msg=det_msg, show=True)
 
     def initialization_failed(self):
-        print 'Catastrophic failure initializing GUI, bailing out...'
+        print('Catastrophic failure initializing GUI, bailing out...')
         QCoreApplication.exit(1)
         raise SystemExit(1)
 
diff --git a/src/calibre/gui2/main_window.py b/src/calibre/gui2/main_window.py
index d11c4b2672..c0cc2c80b1 100644
--- a/src/calibre/gui2/main_window.py
+++ b/src/calibre/gui2/main_window.py
@@ -51,24 +51,24 @@ class GarbageCollector(QObject):
         # return self.debug_cycles()
         l0, l1, l2 = gc.get_count()
         if self.debug:
-            print ('gc_check called:', l0, l1, l2)
+            print('gc_check called:', l0, l1, l2)
         if l0 > self.threshold[0]:
             num = gc.collect(0)
             if self.debug:
-                print ('collecting gen 0, found:', num, 'unreachable')
+                print('collecting gen 0, found:', num, 'unreachable')
             if l1 > self.threshold[1]:
                 num = gc.collect(1)
                 if self.debug:
-                    print ('collecting gen 1, found:', num, 'unreachable')
+                    print('collecting gen 1, found:', num, 'unreachable')
                 if l2 > self.threshold[2]:
                     num = gc.collect(2)
                     if self.debug:
-                        print ('collecting gen 2, found:', num, 'unreachable')
+                        print('collecting gen 2, found:', num, 'unreachable')
 
     def debug_cycles(self):
         gc.collect()
         for obj in gc.garbage:
-            print (obj, repr(obj), type(obj))
+            print(obj, repr(obj), type(obj))
 
 
 class ExceptionHandler(object):
diff --git a/src/calibre/gui2/metadata/config.py b/src/calibre/gui2/metadata/config.py
index a20e35bf5f..cf6b17a661 100644
--- a/src/calibre/gui2/metadata/config.py
+++ b/src/calibre/gui2/metadata/config.py
@@ -101,7 +101,7 @@ class ConfigWidget(QWidget):
         elif opt.type == 'choices':
             widget = QComboBox(self)
             items = list(opt.choices.iteritems())
-            items.sort(key=lambda (k, v): sort_key(v))
+            items.sort(key=lambda k_v: sort_key(k_v[1]))
             for key, label in items:
                 widget.addItem(label, (key))
             idx = widget.findData((val))
diff --git a/src/calibre/gui2/metadata/diff.py b/src/calibre/gui2/metadata/diff.py
index 45ae8fac7a..b20a1d9e4f 100644
--- a/src/calibre/gui2/metadata/diff.py
+++ b/src/calibre/gui2/metadata/diff.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=utf-8
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__ = 'GPL v3'
 __copyright__ = '2013, Kovid Goyal '
diff --git a/src/calibre/gui2/metadata/pdf_covers.py b/src/calibre/gui2/metadata/pdf_covers.py
index 920628259c..897523ea6c 100644
--- a/src/calibre/gui2/metadata/pdf_covers.py
+++ b/src/calibre/gui2/metadata/pdf_covers.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__   = 'GPL v3'
 __copyright__ = '2013, Kovid Goyal '
diff --git a/src/calibre/gui2/open_with.py b/src/calibre/gui2/open_with.py
index 45d509e3dc..31eaf83e91 100644
--- a/src/calibre/gui2/open_with.py
+++ b/src/calibre/gui2/open_with.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=utf-8
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__ = 'GPL v3'
 __copyright__ = '2015, Kovid Goyal '
diff --git a/src/calibre/gui2/preferences/coloring.py b/src/calibre/gui2/preferences/coloring.py
index 3ed684b9a9..27f787998c 100644
--- a/src/calibre/gui2/preferences/coloring.py
+++ b/src/calibre/gui2/preferences/coloring.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__   = 'GPL v3'
 __copyright__ = '2011, Kovid Goyal '
@@ -126,7 +127,7 @@ class ConditionEditor(QWidget):  # {{{
         self.column_box.addItem('', '')
         for key in sorted(
                 conditionable_columns(fm),
-                key=lambda(key): sort_key(fm[key]['name'])):
+                key=lambda key: sort_key(fm[key]['name'])):
             self.column_box.addItem(fm[key]['name'], key)
         self.column_box.setCurrentIndex(0)
 
@@ -428,7 +429,7 @@ class RuleEditor(QDialog):  # {{{
                 b.setMinimumContentsLength(15)
 
         for key in sorted(displayable_columns(fm),
-                          key=lambda(k): sort_key(fm[k]['name']) if k != color_row_key else 0):
+                          key=lambda k: sort_key(fm[k]['name']) if k != color_row_key else 0):
             if key == color_row_key and self.rule_kind != 'color':
                 continue
             name = all_columns_string if key == color_row_key else fm[key]['name']
@@ -1128,7 +1129,7 @@ if __name__ == '__main__':
 
         kind, col, r = d.rule
 
-        print ('Column to be colored:', col)
+        print('Column to be colored:', col)
         print ('Template:')
         print (r.template)
     else:
diff --git a/src/calibre/gui2/preferences/plugboard.py b/src/calibre/gui2/preferences/plugboard.py
index 24108583df..77e64a7e2c 100644
--- a/src/calibre/gui2/preferences/plugboard.py
+++ b/src/calibre/gui2/preferences/plugboard.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 
 __license__   = 'GPL v3'
+from __future__ import print_function
 __copyright__ = '2010, Kovid Goyal '
 __docformat__ = 'restructuredtext en'
 
@@ -155,11 +156,11 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
         self.current_device = unicode(txt)
         fpb = self.current_plugboards.get(self.current_format, None)
         if fpb is None:
-            print 'edit_device_changed: none format!'
+            print('edit_device_changed: none format!')
             return
         dpb = fpb.get(self.current_device, None)
         if dpb is None:
-            print 'edit_device_changed: none device!'
+            print('edit_device_changed: none device!')
             return
         self.set_fields()
         for i,op in enumerate(dpb):
@@ -178,7 +179,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
         txt = unicode(txt)
         fpb = self.current_plugboards.get(txt, None)
         if fpb is None:
-            print 'edit_format_changed: none editable format!'
+            print('edit_format_changed: none editable format!')
             return
         self.current_format = txt
         self.check_if_writer_disabled(txt)
diff --git a/src/calibre/gui2/preferences/texture_chooser.py b/src/calibre/gui2/preferences/texture_chooser.py
index bf50e95ac6..075d8af0ac 100644
--- a/src/calibre/gui2/preferences/texture_chooser.py
+++ b/src/calibre/gui2/preferences/texture_chooser.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=utf-8
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__ = 'GPL v3'
 __copyright__ = '2013, Kovid Goyal '
diff --git a/src/calibre/gui2/preferences/tweaks.py b/src/calibre/gui2/preferences/tweaks.py
index 2a27fc2339..35c0a09361 100644
--- a/src/calibre/gui2/preferences/tweaks.py
+++ b/src/calibre/gui2/preferences/tweaks.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 
 __license__   = 'GPL v3'
+from __future__ import print_function
 __copyright__ = '2010, Kovid Goyal '
 __docformat__ = 'restructuredtext en'
 
@@ -171,7 +172,7 @@ class Tweaks(QAbstractListModel, AdaptSQP):  # {{{
         try:
             exec(custom, g, l)
         except:
-            print 'Failed to load custom tweaks file'
+            print('Failed to load custom tweaks file')
             import traceback
             traceback.print_exc()
         dl, dg = {}, {}
diff --git a/src/calibre/gui2/store/stores/amazon_au_plugin.py b/src/calibre/gui2/store/stores/amazon_au_plugin.py
index ef37e0a71e..021b18fba0 100644
--- a/src/calibre/gui2/store/stores/amazon_au_plugin.py
+++ b/src/calibre/gui2/store/stores/amazon_au_plugin.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 store_version = 5  # Needed for dynamic plugin loading
 
 from contextlib import closing
diff --git a/src/calibre/gui2/store/stores/amazon_ca_plugin.py b/src/calibre/gui2/store/stores/amazon_ca_plugin.py
index baa31f91a3..7e26085f5c 100644
--- a/src/calibre/gui2/store/stores/amazon_ca_plugin.py
+++ b/src/calibre/gui2/store/stores/amazon_ca_plugin.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 store_version = 7  # Needed for dynamic plugin loading
 
 from contextlib import closing
diff --git a/src/calibre/gui2/store/stores/amazon_de_plugin.py b/src/calibre/gui2/store/stores/amazon_de_plugin.py
index 06a6df7859..ed2b28fb43 100644
--- a/src/calibre/gui2/store/stores/amazon_de_plugin.py
+++ b/src/calibre/gui2/store/stores/amazon_de_plugin.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 store_version = 15  # Needed for dynamic plugin loading
 
 from contextlib import closing
diff --git a/src/calibre/gui2/store/stores/amazon_es_plugin.py b/src/calibre/gui2/store/stores/amazon_es_plugin.py
index 859473a660..e0dfcef6bd 100644
--- a/src/calibre/gui2/store/stores/amazon_es_plugin.py
+++ b/src/calibre/gui2/store/stores/amazon_es_plugin.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 store_version = 15  # Needed for dynamic plugin loading
 
 from contextlib import closing
diff --git a/src/calibre/gui2/store/stores/amazon_fr_plugin.py b/src/calibre/gui2/store/stores/amazon_fr_plugin.py
index 59479b70f6..9c63516a81 100644
--- a/src/calibre/gui2/store/stores/amazon_fr_plugin.py
+++ b/src/calibre/gui2/store/stores/amazon_fr_plugin.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 store_version = 15  # Needed for dynamic plugin loading
 
 from contextlib import closing
diff --git a/src/calibre/gui2/store/stores/amazon_in_plugin.py b/src/calibre/gui2/store/stores/amazon_in_plugin.py
index 1b88c529b1..cc25b218c9 100644
--- a/src/calibre/gui2/store/stores/amazon_in_plugin.py
+++ b/src/calibre/gui2/store/stores/amazon_in_plugin.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 store_version = 5  # Needed for dynamic plugin loading
 
 from contextlib import closing
diff --git a/src/calibre/gui2/store/stores/amazon_it_plugin.py b/src/calibre/gui2/store/stores/amazon_it_plugin.py
index a9c79448fa..1761bddf96 100644
--- a/src/calibre/gui2/store/stores/amazon_it_plugin.py
+++ b/src/calibre/gui2/store/stores/amazon_it_plugin.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 store_version = 15  # Needed for dynamic plugin loading
 
 from contextlib import closing
diff --git a/src/calibre/gui2/store/stores/amazon_plugin.py b/src/calibre/gui2/store/stores/amazon_plugin.py
index b7ce325df4..96772c9b0a 100644
--- a/src/calibre/gui2/store/stores/amazon_plugin.py
+++ b/src/calibre/gui2/store/stores/amazon_plugin.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 store_version = 14  # Needed for dynamic plugin loading
 
 from contextlib import closing
diff --git a/src/calibre/gui2/store/stores/amazon_uk_plugin.py b/src/calibre/gui2/store/stores/amazon_uk_plugin.py
index 12fb9064a4..714575f6ea 100644
--- a/src/calibre/gui2/store/stores/amazon_uk_plugin.py
+++ b/src/calibre/gui2/store/stores/amazon_uk_plugin.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 store_version = 15  # Needed for dynamic plugin loading
 
 from contextlib import closing
diff --git a/src/calibre/gui2/store/stores/chitanka_plugin.py b/src/calibre/gui2/store/stores/chitanka_plugin.py
index 4eecf87f9c..32a4f5099a 100644
--- a/src/calibre/gui2/store/stores/chitanka_plugin.py
+++ b/src/calibre/gui2/store/stores/chitanka_plugin.py
@@ -80,7 +80,7 @@ class ChitankaStore(BasicStoreConfig, StorePlugin):
                     s.downloads['TXT'] = base_url + ''.join(data.xpath('.//a[@class="dl dl-txt"]/@href')).strip().replace('.zip', '')
                     s.formats = 'FB2, EPUB, TXT, SFB'
                     yield s
-        except urllib2.HTTPError, e:
+        except urllib2.HTTPError as e:
             if e.code == 404:
                 return
             else:
diff --git a/src/calibre/gui2/tag_browser/model.py b/src/calibre/gui2/tag_browser/model.py
index cb7d3667c8..f7efebac1e 100644
--- a/src/calibre/gui2/tag_browser/model.py
+++ b/src/calibre/gui2/tag_browser/model.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 from future_builtins import map
 
 __license__   = 'GPL v3'
diff --git a/src/calibre/gui2/tweak_book/completion/worker.py b/src/calibre/gui2/tweak_book/completion/worker.py
index 4fb0c966aa..bbefa174c5 100644
--- a/src/calibre/gui2/tweak_book/completion/worker.py
+++ b/src/calibre/gui2/tweak_book/completion/worker.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=utf-8
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__ = 'GPL v3'
 __copyright__ = '2014, Kovid Goyal '
diff --git a/src/calibre/gui2/tweak_book/diff/view.py b/src/calibre/gui2/tweak_book/diff/view.py
index 64de1fa5a8..f7e684c1fa 100644
--- a/src/calibre/gui2/tweak_book/diff/view.py
+++ b/src/calibre/gui2/tweak_book/diff/view.py
@@ -381,7 +381,7 @@ class TextBrowser(PlainTextEdit):  # {{{
         PlainTextEdit.paintEvent(self, event)
         painter = QPainter(self.viewport())
         painter.setClipRect(event.rect())
-        for top, bottom, kind in sorted(lines, key=lambda (t, b, k):{'replace':0}.get(k, 1)):
+        for top, bottom, kind in sorted(lines, key=lambda t_b_k:{'replace':0}.get(t_b_k[2], 1)):
             painter.setPen(QPen(self.diff_foregrounds[kind], 1))
             painter.drawLine(0, top, w, top)
             painter.drawLine(0, bottom - 1, w, bottom - 1)
diff --git a/src/calibre/gui2/tweak_book/download.py b/src/calibre/gui2/tweak_book/download.py
index 8a8b405e19..7543316ea0 100644
--- a/src/calibre/gui2/tweak_book/download.py
+++ b/src/calibre/gui2/tweak_book/download.py
@@ -4,6 +4,7 @@
 
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 from threading import Thread
 
 from PyQt5.Qt import (
diff --git a/src/calibre/gui2/tweak_book/editor/snippets.py b/src/calibre/gui2/tweak_book/editor/snippets.py
index da4bd07687..0d0f710f40 100644
--- a/src/calibre/gui2/tweak_book/editor/snippets.py
+++ b/src/calibre/gui2/tweak_book/editor/snippets.py
@@ -176,7 +176,7 @@ def snippets(refresh=False):
             if snip['trigger'] and isinstance(snip['trigger'], type('')):
                 key = snip_key(snip['trigger'], *snip['syntaxes'])
                 _snippets[key] = {'template':snip['template'], 'description':snip['description']}
-        _snippets = sorted(_snippets.iteritems(), key=(lambda (key, snip):string_length(key.trigger)), reverse=True)
+        _snippets = sorted(_snippets.iteritems(), key=(lambda key_snip:string_length(key_snip[0].trigger)), reverse=True)
     return _snippets
 
 # Editor integration {{{
diff --git a/src/calibre/gui2/tweak_book/editor/syntax/base.py b/src/calibre/gui2/tweak_book/editor/syntax/base.py
index 70eca80c85..d1ecc3d7ec 100644
--- a/src/calibre/gui2/tweak_book/editor/syntax/base.py
+++ b/src/calibre/gui2/tweak_book/editor/syntax/base.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=utf-8
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__ = 'GPL v3'
 __copyright__ = '2013, Kovid Goyal '
@@ -38,7 +39,7 @@ def run_loop(user_data, state_map, formats, text):
                 i += num
         if orig_i == i and state.parse in seen_states[i]:
             # Something went wrong in the syntax highlighter
-            print ('Syntax highlighter returned a zero length format, parse state:', state.parse)
+            print('Syntax highlighter returned a zero length format, parse state:', state.parse)
             break
 
 
diff --git a/src/calibre/gui2/tweak_book/editor/syntax/html.py b/src/calibre/gui2/tweak_book/editor/syntax/html.py
index 900297bbc9..a4774bfafc 100644
--- a/src/calibre/gui2/tweak_book/editor/syntax/html.py
+++ b/src/calibre/gui2/tweak_book/editor/syntax/html.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=utf-8
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__ = 'GPL v3'
 __copyright__ = '2013, Kovid Goyal '
@@ -615,10 +616,10 @@ def profile():
     h.set_document(doc)
     h.join()
     import cProfile
-    print ('Running profile on', sys.argv[-2])
+    print('Running profile on', sys.argv[-2])
     h.rehighlight()
     cProfile.runctx('h.join()', {}, {'h':h}, sys.argv[-1])
-    print ('Stats saved to:', sys.argv[-1])
+    print('Stats saved to:', sys.argv[-1])
     del h
     del doc
     del app
diff --git a/src/calibre/gui2/tweak_book/function_replace.py b/src/calibre/gui2/tweak_book/function_replace.py
index 0a9741d8c9..0aad311d26 100644
--- a/src/calibre/gui2/tweak_book/function_replace.py
+++ b/src/calibre/gui2/tweak_book/function_replace.py
@@ -41,7 +41,7 @@ def compile_code(src, name=''):
     code = compile(src, name, 'exec')
 
     namespace = {}
-    exec code in namespace
+    exec(code, namespace)
     return namespace
 
 
diff --git a/src/calibre/gui2/tweak_book/reports.py b/src/calibre/gui2/tweak_book/reports.py
index 05dfc9f019..5d70291f46 100644
--- a/src/calibre/gui2/tweak_book/reports.py
+++ b/src/calibre/gui2/tweak_book/reports.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=utf-8
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__ = 'GPL v3'
 __copyright__ = '2015, Kovid Goyal '
diff --git a/src/calibre/gui2/tweak_book/widgets.py b/src/calibre/gui2/tweak_book/widgets.py
index 550630a6e6..637c2742bc 100644
--- a/src/calibre/gui2/tweak_book/widgets.py
+++ b/src/calibre/gui2/tweak_book/widgets.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=utf-8
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__ = 'GPL v3'
 __copyright__ = '2014, Kovid Goyal '
@@ -729,7 +730,7 @@ class InsertLink(Dialog):
         c = get_container(sys.argv[-1], tweak_mode=True)
         d = cls(c, next(c.spine_names)[0])
         if d.exec_() == d.Accepted:
-            print (d.href, d.text)
+            print(d.href, d.text)
 
 # }}}
 
diff --git a/src/calibre/gui2/ui.py b/src/calibre/gui2/ui.py
index 8cd9449c07..0d58a3ce84 100644
--- a/src/calibre/gui2/ui.py
+++ b/src/calibre/gui2/ui.py
@@ -1,6 +1,7 @@
 #!/usr/bin/env python2
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 from __future__ import with_statement
+from __future__ import print_function
 
 __license__   = 'GPL v3'
 __copyright__ = '2009, Kovid Goyal '
@@ -664,7 +665,7 @@ class Main(MainWindow, MainWindowMixin, DeviceMixin, EmailMixin,  # {{{
                 import traceback
                 traceback.print_exc()
         else:
-            print msg
+            print(msg)
 
     def current_view(self):
         '''Convenience method that returns the currently visible view '''
diff --git a/src/calibre/gui2/viewer/config.py b/src/calibre/gui2/viewer/config.py
index 4dcddbdd75..1cb8c33385 100644
--- a/src/calibre/gui2/viewer/config.py
+++ b/src/calibre/gui2/viewer/config.py
@@ -242,7 +242,7 @@ class ConfigDialog(QDialog, Ui_Dialog):
 
         def fset(self, wl):
             self.dictionary_list.clear()
-            for langcode, url in sorted(wl.iteritems(), key=lambda (lc, url):sort_key(calibre_langcode_to_name(lc))):
+            for langcode, url in sorted(wl.iteritems(), key=lambda lc_url:sort_key(calibre_langcode_to_name(lc_url[0]))):
                 i = QListWidgetItem('%s: %s' % (calibre_langcode_to_name(langcode), url), self.dictionary_list)
                 i.setData(Qt.UserRole, (langcode, url))
         return property(fget=fget, fset=fset)
diff --git a/src/calibre/gui2/viewer/javascript.py b/src/calibre/gui2/viewer/javascript.py
index 1bc617d8b9..1a2afd50fe 100644
--- a/src/calibre/gui2/viewer/javascript.py
+++ b/src/calibre/gui2/viewer/javascript.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__   = 'GPL v3'
 __copyright__ = '2012, Kovid Goyal '
diff --git a/src/calibre/gui2/viewer/main.py b/src/calibre/gui2/viewer/main.py
index 2eb70877e2..44e703f7a4 100644
--- a/src/calibre/gui2/viewer/main.py
+++ b/src/calibre/gui2/viewer/main.py
@@ -3,6 +3,7 @@
 # License: GPLv3 Copyright: 2015, Kovid Goyal 
 
 import functools
+from __future__ import print_function
 import os
 import sys
 import traceback
diff --git a/src/calibre/gui2/viewer/position.py b/src/calibre/gui2/viewer/position.py
index 8e02683805..c9541b28c2 100644
--- a/src/calibre/gui2/viewer/position.py
+++ b/src/calibre/gui2/viewer/position.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__   = 'GPL v3'
 __copyright__ = '2012, Kovid Goyal '
diff --git a/src/calibre/gui2/widgets.py b/src/calibre/gui2/widgets.py
index f1fbe48207..e99cd3e99b 100644
--- a/src/calibre/gui2/widgets.py
+++ b/src/calibre/gui2/widgets.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
 __license__   = 'GPL v3'
 __copyright__ = '2008, Kovid Goyal '
 '''
@@ -1126,8 +1127,8 @@ class Splitter(QSplitter):
 
     def print_sizes(self):
         if self.count() > 1:
-            print self.save_name, 'side:', self.side_index_size, 'other:',
-            print list(self.sizes())[self.other_index]
+            print(self.save_name, 'side:', self.side_index_size, 'other:', end=' ')
+            print(list(self.sizes())[self.other_index])
 
     @dynamic_property
     def side_index_size(self):
diff --git a/src/calibre/gui2/wizard/__init__.py b/src/calibre/gui2/wizard/__init__.py
index e8ba68abc2..6b854bbda2 100644
--- a/src/calibre/gui2/wizard/__init__.py
+++ b/src/calibre/gui2/wizard/__init__.py
@@ -685,7 +685,7 @@ class LibraryPage(QWizardPage, LibraryUI):
     def change_language(self, idx):
         prefs['language'] = str(self.language.itemData(self.language.currentIndex()) or '')
         import __builtin__
-        __builtin__.__dict__['_'] = lambda(x): x
+        __builtin__.__dict__['_'] = lambda x: x
         from calibre.utils.localization import set_translators
         from calibre.gui2 import qt_app
         from calibre.ebooks.metadata.book.base import reset_field_metadata
diff --git a/src/calibre/library/__init__.py b/src/calibre/library/__init__.py
index 2cef575283..58f07ca924 100644
--- a/src/calibre/library/__init__.py
+++ b/src/calibre/library/__init__.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
 __license__   = 'GPL v3'
 __copyright__ = '2008, Kovid Goyal '
 ''' Code to manage ebook library'''
@@ -34,20 +35,20 @@ def generate_test_db(library_path,  # {{{
                 xrange(length))
 
     all_tags = [randstr(tag_length) for j in xrange(num_of_tags)]
-    print 'Generated', num_of_tags, 'tags'
+    print('Generated', num_of_tags, 'tags')
     all_authors = [randstr(author_length) for j in xrange(num_of_authors)]
-    print 'Generated', num_of_authors, 'authors'
+    print('Generated', num_of_authors, 'authors')
     all_titles = [randstr(title_length) for j in xrange(num_of_records)]
-    print 'Generated', num_of_records, 'titles'
+    print('Generated', num_of_records, 'titles')
 
     testdb = db(library_path)
 
-    print 'Creating', num_of_records, 'records...'
+    print('Creating', num_of_records, 'records...')
 
     start = time.time()
 
     for i, title in enumerate(all_titles):
-        print i+1,
+        print(i+1, end=' ')
         sys.stdout.flush()
         authors = random.randint(1, max_authors)
         authors = [random.choice(all_authors) for i in xrange(authors)]
@@ -59,8 +60,8 @@ def generate_test_db(library_path,  # {{{
         testdb.import_book(mi, [])
 
     t = time.time() - start
-    print '\nGenerated', num_of_records, 'records in:', t, 'seconds'
-    print 'Time per record:', t/float(num_of_records)
+    print('\nGenerated', num_of_records, 'records in:', t, 'seconds')
+    print('Time per record:', t/float(num_of_records))
 # }}}
 
 
diff --git a/src/calibre/library/catalogs/epub_mobi.py b/src/calibre/library/catalogs/epub_mobi.py
index 2dbba57782..4c0d8d5871 100644
--- a/src/calibre/library/catalogs/epub_mobi.py
+++ b/src/calibre/library/catalogs/epub_mobi.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 from __future__ import (unicode_literals, division, absolute_import,
                         print_function)
+from __future__ import print_function
 
 __license__ = 'GPL v3'
 __copyright__ = '2012, Kovid Goyal '
@@ -408,7 +409,7 @@ class EPUB_MOBI(CatalogPlugin):
             if opts.verbose:
                 log.info(" Completed catalog source generation (%s)\n"  %
                          str(datetime.timedelta(seconds=int(time.time() - opts.start_time))))
-        except (AuthorSortMismatchException, EmptyCatalogException), e:
+        except (AuthorSortMismatchException, EmptyCatalogException) as e:
             log.error(" *** Terminated catalog generation: %s ***" % e)
         except:
             log.error(" unhandled exception in catalog generator")
diff --git a/src/calibre/library/catalogs/epub_mobi_builder.py b/src/calibre/library/catalogs/epub_mobi_builder.py
index 95a92d5ea6..b1a4b85a9b 100644
--- a/src/calibre/library/catalogs/epub_mobi_builder.py
+++ b/src/calibre/library/catalogs/epub_mobi_builder.py
@@ -1,6 +1,7 @@
 # -*- coding: utf-8 -*-
 
 __license__ = 'GPL v3'
+from __future__ import print_function
 __copyright__ = '2010, Greg Riker'
 
 import datetime, os, platform, re, shutil, time, unicodedata, zlib
@@ -4255,7 +4256,7 @@ class CatalogBuilder(object):
             else:
                 return _short_description(description, self.opts.description_clip)
         else:
-            print " returning description with unspecified destination '%s'" % description
+            print(" returning description with unspecified destination '%s'" % description)
             raise RuntimeError
 
     def generate_sort_title(self, title):
diff --git a/src/calibre/library/catalogs/utils.py b/src/calibre/library/catalogs/utils.py
index acb4fd0027..bf36063f15 100644
--- a/src/calibre/library/catalogs/utils.py
+++ b/src/calibre/library/catalogs/utils.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 
 __license__   = 'GPL v3'
+from __future__ import print_function
 __copyright__ = '2010, Greg Riker'
 __docformat__ = 'restructuredtext en'
 
@@ -186,7 +187,7 @@ class NumberToText(object):  # {{{
                 thousandsNumber = (number - (millionsNumber * 10**6))/10**3
                 hundredsNumber  = number - (millionsNumber * 10**6) - (thousandsNumber * 10**3)
                 if self.verbose:
-                    print "Converting %s %s %s" % (millionsNumber, thousandsNumber, hundredsNumber)
+                    print("Converting %s %s %s" % (millionsNumber, thousandsNumber, hundredsNumber))
 
                 # Convert hundredsNumber
                 if hundredsNumber :
diff --git a/src/calibre/library/comments.py b/src/calibre/library/comments.py
index 9c143319c5..45a57b76ae 100644
--- a/src/calibre/library/comments.py
+++ b/src/calibre/library/comments.py
@@ -2,6 +2,7 @@
 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
 
 __license__   = 'GPL v3'
+from __future__ import print_function
 __copyright__ = '2010, Kovid Goyal '
 __docformat__ = 'restructuredtext en'
 
@@ -160,12 +161,12 @@ def test():
             ('a b&c\nf', '

a b&c;
f

'), ('a b\n\ncd', '

a b

cd

'), ]: - print - print 'Testing: %r'%pat + print() + print('Testing: %r'%pat) cval = comments_to_html(pat) - print 'Value: %r'%cval + print('Value: %r'%cval) if comments_to_html(pat) != val: - print 'FAILED' + print('FAILED') break diff --git a/src/calibre/library/database.py b/src/calibre/library/database.py index 787269940c..af860fbb14 100644 --- a/src/calibre/library/database.py +++ b/src/calibre/library/database.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' ''' @@ -809,7 +810,7 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE; if func is None: break if self.user_version == i: - print 'Upgrading database from version: %d'%i + print('Upgrading database from version: %d'%i) func(self.conn) def close(self): diff --git a/src/calibre/library/save_to_disk.py b/src/calibre/library/save_to_disk.py index 555ecac27c..d9bad8edea 100644 --- a/src/calibre/library/save_to_disk.py +++ b/src/calibre/library/save_to_disk.py @@ -282,7 +282,7 @@ def get_path_components(opts, mi, book_id, path_length): to_lowercase=opts.to_lowercase, replace_whitespace=opts.replace_whitespace, safe_format=False, last_has_extension=False, single_dir=opts.single_dir) - except Exception, e: + except Exception as e: raise ValueError(_('Failed to calculate path for ' 'save to disk. Template: %(templ)s\n' 'Error: %(err)s')%dict(templ=opts.template, err=e)) diff --git a/src/calibre/library/schema_upgrades.py b/src/calibre/library/schema_upgrades.py index 644ed9b55b..dca844273e 100644 --- a/src/calibre/library/schema_upgrades.py +++ b/src/calibre/library/schema_upgrades.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal ' @@ -21,7 +22,7 @@ class SchemaUpgrade(object): if meth is None: break else: - print 'Upgrading database to version %d...'%(uv+1) + print('Upgrading database to version %d...'%(uv+1)) meth() self.user_version = uv+1 diff --git a/src/calibre/library/sqlite.py b/src/calibre/library/sqlite.py index b53f1c9a8d..d615b8abbf 100644 --- a/src/calibre/library/sqlite.py +++ b/src/calibre/library/sqlite.py @@ -1,4 +1,5 @@ from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' @@ -221,8 +222,8 @@ def load_c_extensions(conn, debug=DEBUG): return True except Exception as e: if debug: - print 'Failed to load high performance sqlite C extension' - print e + print('Failed to load high performance sqlite C extension') + print(e) return False @@ -409,5 +410,5 @@ def connect(dbpath, row_factory=None): def test(): c = sqlite.connect(':memory:') if load_c_extensions(c, True): - print 'Loaded C extension successfully' + print('Loaded C extension successfully') diff --git a/src/calibre/libunzip.py b/src/calibre/libunzip.py index ab58079c4b..cc80f60516 100644 --- a/src/calibre/libunzip.py +++ b/src/calibre/libunzip.py @@ -1,5 +1,6 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' @@ -29,7 +30,7 @@ def update(pathtozip, patterns, filepaths, names, compression=zipfile.ZIP_DEFLAT for pat, fname, new_name in zip(patterns, filepaths, names): if pat.search(name): if verbose: - print 'Updating %s with %s' % (name, fname) + print('Updating %s with %s' % (name, fname)) if new_name is None: z.replace(fname, arcname=name, compress_type=compression) else: diff --git a/src/calibre/linux.py b/src/calibre/linux.py index 841e0b296d..5f56cc0268 100644 --- a/src/calibre/linux.py +++ b/src/calibre/linux.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' @@ -644,12 +645,12 @@ class PostInstall: import traceback tb = '\n\t'.join(traceback.format_exc().splitlines()) self.info('\t'+tb) - print + print() def warning(self, *args, **kwargs): - print '\n'+'_'*20, 'WARNING','_'*20 + print('\n'+'_'*20, 'WARNING','_'*20) prints(*args, **kwargs) - print '_'*50 + print('_'*50) print ('\n') self.warnings.append((args, kwargs)) sys.stdout.flush() @@ -715,7 +716,7 @@ class PostInstall: self.info('\n\nThere were %d warnings\n'%len(self.warnings)) for args, kwargs in self.warnings: self.info('*', *args, **kwargs) - print + print() def create_uninstaller(self): base = self.opts.staging_bindir @@ -753,7 +754,7 @@ class PostInstall: write_completion(bash_comp_dest, zsh) except TypeError as err: if 'resolve_entities' in str(err): - print 'You need python-lxml >= 2.0.5 for calibre' + print('You need python-lxml >= 2.0.5 for calibre') sys.exit(1) raise except EnvironmentError as e: diff --git a/src/calibre/srv/code.py b/src/calibre/srv/code.py index 1f77ebaaba..7c10db898a 100644 --- a/src/calibre/srv/code.py +++ b/src/calibre/srv/code.py @@ -194,7 +194,7 @@ def get_library_init_data(ctx, rd, db, num, sorts, orders, vl): ans['sortable_fields'] = sorted( ((sanitize_sort_field_name(db.field_metadata, k), v) for k, v in sf.iteritems()), - key=lambda (field, name): sort_key(name) + key=lambda field_name: sort_key(field_name[1]) ) ans['field_metadata'] = db.field_metadata.all_metadata() ans['virtual_libraries'] = db._pref('virtual_libraries', {}) diff --git a/src/calibre/srv/http_response.py b/src/calibre/srv/http_response.py index 2c244524d8..cb43b1da85 100644 --- a/src/calibre/srv/http_response.py +++ b/src/calibre/srv/http_response.py @@ -478,7 +478,7 @@ class HTTPConnection(HTTPRequest): if e.log: self.log.warn(e.log) return self.simple_response(e.http_code, msg=e.message or '', close_after_response=e.close_connection, extra_headers=eh) - raise etype, e, tb + raise etype(e).with_traceback(tb) data, output = result output = self.finalize_output(output, data, self.method is HTTP1) diff --git a/src/calibre/srv/metadata.py b/src/calibre/srv/metadata.py index 526a2e4a08..746e2a7c42 100644 --- a/src/calibre/srv/metadata.py +++ b/src/calibre/srv/metadata.py @@ -4,6 +4,7 @@ from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function import os from copy import copy from collections import namedtuple diff --git a/src/calibre/srv/pre_activated.py b/src/calibre/srv/pre_activated.py index 66b1b4161d..62819b7455 100644 --- a/src/calibre/srv/pre_activated.py +++ b/src/calibre/srv/pre_activated.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal ' @@ -61,4 +62,4 @@ if __name__ == '__main__': # /usr/lib/systemd/systemd-activate -l 8081 calibre-debug pre_activated.py # telnet localhost 8081 s = pre_activated_socket() - print (s, s.getsockname()) + print(s, s.getsockname()) diff --git a/src/calibre/startup.py b/src/calibre/startup.py index 48b9d99a87..c18375b6fc 100644 --- a/src/calibre/startup.py +++ b/src/calibre/startup.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' @@ -229,19 +230,19 @@ def test_lopen(): with copen(n, 'w') as f: f.write('one') - print 'O_CREAT tested' + print('O_CREAT tested') with copen(n, 'w+b') as f: f.write('two') with copen(n, 'r') as f: if f.read() == 'two': - print 'O_TRUNC tested' + print('O_TRUNC tested') else: raise Exception('O_TRUNC failed') with copen(n, 'ab') as f: f.write('three') with copen(n, 'r+') as f: if f.read() == 'twothree': - print 'O_APPEND tested' + print('O_APPEND tested') else: raise Exception('O_APPEND failed') with copen(n, 'r+') as f: @@ -249,6 +250,6 @@ def test_lopen(): f.write('xxxxx') f.seek(0) if f.read() == 'twoxxxxx': - print 'O_RANDOM tested' + print('O_RANDOM tested') else: raise Exception('O_RANDOM failed') diff --git a/src/calibre/translations/__init__.py b/src/calibre/translations/__init__.py index 0d21249f3b..7ec2240d14 100644 --- a/src/calibre/translations/__init__.py +++ b/src/calibre/translations/__init__.py @@ -1,3 +1,4 @@ +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' ''' @@ -49,12 +50,12 @@ def import_from_launchpad(url): next = tf.next() continue out = os.path.abspath(os.path.join('.', os.path.basename(po))) - print 'Updating', '%6s'%po, '-->', out + print('Updating', '%6s'%po, '-->', out) open(out, 'wb').write(tf.extractfile(next).read()) next = tf.next() check_for_critical_bugs() path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) - print path + print(path) subprocess.check_call('python setup.py translations'.split(), cwd=path) return 0 @@ -69,8 +70,8 @@ def check_for_critical_bugs(): subprocess.check_call(pofilter) errs = os.listdir('.errors') if errs: - print 'WARNING: Translation errors detected' - print 'See the .errors directory and http://translate.sourceforge.net/wiki/toolkit/using_pofilter' + print('WARNING: Translation errors detected') + print('See the .errors directory and http://translate.sourceforge.net/wiki/toolkit/using_pofilter') if __name__ == '__main__': import sys diff --git a/src/calibre/translations/msgfmt.py b/src/calibre/translations/msgfmt.py index da6b4ba964..0c7ed120a9 100644 --- a/src/calibre/translations/msgfmt.py +++ b/src/calibre/translations/msgfmt.py @@ -23,6 +23,7 @@ Options: --version Display version information and exit. """ +from __future__ import print_function import sys import os @@ -37,9 +38,9 @@ STATS = {'translated': 0, 'untranslated': 0} def usage(code, msg=''): - print >> sys.stderr, __doc__ + print(__doc__, file=sys.stderr) if msg: - print >> sys.stderr, msg + print(msg, file=sys.stderr) sys.exit(code) @@ -85,7 +86,7 @@ def generate(): voffsets += [l2, o2+valuestart] offsets = koffsets + voffsets output = struct.pack("Iiiiiii", - 0x950412deL, # Magic + 0x950412de, # Magic 0, # Version len(keys), # # of entries 7*4, # start of key index @@ -111,8 +112,8 @@ def make(filename, outfile): try: lines = open(infile).readlines() - except IOError, msg: - print >> sys.stderr, msg + except IOError as msg: + print(msg, file=sys.stderr) sys.exit(1) section = None @@ -145,8 +146,8 @@ def make(filename, outfile): # This is a message with plural forms elif l.startswith('msgid_plural'): if section != ID: - print >> sys.stderr, 'msgid_plural not preceeded by msgid on %s:%d' %\ - (infile, lno) + print('msgid_plural not preceeded by msgid on %s:%d' %\ + (infile, lno), file=sys.stderr) sys.exit(1) l = l[12:] msgid += '\0' # separator of singular and plural @@ -156,16 +157,16 @@ def make(filename, outfile): section = STR if l.startswith('msgstr['): if not is_plural: - print >> sys.stderr, 'plural without msgid_plural on %s:%d' %\ - (infile, lno) + print('plural without msgid_plural on %s:%d' %\ + (infile, lno), file=sys.stderr) sys.exit(1) l = l.split(']', 1)[1] if msgstr: msgstr += '\0' # Separator of the various plural forms else: if is_plural: - print >> sys.stderr, 'indexed msgstr required for plural on %s:%d' %\ - (infile, lno) + print('indexed msgstr required for plural on %s:%d' %\ + (infile, lno), file=sys.stderr) sys.exit(1) l = l[6:] # Skip empty lines @@ -179,9 +180,9 @@ def make(filename, outfile): elif section == STR: msgstr += l else: - print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \ - 'before:' - print >> sys.stderr, l + print('Syntax error on %s:%d' % (infile, lno), \ + 'before:', file=sys.stderr) + print(l, file=sys.stderr) sys.exit(1) # Add last entry if section == STR: @@ -201,7 +202,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hVso:', ['help', 'version', 'statistics', 'output-file=']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) outfile = None @@ -211,7 +212,7 @@ def main(): if opt in ('-h', '--help'): usage(0) elif opt in ('-V', '--version'): - print >> sys.stderr, "msgfmt.py", __version__ + print("msgfmt.py", __version__, file=sys.stderr) sys.exit(0) elif opt in ('-o', '--output-file'): outfile = arg @@ -219,15 +220,15 @@ def main(): output_stats = True # do it if not args: - print >> sys.stderr, 'No input file given' - print >> sys.stderr, "Try `msgfmt --help' for more information." + print('No input file given', file=sys.stderr) + print("Try `msgfmt --help' for more information.", file=sys.stderr) return for filename in args: STATS['translated'] = STATS['untranslated'] = 0 make(filename, outfile) if output_stats: - print STATS['translated'], 'translated messages,', STATS['untranslated'], 'untranslated messages.' + print(STATS['translated'], 'translated messages,', STATS['untranslated'], 'untranslated messages.') if __name__ == '__main__': diff --git a/src/calibre/utils/Zeroconf.py b/src/calibre/utils/Zeroconf.py index 60192897a9..c03ce0f163 100755 --- a/src/calibre/utils/Zeroconf.py +++ b/src/calibre/utils/Zeroconf.py @@ -74,6 +74,7 @@ added __ne__ adjuncts where required ensure names end in '.local.' timeout on receiving socket for clean shutdown""" +from __future__ import print_function __author__ = "Paul Scott-Murphy" __email__ = "paul at scott dash murphy dot com" @@ -1627,21 +1628,21 @@ class Zeroconf(object): # query (for Zoe), and service unregistration. if __name__ == '__main__': - print "Multicast DNS Service Discovery for Python, version", __version__ + print("Multicast DNS Service Discovery for Python, version", __version__) r = Zeroconf() - print "1. Testing registration of a service..." + print("1. Testing registration of a service...") desc = {'version':'0.10','a':'test value', 'b':'another value'} info = ServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local.", socket.inet_aton("127.0.0.1"), 1234, 0, 0, desc) - print " Registering service..." + print(" Registering service...") r.registerService(info) - print " Registration done." - print "2. Testing query of service information..." - print " Getting ZOE service:", str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local.")) - print " Query done." - print "3. Testing query of own service..." - print " Getting self:", str(r.getServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local.")) - print " Query done." - print "4. Testing unregister of service information..." + print(" Registration done.") + print("2. Testing query of service information...") + print(" Getting ZOE service:", str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local."))) + print(" Query done.") + print("3. Testing query of own service...") + print(" Getting self:", str(r.getServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local."))) + print(" Query done.") + print("4. Testing unregister of service information...") r.unregisterService(info) - print " Unregister done." + print(" Unregister done.") r.close() diff --git a/src/calibre/utils/chm/chm.py b/src/calibre/utils/chm/chm.py index e317144d94..a7fa8dc8fc 100644 --- a/src/calibre/utils/chm/chm.py +++ b/src/calibre/utils/chm/chm.py @@ -254,7 +254,7 @@ class CHMFile: sys.stderr.write('GetArchiveInfo: #SYSTEM does not exist\n') return 0 - size, text = chmlib.chm_retrieve_object(self.file, ui, 4l, ui.length) + size, text = chmlib.chm_retrieve_object(self.file, ui, 4, ui.length) if (size == 0): sys.stderr.write('GetArchiveInfo: file size = 0\n') return 0 @@ -337,7 +337,7 @@ class CHMFile: if (res != chmlib.CHM_RESOLVE_SUCCESS): return None - size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) + size, text = chmlib.chm_retrieve_object(self.file, ui, 0, ui.length) if (size == 0): sys.stderr.write('GetTopicsTree: file size = 0\n') return None @@ -356,7 +356,7 @@ class CHMFile: if (res != chmlib.CHM_RESOLVE_SUCCESS): return None - size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) + size, text = chmlib.chm_retrieve_object(self.file, ui, 0, ui.length) if (size == 0): sys.stderr.write('GetIndex: file size = 0\n') return None @@ -388,7 +388,7 @@ class CHMFile: else: len = length if start == -1: - st = 0l + st = 0 else: st = long(start) return chmlib.chm_retrieve_object(self.file, ui, st, len) @@ -478,7 +478,7 @@ class CHMFile: if (result != chmlib.CHM_RESOLVE_SUCCESS): return -1 - size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, 8) + size, text = chmlib.chm_retrieve_object(self.file, ui, 0, 8) if (size < 8): return -2 @@ -489,7 +489,7 @@ class CHMFile: if num_entries < 1: return -3 - size, text = chmlib.chm_retrieve_object(self.file, ui, 8l, entry_size) + size, text = chmlib.chm_retrieve_object(self.file, ui, 8, entry_size) if (size < entry_size): return -4 @@ -502,7 +502,7 @@ class CHMFile: if (result != chmlib.CHM_RESOLVE_SUCCESS): return -5 - size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) + size, text = chmlib.chm_retrieve_object(self.file, ui, 0, ui.length) if (size == 0): return -6 diff --git a/src/calibre/utils/config.py b/src/calibre/utils/config.py index de759bcb08..2ab5276bf3 100644 --- a/src/calibre/utils/config.py +++ b/src/calibre/utils/config.py @@ -1,4 +1,5 @@ from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' @@ -221,7 +222,7 @@ class DynamicConfig(dict): except SystemError: pass except: - print 'WARNING: Failed to unpickle stored config object, ignoring' + print('WARNING: Failed to unpickle stored config object, ignoring') if DEBUG: import traceback traceback.print_exc() diff --git a/src/calibre/utils/config_base.py b/src/calibre/utils/config_base.py index cfd4a85dc6..112f08dd7d 100644 --- a/src/calibre/utils/config_base.py +++ b/src/calibre/utils/config_base.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2011, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -200,10 +201,10 @@ class OptionSet(object): if not isinstance(src, unicode): src = src.decode('utf-8') src = src.replace(u'PyQt%d.QtCore' % 4, u'PyQt5.QtCore') - exec src in options + exec(src, options) except: - print 'Failed to parse options string:' - print repr(src) + print('Failed to parse options string:') + print(repr(src)) traceback.print_exc() opts = OptionValues() for pref in self.preferences: @@ -282,7 +283,7 @@ class Config(ConfigInterface): try: src = f.read().decode('utf-8') except ValueError: - print "Failed to parse", self.config_file_path + print("Failed to parse", self.config_file_path) traceback.print_exc() return self.option_set.parse_string(src) @@ -470,13 +471,13 @@ def read_tweaks(): default_tweaks, tweaks = read_raw_tweaks() l, g = {}, {} try: - exec tweaks in g, l + exec(tweaks, g, l) except: import traceback - print 'Failed to load custom tweaks file' + print('Failed to load custom tweaks file') traceback.print_exc() dl, dg = {}, {} - exec default_tweaks in dg, dl + exec(default_tweaks, dg, dl) dl.update(l) return dl @@ -495,7 +496,7 @@ def reset_tweaks_to_default(): default_tweaks = P('default_tweaks.py', data=True, allow_user_override=False) dl, dg = {}, {} - exec default_tweaks in dg, dl + exec(default_tweaks, dg, dl) tweaks.clear() tweaks.update(dl) diff --git a/src/calibre/utils/fonts/sfnt/loca.py b/src/calibre/utils/fonts/sfnt/loca.py index 05426be921..bff74d018a 100644 --- a/src/calibre/utils/fonts/sfnt/loca.py +++ b/src/calibre/utils/fonts/sfnt/loca.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' @@ -62,6 +63,6 @@ class LocaTable(UnknownTable): for i in xrange(len(self.offset_map)-1): off, noff = self.offset_map[i], self.offset_map[i+1] if noff != off: - print ('Glyph id:', i, 'size:', noff-off) + print('Glyph id:', i, 'size:', noff-off) diff --git a/src/calibre/utils/fonts/sfnt/metrics.py b/src/calibre/utils/fonts/sfnt/metrics.py index 892617b9b6..97e5718d1b 100644 --- a/src/calibre/utils/fonts/sfnt/metrics.py +++ b/src/calibre/utils/fonts/sfnt/metrics.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' @@ -120,11 +121,11 @@ if __name__ == '__main__': raw = f.read() sfnt = Sfnt(raw) m = FontMetrics(sfnt) - print ('Ascent:', m.pdf_ascent) - print ('Descent:', m.pdf_descent) - print ('PDF BBox:', m.pdf_bbox) - print ('CapHeight:', m.pdf_capheight) - print ('AvgWidth:', m.pdf_avg_width) - print ('ItalicAngle', m.post.italic_angle) - print ('StemV', m.pdf_stemv) + print('Ascent:', m.pdf_ascent) + print('Descent:', m.pdf_descent) + print('PDF BBox:', m.pdf_bbox) + print('CapHeight:', m.pdf_capheight) + print('AvgWidth:', m.pdf_avg_width) + print('ItalicAngle', m.post.italic_angle) + print('StemV', m.pdf_stemv) diff --git a/src/calibre/utils/fonts/utils.py b/src/calibre/utils/fonts/utils.py index e28660cbc2..91200d6bf4 100644 --- a/src/calibre/utils/fonts/utils.py +++ b/src/calibre/utils/fonts/utils.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' @@ -472,10 +473,10 @@ def test_find_font(): from calibre.utils.fonts.scanner import font_scanner abcd = '诶比西迪' family = font_scanner.find_font_for_text(abcd)[0] - print ('Family for Chinese text:', family) + print('Family for Chinese text:', family) family = font_scanner.find_font_for_text(abcd)[0] abcd = 'لوحة المفاتيح العربية' - print ('Family for Arabic text:', family) + print('Family for Arabic text:', family) def test(): diff --git a/src/calibre/utils/fonts/win_fonts.py b/src/calibre/utils/fonts/win_fonts.py index eec6118e6f..0329192f6c 100644 --- a/src/calibre/utils/fonts/win_fonts.py +++ b/src/calibre/utils/fonts/win_fonts.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/utils/formatter_functions.py b/src/calibre/utils/formatter_functions.py index acbfc96d68..5a3832d379 100644 --- a/src/calibre/utils/formatter_functions.py +++ b/src/calibre/utils/formatter_functions.py @@ -6,6 +6,7 @@ Created on 13 Jan 2011 @author: charles ''' +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal ' @@ -345,7 +346,7 @@ class BuiltinPrint(BuiltinFormatterFunction): 'the output will go to a black hole.') def evaluate(self, formatter, kwargs, mi, locals, *args): - print args + print(args) return '' @@ -1652,8 +1653,8 @@ class UserFunction(FormatterUserFunction): ''' + func locals_ = {} if DEBUG and tweaks.get('enable_template_debug_printing', False): - print prog - exec prog in locals_ + print(prog) + exec(prog, locals_) cls = locals_['UserFunction'](name, doc, arg_count, eval_func) return cls diff --git a/src/calibre/utils/https.py b/src/calibre/utils/https.py index ee7e670c08..7a5a4080e3 100644 --- a/src/calibre/utils/https.py +++ b/src/calibre/utils/https.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal ' diff --git a/src/calibre/utils/icu.py b/src/calibre/utils/icu.py index c91b5a6689..a2b0dc0112 100644 --- a/src/calibre/utils/icu.py +++ b/src/calibre/utils/icu.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal ' @@ -187,7 +188,7 @@ def _make_func(template, name, **kwargs): l = globals() kwargs['name'] = name kwargs['func'] = kwargs.get('func', 'sort_key') - exec template.format(**kwargs) in l + exec(template.format(**kwargs), l) return l[name] diff --git a/src/calibre/utils/inotify.py b/src/calibre/utils/inotify.py index 3d4294de72..ed974a4346 100644 --- a/src/calibre/utils/inotify.py +++ b/src/calibre/utils/inotify.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __copyright__ = '2013, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -323,12 +324,12 @@ class INotifyTreeWatcher(INotify): if __name__ == '__main__': w = INotifyTreeWatcher(sys.argv[-1]) w() - print ('Monitoring', sys.argv[-1], 'press Ctrl-C to stop') + print('Monitoring', sys.argv[-1], 'press Ctrl-C to stop') try: while w.wait(): modified = w() for path in modified: - print (path or sys.argv[-1], 'changed') + print(path or sys.argv[-1], 'changed') raise SystemExit('inotify flaked out') except KeyboardInterrupt: pass diff --git a/src/calibre/utils/ip_routing.py b/src/calibre/utils/ip_routing.py index a6476b1cd2..4665a2dff5 100644 --- a/src/calibre/utils/ip_routing.py +++ b/src/calibre/utils/ip_routing.py @@ -4,6 +4,7 @@ from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function import subprocess, re from calibre.constants import iswindows, isosx diff --git a/src/calibre/utils/ipc/pool.py b/src/calibre/utils/ipc/pool.py index a36de998cd..517f460273 100644 --- a/src/calibre/utils/ipc/pool.py +++ b/src/calibre/utils/ipc/pool.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal ' diff --git a/src/calibre/utils/ipc/server.py b/src/calibre/utils/ipc/server.py index 48463c1c69..176a2e0699 100644 --- a/src/calibre/utils/ipc/server.py +++ b/src/calibre/utils/ipc/server.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -217,7 +218,7 @@ class Server(Thread): if isinstance(cw, basestring): raise CriticalError('Failed to launch worker process:\n'+cw) if DEBUG: - print 'Worker Launch took:', time.time() - start + print('Worker Launch took:', time.time() - start) return cw def do_launch(self, env, gui, redirect_output, rfile, job_name=None): diff --git a/src/calibre/utils/ipc/simple_worker.py b/src/calibre/utils/ipc/simple_worker.py index d754cec621..07095637a0 100644 --- a/src/calibre/utils/ipc/simple_worker.py +++ b/src/calibre/utils/ipc/simple_worker.py @@ -263,7 +263,7 @@ def compile_code(src): namespace = { 'time':time, 're':re, 'os':os, 'io':io, } - exec src in namespace + exec(src, namespace) return namespace diff --git a/src/calibre/utils/ipc/worker.py b/src/calibre/utils/ipc/worker.py index fc56a2c1e8..762e41321d 100644 --- a/src/calibre/utils/ipc/worker.py +++ b/src/calibre/utils/ipc/worker.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -175,7 +176,7 @@ def main(): try: exec (sys.argv[-1]) except Exception: - print 'Failed to run pipe worker with command:', sys.argv[-1] + print('Failed to run pipe worker with command:', sys.argv[-1]) raise return address = cPickle.loads(unhexlify(os.environ['CALIBRE_WORKER_ADDRESS'])) diff --git a/src/calibre/utils/ipython.py b/src/calibre/utils/ipython.py index 4377a2c172..6915dfd198 100644 --- a/src/calibre/utils/ipython.py +++ b/src/calibre/utils/ipython.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal ' diff --git a/src/calibre/utils/iso8601.py b/src/calibre/utils/iso8601.py index 00e6bdfc01..e6d533f7a5 100644 --- a/src/calibre/utils/iso8601.py +++ b/src/calibre/utils/iso8601.py @@ -4,6 +4,7 @@ from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function from datetime import datetime from dateutil.tz import tzlocal, tzutc, tzoffset diff --git a/src/calibre/utils/localization.py b/src/calibre/utils/localization.py index 21e1454443..1cea1e87dc 100644 --- a/src/calibre/utils/localization.py +++ b/src/calibre/utils/localization.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import absolute_import +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' diff --git a/src/calibre/utils/mem.py b/src/calibre/utils/mem.py index 34d5e87c50..e2a10c9c93 100644 --- a/src/calibre/utils/mem.py +++ b/src/calibre/utils/mem.py @@ -2,6 +2,7 @@ # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2010, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -46,6 +47,6 @@ def diff_hists(h1, h2): if k not in h2: h2[k] = 0 if h1[k] != h2[k]: - print "%s: %d -> %d (%s%d)" % ( - k, h1[k], h2[k], h2[k] > h1[k] and "+" or "", h2[k] - h1[k]) + print("%s: %d -> %d (%s%d)" % ( + k, h1[k], h2[k], h2[k] > h1[k] and "+" or "", h2[k] - h1[k])) diff --git a/src/calibre/utils/podofo/__init__.py b/src/calibre/utils/podofo/__init__.py index b30d5079d1..209ad26db4 100644 --- a/src/calibre/utils/podofo/__init__.py +++ b/src/calibre/utils/podofo/__init__.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -149,7 +150,7 @@ def test_outline(src): out = '/tmp/outlined.pdf' with open(out, 'wb') as f: f.write(raw) - print 'Outlined PDF:', out + print('Outlined PDF:', out) def test_save_to(src, dest): @@ -160,7 +161,7 @@ def test_save_to(src, dest): p.load(raw) with open(dest, 'wb') as out: p.save_to_fileobj(out) - print ('Wrote PDF of size:', out.tell()) + print('Wrote PDF of size:', out.tell()) def test_podofo(): diff --git a/src/calibre/utils/resources.py b/src/calibre/utils/resources.py index 97e53308d7..4b2952c92f 100644 --- a/src/calibre/utils/resources.py +++ b/src/calibre/utils/resources.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' diff --git a/src/calibre/utils/search_query_parser.py b/src/calibre/utils/search_query_parser.py index c67a02dcb4..c42bbbaa21 100644 --- a/src/calibre/utils/search_query_parser.py +++ b/src/calibre/utils/search_query_parser.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # encoding: utf-8 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' @@ -309,9 +310,9 @@ class SearchQueryParser(object): prints('\tTesting:', test[0], end=' ') res = parser.parseString(test[0]) if list(res.get(result, None)) == test[1]: - print 'OK' + print('OK') else: - print 'FAILED:', 'Expected:', test[1], 'Got:', list(res.get(result, None)) + print('FAILED:', 'Expected:', test[1], 'Got:', list(res.get(result, None))) failed.append(test[0]) return failed diff --git a/src/calibre/utils/sftp.py b/src/calibre/utils/sftp.py index 0d816af3d0..bd02c211ff 100644 --- a/src/calibre/utils/sftp.py +++ b/src/calibre/utils/sftp.py @@ -1,5 +1,6 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' @@ -26,13 +27,13 @@ def agent_auth(transport, username): return for key in agent_keys: - print 'Trying ssh-agent key %s' % hexlify(key.get_fingerprint()), + print('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()), end=' ') try: transport.auth_publickey(username, key) - print '... success!' + print('... success!') return True except paramiko.SSHException: - print '... failed.' + print('... failed.') return False @@ -78,9 +79,9 @@ def connect_to_url(url, getpw=portable_getpass, mode='r+', bufsize=-1): def main(args=sys.argv): f = connect_to_url(args[1])[-1] - print f.read() + print(f.read()) f.seek(0, 2) - print f.tell() + print(f.tell()) f.close() return 0 diff --git a/src/calibre/utils/shared_file.py b/src/calibre/utils/shared_file.py index f089c9c612..d0dcee82ac 100644 --- a/src/calibre/utils/shared_file.py +++ b/src/calibre/utils/shared_file.py @@ -119,7 +119,7 @@ if iswindows: } def raise_winerror(pywinerr): - raise WindowsError(pywinerr.winerror, (pywinerr.funcname or '') + b': ' + (pywinerr.strerror or '')), None, sys.exc_info()[2] + raise WindowsError(pywinerr.winerror, (pywinerr.funcname or '') + b': ' + (pywinerr.strerror or '')).with_traceback(sys.exc_info()[2]) def os_open(path, flags, mode=0o777, share_flags=FILE_SHARE_VALID_FLAGS): ''' @@ -173,7 +173,7 @@ else: return speedup.fdopen(os.open(path, flags), path, mode, buffering) def raise_winerror(x): - raise NotImplementedError(), None, sys.exc_info()[2] + raise NotImplementedError().with_traceback(sys.exc_info()[2]) def find_tests(): diff --git a/src/calibre/utils/smtp.py b/src/calibre/utils/smtp.py index a29975d52c..d840cc4c37 100644 --- a/src/calibre/utils/smtp.py +++ b/src/calibre/utils/smtp.py @@ -1,4 +1,5 @@ from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL 3' __copyright__ = '2009, Kovid Goyal ' __docformat__ = 'restructuredtext en' @@ -95,7 +96,7 @@ def create_mail(from_, to, subject, text=None, attachment_data=None, def get_mx(host, verbose=0): import dns.resolver if verbose: - print 'Find mail exchanger for', host + print('Find mail exchanger for', host) answers = list(dns.resolver.query(host, 'MX')) answers.sort(cmp=lambda x, y: cmp(int(getattr(x, 'preference', sys.maxint)), int(getattr(y, 'preference', sys.maxint)))) @@ -123,7 +124,7 @@ def sendmail_direct(from_, to, msg, timeout, localhost, verbose, except Exception as e: last_error, last_traceback = e, traceback.format_exc() if last_error is not None: - print last_traceback + print(last_traceback) raise IOError('Failed to send mail: '+repr(last_error)) @@ -302,7 +303,7 @@ def main(args=sys.argv): if outbox is not None: outbox.add(msg) outbox.close() - print 'Delivery failed. Message saved to', opts.outbox + print('Delivery failed. Message saved to', opts.outbox) raise return 0 diff --git a/src/calibre/utils/socket_inheritance.py b/src/calibre/utils/socket_inheritance.py index 4d73045feb..887b4da69b 100644 --- a/src/calibre/utils/socket_inheritance.py +++ b/src/calibre/utils/socket_inheritance.py @@ -11,6 +11,7 @@ Created on 29 Nov 2013 Code taken from https://mail.python.org/pipermail/python-dev/2007-June/073745.html modified to make it work ''' +from __future__ import print_function from calibre.constants import iswindows diff --git a/src/calibre/utils/threadpool.py b/src/calibre/utils/threadpool.py index 2a6109d7ae..73a654ee01 100644 --- a/src/calibre/utils/threadpool.py +++ b/src/calibre/utils/threadpool.py @@ -29,6 +29,7 @@ See the end of the module code for a brief, annotated usage example. Website : http://chrisarndt.de/en/software/python/threadpool/ """ +from __future__ import print_function __all__ = [ 'makeRequests', @@ -287,12 +288,12 @@ if __name__ == '__main__': # this will be called each time a result is available def print_result(request, result): - print "**Result: %s from request #%s" % (result, request.requestID) + print("**Result: %s from request #%s" % (result, request.requestID)) # this will be called when an exception occurs within a thread def handle_exception(request, exc_info): - print "Exception occured in request #%s: %s" % \ - (request.requestID, exc_info[1]) + print("Exception occured in request #%s: %s" % \ + (request.requestID, exc_info[1])) # assemble the arguments for each job to a list... data = [random.randint(1,10) for i in range(20)] @@ -311,7 +312,7 @@ if __name__ == '__main__': # then we put the work requests in the queue... for req in requests: main.putRequest(req) - print "Work request #%s added." % req.requestID + print("Work request #%s added." % req.requestID) # or shorter: # [main.putRequest(req) for req in requests] @@ -325,15 +326,15 @@ if __name__ == '__main__': while 1: try: main.poll() - print "Main thread working..." + print("Main thread working...") time.sleep(0.5) if i == 10: - print "Adding 3 more worker threads..." + print("Adding 3 more worker threads...") main.createWorkers(3) i += 1 except KeyboardInterrupt: - print "Interrupted!" + print("Interrupted!") break except NoResultsPending: - print "All results collected." + print("All results collected.") break diff --git a/src/calibre/utils/wmf/emf.py b/src/calibre/utils/wmf/emf.py index 9ff8cc2a9a..4349abedda 100644 --- a/src/calibre/utils/wmf/emf.py +++ b/src/calibre/utils/wmf/emf.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal ' @@ -50,7 +51,7 @@ class EMF(object): def handle_unknown(self, rtype, size, raw): if self.verbose: - print ('Ignoring unknown record:', RECORD_RMAP.get(rtype, hex(rtype).upper())) + print('Ignoring unknown record:', RECORD_RMAP.get(rtype, hex(rtype).upper())) def handle_header(self, rtype, size, raw): pass diff --git a/src/calibre/utils/zipfile.py b/src/calibre/utils/zipfile.py index 4f72b5115c..74f5ff3cd3 100644 --- a/src/calibre/utils/zipfile.py +++ b/src/calibre/utils/zipfile.py @@ -2,6 +2,7 @@ Read and write ZIP files. Modified by Kovid Goyal to support replacing files in a zip archive, detecting filename encoding, updating zip files, etc. """ +from __future__ import print_function import struct, os, time, sys, shutil, stat, re, io import binascii, cStringIO from contextlib import closing @@ -421,15 +422,15 @@ class ZipInfo (object): idx = 0 # ZIP64 extension (large files and/or large archives) - if self.file_size in (0xffffffffffffffffL, 0xffffffffL): + if self.file_size in (0xffffffffffffffff, 0xffffffff): self.file_size = counts[idx] idx += 1 - if self.compress_size == 0xFFFFFFFFL: + if self.compress_size == 0xFFFFFFFF: self.compress_size = counts[idx] idx += 1 - if self.header_offset == 0xffffffffL: + if self.header_offset == 0xffffffff: self.header_offset = counts[idx] idx+=1 @@ -815,7 +816,7 @@ class ZipFile: if not endrec: raise BadZipfile("File is not a zip file") if self.debug > 1: - print endrec + print(endrec) size_cd = endrec[_ECD_SIZE] # bytes in central directory offset_cd = endrec[_ECD_OFFSET] # offset of central directory self.comment = endrec[_ECD_COMMENT] # archive comment @@ -828,7 +829,7 @@ class ZipFile: if self.debug > 2: inferred = concat + offset_cd - print "given, inferred, offset", offset_cd, inferred, concat + print("given, inferred, offset", offset_cd, inferred, concat) # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) @@ -841,7 +842,7 @@ class ZipFile: raise BadZipfile("Bad magic number for central directory") centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: - print centdir + print(centdir) filename = fp.read(centdir[_CD_FILENAME_LENGTH]) # Create ZipInfo instance to store file information x = ZipInfo(filename) @@ -869,7 +870,7 @@ class ZipFile: centdir[_CD_COMMENT_LENGTH]) if self.debug > 2: - print "total", total + print("total", total) def _calculate_file_offsets(self): for zip_info in self.filelist: @@ -914,7 +915,7 @@ class ZipFile: for i in range(0, len(self.filelist)): if self.filelist[i].filename == name: if self.debug: - print "Removing", name + print("Removing", name) deleted_offset = self.filelist[i].header_offset deleted_size = (self.filelist[i].file_offset - self.filelist[i].header_offset) + self.filelist[i].compress_size zinfo_size = struct.calcsize(structCentralDir) + len(self.filelist[i].filename) + len(self.filelist[i].extra) @@ -943,7 +944,7 @@ class ZipFile: self._didModify = True return if self.debug: - print name, "not in archive" + print(name, "not in archive") def namelist(self): """Return a list of file names in the archive.""" @@ -959,10 +960,10 @@ class ZipFile: def printdir(self): """Print a table of contents for the zip file.""" - print "%-46s %19s %12s" % ("File Name", "Modified ", "Size") + print("%-46s %19s %12s" % ("File Name", "Modified ", "Size")) for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6] - print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size) + print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)) def testzip(self): """Read all the files and check the CRC.""" @@ -1174,7 +1175,7 @@ class ZipFile: """Check for errors before writing a file to the archive.""" if zinfo.filename in self.NameToInfo: if self.debug: # Warning for duplicate names - print "Duplicate name:", zinfo.filename + print("Duplicate name:", zinfo.filename) if self.mode not in ("w", "a"): raise RuntimeError('write() requires mode "w" or "a"') if not self.fp: @@ -1215,7 +1216,7 @@ class ZipFile: if isdir and not arcname.endswith('/'): arcname += '/' zinfo = ZipInfo(arcname, date_time) - zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes + zinfo.external_attr = (st[0] & 0xFFFF) << 16 # Unix attributes if isdir: zinfo.compress_type = ZIP_STORED if compress_type is None: @@ -1278,7 +1279,7 @@ class ZipFile: self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo - def writestr(self, zinfo_or_arcname, bytes, permissions=0600, + def writestr(self, zinfo_or_arcname, bytes, permissions=0o600, compression=ZIP_DEFLATED, raw_bytes=False): """Write a file into the archive. The contents is the string 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or @@ -1329,7 +1330,7 @@ class ZipFile: Add a directory recursively to the zip file with an optional prefix. ''' if prefix: - self.writestr(prefix+'/', '', 0755) + self.writestr(prefix+'/', '', 0o755) cwd = os.path.abspath(os.getcwdu()) try: os.chdir(path) @@ -1376,7 +1377,7 @@ class ZipFile: if zinfo.header_offset > ZIP64_LIMIT: extra.append(zinfo.header_offset) - header_offset = 0xffffffffL + header_offset = 0xffffffff else: header_offset = zinfo.header_offset @@ -1404,14 +1405,14 @@ class ZipFile: 0, zinfo.internal_attr, zinfo.external_attr, header_offset) except DeprecationWarning: - print >>sys.stderr, (structCentralDir, + print((structCentralDir, stringCentralDir, create_version, zinfo.create_system, extract_version, zinfo.reserved, zinfo.flag_bits, zinfo.compress_type, dostime, dosdate, zinfo.CRC, compress_size, file_size, len(zinfo.filename), len(extra_data), len(zinfo.comment), 0, zinfo.internal_attr, zinfo.external_attr, - header_offset) + header_offset), file=sys.stderr) raise self.fp.write(centdir) self.fp.write(filename) @@ -1446,7 +1447,7 @@ class ZipFile: if self.debug > 0: msg = 'Archive comment is too long; truncating to %d bytes' \ % ZIP_MAX_COMMENT - print msg + print(msg) self.comment = self.comment[:ZIP_MAX_COMMENT] endrec = struct.pack(structEndArchive, stringEndArchive, @@ -1539,10 +1540,10 @@ class PyZipFile(ZipFile): else: basename = name if self.debug: - print "Adding package in", pathname, "as", basename + print("Adding package in", pathname, "as", basename) fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: - print "Adding", arcname + print("Adding", arcname) self.write(fname, arcname) dirlist = os.listdir(pathname) dirlist.remove("__init__.py") @@ -1558,12 +1559,12 @@ class PyZipFile(ZipFile): fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: - print "Adding", arcname + print("Adding", arcname) self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: - print "Adding files from directory", pathname + print("Adding files from directory", pathname) for filename in os.listdir(pathname): path = os.path.join(pathname, filename) ext = os.path.splitext(filename)[-1] @@ -1571,7 +1572,7 @@ class PyZipFile(ZipFile): fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: - print "Adding", arcname + print("Adding", arcname) self.write(fname, arcname) else: if pathname[-3:] != ".py": @@ -1579,7 +1580,7 @@ class PyZipFile(ZipFile): 'Files added with writepy() must end with ".py"') fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: - print "Adding file", arcname + print("Adding file", arcname) self.write(fname, arcname) def _get_codename(self, pathname, basename): @@ -1599,11 +1600,11 @@ class PyZipFile(ZipFile): os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime: import py_compile if self.debug: - print "Compiling", file_py + print("Compiling", file_py) try: py_compile.compile(file_py, file_pyc, None, True) - except py_compile.PyCompileError,err: - print err.msg + except py_compile.PyCompileError as err: + print(err.msg) fname = file_pyc else: fname = file_pyc @@ -1626,12 +1627,12 @@ def main(args=None): args = sys.argv[1:] if not args or args[0] not in ('-l', '-c', '-e', '-t'): - print USAGE + print(USAGE) sys.exit(1) if args[0] == '-l': if len(args) != 2: - print USAGE + print(USAGE) sys.exit(1) zf = ZipFile(args[1], 'r') zf.printdir() @@ -1639,17 +1640,17 @@ def main(args=None): elif args[0] == '-t': if len(args) != 2: - print USAGE + print(USAGE) sys.exit(1) zf = ZipFile(args[1], 'r') badfile = zf.testzip() if badfile: print("The following enclosed file is corrupted: {!r}".format(badfile)) - print "Done testing" + print("Done testing") elif args[0] == '-e': if len(args) != 3: - print USAGE + print(USAGE) sys.exit(1) zf = ZipFile(args[1], 'r') @@ -1669,7 +1670,7 @@ def main(args=None): elif args[0] == '-c': if len(args) < 3: - print USAGE + print(USAGE) sys.exit(1) def addToZip(zf, path, zippath): diff --git a/src/calibre/web/feeds/__init__.py b/src/calibre/web/feeds/__init__.py index c01e78d39e..29cdb185bb 100644 --- a/src/calibre/web/feeds/__init__.py +++ b/src/calibre/web/feeds/__init__.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 __license__ = 'GPL v3' +from __future__ import print_function __copyright__ = '2008, Kovid Goyal ' ''' Contains the logic for parsing feeds. @@ -43,8 +44,8 @@ class Article(object): s = html.fragment_fromstring(summary, create_parent=True) summary = html.tostring(s, method='text', encoding=unicode) except: - print 'Failed to process article summary, deleting:' - print summary.encode('utf-8') + print('Failed to process article summary, deleting:') + print(summary.encode('utf-8')) traceback.print_exc() summary = u'' self.text_summary = clean_ascii_chars(summary) @@ -296,8 +297,8 @@ class FeedCollection(list): return x return None - print '#feeds', len(self) - print map(len, self) + print('#feeds', len(self)) + print(map(len, self)) for f in self: dups = [] for a in f: @@ -311,8 +312,8 @@ class FeedCollection(list): f.articles.remove(x) self.duplicates = duplicates - print len(duplicates) - print map(len, self) + print(len(duplicates)) + print(map(len, self)) # raise def find_article(self, article): diff --git a/src/calibre/web/feeds/feedparser.py b/src/calibre/web/feeds/feedparser.py index 16085cf537..66dee74fdb 100755 --- a/src/calibre/web/feeds/feedparser.py +++ b/src/calibre/web/feeds/feedparser.py @@ -324,7 +324,7 @@ class FeedParserDict(dict): try: return dict.__getitem__(self, 'tags')[0]['term'] except IndexError: - raise KeyError, "object doesn't have key 'category'" + raise KeyError("object doesn't have key 'category'") elif key == 'enclosures': norel = lambda link: FeedParserDict([(name,value) for (name,value) in link.items() if name!='rel']) return [norel(link) for link in dict.__getitem__(self, 'links') if link['rel']==u'enclosure'] @@ -405,7 +405,7 @@ class FeedParserDict(dict): try: return self.__getitem__(key) except KeyError: - raise AttributeError, "object has no attribute '%s'" % key + raise AttributeError("object has no attribute '%s'" % key) def __hash__(self): return id(self) @@ -630,7 +630,7 @@ class _FeedParserMixin: # element declared itself as escaped markup, but it isn't really self.contentparams['type'] = u'application/xhtml+xml' if self.incontent and self.contentparams.get('type') == u'application/xhtml+xml': - if tag.find(':') <> -1: + if tag.find(':') != -1: prefix, tag = tag.split(':', 1) namespace = self.namespacesInUse.get(prefix, '') if tag=='math' and namespace=='http://www.w3.org/1998/Math/MathML': @@ -642,7 +642,7 @@ class _FeedParserMixin: return self.handle_data('<%s%s>' % (tag, self.strattrs(attrs)), escape=0) # match namespaces - if tag.find(':') <> -1: + if tag.find(':') != -1: prefix, suffix = tag.split(':', 1) else: prefix, suffix = '', tag @@ -674,7 +674,7 @@ class _FeedParserMixin: def unknown_endtag(self, tag): # match namespaces - if tag.find(':') <> -1: + if tag.find(':') != -1: prefix, suffix = tag.split(':', 1) else: prefix, suffix = '', tag @@ -807,7 +807,7 @@ class _FeedParserMixin: self.version = u'rss10' elif loweruri == 'http://www.w3.org/2005/atom': self.version = u'atom10' - if loweruri.find(u'backend.userland.com/rss') <> -1: + if loweruri.find(u'backend.userland.com/rss') != -1: # match any backend.userland.com namespace uri = u'http://backend.userland.com/rss' loweruri = uri @@ -1038,7 +1038,7 @@ class _FeedParserMixin: def _mapToStandardPrefix(self, name): colonpos = name.find(':') - if colonpos <> -1: + if colonpos != -1: prefix = name[:colonpos] suffix = name[colonpos+1:] prefix = self.namespacemap.get(prefix, prefix) @@ -1780,7 +1780,7 @@ if _XML_AVAILABLE: def startElementNS(self, name, qname, attrs): namespace, localname = name lowernamespace = str(namespace or '').lower() - if lowernamespace.find(u'backend.userland.com/rss') <> -1: + if lowernamespace.find(u'backend.userland.com/rss') != -1: # match any backend.userland.com namespace namespace = u'http://backend.userland.com/rss' lowernamespace = namespace @@ -1790,7 +1790,7 @@ if _XML_AVAILABLE: givenprefix = None prefix = self._matchnamespaces.get(lowernamespace, givenprefix) if givenprefix and (prefix == None or (prefix == '' and lowernamespace == '')) and givenprefix not in self.namespacesInUse: - raise UndeclaredNamespace, "'%s' is not associated with a namespace" % givenprefix + raise UndeclaredNamespace("'%s' is not associated with a namespace" % givenprefix) localname = str(localname).lower() # qname implementation is horribly broken in Python 2.1 (it @@ -2757,7 +2757,7 @@ class _HTMLSanitizer(_BaseHTMLProcessor): # declare xlink namespace, if needed if self.mathmlOK or self.svgOK: - if filter(lambda (n,v): n.startswith('xlink:'),attrs): + if filter(lambda n_v: n_v[0].startswith('xlink:'),attrs): if not ('xmlns:xlink','http://www.w3.org/1999/xlink') in attrs: attrs.append(('xmlns:xlink','http://www.w3.org/1999/xlink')) @@ -3871,7 +3871,7 @@ def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, refer try: f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, request_headers) data = f.read() - except Exception, e: + except Exception as e: result['bozo'] = 1 result['bozo_exception'] = e data = None @@ -3896,7 +3896,7 @@ def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, refer if gzip and 'gzip' in http_headers.get('content-encoding', ''): try: data = gzip.GzipFile(fileobj=_StringIO(data)).read() - except (IOError, struct.error), e: + except (IOError, struct.error) as e: # IOError can occur if the gzip header is bad. # struct.error can occur if the data is damaged. result['bozo'] = 1 @@ -3909,11 +3909,11 @@ def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, refer elif zlib and 'deflate' in http_headers.get('content-encoding', ''): try: data = zlib.decompress(data) - except zlib.error, e: + except zlib.error as e: try: # The data may have no headers and no checksum. data = zlib.decompress(data, -15) - except zlib.error, e: + except zlib.error as e: result['bozo'] = 1 result['bozo_exception'] = e @@ -3986,7 +3986,7 @@ def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, refer source.setByteStream(_StringIO(data)) try: saxparser.parse(source) - except xml.sax.SAXException, e: + except xml.sax.SAXException as e: result['bozo'] = 1 result['bozo_exception'] = feedparser.exc or e use_strict_parser = 0 diff --git a/src/calibre/web/feeds/recipes/__init__.py b/src/calibre/web/feeds/recipes/__init__.py index f02d1a0fee..0b1eb7f22b 100644 --- a/src/calibre/web/feeds/recipes/__init__.py +++ b/src/calibre/web/feeds/recipes/__init__.py @@ -45,7 +45,7 @@ def compile_recipe(src): 'time':time, 're':re, 'BeautifulSoup':BeautifulSoup } - exec src in namespace + exec(src, namespace) for x in namespace.itervalues(): if (isinstance(x, type) and issubclass(x, BasicNewsRecipe) and x not diff --git a/src/calibre/web/feeds/recipes/collection.py b/src/calibre/web/feeds/recipes/collection.py index 43568838e8..80e735dd42 100644 --- a/src/calibre/web/feeds/recipes/collection.py +++ b/src/calibre/web/feeds/recipes/collection.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal ' @@ -117,7 +118,7 @@ def get_custom_recipe_collection(*args): if recipe_class is not None: rmap['custom:%s'%id_] = recipe_class except: - print 'Failed to load recipe from: %r'%fname + print('Failed to load recipe from: %r'%fname) import traceback traceback.print_exc() continue @@ -278,7 +279,7 @@ class SchedulerConfig(object): try: self.root = etree.fromstring(f.read()) except: - print 'Failed to read recipe scheduler config' + print('Failed to read recipe scheduler config') import traceback traceback.print_exc() elif os.path.exists(old_conf_path): diff --git a/src/calibre/web/fetch/simple.py b/src/calibre/web/fetch/simple.py index 822882acd4..238ccfe049 100644 --- a/src/calibre/web/fetch/simple.py +++ b/src/calibre/web/fetch/simple.py @@ -1,5 +1,6 @@ #!/usr/bin/env python2 from __future__ import with_statement +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal ' @@ -486,7 +487,7 @@ class RecursiveFetcher(object): for c, tag in enumerate(tags): if self.show_progress: - print '.', + print('.', end=' ') sys.stdout.flush() sys.stdout.flush() iurl = self.absurl(baseurl, tag, 'href', filter=recursion_level != 0) @@ -568,7 +569,7 @@ class RecursiveFetcher(object): finally: self.current_dir = prev_dir if self.show_progress: - print + print() return res diff --git a/src/css_selectors/select.py b/src/css_selectors/select.py index 583471ac81..e58bab4ed0 100644 --- a/src/css_selectors/select.py +++ b/src/css_selectors/select.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal ' @@ -53,7 +54,7 @@ def trace_wrapper(func): @wraps(func) def trace(*args, **kwargs): targs = args[1:] if args and isinstance(args[0], Select) else args - print ('Called:', func.__name__, 'with args:', targs, kwargs or '') + print('Called:', func.__name__, 'with args:', targs, kwargs or '') return func(*args, **kwargs) return trace diff --git a/src/css_selectors/tests.py b/src/css_selectors/tests.py index b9ffd86da3..1c27650310 100644 --- a/src/css_selectors/tests.py +++ b/src/css_selectors/tests.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal ' diff --git a/src/lzma/xz.py b/src/lzma/xz.py index 900fed697d..c66343576c 100644 --- a/src/lzma/xz.py +++ b/src/lzma/xz.py @@ -99,7 +99,7 @@ class CRCChecker(object): def finish(self): if self.func is not crc32: - self.code = 0xFFFFFFFFFFFFFFFFL & self.code + self.code = 0xFFFFFFFFFFFFFFFF & self.code @property def code_as_bytes(self): diff --git a/src/odf/attrconverters.py b/src/odf/attrconverters.py index fc07642c5e..e09b0f5caf 100644 --- a/src/odf/attrconverters.py +++ b/src/odf/attrconverters.py @@ -48,12 +48,12 @@ def cnv_color(attribute, arg, element): def cnv_configtype(attribute, arg, element): if str(arg) not in ("boolean", "short", "int", "long", "double", "string", "datetime", "base64Binary"): - raise ValueError, "'%s' not allowed" % str(arg) + raise ValueError("'%s' not allowed" % str(arg)) return str(arg) def cnv_data_source_has_labels(attribute, arg, element): if str(arg) not in ("none","row","column","both"): - raise ValueError, "'%s' not allowed" % str(arg) + raise ValueError("'%s' not allowed" % str(arg)) return str(arg) # Understand different date formats @@ -79,7 +79,7 @@ def cnv_family(attribute, arg, element): """ A style family """ if str(arg) not in ("text", "paragraph", "section", "ruby", "table", "table-column", "table-row", "table-cell", "graphic", "presentation", "drawing-page", "chart"): - raise ValueError, "'%s' not allowed" % str(arg) + raise ValueError("'%s' not allowed" % str(arg)) return str(arg) def __save_prefix(attribute, arg, element): @@ -112,7 +112,7 @@ def cnv_integer(attribute, arg, element): def cnv_legend_position(attribute, arg, element): if str(arg) not in ("start", "end", "top", "bottom", "top-start", "bottom-start", "top-end", "bottom-end"): - raise ValueError, "'%s' not allowed" % str(arg) + raise ValueError("'%s' not allowed" % str(arg)) return str(arg) pattern_length = re.compile(r'-?([0-9]+(\.[0-9]*)?|\.[0-9]+)((cm)|(mm)|(in)|(pt)|(pc)|(px))') @@ -123,7 +123,7 @@ def cnv_length(attribute, arg, element): """ global pattern_length if not pattern_length.match(arg): - raise ValueError, "'%s' is not a valid length" % arg + raise ValueError("'%s' is not a valid length" % arg) return arg def cnv_lengthorpercent(attribute, arg, element): @@ -133,17 +133,17 @@ def cnv_lengthorpercent(attribute, arg, element): try: return cnv_percent(attribute, arg, element) except: failed = True if failed: - raise ValueError, "'%s' is not a valid length or percent" % arg + raise ValueError("'%s' is not a valid length or percent" % arg) return arg def cnv_metavaluetype(attribute, arg, element): if str(arg) not in ("float", "date", "time", "boolean", "string"): - raise ValueError, "'%s' not allowed" % str(arg) + raise ValueError("'%s' not allowed" % str(arg)) return str(arg) def cnv_major_minor(attribute, arg, element): if arg not in ('major','minor'): - raise ValueError, "'%s' is not either 'minor' or 'major'" % arg + raise ValueError("'%s' is not either 'minor' or 'major'" % arg) pattern_namespacedToken = re.compile(r'[0-9a-zA-Z_]+:[0-9a-zA-Z._\-]+') @@ -151,7 +151,7 @@ def cnv_namespacedToken(attribute, arg, element): global pattern_namespacedToken if not pattern_namespacedToken.match(arg): - raise ValueError, "'%s' is not a valid namespaced token" % arg + raise ValueError("'%s' is not a valid namespaced token" % arg) return __save_prefix(attribute, arg, element) def cnv_NCName(attribute, arg, element): @@ -195,7 +195,7 @@ pattern_percent = re.compile(r'-?([0-9]+(\.[0-9]*)?|\.[0-9]+)%') def cnv_percent(attribute, arg, element): global pattern_percent if not pattern_percent.match(arg): - raise ValueError, "'%s' is not a valid length" % arg + raise ValueError("'%s' is not a valid length" % arg) return arg # Real one doesn't allow floating point values @@ -205,13 +205,13 @@ def cnv_points(attribute, arg, element): global pattern_points if type(arg) in types.StringTypes: if not pattern_points.match(arg): - raise ValueError, "x,y are separated by a comma and the points are separated by white spaces" + raise ValueError("x,y are separated by a comma and the points are separated by white spaces") return arg else: try: strarg = ' '.join([ "%d,%d" % p for p in arg]) except: - raise ValueError, "Points must be string or [(0,0),(1,1)] - not %s" % arg + raise ValueError("Points must be string or [(0,0),(1,1)] - not %s" % arg) return strarg def cnv_positiveInteger(attribute, arg, element): @@ -222,7 +222,7 @@ def cnv_string(attribute, arg, element): def cnv_textnoteclass(attribute, arg, element): if str(arg) not in ("footnote", "endnote"): - raise ValueError, "'%s' not allowed" % str(arg) + raise ValueError("'%s' not allowed" % str(arg)) return str(arg) # Understand different time formats @@ -237,12 +237,12 @@ pattern_viewbox = re.compile(r'-?[0-9]+([ ]+-?[0-9]+){3}$') def cnv_viewbox(attribute, arg, element): global pattern_viewbox if not pattern_viewbox.match(arg): - raise ValueError, "viewBox must be four integers separated by whitespaces" + raise ValueError("viewBox must be four integers separated by whitespaces") return arg def cnv_xlinkshow(attribute, arg, element): if str(arg) not in ("new", "replace", "embed"): - raise ValueError, "'%s' not allowed" % str(arg) + raise ValueError("'%s' not allowed" % str(arg)) return str(arg) diff --git a/src/odf/draw.py b/src/odf/draw.py index 7692e5aa84..8e8c798ad6 100644 --- a/src/odf/draw.py +++ b/src/odf/draw.py @@ -30,7 +30,7 @@ def StyleRefElement(stylename=None, classnames=None, **args): elif f == 'presentation': qattrs[(PRESENTATIONNS,u'style-name')]= stylename else: - raise ValueError, "Style's family must be either 'graphic' or 'presentation'" + raise ValueError("Style's family must be either 'graphic' or 'presentation'") if classnames is not None: f = classnames[0].getAttrNS(STYLENS, 'family') if f == 'graphic': @@ -38,7 +38,7 @@ def StyleRefElement(stylename=None, classnames=None, **args): elif f == 'presentation': qattrs[(PRESENTATIONNS,u'class-names')]= classnames else: - raise ValueError, "Style's family must be either 'graphic' or 'presentation'" + raise ValueError("Style's family must be either 'graphic' or 'presentation'") return Element(qattributes=qattrs, **args) def DrawElement(name=None, **args): diff --git a/src/odf/element.py b/src/odf/element.py index c9e88d1d7c..7b9310a2aa 100644 --- a/src/odf/element.py +++ b/src/odf/element.py @@ -116,7 +116,7 @@ class Node(xml.dom.Node): If refChild is null, insert newChild at the end of the list of children. """ if newChild.nodeType not in self._child_node_types: - raise IllegalChild, "%s cannot be child of %s" % (newChild.tagName, self.tagName) + raise IllegalChild("%s cannot be child of %s" % (newChild.tagName, self.tagName)) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if refChild is None: @@ -148,7 +148,7 @@ class Node(xml.dom.Node): ### The DOM does not clearly specify what to return in this case return newChild if newChild.nodeType not in self._child_node_types: - raise IllegalChild, "<%s> is not allowed in %s" % ( newChild.tagName, self.tagName) + raise IllegalChild("<%s> is not allowed in %s" % ( newChild.tagName, self.tagName)) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) _append_child(self, newChild) @@ -324,7 +324,7 @@ class Element(Node): if required: for r in required: if self.getAttrNS(r[0],r[1]) is None: - raise AttributeError, "Required attribute missing: %s in <%s>" % (r[1].lower().replace('-',''), self.tagName) + raise AttributeError("Required attribute missing: %s in <%s>" % (r[1].lower().replace('-',''), self.tagName)) def get_knownns(self, prefix): """ Odfpy maintains a list of known namespaces. In some cases a prefix is used, and @@ -360,7 +360,7 @@ class Element(Node): """ if check_grammar and self.allowed_children is not None: if element.qname not in self.allowed_children: - raise IllegalChild, "<%s> is not allowed in <%s>" % ( element.tagName, self.tagName) + raise IllegalChild("<%s> is not allowed in <%s>" % ( element.tagName, self.tagName)) self.appendChild(element) self._setOwnerDoc(element) if self.ownerDocument: @@ -371,7 +371,7 @@ class Element(Node): Setting check_grammar=False turns off grammar checking """ if check_grammar and self.qname not in grammar.allows_text: - raise IllegalText, "The <%s> element does not allow text" % self.tagName + raise IllegalText("The <%s> element does not allow text" % self.tagName) else: if text != '': self.appendChild(Text(text)) @@ -381,7 +381,7 @@ class Element(Node): Setting check_grammar=False turns off grammar checking """ if check_grammar and self.qname not in grammar.allows_text: - raise IllegalText, "The <%s> element does not allow text" % self.tagName + raise IllegalText("The <%s> element does not allow text" % self.tagName) else: self.appendChild(CDATASection(cdata)) @@ -393,12 +393,12 @@ class Element(Node): prefix, localname = attr self.removeAttrNS(prefix, localname) else: - raise AttributeError, "Unable to add simple attribute - use (namespace, localpart)" + raise AttributeError("Unable to add simple attribute - use (namespace, localpart)") else: # Construct a list of allowed arguments allowed_args = [ a[1].lower().replace('-','') for a in allowed_attrs] if check_grammar and attr not in allowed_args: - raise AttributeError, "Attribute %s is not allowed in <%s>" % ( attr, self.tagName) + raise AttributeError("Attribute %s is not allowed in <%s>" % ( attr, self.tagName)) i = allowed_args.index(attr) self.removeAttrNS(allowed_attrs[i][0], allowed_attrs[i][1]) @@ -416,12 +416,12 @@ class Element(Node): prefix, localname = attr self.setAttrNS(prefix, localname, value) else: - raise AttributeError, "Unable to add simple attribute - use (namespace, localpart)" + raise AttributeError("Unable to add simple attribute - use (namespace, localpart)") else: # Construct a list of allowed arguments allowed_args = [ a[1].lower().replace('-','') for a in allowed_attrs] if check_grammar and attr not in allowed_args: - raise AttributeError, "Attribute %s is not allowed in <%s>" % ( attr, self.tagName) + raise AttributeError("Attribute %s is not allowed in <%s>" % ( attr, self.tagName)) i = allowed_args.index(attr) self.setAttrNS(allowed_attrs[i][0], allowed_attrs[i][1], value) @@ -455,7 +455,7 @@ class Element(Node): prefix, localname = attr return self.getAttrNS(prefix, localname) else: - raise AttributeError, "Unable to get simple attribute - use (namespace, localpart)" + raise AttributeError("Unable to get simple attribute - use (namespace, localpart)") else: # Construct a list of allowed arguments allowed_args = [ a[1].lower().replace('-','') for a in allowed_attrs] diff --git a/src/odf/load.py b/src/odf/load.py index 5d2f3d5040..f8077f4071 100644 --- a/src/odf/load.py +++ b/src/odf/load.py @@ -25,6 +25,7 @@ # the structure again. from xml.sax import handler +from __future__ import print_function from element import Element from namespaces import OFFICENS @@ -71,8 +72,8 @@ class LoadParser(handler.ContentHandler): try: e = Element(qname = tag, qattributes=attrdict, check_grammar=False) self.curr = e - except AttributeError, v: - print "Error: %s" % v + except AttributeError as v: + print("Error: %s" % v) if tag == (OFFICENS, 'automatic-styles'): e = self.doc.automaticstyles diff --git a/src/odf/odfmanifest.py b/src/odf/odfmanifest.py index c25a028bbf..ada04f31f1 100644 --- a/src/odf/odfmanifest.py +++ b/src/odf/odfmanifest.py @@ -21,6 +21,7 @@ # This script lists the content of the manifest.xml file import zipfile +from __future__ import print_function from xml.sax import make_parser,handler from xml.sax.xmlreader import InputSource import xml.sax.saxutils @@ -112,5 +113,5 @@ if __name__ == "__main__": import sys result = odfmanifest(sys.argv[1]) for file in result.values(): - print "%-40s %-40s" % (file['media-type'], file['full-path']) + print("%-40s %-40s" % (file['media-type'], file['full-path'])) diff --git a/src/odf/opendocument.py b/src/odf/opendocument.py index 8890c2a21d..0de129bf21 100644 --- a/src/odf/opendocument.py +++ b/src/odf/opendocument.py @@ -34,7 +34,7 @@ __version__= TOOLSVERSION _XMLPROLOGUE = u"\n" -UNIXPERMS = 0100644 << 16L # -rw-r--r-- +UNIXPERMS = 0o100644 << 16 # -rw-r--r-- IS_FILENAME = 0 IS_IMAGE = 1 @@ -601,7 +601,7 @@ def __loadxmlparts(z, manifest, doc, objectpath): parser.setFeature(handler.feature_external_ges, False) # Changed by Kovid to ignore external DTDs parser.parse(inpsrc) del doc._parsing - except KeyError, v: pass + except KeyError as v: pass def load(odffile): """ Load an ODF file into memory diff --git a/src/tinycss/tests/main.py b/src/tinycss/tests/main.py index 30ec5c39a7..d66e51a57d 100644 --- a/src/tinycss/tests/main.py +++ b/src/tinycss/tests/main.py @@ -2,6 +2,7 @@ # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) +from __future__ import print_function __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal '