# Example-5.py
#!/usr/bin/env python3
import sys
import libvirt

conn = None
try:
    conn = libvirt.open("qemu:///system")
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    exit(1)

domainNames = conn.listDefinedDomains()
if domainNames == None:
    print('Failed to get a list of domain names', file=sys.stderr)

domainIDs = conn.listDomainsID()
if domainIDs == None:
    print('Failed to get a list of domain IDs', file=sys.stderr)

domainNames = ""
try:
    if len(domainIDs) != 0:
        for domainID in domainIDs:
            domain = conn.lookupByID(domainID)
            domainNames.append(domain.name)
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    conn.close()
    exit(1)

print("All (active and inactive domain names:")
if len(domainNames) == 0:
    print('  None')
else:
    for domainName in domainNames:
        print('  '+domainName)

conn.close()
exit(0)
