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