2017-08-07 68 views
0

我想通過使用libvirt python API 「lookupbyname()」來檢查域是否存在。如果該域不存在,則會在控制檯上輸出一條錯誤消息,說「Domain not found」。 我只需要syslog中的錯誤或日誌。我試過重定向stderr和stdout。但是,它沒有任何影響。我也嘗試過使用https://libvirt.org/logging.html中描述的libvirt日誌記錄設置。再次沒有效果。 /etc/libvirt/qemu.conf中的「stdio_handler」標誌也被設置爲「file」。避免Libvirt Qemu python API控制檯打印

以下是我的測試代碼:

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

這是一個libvirt的歷史設計錯誤,我們很遺憾地無法在不違背這個錯誤特性的應用程序的情況下將其刪除。所以你需要手動關閉打印到控制檯使用

def libvirt_callback(userdata, err): 
    pass 

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

我一直在處理網絡查找和其他libvirt python API的類似問題。這解決了所有這些問題。謝謝! – Swaru