Binding for Python

Libvirt comes with direct support for the Python language (just make sureyou installed the libvirt-python package if not compiling from sources). Alsonote that Daniel Berrange provides bindings for Perltoo.

The Python binding should be complete and are mostly automaticallygenerated from the formal description of the API in xml. The bindings arearticulated around 2 classes virConnectand virDomain mapping tothe C types. Functions in the C API taking either type as argument thenbecomes methods for the classes, their name is just stripped from thevirConnect or virDomain(Get) prefix and the first letter gets converted tolower case, for example the C functions:

int virConnectNumOfDomains(virConnectPtr conn);

int virDomainSetMaxMemory(virDomainPtr domain, unsigned long memory);

become

virConn::numOfDomains(self)

virDomain::setMaxMemory(self, memory)

This process is fully automated, you can get a summary of the conversionin the file libvirtclass.txt present in the python dir or in the docs.Thereis a couple of function who don't map directly to their C counterparts due tospecificities in their argument conversions:

  • virConnectListDomainsis replaced by virDomain::listDomainsID(self)which returnsa list of the integer ID for the currently running domains
  • virDomainGetInfois replaced by virDomain::info()which returns a list of
    1. state: one of the state values (virDomainState)
    2. maxMemory: the maximum memory used by the domain
    3. memory: the current amount of memory used by the domain
    4. nbVirtCPU: the number of virtual CPU
    5. cpuTime: the time used by the domain in nanoseconds

So let's look at a simple example inspired from the basic.pytest found in python/tests/in the source tree:

import libvirt
import sys

conn = libvirt.openReadOnly(None)
if conn == None:
    print 'Failed to open connection to the hypervisor'
    sys.exit(1)

try:
    dom0 = conn.lookupByName("Domain-0")
except:
    print 'Failed to find the main domain'
    sys.exit(1)

print "Domain 0: id %d running %s" % (dom0.ID(), dom0.OSType())
print dom0.info()

There is not much to comment about it, it really is a straight mappingfrom the C API, the only points to notice are:

  • the import of the module called libvirt
  • getting a connection to the hypervisor, in that case using theopenReadOnly function allows the code to execute as a normal user.
  • getting an object representing the Domain 0 using lookupByName
  • if the domain is not found a libvirtError exception will be raised
  • extracting and printing some informations about the domain usingvarious methodsassociated to the virDomain class.