Skip to content

Commit

Permalink
Prevent .open(...) from closing ext. file objects
Browse files Browse the repository at this point in the history
Fixes #312. Now only closes pdfplumber-created streams, not file objects
passed to pdfplumber.open(...).
  • Loading branch information
jsvine committed Nov 13, 2020
1 parent f398f46 commit 408605f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
10 changes: 8 additions & 2 deletions pdfplumber/pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ def __init__(self, stream, pages=None, laparams=None, precision=0.001, password=
@classmethod
def open(cls, path_or_fp, **kwargs):
if isinstance(path_or_fp, (str, pathlib.Path)):
return cls(open(path_or_fp, "rb"), **kwargs)
fp = open(path_or_fp, "rb")
inst = cls(fp, **kwargs)
inst.close = fp.close
return inst
else:
return cls(path_or_fp, **kwargs)

Expand All @@ -69,7 +72,10 @@ def pages(self):
return self._pages

def close(self):
self.stream.close()
"""
Override this method to execute code on __exit__.
"""
pass

def __enter__(self):
return self
Expand Down
1 change: 1 addition & 0 deletions tests/test_basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ def test_loading_fileobj(self):
with open(path, "rb") as f:
with pdfplumber.open(f) as pdf:
assert len(pdf.metadata)
assert not f.closed

# Will be removed from library soon
with open(path, "rb") as f:
Expand Down

0 comments on commit 408605f

Please sign in to comment.