diff --git a/ebook_converter/ebooks/conversion/plugins/chm_input.py b/ebook_converter/ebooks/conversion/plugins/chm_input.py index 2dd0705..d6d01ff 100644 --- a/ebook_converter/ebooks/conversion/plugins/chm_input.py +++ b/ebook_converter/ebooks/conversion/plugins/chm_input.py @@ -175,7 +175,7 @@ class CHMInput(InputFormatPlugin): return htmlpath, toc def _read_file(self, name): - with lopen(name, 'rb') as f: + with open(name, 'rb') as f: data = f.read() return data diff --git a/ebook_converter/ebooks/conversion/plugins/epub_input.py b/ebook_converter/ebooks/conversion/plugins/epub_input.py index 28abc26..4316aa0 100644 --- a/ebook_converter/ebooks/conversion/plugins/epub_input.py +++ b/ebook_converter/ebooks/conversion/plugins/epub_input.py @@ -22,7 +22,7 @@ def decrypt_font_data(key, data, algorithm): def decrypt_font(key, path, algorithm): - with lopen(path, 'r+b') as f: + with open(path, 'r+b') as f: data = decrypt_font_data(key, f.read(), algorithm) f.seek(0), f.truncate(), f.write(data) @@ -221,7 +221,7 @@ class EPUBInput(InputFormatPlugin): if os.path.exists(guide_cover): renderer = render_html_svg_workaround(guide_cover, log) if renderer is not None: - with lopen('calibre_raster_cover.jpg', 'wb') as f: + with open('calibre_raster_cover.jpg', 'wb') as f: f.write(renderer) # Set the titlepage guide entry @@ -236,7 +236,7 @@ class EPUBInput(InputFormatPlugin): if k.endswith(attr): return v try: - with lopen('META-INF/container.xml', 'rb') as f: + with open('META-INF/container.xml', 'rb') as f: root = safe_xml_fromstring(f.read()) for r in root.xpath('//*[local-name()="rootfile"]'): if attr(r, 'media-type') != "application/oebps-package+xml": @@ -343,7 +343,7 @@ class EPUBInput(InputFormatPlugin): if len(list(opf.iterspine())) == 0: raise ValueError('No valid entries in the spine of this EPUB') - with lopen('content.opf', 'wb') as nopf: + with open('content.opf', 'wb') as nopf: nopf.write(opf.render()) return os.path.abspath('content.opf') @@ -356,7 +356,7 @@ class EPUBInput(InputFormatPlugin): from ebook_converter.ebooks.oeb.polish.toc import first_child from ebook_converter.utils.xml_parse import safe_xml_fromstring from tempfile import NamedTemporaryFile - with lopen(nav_path, 'rb') as f: + with open(nav_path, 'rb') as f: raw = f.read() raw = xml_to_unicode(raw, strip_encoding_pats=True, assume_utf8=True)[0] root = parse(raw, log=log) @@ -420,7 +420,7 @@ class EPUBInput(InputFormatPlugin): changed = True elem.set('data-calibre-removed-titlepage', '1') if changed: - with lopen(nav_path, 'wb') as f: + with open(nav_path, 'wb') as f: f.write(serialize(root, 'application/xhtml+xml')) def postprocess_book(self, oeb, opts, log): diff --git a/ebook_converter/ebooks/conversion/plugins/epub_output.py b/ebook_converter/ebooks/conversion/plugins/epub_output.py index 11294d9..97578ae 100644 --- a/ebook_converter/ebooks/conversion/plugins/epub_output.py +++ b/ebook_converter/ebooks/conversion/plugins/epub_output.py @@ -328,7 +328,7 @@ class EPUBOutput(OutputFormatPlugin): uris.pop(uri) continue self.log.debug('Encrypting font:', uri) - with lopen(path, 'r+b') as f: + with open(path, 'r+b') as f: data = f.read(1024) if len(data) >= 1024: data = bytearray(data) diff --git a/ebook_converter/ebooks/conversion/plugins/fb2_output.py b/ebook_converter/ebooks/conversion/plugins/fb2_output.py index 641f9ba..e1b7883 100644 --- a/ebook_converter/ebooks/conversion/plugins/fb2_output.py +++ b/ebook_converter/ebooks/conversion/plugins/fb2_output.py @@ -189,7 +189,7 @@ class FB2Output(OutputFormatPlugin): close = True if not os.path.exists(os.path.dirname(output_path)) and os.path.dirname(output_path) != '': os.makedirs(os.path.dirname(output_path)) - out_stream = lopen(output_path, 'wb') + out_stream = open(output_path, 'wb') else: out_stream = output_path diff --git a/ebook_converter/ebooks/conversion/plugins/htmlz_output.py b/ebook_converter/ebooks/conversion/plugins/htmlz_output.py index 6c2c301..c9c3f24 100644 --- a/ebook_converter/ebooks/conversion/plugins/htmlz_output.py +++ b/ebook_converter/ebooks/conversion/plugins/htmlz_output.py @@ -113,7 +113,7 @@ class HTMLZOutput(OutputFormatPlugin): if cover_data: from ebook_converter.utils.img import save_cover_data_to cover_path = os.path.join(tdir, u'cover.jpg') - with lopen(cover_path, 'w') as cf: + with open(cover_path, 'w') as cf: cf.write('') save_cover_data_to(cover_data, cover_path) except: diff --git a/ebook_converter/ebooks/conversion/plugins/mobi_input.py b/ebook_converter/ebooks/conversion/plugins/mobi_input.py index 84abd75..e4cdbb2 100644 --- a/ebook_converter/ebooks/conversion/plugins/mobi_input.py +++ b/ebook_converter/ebooks/conversion/plugins/mobi_input.py @@ -51,14 +51,14 @@ class MOBIInput(InputFormatPlugin): if raw: if isinstance(raw, str): raw = raw.encode('utf-8') - with lopen('debug-raw.html', 'wb') as f: + with open('debug-raw.html', 'wb') as f: f.write(raw) from ebook_converter.ebooks.oeb.base import close_self_closing_tags for f, root in parse_cache.items(): raw = html.tostring(root, encoding='utf-8', method='xml', include_meta_content_type=False) raw = close_self_closing_tags(raw) - with lopen(f, 'wb') as q: + with open(f, 'wb') as q: q.write(raw) accelerators['pagebreaks'] = '//h:div[@class="mbp_pagebreak"]' return mr.created_opf_path diff --git a/ebook_converter/ebooks/conversion/plugins/oeb_output.py b/ebook_converter/ebooks/conversion/plugins/oeb_output.py index ab80d3b..6444323 100644 --- a/ebook_converter/ebooks/conversion/plugins/oeb_output.py +++ b/ebook_converter/ebooks/conversion/plugins/oeb_output.py @@ -53,7 +53,7 @@ class OEBOutput(OutputFormatPlugin): # Needed as I can't get lxml to output opf:role and # not output as well raw = re.sub(br'(<[/]{0,1})opf:', br'\1', raw) - with lopen(href, 'wb') as f: + with open(href, 'wb') as f: f.write(raw) for item in oeb_book.manifest: @@ -65,7 +65,7 @@ class OEBOutput(OutputFormatPlugin): dir = os.path.dirname(path) if not os.path.exists(dir): os.makedirs(dir) - with lopen(path, 'wb') as f: + with open(path, 'wb') as f: f.write(item.bytes_representation) item.unload_data_from_memory(memory=path) diff --git a/ebook_converter/ebooks/conversion/plugins/pdb_output.py b/ebook_converter/ebooks/conversion/plugins/pdb_output.py index dee027a..5dc3cad 100644 --- a/ebook_converter/ebooks/conversion/plugins/pdb_output.py +++ b/ebook_converter/ebooks/conversion/plugins/pdb_output.py @@ -39,7 +39,7 @@ class PDBOutput(OutputFormatPlugin): close = True if not os.path.exists(os.path.dirname(output_path)) and os.path.dirname(output_path): os.makedirs(os.path.dirname(output_path)) - out_stream = lopen(output_path, 'wb') + out_stream = open(output_path, 'wb') else: out_stream = output_path diff --git a/ebook_converter/ebooks/conversion/plugins/pdf_input.py b/ebook_converter/ebooks/conversion/plugins/pdf_input.py index 3c7af0c..9c56d6e 100644 --- a/ebook_converter/ebooks/conversion/plugins/pdf_input.py +++ b/ebook_converter/ebooks/conversion/plugins/pdf_input.py @@ -34,7 +34,7 @@ class PDFInput(InputFormatPlugin): from ebook_converter.ebooks.pdf.reflow import PDFDocument pdftohtml(os.getcwd(), stream.name, self.opts.no_images, as_xml=True) - with lopen('index.xml', 'rb') as f: + with open('index.xml', 'rb') as f: xml = clean_ascii_chars(f.read()) PDFDocument(xml, self.opts, self.log) return os.path.join(os.getcwd(), 'metadata.opf') @@ -66,12 +66,12 @@ class PDFInput(InputFormatPlugin): opf.create_spine(['index.html']) log.debug('Rendering manifest...') - with lopen('metadata.opf', 'wb') as opffile: + with open('metadata.opf', 'wb') as opffile: opf.render(opffile) if os.path.exists('toc.ncx'): ncxid = opf.manifest.id_for_path('toc.ncx') if ncxid: - with lopen('metadata.opf', 'r+b') as f: + with open('metadata.opf', 'r+b') as f: raw = f.read().replace(b' 1: # Decouple this file from its links os.unlink(dest) - with lopen(dest, 'wb') as f: + with open(dest, 'wb') as f: f.write(data) def filesize(self, name): @@ -1055,7 +1055,7 @@ class Container(ContainerBase): # {{{ this will commit the file if it is dirtied and remove it from the parse cache. You must finish with this file before accessing the parsed version of it again, or bad things will happen. ''' - return lopen(self.get_file_path_for_processing(name, mode not in {'r', 'rb'}), mode) + return open(self.get_file_path_for_processing(name, mode not in {'r', 'rb'}), mode) def commit(self, outpath=None, keep_parsed=False): ''' @@ -1073,7 +1073,7 @@ class Container(ContainerBase): # {{{ mismatches = [] for name, path in iteritems(self.name_path_map): opath = other.name_path_map[name] - with lopen(path, 'rb') as f1, lopen(opath, 'rb') as f2: + with open(path, 'rb') as f1, open(opath, 'rb') as f2: if f1.read() != f2.read(): mismatches.append('The file %s is not the same'%name) return '\n'.join(mismatches) @@ -1146,7 +1146,7 @@ class EpubContainer(Container): if fname is not None: shutil.copy(os.path.join(dirpath, fname), os.path.join(base, fname)) else: - with lopen(self.pathtoepub, 'rb') as stream: + with open(self.pathtoepub, 'rb') as stream: try: zf = ZipFile(stream) zf.extractall(tdir) @@ -1363,12 +1363,12 @@ class EpubContainer(Container): if err.errno != errno.EEXIST: raise for fname in filenames: - with lopen(os.path.join(dirpath, fname), 'rb') as src, lopen(os.path.join(base, fname), 'wb') as dest: + with open(os.path.join(dirpath, fname), 'rb') as src, open(os.path.join(base, fname), 'wb') as dest: shutil.copyfileobj(src, dest) else: from ebook_converter.ebooks.tweak import zip_rebuilder - with lopen(join(self.root, 'mimetype'), 'wb') as f: + with open(join(self.root, 'mimetype'), 'wb') as f: et = guess_type('a.epub') if not isinstance(et, bytes): et = et.encode('ascii') @@ -1398,7 +1398,7 @@ class InvalidMobi(InvalidBook): def do_explode(path, dest): from ebook_converter.ebooks.mobi.reader.mobi6 import MobiReader from ebook_converter.ebooks.mobi.reader.mobi8 import Mobi8Reader - with lopen(path, 'rb') as stream: + with open(path, 'rb') as stream: mr = MobiReader(stream, default_log, None, None) with CurrentDir(dest): @@ -1456,7 +1456,7 @@ class AZW3Container(Container): tdir = PersistentTemporaryDirectory('_azw3_container') tdir = os.path.abspath(os.path.realpath(tdir)) self.root = tdir - with lopen(pathtoazw3, 'rb') as stream: + with open(pathtoazw3, 'rb') as stream: raw = stream.read(3) if raw == b'TPZ': raise InvalidMobi(_('This is not a MOBI file. It is a Topaz file.')) diff --git a/ebook_converter/ebooks/pdb/plucker/reader.py b/ebook_converter/ebooks/pdb/plucker/reader.py index d5c7be3..62e6fac 100644 --- a/ebook_converter/ebooks/pdb/plucker/reader.py +++ b/ebook_converter/ebooks/pdb/plucker/reader.py @@ -412,7 +412,7 @@ class Reader(FormatReader): for col in row: if col not in images: raise Exception('Image with uid: %s missing.' % col) - w, h = identify(lopen('%s.jpg' % col, 'rb'))[1:] + w, h = identify(open('%s.jpg' % col, 'rb'))[1:] row_width += w if col_height < h: col_height = h @@ -427,14 +427,14 @@ class Reader(FormatReader): x_off = 0 largest_height = 0 for col in row: - im = image_from_data(lopen('%s.jpg' % col, 'rb').read()) + im = image_from_data(open('%s.jpg' % col, 'rb').read()) canvas.compose(im, x_off, y_off) w, h = im.width(), im.height() x_off += w if largest_height < h: largest_height = h y_off += largest_height - with lopen('%s.jpg' % uid) as out: + with open('%s.jpg' % uid) as out: out.write(canvas.export(compression_quality=70)) self.log.debug('Wrote composite image with uid %s to images/%s.jpg' % (uid, uid)) except Exception as e: diff --git a/ebook_converter/ebooks/pdf/pdftohtml.py b/ebook_converter/ebooks/pdf/pdftohtml.py index bf502a7..7353747 100644 --- a/ebook_converter/ebooks/pdf/pdftohtml.py +++ b/ebook_converter/ebooks/pdf/pdftohtml.py @@ -47,7 +47,7 @@ def pdftohtml(output_dir, pdf_path, no_images, as_xml=False): pdfsrc = os.path.join(output_dir, 'src.pdf') index = os.path.join(output_dir, 'index.'+('xml' if as_xml else 'html')) - with lopen(pdf_path, 'rb') as src, lopen(pdfsrc, 'wb') as dest: + with open(pdf_path, 'rb') as src, open(pdfsrc, 'wb') as dest: shutil.copyfileobj(src, dest) with CurrentDir(output_dir): @@ -79,7 +79,7 @@ def pdftohtml(output_dir, pdf_path, no_images, as_xml=False): ret = eintr_retry_call(p.wait) logf.flush() logf.close() - out = lopen(logf.name, 'rb').read().decode('utf-8', 'replace').strip() + out = open(logf.name, 'rb').read().decode('utf-8', 'replace').strip() if ret != 0: raise ConversionError('pdftohtml failed with return code: %d\n%s' % (ret, out)) if out: @@ -89,7 +89,7 @@ def pdftohtml(output_dir, pdf_path, no_images, as_xml=False): raise DRMError() if not as_xml: - with lopen(index, 'r+b') as i: + with open(index, 'r+b') as i: raw = i.read().decode('utf-8', 'replace') raw = flip_images(raw) raw = raw.replace('\n = 3 native_string_type = str iterkeys = iter diff --git a/ebook_converter/startup.py b/ebook_converter/startup.py index 30f2ea5..0793039 100644 --- a/ebook_converter/startup.py +++ b/ebook_converter/startup.py @@ -9,10 +9,10 @@ Perform various initialization tasks. import builtins import locale import sys -import os + +from ebook_converter import constants # Default translation is NOOP -from ebook_converter.polyglot.builtins import is_py3 builtins.__dict__['_'] = lambda s: s # For strings which belong in the translation tables, but which shouldn't be @@ -23,7 +23,6 @@ builtins.__dict__['__'] = lambda s: s builtins.__dict__['dynamic_property'] = lambda func: func(None) -from ebook_converter.constants import iswindows, preferred_encoding, plugins, isosx, islinux, isfrozen, DEBUG, isfreebsd, ispy3 _run_once = False winutil = winutilerror = None @@ -32,74 +31,30 @@ if not _run_once: _run_once = True from importlib import import_module - if not isfrozen and not ispy3: - # Prevent PyQt4 from being loaded - class PyQt4Ban(object): - - def find_module(self, fullname, path=None): - if fullname.startswith('PyQt4'): - return self - - def load_module(self, fullname): - raise ImportError('Importing PyQt4 is not allowed as calibre uses PyQt5') - - sys.meta_path.insert(0, PyQt4Ban()) - class DeVendor(object): - if ispy3: + def find_spec(self, fullname, path, target=None): + spec = None + if fullname == 'calibre.web.feeds.feedparser': + m = import_module('feedparser') + spec = m.__spec__ + elif fullname.startswith('calibre.ebooks.markdown'): + m = import_module(fullname[len('calibre.ebooks.'):]) + spec = m.__spec__ + return spec - def find_spec(self, fullname, path, target=None): - spec = None - if fullname == 'calibre.web.feeds.feedparser': - m = import_module('feedparser') - spec = m.__spec__ - elif fullname.startswith('calibre.ebooks.markdown'): - m = import_module(fullname[len('calibre.ebooks.'):]) - spec = m.__spec__ - return spec - - else: - - def find_module(self, fullname, path=None): - if fullname == 'calibre.web.feeds.feedparser' or fullname.startswith('calibre.ebooks.markdown'): - return self - - def load_module(self, fullname): - if fullname == 'calibre.web.feeds.feedparser': - return import_module('feedparser') - return import_module(fullname[len('calibre.ebooks.'):]) sys.meta_path.insert(0, DeVendor()) # # Platform specific modules - if iswindows: - winutil, winutilerror = plugins['winutil'] + if constants.iswindows: + winutil, winutilerror = constants.plugins['winutil'] if not winutil: raise RuntimeError('Failed to load the winutil plugin: %s'%winutilerror) if len(sys.argv) > 1 and not isinstance(sys.argv[1], str): sys.argv[1:] = winutil.argv()[1-len(sys.argv):] - if not ispy3: - # Python2's expanduser is broken for non-ASCII usernames - # and unicode paths - - def expanduser(path): - if isinstance(path, bytes): - path = path.decode('mbcs') - if path[:1] != '~': - return path - i, n = 1, len(path) - while i < n and path[i] not in '/\\': - i += 1 - userhome = winutil.special_folder_path(winutil.CSIDL_PROFILE) - if i != 1: # ~user - userhome = os.path.join(os.path.dirname(userhome), path[1:i]) - - return userhome + path[i:] - os.path.expanduser = expanduser - # Ensure that all temp files/dirs are created under a calibre tmp dir from ebook_converter.ptempfile import base_dir try: @@ -109,8 +64,8 @@ if not _run_once: # # Convert command line arguments to unicode - enc = preferred_encoding - if isosx: + enc = constants.preferred_encoding + if constants.isosx: enc = 'utf-8' for i in range(1, len(sys.argv)): if not isinstance(sys.argv[i], str): @@ -118,7 +73,7 @@ if not _run_once: # # Ensure that the max number of open files is at least 1024 - if iswindows: + if constants.iswindows: # See https://msdn.microsoft.com/en-us/library/6e3b887c.aspx if hasattr(winutil, 'setmaxstdio'): winutil.setmaxstdio(max(1024, winutil.getmaxstdio())) @@ -129,7 +84,7 @@ if not _run_once: try: resource.setrlimit(resource.RLIMIT_NOFILE, (min(1024, hard), hard)) except Exception: - if DEBUG: + if constants.DEBUG: import traceback traceback.print_exc() @@ -162,47 +117,6 @@ if not _run_once: except: pass - # local_open() opens a file that wont be inherited by child processes - if is_py3: - local_open = open # PEP 446 - elif iswindows: - def local_open(name, mode='r', bufsize=-1): - mode += 'N' - return open(name, mode, bufsize) - elif isosx: - import fcntl - FIOCLEX = 0x20006601 - - def local_open(name, mode='r', bufsize=-1): - ans = open(name, mode, bufsize) - try: - fcntl.ioctl(ans.fileno(), FIOCLEX) - except EnvironmentError: - fcntl.fcntl(ans, fcntl.F_SETFD, fcntl.fcntl(ans, fcntl.F_GETFD) | fcntl.FD_CLOEXEC) - return ans - else: - import fcntl - try: - cloexec_flag = fcntl.FD_CLOEXEC - except AttributeError: - cloexec_flag = 1 - supports_mode_e = False - - def local_open(name, mode='r', bufsize=-1): - global supports_mode_e - mode += 'e' - ans = open(name, mode, bufsize) - if supports_mode_e: - return ans - old = fcntl.fcntl(ans, fcntl.F_GETFD) - if not (old & cloexec_flag): - fcntl.fcntl(ans, fcntl.F_SETFD, old | cloexec_flag) - else: - supports_mode_e = True - return ans - - builtins.__dict__['lopen'] = local_open - from ebook_converter.utils.icu import lower as icu_lower, upper as icu_upper builtins.__dict__['icu_lower'] = icu_lower builtins.__dict__['icu_upper'] = icu_upper @@ -226,7 +140,7 @@ if not _run_once: bound_signal.connect(slot, **kw) builtins.__dict__['connect_lambda'] = connect_lambda - if islinux or isosx or isfreebsd: + if constants.islinux or constants.isosx or constants.isfreebsd: # Name all threads at the OS level created using the threading module, see # http://bugs.python.org/issue15500 import threading @@ -244,7 +158,7 @@ if not _run_once: if name: if isinstance(name, str): name = name.encode('ascii', 'replace').decode('ascii') - plugins['speedup'][0].set_thread_name(name[:15]) + constants.plugins['speedup'][0].set_thread_name(name[:15]) except Exception: pass # Don't care about failure to set name threading.Thread.start = new_start @@ -254,9 +168,9 @@ def test_lopen(): from ebook_converter.ptempfile import TemporaryDirectory from ebook_converter import CurrentDir n = 'f\xe4llen' - print('testing lopen()') + print('testing open()') - if iswindows: + if constants.iswindows: import msvcrt, win32api def assert_not_inheritable(f): @@ -270,7 +184,7 @@ def test_lopen(): raise SystemExit('File handle is inheritable!') def copen(*args): - ans = lopen(*args) + ans = open(*args) assert_not_inheritable(ans) return ans diff --git a/ebook_converter/utils/filenames.py b/ebook_converter/utils/filenames.py index 9a1c3ff..46d220b 100644 --- a/ebook_converter/utils/filenames.py +++ b/ebook_converter/utils/filenames.py @@ -195,7 +195,7 @@ def case_preserving_open_file(path, mode='wb', mkdir_mode=0o777): ans = fpath = cpath else: fname = components[-1] - ans = lopen(os.path.join(cpath, fname), mode) + ans = open(os.path.join(cpath, fname), mode) # Ensure file and all its metadata is written to disk so that subsequent # listdir() has file name in it. I don't know if this is actually # necessary, but given the diversity of platforms, best to be safe. @@ -434,7 +434,7 @@ class WindowsAtomicFolderMove(object): pass win32file.SetFilePointer(handle, 0, win32file.FILE_BEGIN) - with lopen(dest, 'wb') as f: + with open(dest, 'wb') as f: while True: hr, raw = win32file.ReadFile(handle, 1024*1024) if hr != 0: diff --git a/ebook_converter/utils/fonts/scanner.py b/ebook_converter/utils/fonts/scanner.py index 2f93d3b..706aae3 100644 --- a/ebook_converter/utils/fonts/scanner.py +++ b/ebook_converter/utils/fonts/scanner.py @@ -245,7 +245,7 @@ class FontScanner(Thread): path = font_or_path if isinstance(font_or_path, dict): path = font_or_path['path'] - with lopen(path, 'rb') as f: + with open(path, 'rb') as f: return f.read() def find_font_for_text(self, text, allowed_families={'serif', 'sans-serif'}, @@ -366,7 +366,7 @@ class FontScanner(Thread): self.write_cache() def read_font_metadata(self, path, fileid): - with lopen(path, 'rb') as f: + with open(path, 'rb') as f: try: fm = FontMetadata(f) except UnsupportedFont: diff --git a/ebook_converter/utils/fonts/utils.py b/ebook_converter/utils/fonts/utils.py index 0292db6..327e341 100644 --- a/ebook_converter/utils/fonts/utils.py +++ b/ebook_converter/utils/fonts/utils.py @@ -441,7 +441,7 @@ def get_font_for_text(text, candidate_font_data=None): from ebook_converter.utils.fonts.scanner import font_scanner family, faces = font_scanner.find_font_for_text(text) if faces: - with lopen(faces[0]['path'], 'rb') as f: + with open(faces[0]['path'], 'rb') as f: candidate_font_data = f.read() return candidate_font_data diff --git a/ebook_converter/utils/img.py b/ebook_converter/utils/img.py index c2aa997..7945d20 100644 --- a/ebook_converter/utils/img.py +++ b/ebook_converter/utils/img.py @@ -49,11 +49,11 @@ def load_jxr_data(data): with TemporaryDirectory() as tdir: if iswindows and isinstance(tdir, str): tdir = tdir.encode('mbcs') - with lopen(os.path.join(tdir, 'input.jxr'), 'wb') as f: + with open(os.path.join(tdir, 'input.jxr'), 'wb') as f: f.write(data) cmd = [get_exe_path('JxrDecApp'), '-i', 'input.jxr', '-o', 'output.tif'] creationflags = 0x08 if iswindows else 0 - subprocess.Popen(cmd, cwd=tdir, stdout=lopen(os.devnull, 'wb'), stderr=subprocess.STDOUT, creationflags=creationflags).wait() + subprocess.Popen(cmd, cwd=tdir, stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT, creationflags=creationflags).wait() i = QImage() if not i.load(os.path.join(tdir, 'output.tif')): raise NotImage('Failed to convert JPEG-XR image') @@ -124,7 +124,7 @@ def image_from_data(data): def image_from_path(path): ' Load an image from the specified path. ' - with lopen(path, 'rb') as f: + with open(path, 'rb') as f: return image_from_data(f.read()) @@ -200,7 +200,7 @@ def save_image(img, path, **kw): `image_to_data()` function. ''' fmt = path.rpartition('.')[-1] kw['fmt'] = kw.get('fmt', fmt) - with lopen(path, 'wb') as f: + with open(path, 'wb') as f: f.write(image_to_data(image_from_data(img), **kw)) @@ -286,7 +286,7 @@ def save_cover_data_to( changed = True if path is None: return image_to_data(img, compression_quality, fmt, compression_quality // 10) if changed else data - with lopen(path, 'wb') as f: + with open(path, 'wb') as f: f.write(image_to_data(img, compression_quality, fmt, compression_quality // 10) if changed else data) # }}} @@ -667,7 +667,7 @@ def test(): # {{{ if __name__ == '__main__': # {{{ args = sys.argv[1:] infile = args.pop(0) - img = image_from_data(lopen(infile, 'rb').read()) + img = image_from_data(open(infile, 'rb').read()) func = globals()[args[0]] kw = {} args.pop(0) @@ -692,6 +692,6 @@ if __name__ == '__main__': # {{{ bn = os.path.basename(infile) outf = bn.rpartition('.')[0] + '.' + '-output' + bn.rpartition('.')[-1] img = func(img, **kw) - with lopen(outf, 'wb') as f: + with open(outf, 'wb') as f: f.write(image_to_data(img, fmt=outf.rpartition('.')[-1])) # }}} diff --git a/ebook_converter/utils/imghdr.py b/ebook_converter/utils/imghdr.py index 886013b..e046484 100644 --- a/ebook_converter/utils/imghdr.py +++ b/ebook_converter/utils/imghdr.py @@ -15,7 +15,7 @@ def what(file, h=None): ' Recognize image headers ' if h is None: if isinstance(file, (str, bytes)): - with lopen(file, 'rb') as f: + with open(file, 'rb') as f: h = f.read(HSIZE) else: location = file.tell() @@ -41,7 +41,7 @@ def identify(src): width = height = -1 if isinstance(src, str): - stream = lopen(src, 'rb') + stream = open(src, 'rb') elif isinstance(src, bytes): stream = ReadOnlyFileBuffer(src) else: diff --git a/ebook_converter/utils/localization.py b/ebook_converter/utils/localization.py index 497fe4a..baa0b5c 100644 --- a/ebook_converter/utils/localization.py +++ b/ebook_converter/utils/localization.py @@ -7,7 +7,7 @@ import json from gettext import GNUTranslations, NullTranslations import pkg_resources -from ebook_converter.polyglot.builtins import is_py3, iteritems +from ebook_converter.polyglot.builtins import iteritems _available_translations = None diff --git a/ebook_converter/utils/lock.py b/ebook_converter/utils/lock.py index b9ab07a..0afd1e5 100644 --- a/ebook_converter/utils/lock.py +++ b/ebook_converter/utils/lock.py @@ -190,7 +190,7 @@ else: def create_single_instance_mutex(name, per_user=True): from ebook_converter.utils.ipc import eintr_retry_call path = singleinstance_path(name, per_user) - f = lopen(path, 'w') + f = open(path, 'w') try: eintr_retry_call(fcntl.lockf, f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) return partial(_clean_lock_file, f)