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