Improve silent uuid lookup function

This commit is contained in:
Joshua Boniface 2018-06-04 01:35:23 -04:00
parent 0ec1399424
commit 012f341e75
1 changed files with 14 additions and 5 deletions

19
pvcf.py
View File

@ -12,18 +12,22 @@ import os, sys, libvirt, uuid
# 2. Disables stdout to avoid stupid printouts # 2. Disables stdout to avoid stupid printouts
# 3. Try's it and returns a sensible value if not # 3. Try's it and returns a sensible value if not
def lookupByUUID(tuuid): def lookupByUUID(tuuid):
conn = None
dom = None dom = None
libvirt_name = "qemu:///system"
# Convert the text UUID to bytes # Convert the text UUID to bytes
buuid = uuid.UUID(tuuid).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.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w')
# Try # Try
try: try:
# Open a libvirt connection # Open a libvirt connection
libvirt_name = "qemu:///system"
conn = libvirt.open(libvirt_name) conn = libvirt.open(libvirt_name)
if conn == None: if conn == None:
print('>>> %s - Failed to open local libvirt connection.' % self.domuuid) print('>>> %s - Failed to open local libvirt connection.' % self.domuuid)
@ -32,16 +36,21 @@ def lookupByUUID(tuuid):
# Lookup the UUID # Lookup the UUID
dom = conn.lookupByUUID(buuid) dom = conn.lookupByUUID(buuid)
# Close the libvirt connection
conn.close()
# Fail # Fail
except: except:
pass
# After everything
finally:
# Close the libvirt connection # Close the libvirt connection
if conn != None: if conn != None:
conn.close() conn.close()
# Enable stdout # Flush and enable stdout and stderr
sys.stdout.flush()
sys.stderr.flush()
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
# Return the dom object (or None) # Return the dom object (or None)
return dom return dom