说它坑,是因为:一、即使进入Python运行环境,import之后,运行help()来查看,看到的也仍是C API的描述;二、官方网站上只有C版本API的文档;三、上述的那个对应关系文章并不很详尽,很多由C到Python的对应规则还需自行领悟。这三点会对初学者使用非C版本的libvirt API造成一定的障碍。
笔者大致总结了一下从C到Python的API的对应规则,可能并不全面,但应该会有一点帮助:
1. C语言API里的一些全局函数,对应于Python版本里的特定类的成员函数,比如:#!/usr/bin/python
import libvirt
import sys
from pprint import pprint
def set_memory(instance_id, size_in_kb):
conn = libvirt.open(None)
if conn == None:
print 'Failed to open connection to the hypervisor'
sys.exit(1)
else:
print 'Get the connection'
try:
# dom = conn.lookupByUUIDString('790208f9-6379-4172-bc8e-d2b325496a14')
dom = conn.lookupByID(instance_id)
result = dom.setMemory(1024*size_in_kb)
if result == 0:
print 'Succeeded to set Memory!'
else:
print 'Failed to set Memory!'
except Exception as ex:
print 'Failed to execution: %s' % ex
sys.exit(1)
def get_memory(instance_id):
conn = libvirt.open(None)
if conn == None:
print 'Failed to open connection to the hypervisor'
sys.exit(1)
else:
print 'Get the connection'
try:
# dom = conn.lookupByUUIDString('790208f9-6379-4172-bc8e-d2b325496a14')
dom = conn.lookupByID(instance_id)
result = dom.memoryStats()
pprint(result)
except Exception as ex:
print 'Failed to execution: %s' % ex
sys.exit(1)
def main():
set(5, 1200)
get(5)
if __name__ == "__main__":
main()
以上这个程序中,set_memory(instance_id, size_in_kb)函数就是用来设定指定虚机(dom)的实际最大内存,而get_memory(instance_id)函数,就是用来获取指定虚机的实际最大内存。
(完)