【问题标题】:Avoiding console prints by Libvirt Qemu python APIsLibvirt Qemu python API 避免控制台打印
【发布时间】:2017-08-07 07:43:39
【问题描述】:

我正在尝试使用 libvirt python API “lookupbyname()”检查域是否存在。如果域不存在,它会在控制台上打印一条错误消息“Domain not found”。 我只需要系统日志中的错误或日志。我试过重定向标准错误和标准输出。但是,它没有任何作用。我还尝试过使用 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'
$

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

【问题讨论】:

    标签: python logging qemu libvirt


    【解决方案1】:

    这是 libvirt 的一个历史性设计错误,很遗憾,我们无法在不破坏依赖此错误功能的应用程序的反向兼容的情况下将其删除。所以你需要手动关闭打印到控制台使用

    def libvirt_callback(userdata, err):
        pass
    
    libvirt.registerErrorHandler(f=libvirt_callback, ctx=None)
    

    【讨论】:

    • 我在处理网络查找和其他 libvirt python API 的类似问题。这解决了所有这些问题。谢谢!
    猜你喜欢
    • 2021-08-26
    • 2016-08-16
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 2021-12-13
    相关资源
    最近更新 更多