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

Erik Skultety eskultet at redhat.com
Wed May 6 12:05:53 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>
Reviewed-by: Andrea Bolognani <abologna at redhat.com>
---
 guests/lcitool | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/guests/lcitool b/guests/lcitool
index c8d0d9a..759e604 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:
                         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)
@@ -663,8 +662,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




More information about the libvir-list mailing list