[libvirt-ci PATCH 03/13] lcitool: Prefer tempfile's native wrappers over low level primitives

Erik Skultety eskultet at redhat.com
Wed Apr 22 13:28:21 UTC 2020

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 <eskultet at redhat.com>
 guests/lcitool | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/guests/lcitool b/guests/lcitool
index 9a9326d..51ee211 100755
--- a/guests/lcitool
+++ b/guests/lcitool
@@ -23,7 +23,6 @@ import json
 import os
 import platform
 import random
-import shutil
 import string
 import subprocess
 import sys
@@ -608,8 +607,8 @@ class Application:
-            tempdir = tempfile.mkdtemp()
-            initrd_inject = os.path.join(tempdir, install_config)
+            tempdir = tempfile.TemporaryDirectory()
+            initrd_inject = os.path.join(tempdir.name, install_config)
             with open(initrd_inject, "w") as inject:
@@ -663,8 +662,8 @@ class Application:
             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,

More information about the libvir-list mailing list