Skip to content

Commit 86d39f1

Browse files
authored
Merge pull request #207 from stefdoerr/fix_filehandler_leak
Fix zip file handler leak
2 parents a8de9a7 + c989290 commit 86d39f1

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

propka/input.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,24 @@ def open_file_for_reading(input_file: _TextIOSource) -> ContextManager[IO[str]]:
4040
if not zipfile.is_zipfile(p):
4141
print(f"Parent {p} is not ZIP file.")
4242
continue
43-
zf = zipfile.ZipFile(p)
44-
path_string = Path.as_posix(input_file.relative_to(p))
45-
stream = zf.open(path_string)
46-
return io.TextIOWrapper(stream)
43+
# Create a custom context manager that closes both
44+
# the ZIP file and the stream when the context is exited.
45+
@contextlib.contextmanager
46+
def zip_file_reader():
47+
zf = zipfile.ZipFile(p)
48+
try:
49+
path_string = Path.as_posix(input_file.relative_to(p))
50+
stream = zf.open(path_string)
51+
wrapped = io.TextIOWrapper(stream)
52+
try:
53+
yield wrapped
54+
finally:
55+
wrapped.close()
56+
stream.close()
57+
finally:
58+
zf.close()
59+
60+
return zip_file_reader()
4761

4862
return contextlib.closing(open(input_file, 'rt'))
4963

0 commit comments

Comments
 (0)