通过Libvirt Qemu python API避免控制台打印

时间:2017-08-07 07:43:39

标签: python logging qemu libvirt

我正在尝试使用libvirt python API “lookupbyname()”检查域是否存在。如果域不存在,它会在控制台上输出错误消息“未找到域”。   我只需要syslog中的错误或日志。我试过重定向stderr和stdout。但是,它没有任何影响。我也尝试过使用https://libvirt.org/logging.html中描述的libvirt日志记录设置。再没有效果。 /etc/libvirt/qemu.conf中的“stdio_handler”标志也设置为“file”。

以下是我的测试代码:

import os, sys
import libvirt
conn = libvirt.open('qemu:///system')

# Find the application in the virsh domain
try:
    sys.stdout = open(os.devnull, "w")
    sys.stderr = open(os.devnull, "w")
    dom = conn.lookupByName('abcd')
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
except Exception as e:
    syslog.syslog (syslog.LOG_ERR, 'Could not find the domain. ERROR: %s.' % (e))
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__

输出:

$ python test.py
libvirt: QEMU Driver error : Domain not found: no domain with matching name 'abcd'
$

有没有办法避免这个控制台打印?

1 个答案:

答案 0 :(得分:2)

这是libvirt的一个历史性设计错误,我们不幸的是,如果不依赖于这个错误功能的应用程序,那么我们就可以删除它。因此,您需要使用

手动关闭打印到控制台
def libvirt_callback(userdata, err):
    pass

libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)