gpt4 book ai didi

python - virsh (libvirt) 的替代品

转载 作者:太空狗 更新时间:2023-10-29 21:25:07 26 4
gpt4 key购买 nike

我正在使用 virsh list 来显示计算机上运行的虚拟机列表。我希望以二维数组的形式打印过程中的信息。

解决此问题的一种方法是获得输出,使用分词器并将其存储在数组中。但是有没有其他方法可以直接将其转化为数组或其他形式,从而使代码更具可扩展性。 (我能想到的是在 python 中使用 libvirt api)

最佳答案

确实有libvirt Python API bindings .

import libvirt

conn = libvirt.openReadOnly(None) # $LIBVIRT_DEFAULT_URI, or give a URI here
assert conn, 'Failed to open connection'

names = conn.listDefinedDomains()
domains = map(conn.lookupByName, names)

ids = conn.listDomainsID()
running = map(conn.lookupByID, ids)

columns = 3

states = {
libvirt.VIR_DOMAIN_NOSTATE: 'no state',
libvirt.VIR_DOMAIN_RUNNING: 'running',
libvirt.VIR_DOMAIN_BLOCKED: 'blocked on resource',
libvirt.VIR_DOMAIN_PAUSED: 'paused by user',
libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
libvirt.VIR_DOMAIN_SHUTOFF: 'shut off',
libvirt.VIR_DOMAIN_CRASHED: 'crashed',
}
def info(dom):
[state, maxmem, mem, ncpu, cputime] = dom.info()
return '%s is %s,' % (dom.name(), states.get(state, state))

print 'Defined domains:'
for row in map(None, *[iter(domains)] * columns):
for domain in row:
if domain:
print info(domain),
print
print

print 'Running domains:'
for row in map(None, *[iter(running)] * columns):
for domain in row:
if domain:
print info(domain),
print

关于python - virsh (libvirt) 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4986076/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com