From e8921643a4136d12cca09a7a26e3008e18e3ab58 Mon Sep 17 00:00:00 2001 From: Kevin Murphy Date: Tue, 31 Dec 2019 08:38:44 -0800 Subject: [PATCH] TextGridLoader: Explicitly manage our temporary file contexts Before, we were relying on garbage collection to clean up our temp files, which is probably not tenable long-term. --- ultratrace2/model/files/loaders/textgrid.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ultratrace2/model/files/loaders/textgrid.py b/ultratrace2/model/files/loaders/textgrid.py index 1048633..ca10d15 100644 --- a/ultratrace2/model/files/loaders/textgrid.py +++ b/ultratrace2/model/files/loaders/textgrid.py @@ -104,17 +104,17 @@ def load_with_encoding(path: str, encoding: str) -> textgrid.TextGrid: if encoding == "utf-8" or encoding == "utf-16": return textgrid.TextGrid.fromFile(path) else: - transcoded_file = TextGridLoader.copy_to_temp_file_with_encoding(path, encoding) - return textgrid.TextGrid.fromFile(transcoded_file.name) + with tempfile.NamedTemporaryFile() as temp_file: + TextGridLoader.copy_to_temp_file_with_encoding( + path, temp_file, encoding + ) + return textgrid.TextGrid.fromFile(temp_file.name) @staticmethod def copy_to_temp_file_with_encoding( - cls, original_path: str, encoding: str - ) -> IO[bytes]: - # this gets ::close()d when it is GC'ed - temp_file = tempfile.NamedTemporaryFile() + original_path: str, temp_file: IO[bytes], encoding: str + ) -> None: with open(original_path, "rb") as orig_file: transcoded_contents = orig_file.read().decode(encoding).encode("utf-8") temp_file.write(transcoded_contents) temp_file.seek(0) - return temp_file