handlers: Close file streams explicitly

No harm in closing these streams explicitly. Best case
scenario, this prevents descriptors leaks, worse case
scenario, it reduces the amount of  messages like the
following during tests:

ResourceWarning: unclosed file
This commit is contained in:
Martin Abente Lahaye
2020-10-22 11:00:00 -03:00
committed by Martin Abente Lahaye
parent d17dc43ab2
commit 13a50e2ba2
+6 -2
View File
@@ -70,7 +70,8 @@ class PDFHandler(object):
if pages == "1":
page_numbers.append({"start": 1, "end": 1})
else:
infile = PdfFileReader(open(filepath, "rb"), strict=False)
instream = open(filepath, "rb")
infile = PdfFileReader(instream, strict=False)
if infile.isEncrypted:
infile.decrypt(self.password)
if pages == "all":
@@ -84,6 +85,7 @@ class PDFHandler(object):
page_numbers.append({"start": int(a), "end": int(b)})
else:
page_numbers.append({"start": int(r), "end": int(r)})
instream.close()
P = []
for p in page_numbers:
P.extend(range(p["start"], p["end"] + 1))
@@ -122,7 +124,8 @@ class PDFHandler(object):
if rotation != "":
fpath_new = "".join([froot.replace("page", "p"), "_rotated", fext])
os.rename(fpath, fpath_new)
infile = PdfFileReader(open(fpath_new, "rb"), strict=False)
instream = open(fpath_new, "rb")
infile = PdfFileReader(instream, strict=False)
if infile.isEncrypted:
infile.decrypt(self.password)
outfile = PdfFileWriter()
@@ -134,6 +137,7 @@ class PDFHandler(object):
outfile.addPage(p)
with open(fpath, "wb") as f:
outfile.write(f)
instream.close()
def parse(
self, flavor="lattice", suppress_stdout=False, layout_kwargs={}, **kwargs