From 13a50e2ba23d51d223020a25813fde99179db49f Mon Sep 17 00:00:00 2001 From: Martin Abente Lahaye Date: Thu, 22 Oct 2020 11:00:00 -0300 Subject: [PATCH] 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 --- camelot/handlers.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/camelot/handlers.py b/camelot/handlers.py index 6aa3a31..9ec10bb 100644 --- a/camelot/handlers.py +++ b/camelot/handlers.py @@ -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