From 3173fa1e285cbbae510b6cf8f8f36f4838d3e3d5 Mon Sep 17 00:00:00 2001 From: John Whitlock Date: Thu, 4 Nov 2021 12:14:41 -0500 Subject: [PATCH] Cleanup temporary files Use context managers to automatically remove the named temporary files --- tcadmin/diff.py | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/tcadmin/diff.py b/tcadmin/diff.py index 3c9e0d45..83849ef4 100644 --- a/tcadmin/diff.py +++ b/tcadmin/diff.py @@ -8,8 +8,8 @@ import click import blessings import attr -import tempfile import subprocess +from tempfile import NamedTemporaryFile from .util.ansi import strip_ansi from .resources import Resources @@ -19,25 +19,24 @@ def fast_diff(left, right, n): - left_file = tempfile.NamedTemporaryFile("w") - left_file.write("\n".join(left)) - right_file = tempfile.NamedTemporaryFile("w") - right_file.write("\n".join(right)) - output = subprocess.run( - [ - "diff", - f"-U{n}", - "--label", - "current", - "--label", - "generated", - left_file.name, - right_file.name, - ], - encoding="utf8", - stdout=subprocess.PIPE, - ).stdout - return output.split("\n") + with NamedTemporaryFile("w") as left_file, NamedTemporaryFile("w") as right_file: + left_file.write("\n".join(left)) + right_file.write("\n".join(right)) + output = subprocess.run( + [ + "diff", + f"-U{n}", + "--label", + "current", + "--label", + "generated", + left_file.name, + right_file.name, + ], + encoding="utf8", + stdout=subprocess.PIPE, + ).stdout + return output.split("\n") diff_options.add(