From 012f341e75632d2a054d71b991e4d3c72758e7cf Mon Sep 17 00:00:00 2001 From: Joshua Boniface Date: Mon, 4 Jun 2018 01:35:23 -0400 Subject: [PATCH] Improve silent uuid lookup function --- pvcf.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/pvcf.py b/pvcf.py index 6d9e8d78..1acb8679 100644 --- a/pvcf.py +++ b/pvcf.py @@ -12,18 +12,22 @@ import os, sys, libvirt, uuid # 2. Disables stdout to avoid stupid printouts # 3. Try's it and returns a sensible value if not def lookupByUUID(tuuid): + conn = None dom = None + libvirt_name = "qemu:///system" # Convert the text UUID to bytes buuid = uuid.UUID(tuuid).bytes - # Disable stdout + # Flush and disable stdout and stderr + sys.stdout.flush() + sys.stderr.flush() sys.stdout = open(os.devnull, 'w') + sys.stderr = open(os.devnull, 'w') # Try try: # Open a libvirt connection - libvirt_name = "qemu:///system" conn = libvirt.open(libvirt_name) if conn == None: print('>>> %s - Failed to open local libvirt connection.' % self.domuuid) @@ -32,16 +36,21 @@ def lookupByUUID(tuuid): # Lookup the UUID dom = conn.lookupByUUID(buuid) - # Close the libvirt connection - conn.close() # Fail except: + pass + + # After everything + finally: # Close the libvirt connection if conn != None: conn.close() - # Enable stdout + # Flush and enable stdout and stderr + sys.stdout.flush() + sys.stderr.flush() sys.stdout = sys.__stdout__ + sys.stderr = sys.__stderr__ # Return the dom object (or None) return dom