mirror of
https://github.com/kovidgoyal/calibre.git
synced 2025-07-07 10:14:46 -04:00
use contextmanagers for open()
This commit is contained in:
parent
cb28cf5d92
commit
0cee082978
@ -102,7 +102,8 @@ class ComicInput(InputFormatPlugin):
|
|||||||
'%s is not a valid comic collection'
|
'%s is not a valid comic collection'
|
||||||
' no comics.txt was found in the file')
|
' no comics.txt was found in the file')
|
||||||
%stream.name)
|
%stream.name)
|
||||||
raw = open('comics.txt', 'rb').read()
|
with open('comics.txt', 'rb') as f:
|
||||||
|
raw = f.read()
|
||||||
if raw.startswith(codecs.BOM_UTF16_BE):
|
if raw.startswith(codecs.BOM_UTF16_BE):
|
||||||
raw = raw.decode('utf-16-be')[1:]
|
raw = raw.decode('utf-16-be')[1:]
|
||||||
elif raw.startswith(codecs.BOM_UTF16_LE):
|
elif raw.startswith(codecs.BOM_UTF16_LE):
|
||||||
@ -230,7 +231,7 @@ class ComicInput(InputFormatPlugin):
|
|||||||
_('Page')+' %d'%(i+1), play_order=po)
|
_('Page')+' %d'%(i+1), play_order=po)
|
||||||
po += 1
|
po += 1
|
||||||
opf.set_toc(toc)
|
opf.set_toc(toc)
|
||||||
m, n = open(u'metadata.opf', 'wb'), open('toc.ncx', 'wb')
|
with open(u'metadata.opf', 'wb') as m, open('toc.ncx', 'wb') as n:
|
||||||
opf.render(m, n, u'toc.ncx')
|
opf.render(m, n, u'toc.ncx')
|
||||||
return os.path.abspath(u'metadata.opf')
|
return os.path.abspath(u'metadata.opf')
|
||||||
|
|
||||||
|
@ -367,7 +367,8 @@ class EPUBOutput(OutputFormatPlugin):
|
|||||||
if tag.tail:
|
if tag.tail:
|
||||||
tag.tail = tag.tail.strip()
|
tag.tail = tag.tail.strip()
|
||||||
compressed = etree.tostring(tree.getroot(), encoding='utf-8')
|
compressed = etree.tostring(tree.getroot(), encoding='utf-8')
|
||||||
open(ncx_path, 'wb').write(compressed)
|
with open(ncx_path, 'wb') as f:
|
||||||
|
f.write(compressed)
|
||||||
# }}}
|
# }}}
|
||||||
|
|
||||||
def workaround_ade_quirks(self): # {{{
|
def workaround_ade_quirks(self): # {{{
|
||||||
|
@ -91,17 +91,20 @@ class HTMLOutput(OutputFormatPlugin):
|
|||||||
|
|
||||||
# read template files
|
# read template files
|
||||||
if opts.template_html_index is not None:
|
if opts.template_html_index is not None:
|
||||||
template_html_index_data = open(opts.template_html_index, 'rb').read()
|
with open(opts.template_html_index, 'rb') as f:
|
||||||
|
template_html_index_data = f.read()
|
||||||
else:
|
else:
|
||||||
template_html_index_data = P('templates/html_export_default_index.tmpl', data=True)
|
template_html_index_data = P('templates/html_export_default_index.tmpl', data=True)
|
||||||
|
|
||||||
if opts.template_html is not None:
|
if opts.template_html is not None:
|
||||||
template_html_data = open(opts.template_html, 'rb').read()
|
with open(opts.template_html, 'rb') as f:
|
||||||
|
template_html_data = f.read()
|
||||||
else:
|
else:
|
||||||
template_html_data = P('templates/html_export_default.tmpl', data=True)
|
template_html_data = P('templates/html_export_default.tmpl', data=True)
|
||||||
|
|
||||||
if opts.template_css is not None:
|
if opts.template_css is not None:
|
||||||
template_css_data = open(opts.template_css, 'rb').read()
|
with open(opts.template_css, 'rb') as f:
|
||||||
|
template_css_data = f.read()
|
||||||
else:
|
else:
|
||||||
template_css_data = P('templates/html_export_default.css', data=True)
|
template_css_data = P('templates/html_export_default.css', data=True)
|
||||||
|
|
||||||
|
@ -96,15 +96,14 @@ class SNBInput(InputFormatPlugin):
|
|||||||
if data is None:
|
if data is None:
|
||||||
continue
|
continue
|
||||||
snbc = etree.fromstring(data)
|
snbc = etree.fromstring(data)
|
||||||
outputFile = open(os.path.join(tdir, fname), 'wb')
|
|
||||||
lines = []
|
lines = []
|
||||||
for line in snbc.find('.//body'):
|
for line in snbc.find('.//body'):
|
||||||
if line.tag == 'text':
|
if line.tag == 'text':
|
||||||
lines.append(u'<p>%s</p>' % html_encode(line.text))
|
lines.append(u'<p>%s</p>' % html_encode(line.text))
|
||||||
elif line.tag == 'img':
|
elif line.tag == 'img':
|
||||||
lines.append(u'<p><img src="%s" /></p>' % html_encode(line.text))
|
lines.append(u'<p><img src="%s" /></p>' % html_encode(line.text))
|
||||||
outputFile.write((HTML_TEMPLATE % (chapterName, u'\n'.join(lines))).encode('utf-8', 'replace'))
|
with open(os.path.join(tdir, fname), 'wb') as f:
|
||||||
outputFile.close()
|
f.write((HTML_TEMPLATE % (chapterName, u'\n'.join(lines))).encode('utf-8', 'replace'))
|
||||||
oeb.toc.add(ch.text, fname)
|
oeb.toc.add(ch.text, fname)
|
||||||
id, href = oeb.manifest.generate(id='html',
|
id, href = oeb.manifest.generate(id='html',
|
||||||
href=ascii_filename(fname))
|
href=ascii_filename(fname))
|
||||||
|
@ -113,9 +113,8 @@ class SNBOutput(OutputFormatPlugin):
|
|||||||
etree.SubElement(headTree, "cover").text = ProcessFileName(href)
|
etree.SubElement(headTree, "cover").text = ProcessFileName(href)
|
||||||
else:
|
else:
|
||||||
etree.SubElement(headTree, "cover")
|
etree.SubElement(headTree, "cover")
|
||||||
bookInfoFile = open(os.path.join(snbfDir, 'book.snbf'), 'wb')
|
with open(os.path.join(snbfDir, 'book.snbf'), 'wb') as f:
|
||||||
bookInfoFile.write(etree.tostring(bookInfoTree, pretty_print=True, encoding='utf-8'))
|
f.write(etree.tostring(bookInfoTree, pretty_print=True, encoding='utf-8'))
|
||||||
bookInfoFile.close()
|
|
||||||
|
|
||||||
# Output TOC
|
# Output TOC
|
||||||
tocInfoTree = etree.Element("toc-snbf")
|
tocInfoTree = etree.Element("toc-snbf")
|
||||||
@ -168,9 +167,8 @@ class SNBOutput(OutputFormatPlugin):
|
|||||||
|
|
||||||
etree.SubElement(tocHead, "chapters").text = '%d' % len(tocBody)
|
etree.SubElement(tocHead, "chapters").text = '%d' % len(tocBody)
|
||||||
|
|
||||||
tocInfoFile = open(os.path.join(snbfDir, 'toc.snbf'), 'wb')
|
with open(os.path.join(snbfDir, 'toc.snbf'), 'wb') as f:
|
||||||
tocInfoFile.write(etree.tostring(tocInfoTree, pretty_print=True, encoding='utf-8'))
|
f.write(etree.tostring(tocInfoTree, pretty_print=True, encoding='utf-8'))
|
||||||
tocInfoFile.close()
|
|
||||||
|
|
||||||
# Output Files
|
# Output Files
|
||||||
oldTree = None
|
oldTree = None
|
||||||
@ -185,9 +183,8 @@ class SNBOutput(OutputFormatPlugin):
|
|||||||
else:
|
else:
|
||||||
if oldTree is not None and mergeLast:
|
if oldTree is not None and mergeLast:
|
||||||
log.debug('Output the modified chapter again: %s' % lastName)
|
log.debug('Output the modified chapter again: %s' % lastName)
|
||||||
outputFile = open(os.path.join(snbcDir, lastName), 'wb')
|
with open(os.path.join(snbcDir, lastName), 'wb') as f:
|
||||||
outputFile.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8'))
|
f.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8'))
|
||||||
outputFile.close()
|
|
||||||
mergeLast = False
|
mergeLast = False
|
||||||
|
|
||||||
log.debug('Converting %s to snbc...' % item.href)
|
log.debug('Converting %s to snbc...' % item.href)
|
||||||
@ -201,9 +198,8 @@ class SNBOutput(OutputFormatPlugin):
|
|||||||
postfix = '_' + subName
|
postfix = '_' + subName
|
||||||
lastName = ProcessFileName(item.href + postfix + ".snbc")
|
lastName = ProcessFileName(item.href + postfix + ".snbc")
|
||||||
oldTree = snbcTrees[subName]
|
oldTree = snbcTrees[subName]
|
||||||
outputFile = open(os.path.join(snbcDir, lastName), 'wb')
|
with open(os.path.join(snbcDir, lastName), 'wb') as f:
|
||||||
outputFile.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8'))
|
f.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8'))
|
||||||
outputFile.close()
|
|
||||||
else:
|
else:
|
||||||
log.debug('Merge %s with last TOC item...' % item.href)
|
log.debug('Merge %s with last TOC item...' % item.href)
|
||||||
snbwriter.merge_content(oldTree, oeb_book, item, [('', _("Start"))], opts)
|
snbwriter.merge_content(oldTree, oeb_book, item, [('', _("Start"))], opts)
|
||||||
@ -211,9 +207,8 @@ class SNBOutput(OutputFormatPlugin):
|
|||||||
# Output the last one if needed
|
# Output the last one if needed
|
||||||
log.debug('Output the last modified chapter again: %s' % lastName)
|
log.debug('Output the last modified chapter again: %s' % lastName)
|
||||||
if oldTree is not None and mergeLast:
|
if oldTree is not None and mergeLast:
|
||||||
outputFile = open(os.path.join(snbcDir, lastName), 'wb')
|
with open(os.path.join(snbcDir, lastName), 'wb') as f:
|
||||||
outputFile.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8'))
|
f.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8'))
|
||||||
outputFile.close()
|
|
||||||
mergeLast = False
|
mergeLast = False
|
||||||
|
|
||||||
for item in m:
|
for item in m:
|
||||||
|
@ -79,7 +79,8 @@ class LRFDocument(LRFMetaFile):
|
|||||||
|
|
||||||
def write_files(self):
|
def write_files(self):
|
||||||
for obj in chain(itervalues(self.image_map), itervalues(self.font_map)):
|
for obj in chain(itervalues(self.image_map), itervalues(self.font_map)):
|
||||||
open(obj.file, 'wb').write(obj.stream)
|
with open(obj.file, 'wb') as f:
|
||||||
|
f.write(obj.stream)
|
||||||
|
|
||||||
def to_xml(self, write_files=True):
|
def to_xml(self, write_files=True):
|
||||||
bookinfo = u'<BookInformation>\n<Info version="1.1">\n<BookInfo>\n'
|
bookinfo = u'<BookInformation>\n<Info version="1.1">\n<BookInfo>\n'
|
||||||
@ -96,7 +97,8 @@ class LRFDocument(LRFMetaFile):
|
|||||||
prefix = ascii_filename(self.metadata.title)
|
prefix = ascii_filename(self.metadata.title)
|
||||||
bookinfo += u'<CThumbnail file="%s" />\n'%(prefix+'_thumbnail.'+self.doc_info.thumbnail_extension,)
|
bookinfo += u'<CThumbnail file="%s" />\n'%(prefix+'_thumbnail.'+self.doc_info.thumbnail_extension,)
|
||||||
if write_files:
|
if write_files:
|
||||||
open(prefix+'_thumbnail.'+self.doc_info.thumbnail_extension, 'wb').write(th)
|
with open(prefix+'_thumbnail.'+self.doc_info.thumbnail_extension, 'wb') as f:
|
||||||
|
f.write(th)
|
||||||
bookinfo += u'<Language reading="">%s</Language>\n'%(self.doc_info.language,)
|
bookinfo += u'<Language reading="">%s</Language>\n'%(self.doc_info.language,)
|
||||||
bookinfo += u'<Creator reading="">%s</Creator>\n'%(self.doc_info.creator,)
|
bookinfo += u'<Creator reading="">%s</Creator>\n'%(self.doc_info.creator,)
|
||||||
bookinfo += u'<Producer reading="">%s</Producer>\n'%(self.doc_info.producer,)
|
bookinfo += u'<Producer reading="">%s</Producer>\n'%(self.doc_info.producer,)
|
||||||
@ -159,13 +161,13 @@ def main(args=sys.argv, logger=None):
|
|||||||
return 1
|
return 1
|
||||||
if opts.out is None:
|
if opts.out is None:
|
||||||
opts.out = os.path.join(os.path.dirname(args[1]), os.path.splitext(os.path.basename(args[1]))[0]+".lrs")
|
opts.out = os.path.join(os.path.dirname(args[1]), os.path.splitext(os.path.basename(args[1]))[0]+".lrs")
|
||||||
o = codecs.open(os.path.abspath(os.path.expanduser(opts.out)), 'wb', 'utf-8')
|
|
||||||
o.write(u'<?xml version="1.0" encoding="UTF-8"?>\n')
|
|
||||||
logger.info(_('Parsing LRF...'))
|
logger.info(_('Parsing LRF...'))
|
||||||
d = LRFDocument(open(args[1], 'rb'))
|
d = LRFDocument(open(args[1], 'rb'))
|
||||||
d.parse()
|
d.parse()
|
||||||
logger.info(_('Creating XML...'))
|
logger.info(_('Creating XML...'))
|
||||||
o.write(d.to_xml(write_files=opts.output_resources))
|
with codecs.open(os.path.abspath(os.path.expanduser(opts.out)), 'wb', 'utf-8') as f:
|
||||||
|
f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
|
||||||
|
f.write(d.to_xml(write_files=opts.output_resources))
|
||||||
logger.info(_('LRS written to ')+opts.out)
|
logger.info(_('LRS written to ')+opts.out)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
@ -703,9 +703,8 @@ def main(args=sys.argv):
|
|||||||
lrf.producer = options.producer
|
lrf.producer = options.producer
|
||||||
if options.thumbnail:
|
if options.thumbnail:
|
||||||
path = os.path.expanduser(os.path.expandvars(options.thumbnail))
|
path = os.path.expanduser(os.path.expandvars(options.thumbnail))
|
||||||
f = open(path, "rb")
|
with open(path, "rb") as f:
|
||||||
lrf.thumbnail = f.read()
|
lrf.thumbnail = f.read()
|
||||||
f.close()
|
|
||||||
if options.book_id is not None:
|
if options.book_id is not None:
|
||||||
lrf.book_id = options.book_id
|
lrf.book_id = options.book_id
|
||||||
if options.comment:
|
if options.comment:
|
||||||
@ -716,9 +715,8 @@ def main(args=sys.argv):
|
|||||||
td = "None"
|
td = "None"
|
||||||
if t and len(t) > 0:
|
if t and len(t) > 0:
|
||||||
td = os.path.basename(args[1])+"_thumbnail."+lrf.thumbail_extension()
|
td = os.path.basename(args[1])+"_thumbnail."+lrf.thumbail_extension()
|
||||||
f = open(td, "w")
|
with open(td, "w") as f:
|
||||||
f.write(t)
|
f.write(t)
|
||||||
f.close()
|
|
||||||
|
|
||||||
fields = LRFMetaFile.__dict__.items()
|
fields = LRFMetaFile.__dict__.items()
|
||||||
fields.sort()
|
fields.sort()
|
||||||
@ -734,7 +732,8 @@ def main(args=sys.argv):
|
|||||||
ext, data = None, None
|
ext, data = None, None
|
||||||
if data:
|
if data:
|
||||||
cover = os.path.splitext(os.path.basename(args[1]))[0]+"_cover."+ext
|
cover = os.path.splitext(os.path.basename(args[1]))[0]+"_cover."+ext
|
||||||
open(cover, 'wb').write(data)
|
with open(cover, 'wb') as f:
|
||||||
|
f.write(data)
|
||||||
print('Cover:', cover)
|
print('Cover:', cover)
|
||||||
else:
|
else:
|
||||||
print('Could not find cover in the LRF file')
|
print('Could not find cover in the LRF file')
|
||||||
|
Loading…
x
Reference in New Issue
Block a user