More explicit closing of resources

This commit is contained in:
Kovid Goyal 2023-10-16 12:13:18 +05:30
parent 6e3b948bc9
commit 89f9b14fc2
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
3 changed files with 9 additions and 3 deletions

View File

@ -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')

View File

@ -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)

View File

@ -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)