Rather than requiring shutil module to get rid of the temporary
directory we're creating for virt-install, let's use the
TemporaryDirectory method instead which returns a file-like object which
can be used to clean up the standard Python way.
Although the internal exit handlers will take care of closing the
temporary directories (and thus removing their contents) automatically,
let's be explicit anyway and use the 'finally' clause to clean these up
on both success and failure.

Signed-off-by: Erik Skultety <eskul...@redhat.com>
Reviewed-by: Andrea Bolognani <abolo...@redhat.com>
---
 guests/lcitool | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/guests/lcitool b/guests/lcitool
index dcc54ae..56eb543 100755
--- a/guests/lcitool
+++ b/guests/lcitool
@@ -24,7 +24,6 @@ import json
 import os
 import platform
 import random
-import shutil
 import string
 import subprocess
 import sys
@@ -610,8 +609,8 @@ class Application:
                         facts[option]
                     )
 
-            tempdir = tempfile.mkdtemp()
-            initrd_inject = os.path.join(tempdir, install_config)
+            tempdir = tempfile.TemporaryDirectory(prefix="lcitool")
+            initrd_inject = os.path.join(tempdir.name, install_config)
 
             with open(initrd_inject, "w") as inject:
                 inject.write(content)
@@ -665,8 +664,8 @@ class Application:
                 subprocess.check_call(cmd)
             except Exception as ex:
                 raise Exception("Failed to install '{}': {}".format(host, ex))
-
-            shutil.rmtree(tempdir, ignore_errors=True)
+            finally:
+                tempdir.cleanup()
 
     def _action_update(self, args):
         self._execute_playbook("update", args.hosts, args.projects,
-- 
2.25.3

Reply via email to