From 89f9b14fc27b686b53d7e5a7a9d780011701334e Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Mon, 16 Oct 2023 12:13:18 +0530 Subject: [PATCH] More explicit closing of resources --- src/calibre/db/fts/text.py | 1 + src/calibre/ebooks/metadata/utils.py | 9 +++++++-- src/calibre/library/database2.py | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/calibre/db/fts/text.py b/src/calibre/db/fts/text.py index 70458f9b35..93664e79ee 100644 --- a/src/calibre/db/fts/text.py +++ b/src/calibre/db/fts/text.py @@ -70,6 +70,7 @@ def pdftotext(path): cmd = [PDFTOTEXT] + '-enc UTF-8 -nodiag -eol unix'.split() + [os.path.basename(path), '-'] p = popen(cmd, cwd=os.path.dirname(path), stdout=subprocess.PIPE, stdin=subprocess.DEVNULL) raw = p.stdout.read() + p.stdout.close() if p.wait() != 0: return '' return clean_ascii_chars(raw).decode('utf-8', 'replace') diff --git a/src/calibre/ebooks/metadata/utils.py b/src/calibre/ebooks/metadata/utils.py index c7f518a209..f45a5c6e48 100644 --- a/src/calibre/ebooks/metadata/utils.py +++ b/src/calibre/ebooks/metadata/utils.py @@ -32,9 +32,14 @@ def parse_opf_version(raw): def parse_opf(stream_or_path): stream = stream_or_path - if not hasattr(stream, 'read'): + needs_close = not hasattr(stream, 'read') + if needs_close: stream = open(stream, 'rb') - raw = stream.read() + try: + raw = stream.read() + finally: + if needs_close: + stream.close() if not raw: raise ValueError('Empty file: '+getattr(stream, 'name', 'stream')) raw, encoding = xml_to_unicode(raw, strip_encoding_pats=True, resolve_entities=True, assume_utf8=True) diff --git a/src/calibre/library/database2.py b/src/calibre/library/database2.py index 1f63a0a59e..79cb6aaf75 100644 --- a/src/calibre/library/database2.py +++ b/src/calibre/library/database2.py @@ -1478,7 +1478,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns): f = open(path, 'rb') except OSError: time.sleep(0.2) - f = open(path, 'rb') + f = open(path, 'rb') with f: if hasattr(dest, 'write'): shutil.copyfileobj(f, dest)