Product SiteDocumentation Site

4.3. Obtaining State Information About a Domain

Once a domain instance has been obtained, it is possible to fetch information about the state of the domain. Information such as the type of OS being hosted, running state, ID, UUID, etc. The following methods will demonstrate how to fetch this information.

4.3.1. Fetching the ID of a domain

The ID of a domain can be obtained by using the ID method. Only running domains have an ID, fetching the ID of a non-running domain always returns -1.

Example 4.7. Fetching the ID of a domain

# Example-43.py
#!/usr/bin/env python3
import sys
import libvirt
from xml.dom import minidom

domName = 'CentOS7'

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

dom = None
try:
    dom = conn.lookupByName(domName)
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    exit(1)

id = dom.ID()
if id == -1:
    print('The domain is not running so has no ID.')
else:
    print('The ID of the domain is ' + str(id))

conn.close()
exit(0)