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(...)
This commit is contained in:
Flaviu Tamas 2018-09-04 10:49:18 -04:00 committed by Kovid Goyal
parent 2aacfeffa5
commit 0889ee85ec
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
298 changed files with 987 additions and 747 deletions

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import os, re, textwrap import os, re, textwrap
from functools import partial 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 '' old_raw = open(path, 'rb').read() if os.path.exists(path) else ''
if not os.path.exists(path) or old_raw != raw: if not os.path.exists(path) or old_raw != raw:
import difflib import difflib
print path, 'has changed' print(path, 'has changed')
if old_raw: if old_raw:
lines = difflib.unified_diff(old_raw.splitlines(), raw.splitlines(), lines = difflib.unified_diff(old_raw.splitlines(), raw.splitlines(),
path, path) path, path)
for line in lines: for line in lines:
print line print(line)
app.builder.info('creating '+os.path.splitext(os.path.basename(path))[0]) app.builder.info('creating '+os.path.splitext(os.path.basename(path))[0])
p = os.path.dirname(path) p = os.path.dirname(path)
if p and not os.path.exists(p): if p and not os.path.exists(p):

View File

@ -1,3 +1,4 @@
from __future__ import print_function
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe
import re import re
@ -30,7 +31,7 @@ class DrawAndCook(BasicNewsRecipe):
articles = self.make_links(url) articles = self.make_links(url)
if articles: if articles:
feeds.append((title, articles)) feeds.append((title, articles))
print 'feeds are: ', feeds print('feeds are: ', feeds)
return feeds return feeds
def make_links(self, url): def make_links(self, url):
@ -45,9 +46,9 @@ class DrawAndCook(BasicNewsRecipe):
'li', attrs={'data-id': re.compile(r'artwork_entry_\d+', re.DOTALL)}) 'li', attrs={'data-id': re.compile(r'artwork_entry_\d+', re.DOTALL)})
for recipe in recipes: for recipe in recipes:
page_url = self.INDEX + recipe.a['href'] page_url = self.INDEX + recipe.a['href']
print 'page_url is: ', page_url print('page_url is: ', page_url)
title = recipe.find('strong').string title = recipe.find('strong').string
print 'title is: ', title print('title is: ', title)
current_articles.append( current_articles.append(
{'title': title, 'url': page_url, 'description': '', 'date': date}) {'title': title, 'url': page_url, 'description': '', 'date': date})
return current_articles return current_articles

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2014, spswerling' __copyright__ = '2014, spswerling'
''' '''
http://www.al-monitor.com/ http://www.al-monitor.com/

View File

@ -1,5 +1,6 @@
# vim:fileencoding=UTF-8 # vim:fileencoding=UTF-8
from __future__ import unicode_literals from __future__ import unicode_literals
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2013, Eddie Lau' __copyright__ = '2013, Eddie Lau'
__Date__ = '' __Date__ = ''
@ -60,7 +61,7 @@ class AM730(BasicNewsRecipe):
title = href.split('/')[-1].split('-')[0] title = href.split('/')[-1].split('-')[0]
title = urllib.unquote(title.encode('ASCII')) # .decode('utf-8') title = urllib.unquote(title.encode('ASCII')) # .decode('utf-8')
if self.debug: if self.debug:
print title print(title)
try: try:
if articles.index({'title':title,'url':href})>=0: if articles.index({'title':title,'url':href})>=0:
# print 'already added' # print 'already added'
@ -73,7 +74,7 @@ class AM730(BasicNewsRecipe):
if (len(articles) >= self.max_articles_per_feed): if (len(articles) >= self.max_articles_per_feed):
break break
if self.debug: if self.debug:
print articles print(articles)
return (sectionName,articles) return (sectionName,articles)
def parse_index(self): def parse_index(self):
@ -89,8 +90,8 @@ class AM730(BasicNewsRecipe):
SectionsArticles=[] SectionsArticles=[]
for (title, url) in Sections: for (title, url) in Sections:
if self.debug: if self.debug:
print title print(title)
print url print(url)
SectionsArticles.append(self.getAMSectionArticles(title,url)) SectionsArticles.append(self.getAMSectionArticles(title,url))
# feeds.append(articles[0]['url']) # feeds.append(articles[0]['url'])
return SectionsArticles return SectionsArticles

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__author__ = 'GabrieleMarini, based on Darko Miletic' __author__ = 'GabrieleMarini, based on Darko Miletic'
__copyright__ = '2009, Darko Miletic <darko.miletic at gmail.com>, Gabriele Marini' __copyright__ = '2009, Darko Miletic <darko.miletic at gmail.com>, Gabriele Marini'
__version__ = 'v1.02 Marini Gabriele ' __version__ = 'v1.02 Marini Gabriele '
@ -56,7 +57,7 @@ class AutoPR(BasicNewsRecipe):
]: ]:
soup = self.index_to_soup(url) soup = self.index_to_soup(url)
soup = soup.find('channel') soup = soup.find('channel')
print soup print(soup)
for article in soup.findAllNext('item'): for article in soup.findAllNext('item'):
title = self.tag_to_string(article.title) title = self.tag_to_string(article.title)

View File

@ -1,3 +1,4 @@
from __future__ import print_function
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe
import re import re
import mechanize import mechanize
@ -26,11 +27,11 @@ class AdvancedUserRecipe1306097511(BasicNewsRecipe):
# look for the block containing the sun button and url # look for the block containing the sun button and url
cov = soup.find(attrs={'height': re.compile( cov = soup.find(attrs={'height': re.compile(
'3'), 'alt': re.compile('Post')}) '3'), 'alt': re.compile('Post')})
print print()
print '%%%%%%%%%%%%%%%', cov print('%%%%%%%%%%%%%%%', cov)
print print()
cov2 = str(cov['src']) cov2 = str(cov['src'])
print '88888888 ', cov2, ' 888888888888' print('88888888 ', cov2, ' 888888888888')
# cover_url=cov2 # cover_url=cov2
# return cover_url # return cover_url

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe
import datetime import datetime
@ -142,7 +143,7 @@ class brewiarz(BasicNewsRecipe):
if x == tag: if x == tag:
break break
else: else:
print "Can't find", tag, "in", tag.parent print("Can't find", tag, "in", tag.parent)
continue continue
for r in reversed(tag.contents): for r in reversed(tag.contents):
tag.parent.insert(i, r) tag.parent.insert(i, r)

View File

@ -5,6 +5,7 @@ __license__ = 'GPL v3'
''' '''
www.canada.com www.canada.com
''' '''
from __future__ import print_function
import re import re
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag

View File

@ -1,3 +1,4 @@
from __future__ import print_function
# Los primeros comentarios son las dificultades que he tenido con el Piton # 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. # 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 # 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 if INDEX.startswith('/'): # protegiendonos de que dejen de usarlos
INDEX = 'http://www.cio.com' + INDEX INDEX = 'http://www.cio.com' + INDEX
# Y nos aseguramos en los logs que lo estamos haciendo bien # 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. # Ya sabemos cual es la revista... procesemosla.
soup = self.index_to_soup(INDEX) soup = self.index_to_soup(INDEX)
@ -103,7 +104,7 @@ class CIO_Magazine(BasicNewsRecipe):
if div['class'] == 'heading': if div['class'] == 'heading':
key = string.capwords(self.tag_to_string(div.span)) 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] = [] articles[key] = []
feeds.append(key) feeds.append(key)
@ -126,7 +127,7 @@ class CIO_Magazine(BasicNewsRecipe):
if summary: if summary:
description = self.tag_to_string(summary, use_alt=False) description = self.tag_to_string(summary, use_alt=False)
print ("Description = ", description) print("Description = ", description)
# Esto esta copiado del NY times # Esto esta copiado del NY times
feed = key if key is not None else 'Uncategorized' feed = key if key is not None else 'Uncategorized'

View File

@ -1,5 +1,6 @@
# vim:fileencoding=UTF-8 # vim:fileencoding=UTF-8
from __future__ import unicode_literals from __future__ import unicode_literals
from __future__ import print_function
import re import re
@ -65,7 +66,7 @@ class AdvancedUserRecipe1390132023(BasicNewsRecipe):
feeds = BasicNewsRecipe.parse_feeds(self) feeds = BasicNewsRecipe.parse_feeds(self)
for feed in feeds: for feed in feeds:
for article in feed.articles[:]: for article in feed.articles[:]:
print 'article.title is: ', article.title print('article.title is: ', article.title)
if 'WATCH:' in article.title.upper(): if 'WATCH:' in article.title.upper():
feed.articles.remove(article) feed.articles.remove(article)

View File

@ -2,6 +2,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = u'2014-01-09, Silviu Cotoar\u0103, Marius Popescu' __copyright__ = u'2014-01-09, Silviu Cotoar\u0103, Marius Popescu'
''' '''
dilemaveche.ro dilemaveche.ro

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
__author__ = 'Darko Spasovski' __author__ = 'Darko Spasovski'
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2011, Darko Spasovski <darko.spasovski at gmail.com>' __copyright__ = '2011, Darko Spasovski <darko.spasovski at gmail.com>'
''' '''
@ -64,7 +65,7 @@ class Dnevnik(BasicNewsRecipe):
containerTable = section.findPrevious( containerTable = section.findPrevious(
name='table').findNextSibling(name='table') name='table').findNextSibling(name='table')
if containerTable is None: 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 continue
articles = [] articles = []
for article in containerTable.findAll('a', attrs={'class': 'WB_DNEVNIK_ArhivaFormText'}): for article in containerTable.findAll('a', attrs={'class': 'WB_DNEVNIK_ArhivaFormText'}):

View File

@ -5,6 +5,7 @@ __license__ = 'GPL v3'
''' '''
www.canada.com www.canada.com
''' '''
from __future__ import print_function
import re import re
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag

View File

@ -1,3 +1,4 @@
from __future__ import print_function
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
@ -31,7 +32,7 @@ class RevistaElCultural(BasicNewsRecipe):
# TO GET ARTICLES IN SECTION # TO GET ARTICLES IN SECTION
def ec_parse_section(self, url, titleSection): def ec_parse_section(self, url, titleSection):
print 'Section: ' + titleSection print('Section: ' + titleSection)
soup = self.index_to_soup(url) soup = self.index_to_soup(url)
div = soup.find(attrs={'id': 'gallery'}) div = soup.find(attrs={'id': 'gallery'})
current_articles = [] current_articles = []

View File

@ -1,3 +1,4 @@
from __future__ import print_function
# -*- mode: python -*- # -*- mode: python -*-
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vim:fileencoding=utf-8 # vim:fileencoding=utf-8
@ -100,7 +101,7 @@ class ElMundo(BasicNewsRecipe):
html = response.read() html = response.read()
count = tries count = tries
except: except:
print "Retrying download..." print("Retrying download...")
count += 1 count += 1
if html is not None: if html is not None:
tfile = PersistentTemporaryFile('_fa.html') tfile = PersistentTemporaryFile('_fa.html')

View File

@ -1,3 +1,4 @@
from __future__ import print_function
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe
from datetime import datetime, timedelta from datetime import datetime, timedelta
from calibre.ebooks.BeautifulSoup import Tag, BeautifulSoup from calibre.ebooks.BeautifulSoup import Tag, BeautifulSoup
@ -92,12 +93,12 @@ class Estadao(BasicNewsRecipe):
img = Image() img = Image()
img.open(iurl) img.open(iurl)
width, height = img.size 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: if img < 0:
raise RuntimeError('Out of memory') raise RuntimeError('Out of memory')
pw = PixelWand() pw = PixelWand()
if(width > height and width > 590): if(width > height and width > 590):
print 'Rotate image' print('Rotate image')
img.rotate(pw, -90) img.rotate(pw, -90)
img.save(iurl) img.save(iurl)
return soup return soup

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import time import time
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import Comment from calibre.ebooks.BeautifulSoup import Comment
@ -37,7 +38,7 @@ class GryOnlinePl(BasicNewsRecipe):
soup2 = self.index_to_soup(finalurl) soup2 = self.index_to_soup(finalurl)
break break
except: except:
print 'retrying in 0.5s' print('retrying in 0.5s')
time.sleep(0.5) time.sleep(0.5)
pagetext = soup2.find(attrs={'class': 'gc660'}) pagetext = soup2.find(attrs={'class': 'gc660'})
for r in pagetext.findAll(name='header'): for r in pagetext.findAll(name='header'):
@ -73,7 +74,7 @@ class GryOnlinePl(BasicNewsRecipe):
soup2 = self.index_to_soup(finalurl) soup2 = self.index_to_soup(finalurl)
break break
except: except:
print 'retrying in 0.5s' print('retrying in 0.5s')
time.sleep(0.5) time.sleep(0.5)
tag = soup2.find('div', attrs={'class': 'S018stronyr'}) tag = soup2.find('div', attrs={'class': 'S018stronyr'})
pagetext = soup2.find(attrs={'class': 'gc660'}) pagetext = soup2.find(attrs={'class': 'gc660'})

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2018, Dale Furrow dkfurrow@gmail.com' __copyright__ = '2018, Dale Furrow dkfurrow@gmail.com'
''' '''
chron.com chron.com

View File

@ -1,3 +1,4 @@
from __future__ import print_function
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe
import re import re

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2014, spswerling' __copyright__ = '2014, spswerling'
''' '''
www.hurriyetdailynews.com www.hurriyetdailynews.com

View File

@ -1,3 +1,4 @@
from __future__ import print_function
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe
@ -64,6 +65,6 @@ class AdvancedUserRecipe1299694372(BasicNewsRecipe):
for link_tag in soup.findAll(attrs={"id": "story"}): for link_tag in soup.findAll(attrs={"id": "story"}):
link_tag.insert( link_tag.insert(
0, '<h1>' + soup.find('title').contents[0].strip() + '</h1>') 0, '<h1>' + soup.find('title').contents[0].strip() + '</h1>')
print link_tag print(link_tag)
return soup return soup

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__author__ = 'Lorenzo Vigentini' __author__ = 'Lorenzo Vigentini'
__copyright__ = '2009, Lorenzo Vigentini <l.vigentini at gmail.com>' __copyright__ = '2009, Lorenzo Vigentini <l.vigentini at gmail.com>'
__version__ = 'v1.02' __version__ = 'v1.02'
@ -77,5 +78,5 @@ class laGazzetta(BasicNewsRecipe):
myArticle = myArticleSegs[0] myArticle = myArticleSegs[0]
printVerString = myArticle + '_print.html' printVerString = myArticle + '_print.html'
myURL = basename + subPath + printVerString myURL = basename + subPath + printVerString
print 'this is the url: ' + myURL print('this is the url: ' + myURL)
return basename + subPath + printVerString return basename + subPath + printVerString

View File

@ -1,3 +1,4 @@
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__author__ = 'Lorenzo Vigentini, based on Darko Miletic, Gabriele Marini; minor fixes by faber1971' __author__ = 'Lorenzo Vigentini, based on Darko Miletic, Gabriele Marini; minor fixes by faber1971'
__copyright__ = '2009-2012, Darko Miletic <darko.miletic at gmail.com>, Lorenzo Vigentini <l.vigentini at gmail.com>, faber1971' __copyright__ = '2009-2012, Darko Miletic <darko.miletic at gmail.com>, Lorenzo Vigentini <l.vigentini at gmail.com>, faber1971'
@ -48,7 +49,7 @@ class LaRepubblica(BasicNewsRecipe):
html = response.read() html = response.read()
count = 10 count = 10
except: except:
print "Retrying download..." print("Retrying download...")
count += 1 count += 1
self.temp_files.append(PersistentTemporaryFile('_fa.html')) self.temp_files.append(PersistentTemporaryFile('_fa.html'))
self.temp_files[-1].write(html) self.temp_files[-1].write(html)

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -60,7 +61,7 @@ class LeTemps(BasicNewsRecipe):
if key.endswith('_origlink'): if key.endswith('_origlink'):
url = article[key] url = article[key]
if url and url.startswith('https://'): if url and url.startswith('https://'):
print ('Url is :', url) print('Url is :', url)
return url return url
ans = article.get('link', None) ans = article.get('link', None)
if not ans and getattr(article, 'links', None): if not ans and getattr(article, 'links', None):

View File

@ -109,7 +109,7 @@ class LentaRURecipe(BasicNewsRecipe):
return result return result
except Exception, err: except Exception as err:
self.log(err) self.log(err)
raise NotImplementedError raise NotImplementedError

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2011, Davide Cavalca <davide125 at tiscali.it>' __copyright__ = '2011, Davide Cavalca <davide125 at tiscali.it>'
''' '''
lwn.net lwn.net
@ -120,8 +121,8 @@ class WeeklyLWN(BasicNewsRecipe):
if article_anchor: if article_anchor:
article_url = article_anchor.get('href') article_url = article_anchor.get('href')
if not article_url: if not article_url:
print >>sys.stderr, 'article_url is None for article_anchor "%s": "%s"' \ print('article_url is None for article_anchor "%s": "%s"' \
% (str(article_anchor), article_title) % (str(article_anchor), article_title), file=sys.stderr)
continue continue
else: else:

View File

@ -1,5 +1,6 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe
from __future__ import print_function
import re import re
from calibre.utils.magick import Image from calibre.utils.magick import Image
from calibre.ebooks.BeautifulSoup import BeautifulSoup from calibre.ebooks.BeautifulSoup import BeautifulSoup
@ -140,7 +141,7 @@ class MerryPreProcess():
img.trim(0) img.trim(0)
img.save(iurl) img.save(iurl)
except: except:
print '\n!!image optimize failed!!\n' print('\n!!image optimize failed!!\n')
continue continue
return soup return soup
@ -198,7 +199,7 @@ class MerryProcess(BeautifulSoup):
try: try:
pubdate.parent.insert(0, moveitem) pubdate.parent.insert(0, moveitem)
except: except:
print '\n!!error in moving title!!\n' print('\n!!error in moving title!!\n')
pass pass
moveitem = None moveitem = None
moveitem = soup.find('div', {'class': 'byline'}) moveitem = soup.find('div', {'class': 'byline'})
@ -206,7 +207,7 @@ class MerryProcess(BeautifulSoup):
try: try:
moveitem.parent.parent.insert(-1, moveitem) moveitem.parent.parent.insert(-1, moveitem)
except: except:
print '\n!!error in moving byline!!\n' print('\n!!error in moving byline!!\n')
pass pass
return soup return soup

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import re import re
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe
@ -41,7 +42,7 @@ class AdvancedUserRecipe1390146870(BasicNewsRecipe):
feeds = BasicNewsRecipe.parse_feeds(self) feeds = BasicNewsRecipe.parse_feeds(self)
for feed in feeds: for feed in feeds:
for article in feed.articles[:]: for article in feed.articles[:]:
print 'article.title is: ', article.title print('article.title is: ', article.title)
if 'VIDEO:' in article.title.upper(): if 'VIDEO:' in article.title.upper():
feed.articles.remove(article) feed.articles.remove(article)

View File

@ -1,3 +1,4 @@
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2010-2013, Eddie Lau' __copyright__ = '2010-2013, Eddie Lau'
@ -630,7 +631,7 @@ class MPRecipe(BasicNewsRecipe):
{'title': title, 'url': url, 'description': ''}) {'title': title, 'url': url, 'description': ''})
included_urls.append(url) included_urls.append(url)
except: except:
print 'skipping a premium article' print('skipping a premium article')
current_articles.reverse() current_articles.reverse()
return current_articles return current_articles
@ -822,7 +823,7 @@ class MPRecipe(BasicNewsRecipe):
else: else:
if next_is_img_txt is False: if next_is_img_txt is False:
if item.startswith("=@"): if item.startswith("=@"):
print 'skip movie link' print('skip movie link')
elif item.startswith("=?"): elif item.startswith("=?"):
next_is_img_txt = True next_is_img_txt = True
new_raw_html += '<img src="' + \ new_raw_html += '<img src="' + \

View File

@ -1,3 +1,4 @@
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2010-2011, Eddie Lau' __copyright__ = '2010-2011, Eddie Lau'
@ -492,7 +493,7 @@ class MPRecipe(BasicNewsRecipe):
{'title': title, 'url': url, 'description': ''}) {'title': title, 'url': url, 'description': ''})
included_urls.append(url) included_urls.append(url)
except: except:
print 'skipping a premium article' print('skipping a premium article')
current_articles.reverse() current_articles.reverse()
return current_articles return current_articles
@ -669,7 +670,7 @@ class MPRecipe(BasicNewsRecipe):
else: else:
if next_is_img_txt is False: if next_is_img_txt is False:
if item.startswith("=@"): if item.startswith("=@"):
print 'skip movie link' print('skip movie link')
elif item.startswith("=?"): elif item.startswith("=?"):
next_is_img_txt = True next_is_img_txt = True
new_raw_html += '<img src="' + \ new_raw_html += '<img src="' + \

View File

@ -1,3 +1,4 @@
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2010-2011, Eddie Lau' __copyright__ = '2010-2011, Eddie Lau'
@ -492,7 +493,7 @@ class MPRecipe(BasicNewsRecipe):
{'title': title, 'url': url, 'description': ''}) {'title': title, 'url': url, 'description': ''})
included_urls.append(url) included_urls.append(url)
except: except:
print 'skipping a premium article' print('skipping a premium article')
current_articles.reverse() current_articles.reverse()
return current_articles return current_articles
@ -669,7 +670,7 @@ class MPRecipe(BasicNewsRecipe):
else: else:
if next_is_img_txt is False: if next_is_img_txt is False:
if item.startswith("=@"): if item.startswith("=@"):
print 'skip movie link' print('skip movie link')
elif item.startswith("=?"): elif item.startswith("=?"):
next_is_img_txt = True next_is_img_txt = True
new_raw_html += '<img src="' + \ new_raw_html += '<img src="' + \

View File

@ -5,6 +5,7 @@ __license__ = 'GPL v3'
''' '''
www.canada.com www.canada.com
''' '''
from __future__ import print_function
import re import re
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag

View File

@ -2,6 +2,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2010, matek09, matek09@gmail.com; 2012-2013, admroz, a.rozewicki@gmail.com' __copyright__ = '2010, matek09, matek09@gmail.com; 2012-2013, admroz, a.rozewicki@gmail.com'
import re import re
@ -105,7 +106,7 @@ class Newsweek(BasicNewsRecipe):
matches = re.search(r'<article>(.*)</article>', source, re.DOTALL) matches = re.search(r'<article>(.*)</article>', source, re.DOTALL)
if matches is None: if matches is None:
print "no article tag found, returning..." print("no article tag found, returning...")
return return
main_section = BeautifulSoup(matches.group(0)) main_section = BeautifulSoup(matches.group(0))

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=utf-8 # vim:fileencoding=utf-8
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
from __future__ import print_function
import re import re
import unicodedata import unicodedata
@ -40,39 +41,39 @@ class NikkeiNet_paper_subscription(BasicNewsRecipe):
br = BasicNewsRecipe.get_browser(self) br = BasicNewsRecipe.get_browser(self)
if self.username is not None and self.password is not None: 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/') br.open('http://www.nikkei.com/')
print "-------------------------open first login form-----------------------------" print("-------------------------open first login form-----------------------------")
try: try:
url = list(br.links( url = list(br.links(
url_regex="www.nikkei.com/etc/accounts/login"))[0].url url_regex="www.nikkei.com/etc/accounts/login"))[0].url
except IndexError: 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' url = 'http://www.nikkei.com/etc/accounts/login?dps=3&pageflag=top&url=http%3A%2F%2Fwww.nikkei.com%2F'
except StopIteration: except StopIteration:
url = 'http://www.nikkei.com/etc/accounts/login?dps=3&pageflag=top&url=http%3A%2F%2Fwww.nikkei.com%2F' url = 'http://www.nikkei.com/etc/accounts/login?dps=3&pageflag=top&url=http%3A%2F%2Fwww.nikkei.com%2F'
br.open(url) br.open(url)
print "-------------------------JS redirect(send autoPostForm)--------------------" print("-------------------------JS redirect(send autoPostForm)--------------------")
br.select_form(name='autoPostForm') br.select_form(name='autoPostForm')
br.submit() br.submit()
# response = br.response() # response = br.response()
print "-------------------------got login form------------------------------------" print("-------------------------got login form------------------------------------")
br.select_form(name='LA7010Form01') br.select_form(name='LA7010Form01')
br['LA7010Form01:LA7010Email'] = self.username br['LA7010Form01:LA7010Email'] = self.username
br['LA7010Form01:LA7010Password'] = self.password br['LA7010Form01:LA7010Password'] = self.password
br.submit(id='LA7010Form01:submitBtn') br.submit(id='LA7010Form01:submitBtn')
print "-------------------------JS redirect---------------------------------------" print("-------------------------JS redirect---------------------------------------")
br.select_form(nr=0) br.select_form(nr=0)
br.submit() br.submit()
return br return br
def cleanup(self): def cleanup(self):
print "-------------------------logout--------------------------------------------" print("-------------------------logout--------------------------------------------")
self.browser.open('https://regist.nikkei.com/ds/etc/accounts/logout') self.browser.open('https://regist.nikkei.com/ds/etc/accounts/logout')
def parse_index(self): def parse_index(self):
print "-------------------------get index of paper--------------------------------" print("-------------------------get index of paper--------------------------------")
result = [] result = []
soup = self.index_to_soup('http://www.nikkei.com/paper/') soup = self.index_to_soup('http://www.nikkei.com/paper/')
sections = soup.findAll(attrs={'class': re.compile(".*cmn-article_title.*")}) sections = soup.findAll(attrs={'class': re.compile(".*cmn-article_title.*")})

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import re import re
from calibre import strftime from calibre import strftime
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
@ -48,7 +49,7 @@ class Nuus24(BasicNewsRecipe):
attrs={'id': ['lnkLink']}): attrs={'id': ['lnkLink']}):
url = re.sub(r'\?.*', '', anchor['href']) url = re.sub(r'\?.*', '', anchor['href'])
title = self.tag_to_string(anchor, use_alt=True).strip() title = self.tag_to_string(anchor, use_alt=True).strip()
print title print(title)
description = '' description = ''
pubdate = strftime('%a, %d %b') pubdate = strftime('%a, %d %b')
articles[key].append( articles[key].append(

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__author__ = '2010, Gustavo Azambuja <hola at gazambuja.com>' __author__ = '2010, Gustavo Azambuja <hola at gazambuja.com>'
''' '''
observa.com.uy observa.com.uy
@ -54,7 +55,7 @@ class Noticias(BasicNewsRecipe):
cover_url = 'http://www.elobservador.com.uy' + \ cover_url = 'http://www.elobservador.com.uy' + \
link_item['src'].strip() link_item['src'].strip()
print cover_url print(cover_url)
return cover_url return cover_url

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import re import re
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe
coverpage = None coverpage = None
@ -30,7 +31,7 @@ class ObservatorulCultural(BasicNewsRecipe):
issueTag = soup.find('a', href=re.compile( issueTag = soup.find('a', href=re.compile(
"observatorcultural.ro\/Numarul")) "observatorcultural.ro\/Numarul"))
issueURL = issueTag['href'] issueURL = issueTag['href']
print issueURL print(issueURL)
issueSoup = self.index_to_soup(issueURL) issueSoup = self.index_to_soup(issueURL)
feeds = [] feeds = []
stories = [] stories = []
@ -59,7 +60,7 @@ class ObservatorulCultural(BasicNewsRecipe):
coverpage = title[1]['href'] coverpage = title[1]['href']
feeds.append((categ, stories)) feeds.append((categ, stories))
stories = [] stories = []
print feeds print(feeds)
return feeds return feeds
# procedura de luat coperta # procedura de luat coperta

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import time import time
import traceback import traceback
# above for debugging via stack # above for debugging via stack

View File

@ -5,6 +5,7 @@ __license__ = 'GPL v3'
''' '''
www.canada.com www.canada.com
''' '''
from __future__ import print_function
import re import re
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
''' '''
pagina12.com.ar pagina12.com.ar
@ -34,7 +35,7 @@ class Pagina12(BasicNewsRecipe):
for image in soup.findAll('img', alt=True): for image in soup.findAll('img', alt=True):
if image['alt'].startswith('Tapa de la fecha'): if image['alt'].startswith('Tapa de la fecha'):
return image['src'] return image['src']
print image print(image)
return None return None
def parse_index(self): def parse_index(self):

View File

@ -38,7 +38,8 @@ class pravo(BasicNewsRecipe):
articles.append(self.parse_page(feed)) articles.append(self.parse_page(feed))
return articles return articles
def parse_page(self, (feed_title, url)): def parse_page(self, xxx_todo_changeme):
(feed_title, url) = xxx_todo_changeme
articles = [] articles = []
soup = self.index_to_soup(url) soup = self.index_to_soup(url)

View File

@ -1,3 +1,4 @@
from __future__ import print_function
# Test with "\Program Files\Calibre2\ebook-convert.exe" RealClear.recipe # Test with "\Program Files\Calibre2\ebook-convert.exe" RealClear.recipe
# .epub --test -vv --debug-pipeline debug # .epub --test -vv --debug-pipeline debug
import re import re

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2014, spswerling' __copyright__ = '2014, spswerling'
''' '''
www.todayszaman.com www.todayszaman.com
@ -73,7 +74,7 @@ class TodaysZaman(BasicNewsRecipe):
def parse_section(self, sect_title, sect_uri): def parse_section(self, sect_title, sect_uri):
url = 'http://www.todayszaman.com/' + sect_uri url = 'http://www.todayszaman.com/' + sect_uri
print 'Start section ' + sect_title + ', ' + url print('Start section ' + sect_title + ', ' + url)
try: try:
soup = self.index_to_soup(url) soup = self.index_to_soup(url)
except: except:
@ -89,11 +90,11 @@ class TodaysZaman(BasicNewsRecipe):
for link in div.findAll('a', href=True): for link in div.findAll('a', href=True):
self.process_link(sect_title, div_class, link) 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 process_link(self, section_title, layout, link):
def p(s): def p(s):
print '[PROCESS LINK] ' + s[0:80] print('[PROCESS LINK] ' + s[0:80])
href = link['href'] href = link['href']
full_href = urljoin('http://www.todayszaman.com/', 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 populate_article_metadata(self, article, soup, first):
def p(s): def p(s):
print '[POPULATE METADATA] ' + s[0:80] print('[POPULATE METADATA] ' + s[0:80])
tnode = soup.find('title') tnode = soup.find('title')
if tnode: if tnode:

View File

@ -5,6 +5,7 @@ __license__ = 'GPL v3'
''' '''
www.canada.com www.canada.com
''' '''
from __future__ import print_function
import re import re
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag

View File

@ -5,6 +5,7 @@ __license__ = 'GPL v3'
''' '''
www.canada.com www.canada.com
''' '''
from __future__ import print_function
import re import re
from calibre.web.feeds.recipes import BasicNewsRecipe from calibre.web.feeds.recipes import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup, Tag

View File

@ -113,7 +113,7 @@ class VedomostiRecipe(BasicNewsRecipe):
return result return result
except Exception, err: except Exception as err:
self.log(err) self.log(err)
raise NotImplementedError raise NotImplementedError

View File

@ -5,6 +5,7 @@ __license__ = 'GPL v3'
''' '''
www.canada.com www.canada.com
''' '''
from __future__ import print_function
import re import re
from calibre.web.feeds.news import BasicNewsRecipe from calibre.web.feeds.news import BasicNewsRecipe

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -75,10 +76,10 @@ def require_clean_git():
c('git rev-parse --verify HEAD'.split(), stdout=null) c('git rev-parse --verify HEAD'.split(), stdout=null)
c('git update-index -q --ignore-submodules --refresh'.split()) c('git update-index -q --ignore-submodules --refresh'.split())
if p('git diff-files --quiet --ignore-submodules'.split()).wait() != 0: 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) raise SystemExit(1)
if p('git diff-index --cached --quiet --ignore-submodules HEAD --'.split()).wait() != 0: 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) raise SystemExit(1)
@ -269,9 +270,9 @@ class Command(object):
sys.stdout.flush() sys.stdout.flush()
def warn(self, *args, **kwargs): def warn(self, *args, **kwargs):
print '\n'+'_'*20, 'WARNING','_'*20 print('\n'+'_'*20, 'WARNING','_'*20)
prints(*args, **kwargs) prints(*args, **kwargs)
print '_'*50 print('_'*50)
warnings.append((args, kwargs)) warnings.append((args, kwargs))
sys.stdout.flush() sys.stdout.flush()

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -343,7 +344,7 @@ class Build(Command):
subprocess.check_call(*args, **kwargs) subprocess.check_call(*args, **kwargs)
except: except:
cmdline = ' '.join(['"%s"' % (arg) if ' ' in arg else arg for arg in args[0]]) 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 raise
def build_headless(self): def build_headless(self):

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -51,7 +52,7 @@ def run_pkgconfig(name, envvar, default, flag, prefix):
ans = [x.strip() for x in raw.split(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))] ans = [x for x in ans if x and (prefix=='-l' or os.path.exists(x))]
except: 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 []) return ans or ([default] if default else [])

View File

@ -4,6 +4,7 @@
import importlib import importlib
from __future__ import print_function
import json import json
import re import re
import socket import socket

View File

@ -2,6 +2,7 @@
# vim:fileencoding=utf-8 # vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -319,7 +320,7 @@ def download_tarball():
dest = os.path.join(cache, fname) dest = os.path.join(cache, fname)
raw = check_signature(dest, signature) raw = check_signature(dest, signature)
if raw is not None: if raw is not None:
print ('Using previously downloaded', fname) print('Using previously downloaded', fname)
return raw return raw
cached_sigf = dest +'.signature' cached_sigf = dest +'.signature'
cached_sig = None cached_sig = None
@ -671,7 +672,7 @@ def run_installer(install_dir, isolated, bin_dir, share_dir):
if not os.path.isdir(destdir): if not os.path.isdir(destdir):
prints(destdir, 'exists and is not a directory. Choose a location like /opt or /usr/local') prints(destdir, 'exists and is not a directory. Choose a location like /opt or /usr/local')
return 1 return 1
print ('Installing to', destdir) print('Installing to', destdir)
download_and_extract(destdir) download_and_extract(destdir)

View File

@ -40,7 +40,7 @@ class MathJax(Command):
raw = f.read() raw = f.read()
self.h.update(raw) self.h.update(raw)
zi = ZipInfo(name) zi = ZipInfo(name)
zi.external_attr = 0o444 << 16L zi.external_attr = 0o444 << 16
zf.writestr(zi, raw) zf.writestr(zi, raw)
def add_tree(self, zf, base, prefix, ignore=lambda n:False): def add_tree(self, zf, base, prefix, ignore=lambda n:False):

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -129,7 +130,7 @@ class PyPIRegister(Command):
''' '''
# send the info to the server and report the result # send the info to the server and report the result
(code, result) = self.post_to_server(self.build_post_data('verify')) (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): def build_post_data(self, action):
# figure the data to send - the metadata plus some additional # figure the data to send - the metadata plus some additional
@ -199,18 +200,18 @@ class PyPIRegister(Command):
data = '' data = ''
try: try:
result = opener.open(req) result = opener.open(req)
except urllib2.HTTPError, e: except urllib2.HTTPError as e:
if self.show_response: if self.show_response:
data = e.fp.read() data = e.fp.read()
result = e.code, e.msg result = e.code, e.msg
except urllib2.URLError, e: except urllib2.URLError as e:
result = 500, str(e) result = 500, str(e)
else: else:
if self.show_response: if self.show_response:
data = result.read() data = result.read()
result = 200, 'OK' result = 200, 'OK'
if self.show_response: if self.show_response:
print '-'*75, data, '-'*75 print('-'*75, data, '-'*75)
return result return result
class PyPIUpload(PyPIRegister): class PyPIUpload(PyPIRegister):
@ -341,7 +342,7 @@ class PyPIUpload(PyPIRegister):
http.putheader('Authorization', auth) http.putheader('Authorization', auth)
http.endheaders() http.endheaders()
http.send(body) http.send(body)
except socket.error, e: except socket.error as e:
self.warn(str(e)) self.warn(str(e))
raise SystemExit(1) raise SystemExit(1)
@ -352,4 +353,4 @@ class PyPIUpload(PyPIRegister):
self.info('Upload failed (%s): %s' % (r.status, r.reason)) self.info('Upload failed (%s): %s' % (r.status, r.reason))
raise SystemExit(1) raise SystemExit(1)
if self.show_response: if self.show_response:
print '-'*75, r.read(), '-'*75 print('-'*75, r.read(), '-'*75)

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -55,7 +56,7 @@ class Coffee(Command): # {{{
from pygments.lexers import JavascriptLexer from pygments.lexers import JavascriptLexer
from pygments.formatters import TerminalFormatter from pygments.formatters import TerminalFormatter
from pygments import highlight 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): def do_coffee_compile(self, opts, timestamp=False, ignore_errors=False):
from calibre.utils.serve_coffee import compile_coffeescript from calibre.utils.serve_coffee import compile_coffeescript
@ -96,7 +97,7 @@ class Coffee(Command): # {{{
if errors: if errors:
print ('\n\tCompilation of %s failed'%name) print ('\n\tCompilation of %s failed'%name)
for line in errors: for line in errors:
print >>sys.stderr, line print(line, file=sys.stderr)
if ignore_errors: if ignore_errors:
js = u'# Compilation from coffeescript failed' js = u'# Compilation from coffeescript failed'
else: else:

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
@ -143,7 +144,7 @@ def calibre_cmdline(ver):
def run_remote_upload(args): def run_remote_upload(args):
print 'Running remotely:', ' '.join(args) print('Running remotely:', ' '.join(args))
subprocess.check_call([ subprocess.check_call([
'ssh', '-x', '%s@%s' % (STAGING_USER, STAGING_HOST), 'cd', STAGING_DIR, '&&', 'ssh', '-x', '%s@%s' % (STAGING_USER, STAGING_HOST), 'cd', STAGING_DIR, '&&',
'python2', 'hosting.py' 'python2', 'hosting.py'

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'

View File

@ -3,6 +3,7 @@
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from future_builtins import map from future_builtins import map
from __future__ import print_function
import sys, locale, codecs, os, importlib, collections import sys, locale, codecs, os, importlib, collections
__appname__ = u'calibre' __appname__ = u'calibre'
@ -231,7 +232,7 @@ if plugins is None:
# config_dir {{{ # config_dir {{{
CONFIG_DIR_MODE = 0700 CONFIG_DIR_MODE = 0o700
if 'CALIBRE_CONFIG_DIRECTORY' in os.environ: if 'CALIBRE_CONFIG_DIRECTORY' in os.environ:
config_dir = os.path.abspath(os.environ['CALIBRE_CONFIG_DIRECTORY']) config_dir = os.path.abspath(os.environ['CALIBRE_CONFIG_DIRECTORY'])
@ -257,7 +258,7 @@ else:
if not os.path.exists(config_dir) or \ if not os.path.exists(config_dir) or \
not os.access(config_dir, os.W_OK) or not \ not os.access(config_dir, os.W_OK) or not \
os.access(config_dir, os.X_OK): 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 import tempfile, atexit
config_dir = tempfile.mkdtemp(prefix='calibre-config-') config_dir = tempfile.mkdtemp(prefix='calibre-config-')

View File

@ -1,4 +1,5 @@
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
@ -563,7 +564,7 @@ class CatalogPlugin(Plugin): # {{{
try: try:
resources.extract(file, self.resources_path) resources.extract(file, self.resources_path)
except: 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 continue
resources.close() resources.close()

View File

@ -1,4 +1,5 @@
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
@ -170,7 +171,7 @@ def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'):
try: try:
nfp = plugin.run(nfp) or nfp nfp = plugin.run(nfp) or nfp
except: 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) traceback.print_exc(file=oe)
sys.stdout, sys.stderr = oo, oe sys.stdout, sys.stderr = oo, oe
x = lambda j: os.path.normpath(os.path.normcase(j)) x = lambda j: os.path.normpath(os.path.normcase(j))
@ -673,7 +674,7 @@ def initialize_plugin(plugin, path_to_zip_file):
p.initialize() p.initialize()
return p return p
except Exception: except Exception:
print 'Failed to initialize plugin:', plugin.name, plugin.version print('Failed to initialize plugin:', plugin.name, plugin.version)
tb = traceback.format_exc() tb = traceback.format_exc()
raise InvalidPlugin((_('Initialization of plugin %s failed with traceback:') raise InvalidPlugin((_('Initialization of plugin %s failed with traceback:')
%tb) + '\n'+tb) %tb) + '\n'+tb)
@ -718,7 +719,7 @@ def initialize_plugins(perf=False):
times[plugin.name] = time.time() - st times[plugin.name] = time.time() - st
_initialized_plugins.append(plugin) _initialized_plugins.append(plugin)
except: except:
print 'Failed to initialize plugin:', repr(zfp) print('Failed to initialize plugin:', repr(zfp))
if DEBUG: if DEBUG:
traceback.print_exc() traceback.print_exc()
# Prevent a custom plugin from overriding stdout/stderr as this breaks # 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) opts, args = parser.parse_args(args)
if opts.add_plugin is not None: if opts.add_plugin is not None:
plugin = add_plugin(opts.add_plugin) 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: if opts.build_plugin is not None:
build_plugin(opts.build_plugin) build_plugin(opts.build_plugin)
if opts.remove_plugin is not None: if opts.remove_plugin is not None:
if remove_plugin(opts.remove_plugin): if remove_plugin(opts.remove_plugin):
print 'Plugin removed' print('Plugin removed')
else: else:
print 'No custom plugin named', opts.remove_plugin print('No custom plugin named', opts.remove_plugin)
if opts.customize_plugin is not None: if opts.customize_plugin is not None:
name, custom = opts.customize_plugin.split(',') name, custom = opts.customize_plugin.split(',')
plugin = find_plugin(name.strip()) plugin = find_plugin(name.strip())
if plugin is None: if plugin is None:
print 'No plugin with the name %s exists'%name print('No plugin with the name %s exists'%name)
return 1 return 1
customize_plugin(plugin, custom) customize_plugin(plugin, custom)
if opts.enable_plugin is not None: if opts.enable_plugin is not None:
@ -819,21 +820,21 @@ def main(args=sys.argv):
for plugin in initialized_plugins(): for plugin in initialized_plugins():
type_len, name_len = max(type_len, len(plugin.type)), max(name_len, len(plugin.name)) 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) fmt = '%-{}s%-{}s%-15s%-15s%s'.format(type_len+1, name_len+1)
print fmt%tuple(('Type|Name|Version|Disabled|Site Customization'.split('|'))) print(fmt%tuple(('Type|Name|Version|Disabled|Site Customization'.split('|'))))
print print()
for plugin in initialized_plugins(): for plugin in initialized_plugins():
print fmt%( print(fmt%(
plugin.type, plugin.name, plugin.type, plugin.name,
plugin.version, is_disabled(plugin), plugin.version, is_disabled(plugin),
plugin_customization(plugin) plugin_customization(plugin)
) ))
print '\t', plugin.description print('\t', plugin.description)
if plugin.is_customizable(): if plugin.is_customizable():
try: try:
print '\t', plugin.customization_help() print('\t', plugin.customization_help())
except NotImplementedError: except NotImplementedError:
pass pass
print print()
return 0 return 0

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
from future_builtins import map from future_builtins import map
__license__ = 'GPL v3' __license__ = 'GPL v3'
@ -180,7 +181,7 @@ class PluginLoader(object):
mod.__dict__['get_resources'] = partial(get_resources, zfp) mod.__dict__['get_resources'] = partial(get_resources, zfp)
mod.__dict__['get_icons'] = partial(get_icons, zfp) mod.__dict__['get_icons'] = partial(get_icons, zfp)
mod.__dict__['load_translations'] = partial(load_translations, mod.__dict__, zfp) mod.__dict__['load_translations'] = partial(load_translations, mod.__dict__, zfp)
exec compiled in mod.__dict__ exec(compiled, mod.__dict__)
return mod return mod
@ -309,11 +310,11 @@ if __name__ == '__main__':
with CurrentDir(path): with CurrentDir(path):
for x in os.listdir('.'): for x in os.listdir('.'):
if x[0] != '.': if x[0] != '.':
print ('Adding', x) print('Adding', x)
zf.write(x) zf.write(x)
if os.path.isdir(x): if os.path.isdir(x):
for y in os.listdir(x): for y in os.listdir(x):
zf.write(os.path.join(x, y)) zf.write(os.path.join(x, y))
add_plugin(f.name) add_plugin(f.name)
print ('Added plugin from', sys.argv[-1]) print('Added plugin from', sys.argv[-1])

View File

@ -1626,7 +1626,7 @@ class DB(object):
except EnvironmentError as err: except EnvironmentError as err:
if err.errno == errno.EEXIST: if err.errno == errno.EEXIST:
# Parent directory already exists, re-raise original exception # 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 raise
finally: finally:
del exc_info del exc_info

View File

@ -2,6 +2,7 @@
# vim:fileencoding=utf-8 # vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
@ -38,7 +39,7 @@ def main():
pr.disable() pr.disable()
pr.dump_stats(stats) pr.dump_stats(stats)
show_stats(stats) show_stats(stats)
print ('Stats saved to', stats) print('Stats saved to', stats)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
''' '''
Embedded console for debugging. Embedded console for debugging.
@ -254,7 +255,7 @@ def inspect_mobi(path):
from calibre.ebooks.mobi.debug.main import inspect_mobi from calibre.ebooks.mobi.debug.main import inspect_mobi
prints('Inspecting:', path) prints('Inspecting:', path)
inspect_mobi(path) inspect_mobi(path)
print print()
def main(args=sys.argv): def main(args=sys.argv):
@ -325,7 +326,7 @@ def main(args=sys.argv):
from calibre.utils.winreg.default_programs import register as func from calibre.utils.winreg.default_programs import register as func
else: else:
from calibre.utils.winreg.default_programs import unregister as func from calibre.utils.winreg.default_programs import unregister as func
print 'Running', func.__name__, '...' print('Running', func.__name__, '...')
func() func()
elif opts.export_all_calibre_data: elif opts.export_all_calibre_data:
args = args[1:] args = args[1:]

View File

@ -1,3 +1,4 @@
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
@ -45,7 +46,7 @@ def get_connected_device():
connected_devices.append((det, dev)) connected_devices.append((det, dev))
if dev is None: 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 return
for det, d in connected_devices: for det, d in connected_devices:

View File

@ -1,3 +1,4 @@
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
""" """
@ -100,10 +101,10 @@ class FileFormatter(object):
def info(dev): def info(dev):
info = dev.get_device_information() info = dev.get_device_information()
print "Device name: ", info[0] print("Device name: ", info[0])
print "Device version: ", info[1] print("Device version: ", info[1])
print "Software version:", info[2] print("Software version:", info[2])
print "Mime type: ", info[3] print("Mime type: ", info[3])
def ls(dev, path, recurse=False, human_readable_size=False, ll=False, cols=0): 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) dirs = dev.list(path, recurse)
for dir in dirs: for dir in dirs:
if recurse: if recurse:
print >>output, dir[0] + ":" print(dir[0] + ":", file=output)
lsoutput, lscoloutput = [], [] lsoutput, lscoloutput = [], []
files = dir[1] files = dir[1]
maxlen = 0 maxlen = 0
@ -153,7 +154,7 @@ def ls(dev, path, recurse=False, human_readable_size=False, ll=False, cols=0):
size = str(file.size) size = str(file.size)
if human_readable_size: if human_readable_size:
size = file.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: if not ll and len(lsoutput) > 0:
trytable = [] trytable = []
for colwidth in range(MINIMUM_COL_WIDTH, cols): 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 r in range(len(trytable)):
for c in range(len(trytable[r])): for c in range(len(trytable[r])):
padding = rowwidths[c] - len(trytable[r][c]) padding = rowwidths[c] - len(trytable[r][c])
print >>output, trytablecol[r][c], "".ljust(padding), print(trytablecol[r][c], "".ljust(padding), end=' ', file=output)
print >>output print(file=output)
print >>output print(file=output)
listing = output.getvalue().rstrip()+ "\n" listing = output.getvalue().rstrip()+ "\n"
output.close() output.close()
return listing return listing
@ -235,7 +236,7 @@ def main():
connected_devices.append((det, dev)) connected_devices.append((det, dev))
if dev is None: 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() shutdown_plugins()
return 1 return 1
@ -254,22 +255,22 @@ def main():
total = dev.total_space(end_session=False) total = dev.total_space(end_session=False)
free = dev.free_space() free = dev.free_space()
where = ("Memory", "Card A", "Card B") where = ("Memory", "Card A", "Card B")
print "Filesystem\tSize \tUsed \tAvail \tUse%" print("Filesystem\tSize \tUsed \tAvail \tUse%")
for i in range(3): 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]), 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.)))+"%") str(0 if total[i]==0 else int(100*(total[i]-free[i])/(total[i]*1.)))+"%"))
elif command == 'eject': elif command == 'eject':
dev.eject() dev.eject()
elif command == "books": elif command == "books":
print "Books in main memory:" print("Books in main memory:")
for book in dev.books(): for book in dev.books():
print book print(book)
print "\nBooks on storage carda:" print("\nBooks on storage carda:")
for book in dev.books(oncard='carda'): for book in dev.books(oncard='carda'):
print book print(book)
print "\nBooks on storage cardb:" print("\nBooks on storage cardb:")
for book in dev.books(oncard='cardb'): for book in dev.books(oncard='cardb'):
print book print(book)
elif command == "mkdir": elif command == "mkdir":
parser = OptionParser(usage="usage: %prog mkdir [options] path\nCreate a directory on the device\n\npath must begin with / or card:/") 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: if len(args) != 1:
@ -289,7 +290,7 @@ def main():
if len(args) != 1: if len(args) != 1:
parser.print_help() parser.print_help()
return 1 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": elif command == "info":
info(dev) info(dev)
elif command == "cp": elif command == "cp":
@ -316,7 +317,7 @@ def main():
try: try:
outfile = lopen(outfile, "wb") outfile = lopen(outfile, "wb")
except IOError as e: except IOError as e:
print >> sys.stderr, e print(e, file=sys.stderr)
parser.print_help() parser.print_help()
return 1 return 1
dev.get_file(path, outfile) dev.get_file(path, outfile)
@ -326,7 +327,7 @@ def main():
try: try:
infile = lopen(args[0], "rb") infile = lopen(args[0], "rb")
except IOError as e: except IOError as e:
print >> sys.stderr, e print(e, file=sys.stderr)
parser.print_help() parser.print_help()
return 1 return 1
dev.put_file(infile, args[1][4:], replace_file=options.force) dev.put_file(infile, args[1][4:], replace_file=options.force)
@ -376,8 +377,8 @@ def main():
path = args[0] path = args[0]
from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.metadata.meta import get_metadata
mi = get_metadata(lopen(path, 'rb'), path.rpartition('.')[-1].lower()) mi = get_metadata(lopen(path, 'rb'), path.rpartition('.')[-1].lower())
print dev.upload_books([args[0]], [os.path.basename(args[0])], print(dev.upload_books([args[0]], [os.path.basename(args[0])],
end_session=False, metadata=[mi]) end_session=False, metadata=[mi]))
dev.eject() dev.eject()
else: else:
parser.print_help() parser.print_help()
@ -385,9 +386,9 @@ def main():
dev.close() dev.close()
return 1 return 1
except DeviceLocked: 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: except (ArgumentError, DeviceError) as e:
print >>sys.stderr, e print(e, file=sys.stderr)
return 1 return 1
finally: finally:
shutdown_plugins() shutdown_plugins()

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os import os
@ -276,7 +277,7 @@ class Bookmark(): # {{{
self.last_read_location = self.last_read - self.pdf_page_offset self.last_read_location = self.last_read - self.pdf_page_offset
else: else:
print "unsupported bookmark_extension: %s" % self.bookmark_extension print("unsupported bookmark_extension: %s" % self.bookmark_extension)
self.user_notes = user_notes self.user_notes = user_notes
def get_book_length(self): def get_book_length(self):
@ -312,6 +313,6 @@ class Bookmark(): # {{{
pass pass
else: else:
print "unsupported bookmark_extension: %s" % self.bookmark_extension print("unsupported bookmark_extension: %s" % self.bookmark_extension)
# }}} # }}}

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2009, John Schember <john at nachtimwald.com>' __copyright__ = '2009, John Schember <john at nachtimwald.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
@ -555,7 +556,7 @@ class KINDLE2(KINDLE):
print('Could not retrieve override method choice, using default.') print('Could not retrieve override method choice, using default.')
apnx_builder.write_apnx(filepath, apnx_path, method=method, page_count=custom_page_count) apnx_builder.write_apnx(filepath, apnx_path, method=method, page_count=custom_page_count)
except: except:
print 'Failed to generate APNX' print('Failed to generate APNX')
import traceback import traceback
traceback.print_exc() traceback.print_exc()

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import division from __future__ import division
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2010-2012, Timothy Legge <timlegge@gmail.com>, Kovid Goyal <kovid@kovidgoyal.net> and David Forrester <davidfor@internode.on.net>' __copyright__ = '2010-2012, Timothy Legge <timlegge@gmail.com>, Kovid Goyal <kovid@kovidgoyal.net> and David Forrester <davidfor@internode.on.net>'
@ -646,7 +647,7 @@ class KOBO(USBMS):
path = ContentID path = ContentID
if oncard == 'cardb': if oncard == 'cardb':
print 'path from_contentid cardb' print('path from_contentid cardb')
elif oncard == 'carda': elif oncard == 'carda':
path = path.replace("file:///mnt/sd/", self._card_a_prefix) path = path.replace("file:///mnt/sd/", self._card_a_prefix)
# print "SD Card: " + path # print "SD Card: " + path
@ -1929,7 +1930,7 @@ class KOBOTOUCH(KOBO):
return super(KOBOTOUCH, self).path_from_contentid(ContentID, ContentType, MimeType, oncard) return super(KOBOTOUCH, self).path_from_contentid(ContentID, ContentType, MimeType, oncard)
if oncard == 'cardb': if oncard == 'cardb':
print 'path from_contentid cardb' print('path from_contentid cardb')
else: else:
if (ContentType == "6" or ContentType == "10"): # and MimeType == 'application/x-kobo-epub+zip': if (ContentType == "6" or ContentType == "10"): # and MimeType == 'application/x-kobo-epub+zip':
if path.startswith("file:///mnt/onboard/"): if path.startswith("file:///mnt/onboard/"):
@ -3399,6 +3400,6 @@ if __name__ == '__main__':
dev.set_progress_reporter(prints) dev.set_progress_reporter(prints)
# dev.open(cd, None) # dev.open(cd, None)
# dev.filesystem_cache.dump() # dev.filesystem_cache.dump()
print ('Prefix for main memory:', dev.dbversion) print('Prefix for main memory:', dev.dbversion)
finally: finally:
dev.shutdown() dev.shutdown()

View File

@ -238,7 +238,7 @@ class TREKSTOR(USBMS):
0x0067, # This is for the Pyrus Mini 0x0067, # This is for the Pyrus Mini
0x006f, # This is for the Pyrus Maxi 0x006f, # This is for the Pyrus Maxi
0x003e, # This is for the EBOOK_PLAYER_5M https://bugs.launchpad.net/bugs/792091 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 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 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 0x73, # This is for the Pyrus 2 LED https://bugs.launchpad.net/bugs/1376018

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
@ -572,6 +573,6 @@ if __name__ == '__main__':
dev.set_progress_reporter(prints) dev.set_progress_reporter(prints)
dev.open(cd, None) dev.open(cd, None)
dev.filesystem_cache.dump() 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: finally:
dev.shutdown() dev.shutdown()

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
@ -64,7 +65,7 @@ def main():
from calibre.devices.mtp.driver import MTP_DEVICE from calibre.devices.mtp.driver import MTP_DEVICE
dev = MTP_DEVICE(None) dev = MTP_DEVICE(None)
dev.startup() dev.startup()
print (dev.wpd, dev.wpd_error) print(dev.wpd, dev.wpd_error)
try: try:
devices = scan_usb_devices() devices = scan_usb_devices()
@ -72,12 +73,12 @@ def main():
if not pnp_id: if not pnp_id:
raise ValueError('Failed to detect device') raise ValueError('Failed to detect device')
# pprint.pprint(dev.detected_devices) # pprint.pprint(dev.detected_devices)
print ('Trying to connect to:', pnp_id) print('Trying to connect to:', pnp_id)
dev.open(pnp_id, '') dev.open(pnp_id, '')
pprint.pprint(dev.dev.data) pprint.pprint(dev.dev.data)
print ('Connected to:', dev.get_gui_name()) print('Connected to:', dev.get_gui_name())
print ('Total space', dev.total_space()) print('Total space', dev.total_space())
print ('Free space', dev.free_space()) print('Free space', dev.free_space())
# pprint.pprint(dev.dev.create_folder(dev.filesystem_cache.entries[0].object_id, # pprint.pprint(dev.dev.create_folder(dev.filesystem_cache.entries[0].object_id,
# 'zzz')) # 'zzz'))
# print ('Fetching file: oFF (198214 bytes)') # print ('Fetching file: oFF (198214 bytes)')

View File

@ -221,9 +221,9 @@ class PALADIN(USBMS):
'\n'+tb) '\n'+tb)
def get_database_min_id(self, source_id): def get_database_min_id(self, source_id):
sequence_min = 0L sequence_min = 0
if source_id == 1: if source_id == 1:
sequence_min = 4294967296L sequence_min = 4294967296
return sequence_min return sequence_min

View File

@ -130,10 +130,10 @@ class PRS505(USBMS):
dname = os.path.dirname(cachep) dname = os.path.dirname(cachep)
if not os.path.exists(dname): if not os.path.exists(dname):
try: try:
os.makedirs(dname, mode=0777) os.makedirs(dname, mode=0o777)
except: except:
time.sleep(5) time.sleep(5)
os.makedirs(dname, mode=0777) os.makedirs(dname, mode=0o777)
with lopen(cachep, 'wb') as f: with lopen(cachep, 'wb') as f:
f.write(u'''<?xml version="1.0" encoding="UTF-8"?> f.write(u'''<?xml version="1.0" encoding="UTF-8"?>
<cache xmlns="http://www.kinoma.com/FskCache/1"> <cache xmlns="http://www.kinoma.com/FskCache/1">

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
@ -332,9 +333,9 @@ class PRST1(USBMS):
return long(row[0]) return long(row[0])
def get_database_min_id(self, source_id): def get_database_min_id(self, source_id):
sequence_min = 0L sequence_min = 0
if source_id == 1: if source_id == 1:
sequence_min = 4294967296L sequence_min = 4294967296
return sequence_min return sequence_min

View File

@ -1,3 +1,4 @@
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
''' '''
@ -90,8 +91,8 @@ class LibUSBScanner(object):
self() self()
for i in xrange(3): for i in xrange(3):
gc.collect() gc.collect()
print 'Mem consumption increased by:', memory() - start, 'MB', print('Mem consumption increased by:', memory() - start, 'MB', end=' ')
print 'after', num, 'repeats' print('after', num, 'repeats')
class LinuxScanner(object): class LinuxScanner(object):

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
@ -201,13 +202,13 @@ def umount(node_path):
def test_udisks(ver=None): def test_udisks(ver=None):
import sys import sys
dev = sys.argv[1] dev = sys.argv[1]
print 'Testing with node', dev print('Testing with node', dev)
u = get_udisks(ver=ver) u = get_udisks(ver=ver)
print 'Using Udisks:', u.__class__.__name__ print('Using Udisks:', u.__class__.__name__)
print 'Mounted at:', u.mount(dev) print('Mounted at:', u.mount(dev))
print 'Unmounting' print('Unmounting')
u.unmount(dev) u.unmount(dev)
print 'Ejecting:' print('Ejecting:')
u.eject(dev) u.eject(dev)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL 3' __license__ = 'GPL 3'
from __future__ import print_function
__copyright__ = '2009, John Schember <john@nachtimwald.com>' __copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
@ -54,7 +55,7 @@ class CLI(object):
try: try:
shutil.copyfileobj(infile, dest) shutil.copyfileobj(infile, dest)
except IOError: 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) time.sleep(0.2)
infile.seek(0) infile.seek(0)
dest.seek(0) dest.seek(0)

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2009, John Schember <john at nachtimwald.com> ' \ __copyright__ = '2009, John Schember <john at nachtimwald.com> ' \
'2009, Kovid Goyal <kovid@kovidgoyal.net>' '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
@ -404,7 +405,7 @@ class Device(DeviceConfig, DevicePlugin):
mount_map = usbobserver.get_mounted_filesystems() mount_map = usbobserver.get_mounted_filesystems()
drives = {k: mount_map.get(v) for k, v in drives.iteritems()} drives = {k: mount_map.get(v) for k, v in drives.iteritems()}
if DEBUG: if DEBUG:
print print()
from pprint import pprint from pprint import pprint
pprint({'bsd_drives': bsd_drives, 'mount_map': mount_map, 'drives': drives}) pprint({'bsd_drives': bsd_drives, 'mount_map': mount_map, 'drives': drives})
if drives.get('carda') is None and drives.get('cardb') is not None: if drives.get('carda') is None and drives.get('cardb') is not None:
@ -504,7 +505,7 @@ class Device(DeviceConfig, DevicePlugin):
except: except:
ok[node] = False ok[node] = False
if DEBUG and not ok[node]: 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) devnodes.append(node)
@ -553,7 +554,7 @@ class Device(DeviceConfig, DevicePlugin):
mount(node) mount(node)
return 0 return 0
except: except:
print 'Udisks mount call failed:' print('Udisks mount call failed:')
import traceback import traceback
traceback.print_exc() traceback.print_exc()
return 1 return 1
@ -570,7 +571,7 @@ class Device(DeviceConfig, DevicePlugin):
'kernel is exporting a deprecated version of SYSFS.') 'kernel is exporting a deprecated version of SYSFS.')
%self.__class__.__name__) %self.__class__.__name__)
if DEBUG: if DEBUG:
print '\nFound device nodes:', main, carda, cardb print('\nFound device nodes:', main, carda, cardb)
self._linux_mount_map = {} self._linux_mount_map = {}
mp, ret = mount(main, 'main') mp, ret = mount(main, 'main')
@ -589,7 +590,7 @@ class Device(DeviceConfig, DevicePlugin):
continue continue
mp, ret = mount(card, typ) mp, ret = mount(card, typ)
if mp is None: 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: else:
if not mp.endswith('/'): if not mp.endswith('/'):
mp += '/' mp += '/'
@ -616,7 +617,7 @@ class Device(DeviceConfig, DevicePlugin):
except: except:
pass pass
if DEBUG and ro: if DEBUG and ro:
print '\nThe mountpoint', mp, 'is readonly, ignoring it' print('\nThe mountpoint', mp, 'is readonly, ignoring it')
return ro return ro
for mp in ('_main_prefix', '_card_a_prefix', '_card_b_prefix'): for mp in ('_main_prefix', '_card_a_prefix', '_card_b_prefix'):
@ -701,10 +702,10 @@ class Device(DeviceConfig, DevicePlugin):
'label': vdevif.GetProperty('volume.label')} 'label': vdevif.GetProperty('volume.label')}
vols.append(vol) vols.append(vol)
except dbus.exceptions.DBusException as e: except dbus.exceptions.DBusException as e:
print e print(e)
continue continue
except dbus.exceptions.DBusException as e: except dbus.exceptions.DBusException as e:
print e print(e)
continue continue
except dbus.exceptions.DBusException as e: except dbus.exceptions.DBusException as e:
continue continue
@ -719,7 +720,7 @@ class Device(DeviceConfig, DevicePlugin):
vols.sort(cmp=ocmp) vols.sort(cmp=ocmp)
if verbose: if verbose:
print "FBSD: ", vols print("FBSD: ", vols)
mtd=0 mtd=0
@ -736,33 +737,33 @@ class Device(DeviceConfig, DevicePlugin):
time.sleep(1) time.sleep(1)
loops += 1 loops += 1
if loops > 100: if loops > 100:
print "ERROR: Timeout waiting for mount to complete" print("ERROR: Timeout waiting for mount to complete")
continue continue
mp = vol['dev'].GetProperty('volume.mount_point') mp = vol['dev'].GetProperty('volume.mount_point')
except dbus.exceptions.DBusException as e: except dbus.exceptions.DBusException as e:
print "Failed to mount ", e print("Failed to mount ", e)
continue continue
# Mount Point becomes Mount Path # Mount Point becomes Mount Path
mp += '/' mp += '/'
if verbose: if verbose:
print "FBSD: mounted", vol['label'], "on", mp print("FBSD: mounted", vol['label'], "on", mp)
if mtd == 0: if mtd == 0:
self._main_prefix = mp self._main_prefix = mp
self._main_vol = vol['vol'] self._main_vol = vol['vol']
if verbose: if verbose:
print "FBSD: main = ", self._main_prefix print("FBSD: main = ", self._main_prefix)
if mtd == 1: if mtd == 1:
self._card_a_prefix = mp self._card_a_prefix = mp
self._card_a_vol = vol['vol'] self._card_a_vol = vol['vol']
if verbose: if verbose:
print "FBSD: card a = ", self._card_a_prefix print("FBSD: card a = ", self._card_a_prefix)
if mtd == 2: if mtd == 2:
self._card_b_prefix = mp self._card_b_prefix = mp
self._card_b_vol = vol['vol'] self._card_b_vol = vol['vol']
if verbose: 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. # Note that mtd is used as a bool... not incrementing is fine.
break break
mtd += 1 mtd += 1
@ -785,27 +786,27 @@ class Device(DeviceConfig, DevicePlugin):
if self._main_prefix: if self._main_prefix:
if verbose: if verbose:
print "FBSD: umount main:", self._main_prefix print("FBSD: umount main:", self._main_prefix)
try: try:
self._main_vol.Unmount([]) self._main_vol.Unmount([])
except dbus.exceptions.DBusException as e: except dbus.exceptions.DBusException as e:
print 'Unable to eject ', e print('Unable to eject ', e)
if self._card_a_prefix: if self._card_a_prefix:
if verbose: if verbose:
print "FBSD: umount card a:", self._card_a_prefix print("FBSD: umount card a:", self._card_a_prefix)
try: try:
self._card_a_vol.Unmount([]) self._card_a_vol.Unmount([])
except dbus.exceptions.DBusException as e: except dbus.exceptions.DBusException as e:
print 'Unable to eject ', e print('Unable to eject ', e)
if self._card_b_prefix: if self._card_b_prefix:
if verbose: if verbose:
print "FBSD: umount card b:", self._card_b_prefix print("FBSD: umount card b:", self._card_b_prefix)
try: try:
self._card_b_vol.Unmount([]) self._card_b_vol.Unmount([])
except dbus.exceptions.DBusException as e: except dbus.exceptions.DBusException as e:
print 'Unable to eject ', e print('Unable to eject ', e)
self._main_prefix = None self._main_prefix = None
self._card_a_prefix = None self._card_a_prefix = None
@ -885,8 +886,8 @@ class Device(DeviceConfig, DevicePlugin):
try: try:
eject(d) eject(d)
except Exception as e: except Exception as e:
print 'Udisks eject call for:', d, 'failed:' print('Udisks eject call for:', d, 'failed:')
print '\t', e print('\t', e)
def eject(self): def eject(self):
if islinux: if islinux:

View File

@ -1,7 +1,8 @@
from __future__ import print_function
import gc, usbobserver import gc, usbobserver
a = None a = None
print len(gc.get_objects()) print(len(gc.get_objects()))
usbobserver.get_devices() usbobserver.get_devices()
gc.collect() gc.collect()
print len(gc.get_objects()) print(len(gc.get_objects()))

View File

@ -4,6 +4,7 @@
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
import os, string, _winreg as winreg, re, sys import os, string, _winreg as winreg, re, sys
from collections import namedtuple, defaultdict 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_DETAIL_DATA = POINTER(SP_DEVICE_INTERFACE_DETAIL_DATA)
PSP_DEVICE_INTERFACE_DATA = POINTER(SP_DEVICE_INTERFACE_DATA) PSP_DEVICE_INTERFACE_DATA = POINTER(SP_DEVICE_INTERFACE_DATA)
INVALID_HANDLE_VALUE = c_void_p(-1).value INVALID_HANDLE_VALUE = c_void_p(-1).value
GENERIC_READ = 0x80000000L GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000L GENERIC_WRITE = 0x40000000
FILE_SHARE_READ = 0x1 FILE_SHARE_READ = 0x1
FILE_SHARE_WRITE = 0x2 FILE_SHARE_WRITE = 0x2
OPEN_EXISTING = 0x3 OPEN_EXISTING = 0x3

View File

@ -77,6 +77,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT.
""" """
from __future__ import generators from __future__ import generators
from __future__ import print_function
__author__ = "Leonard Richardson (leonardr@segfault.org)" __author__ = "Leonard Richardson (leonardr@segfault.org)"
__version__ = "3.0.5" __version__ = "3.0.5"
@ -419,7 +420,7 @@ class NavigableString(unicode, PageElement):
if attr == 'string': if attr == 'string':
return self return self
else: 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): def __unicode__(self):
return unicode(str(self), DEFAULT_OUTPUT_ENCODING) # Changed by Kovid return unicode(str(self), DEFAULT_OUTPUT_ENCODING) # Changed by Kovid
@ -517,10 +518,10 @@ class Tag(PageElement):
self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities
# Convert any HTML, XML, or numeric entities in the attribute values. # 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+);", re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);",
self._convertEntities, self._convertEntities,
val)) k_val[1]))
self.attrs = map(convert, self.attrs) self.attrs = map(convert, self.attrs)
def get(self, key, default=None): def get(self, key, default=None):
@ -589,7 +590,7 @@ class Tag(PageElement):
return self.find(tag[:-3]) return self.find(tag[:-3])
elif tag.find('__') != 0: elif tag.find('__') != 0:
return self.find(tag) 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): def __eq__(self, other):
"""Returns true iff this tag has the same name, the same attributes, """Returns true iff this tag has the same name, the same attributes,
@ -881,8 +882,8 @@ class SoupStrainer:
if self._matches(markup, self.text): if self._matches(markup, self.text):
found = markup found = markup
else: else:
raise Exception, "I don't know how to match against a %s" \ raise Exception("I don't know how to match against a %s" \
% markup.__class__ % markup.__class__)
return found return found
def _matches(self, markup, matchAgainst): def _matches(self, markup, matchAgainst):
@ -1261,7 +1262,7 @@ class BeautifulStoneSoup(Tag, SGMLParser):
if self.quoteStack: if self.quoteStack:
#This is not a real tag. #This is not a real tag.
#print "<%s> is not real!" % name #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)) self.handle_data('<%s%s>' % (name, attrs))
return return
self.endData() self.endData()
@ -1535,7 +1536,7 @@ class BeautifulSoup(BeautifulStoneSoup):
# else an encoding was specified explicitly and it # else an encoding was specified explicitly and it
# worked. Rewrite the meta tag. # worked. Rewrite the meta tag.
newAttr = self.CHARSET_RE.sub\ newAttr = self.CHARSET_RE.sub\
(lambda(match):match.group(1) + (lambda match:match.group(1) +
"%SOUP-ENCODING%", value) "%SOUP-ENCODING%", value)
attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], attrs[contentTypeIndex] = (attrs[contentTypeIndex][0],
newAttr) newAttr)
@ -1738,7 +1739,7 @@ class UnicodeDammit:
"iso-8859-1", "iso-8859-1",
"iso-8859-2"): "iso-8859-2"):
markup = re.compile("([\x80-\x9f])").sub \ markup = re.compile("([\x80-\x9f])").sub \
(lambda(x): self._subMSChar(x.group(1)), (lambda x: self._subMSChar(x.group(1)),
markup) markup)
try: try:
@ -1934,4 +1935,4 @@ class UnicodeDammit:
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
soup = BeautifulSoup(sys.stdin.read()) soup = BeautifulSoup(sys.stdin.read())
print soup.prettify() print(soup.prettify())

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -2,6 +2,7 @@
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3' __license__ = 'GPL v3'
from __future__ import print_function
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
from cStringIO import StringIO from cStringIO import StringIO
@ -34,17 +35,17 @@ def test():
'owaic jociowapjcivcjpoivjporeivjpoavca; p9aw8743y6r74%$^$^%8 ') 'owaic jociowapjcivcjpoivjporeivjpoavca; p9aw8743y6r74%$^$^%8 ')
] ]
for test in TESTS: for test in TESTS:
print 'Test:', repr(test) print('Test:', repr(test))
print '\tTesting compression...' print('\tTesting compression...')
good = py_compress_doc(test) good = py_compress_doc(test)
x = compress_doc(test) x = compress_doc(test)
print '\t\tgood:', repr(good) print('\t\tgood:', repr(good))
print '\t\tx :', repr(x) print('\t\tx :', repr(x))
assert x == good assert x == good
print '\tTesting decompression...' print('\tTesting decompression...')
print '\t\t', repr(decompress_doc(x)) print('\t\t', repr(decompress_doc(x)))
assert decompress_doc(x) == test assert decompress_doc(x) == test
print print()
def py_compress_doc(data): def py_compress_doc(data):

View File

@ -174,7 +174,8 @@ class Block(object):
def fget(self): def fget(self):
return self._position return self._position
def fset(self, (x, y)): def fset(self, xxx_todo_changeme):
(x, y) = xxx_todo_changeme
self._position = Point(x, y) self._position = Point(x, y)
if self.layouts: if self.layouts:
self.layouts[0].setPosition(QPointF(x, y)) self.layouts[0].setPosition(QPointF(x, y))

View File

@ -2,6 +2,7 @@
# coding: utf-8 # coding: utf-8
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2011, Anthon van der Neut <A.van.der.Neut@ruamel.eu>' __copyright__ = '2011, Anthon van der Neut <A.van.der.Neut@ruamel.eu>'

View File

@ -2,6 +2,7 @@
# vim:fileencoding=utf-8 # vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'

View File

@ -2,6 +2,7 @@
# vim:fileencoding=utf-8 # vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
@ -39,7 +40,7 @@ def dump(path):
dest += '-dumped' dest += '-dumped'
do_dump(path, dest) do_dump(path, dest)
print (path, 'dumped to', dest) print(path, 'dumped to', dest)
if __name__ == '__main__': if __name__ == '__main__':
dump(sys.argv[-1]) dump(sys.argv[-1])

View File

@ -2,6 +2,7 @@
# vim:fileencoding=utf-8 # vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'

View File

@ -41,7 +41,7 @@ def initialize_container(path_to_container, opf_name='metadata.opf',
CONTAINER = simple_container_xml(opf_name, rootfiles).encode('utf-8') CONTAINER = simple_container_xml(opf_name, rootfiles).encode('utf-8')
zf = ZipFile(path_to_container, 'w') zf = ZipFile(path_to_container, 'w')
zf.writestr('mimetype', 'application/epub+zip', compression=ZIP_STORED) 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) zf.writestr('META-INF/container.xml', CONTAINER)
for path, _, data in extra_entries: for path, _, data in extra_entries:
zf.writestr(path, data) zf.writestr(path, data)

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -220,7 +221,7 @@ def traverse(path_to_html_file, max_levels=sys.maxint, verbose=0, encoding=None)
except IgnoreFile as err: except IgnoreFile as err:
rejects.append(link) rejects.append(link)
if not err.doesnt_exist or verbose > 1: if not err.doesnt_exist or verbose > 1:
print repr(err) print(repr(err))
for link in rejects: for link in rejects:
hf.links.remove(link) hf.links.remove(link)

View File

@ -13,6 +13,7 @@
Ned Batchelder, July 2007. Ned Batchelder, July 2007.
This Python code is in the public domain. This Python code is in the public domain.
""" """
from __future__ import print_function
import re import re
@ -520,7 +521,7 @@ if __name__ == '__main__':
import sys import sys
if len(sys.argv) > 1: if len(sys.argv) > 1:
for word in sys.argv[1:]: for word in sys.argv[1:]:
print '-'.join(hyphenate_word(word)) print('-'.join(hyphenate_word(word)))
else: else:
import doctest import doctest
doctest.testmod(verbose=True) doctest.testmod(verbose=True)

View File

@ -1,4 +1,5 @@
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
@ -56,7 +57,7 @@ def main(args=sys.argv):
opts, args = parser.parse_args(args) opts, args = parser.parse_args(args)
if len(args) < 2: if len(args) < 2:
parser.print_help() parser.print_help()
print 'No input file specified.' print('No input file specified.')
return 1 return 1
any2lit(opts, args[1]) any2lit(opts, args[1])
return 0 return 0

View File

@ -3,6 +3,7 @@ Modified version of SHA-1 used in Microsoft LIT files.
Adapted from the PyPy pure-Python SHA-1 implementation. Adapted from the PyPy pure-Python SHA-1 implementation.
""" """
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>' __copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
@ -29,7 +30,7 @@ def _long2bytesBigEndian(n, blocksize=0):
s = '' s = ''
pack = struct.pack pack = struct.pack
while n > 0: while n > 0:
s = pack('>I', n & 0xffffffffL) + s s = pack('>I', n & 0xffffffff) + s
n = n >> 32 n = n >> 32
# Strip off leading zeros. # Strip off leading zeros.
@ -55,7 +56,7 @@ def _bytelist2longBigEndian(list):
"Transform a list of characters into a list of longs." "Transform a list of characters into a list of longs."
imax = len(list)/4 imax = len(list)/4
hl = [0L] * imax hl = [0] * imax
j = 0 j = 0
i = 0 i = 0
@ -119,10 +120,10 @@ f[68] = f0_19
# Constants to be used # Constants to be used
K = [ K = [
0x5A827999L, # ( 0 <= t <= 19) 0x5A827999, # ( 0 <= t <= 19)
0x6ED9EBA1L, # (20 <= t <= 39) 0x6ED9EBA1, # (20 <= t <= 39)
0x8F1BBCDCL, # (40 <= t <= 59) 0x8F1BBCDC, # (40 <= t <= 59)
0xCA62C1D6L # (60 <= t <= 79) 0xCA62C1D6 # (60 <= t <= 79)
] ]
@ -133,7 +134,7 @@ class mssha1(object):
"Initialisation." "Initialisation."
# Initial message length in bits(!). # Initial message length in bits(!).
self.length = 0L self.length = 0
self.count = [0, 0] self.count = [0, 0]
# Initial empty message as a sequence of bytes (8 bit characters). # Initial empty message as a sequence of bytes (8 bit characters).
@ -146,21 +147,21 @@ class mssha1(object):
def init(self): def init(self):
"Initialize the message-digest and set all fields to zero." "Initialize the message-digest and set all fields to zero."
self.length = 0L self.length = 0
self.input = [] self.input = []
# Initial 160 bit message digest (5 times 32 bit). # Initial 160 bit message digest (5 times 32 bit).
# Also changed by Microsoft from standard. # Also changed by Microsoft from standard.
self.H0 = 0x32107654L self.H0 = 0x32107654
self.H1 = 0x23016745L self.H1 = 0x23016745
self.H2 = 0xC4E680A2L self.H2 = 0xC4E680A2
self.H3 = 0xDC679823L self.H3 = 0xDC679823
self.H4 = 0xD0857A34L self.H4 = 0xD0857A34
def _transform(self, W): def _transform(self, W):
for t in range(16, 80): for t in range(16, 80):
W.append(_rotateLeft( 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 A = self.H0
B = self.H1 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] TEMP = _rotateLeft(A, 5) + f[t](B, C, D) + E + W[t] + K[t/20]
E = D E = D
D = C D = C
C = _rotateLeft(B, 30) & 0xffffffffL C = _rotateLeft(B, 30) & 0xffffffff
B = A B = A
A = TEMP & 0xffffffffL A = TEMP & 0xffffffff
self.H0 = (self.H0 + A) & 0xffffffffL self.H0 = (self.H0 + A) & 0xffffffff
self.H1 = (self.H1 + B) & 0xffffffffL self.H1 = (self.H1 + B) & 0xffffffff
self.H2 = (self.H2 + C) & 0xffffffffL self.H2 = (self.H2 + C) & 0xffffffff
self.H3 = (self.H3 + D) & 0xffffffffL self.H3 = (self.H3 + D) & 0xffffffff
self.H4 = (self.H4 + E) & 0xffffffffL self.H4 = (self.H4 + E) & 0xffffffff
# Down from here all methods follow the Python Standard Library # Down from here all methods follow the Python Standard Library
# API of the sha module. # API of the sha module.
@ -204,7 +205,7 @@ class mssha1(object):
leninBuf = long(len(inBuf)) leninBuf = long(len(inBuf))
# Compute number of bytes mod 64. # Compute number of bytes mod 64.
index = (self.count[1] >> 3) & 0x3FL index = (self.count[1] >> 3) & 0x3F
# Update number of bits. # Update number of bits.
self.count[1] = self.count[1] + (leninBuf << 3) self.count[1] = self.count[1] + (leninBuf << 3)
@ -243,7 +244,7 @@ class mssha1(object):
input = [] + self.input input = [] + self.input
count = [] + self.count count = [] + self.count
index = (self.count[1] >> 3) & 0x3fL index = (self.count[1] >> 3) & 0x3f
if index < 56: if index < 56:
padLen = 56 - index padLen = 56 - index
@ -325,7 +326,7 @@ if __name__ == '__main__':
import sys import sys
file = None file = None
if len(sys.argv) > 2: if len(sys.argv) > 2:
print "usage: %s [FILE]" % sys.argv[0] print("usage: %s [FILE]" % sys.argv[0])
return return
elif len(sys.argv) < 2: elif len(sys.argv) < 2:
file = sys.stdin file = sys.stdin
@ -339,6 +340,6 @@ if __name__ == '__main__':
file.close() file.close()
digest = context.hexdigest().upper() digest = context.hexdigest().upper()
for i in xrange(0, 40, 8): for i in xrange(0, 40, 8):
print digest[i:i+8], print(digest[i:i+8], end=' ')
print print()
main() main()

View File

@ -2,6 +2,7 @@
Support for reading LIT files. Support for reading LIT files.
''' '''
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net> ' \ __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net> ' \
@ -244,7 +245,7 @@ class UnBinary(object):
errors += 1 errors += 1
tag_name = '?'+unichr(tag)+'?' tag_name = '?'+unichr(tag)+'?'
current_map = self.tag_to_attr_map[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)) buf.write(encode(tag_name))
elif flags & FLAG_CLOSING: elif flags & FLAG_CLOSING:
if depth == 0: if depth == 0:
@ -920,7 +921,7 @@ class LitContainer(object):
except LitError: except LitError:
if 'PENGUIN group' not in raw: if 'PENGUIN group' not in raw:
raise raise
print "WARNING: attempting PENGUIN malformed OPF fix" print("WARNING: attempting PENGUIN malformed OPF fix")
raw = raw.replace( raw = raw.replace(
'PENGUIN group', '\x00\x01\x18\x00PENGUIN group', 1) 'PENGUIN group', '\x00\x01\x18\x00PENGUIN group', 1)
unbin = UnBinary(raw, path, self._litfile.manifest, OPF_MAP) unbin = UnBinary(raw, path, self._litfile.manifest, OPF_MAP)

View File

@ -2,6 +2,7 @@
Basic support for writing LIT files. Basic support for writing LIT files.
''' '''
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>' __copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
@ -135,7 +136,7 @@ def randbytes(n):
def warn(x): def warn(x):
print x print(x)
class ReBinary(object): class ReBinary(object):

View File

@ -1,3 +1,4 @@
from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
""" """
@ -731,7 +732,7 @@ class HTMLConverter(object):
if self.minimize_memory_usage: if self.minimize_memory_usage:
ptag.extract() ptag.extract()
except AttributeError: except AttributeError:
print ptag, type(ptag) print(ptag, type(ptag))
def get_alignment(self, css): def get_alignment(self, css):
val = css['text-align'].lower() if css.has_key('text-align') else None # noqa 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) self.process_children(tag, tag_css, tag_pseudo_css)
elif tagname == 'table' and not self.ignore_tables and not self.in_table: elif tagname == 'table' and not self.ignore_tables and not self.in_table:
if self.render_tables_as_images: if self.render_tables_as_images:
print 'Rendering table...' print('Rendering table...')
from calibre.ebooks.lrf.html.table_as_image import render_table from calibre.ebooks.lrf.html.table_as_image import render_table
pheight = int(self.current_page.pageStyle.attrs['textheight']) pheight = int(self.current_page.pageStyle.attrs['textheight'])
pwidth = int(self.current_page.pageStyle.attrs['textwidth']) pwidth = int(self.current_page.pageStyle.attrs['textwidth'])

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