1


在我的 Python 程序中使用 libvirt 时,我想设置一个短的连接超时(只有几秒钟),而不是长的默认超时。

我在这里找到了 C 函数:virEventAddTimeoutFunc()在 C libvirt API 中:http:
//libvirt.org/html/libvirt-libvirt.html#virEventAddTimeoutFunc

eventInvokeTimeoutCallback(timer, callback, opaque)在#150 附近,libvirt.py但我不知道如何使用它。我在网上没有找到任何例子。

我试过这个,但我得到一个分段错误: :-(

import libvirt

def timeout_cb_d():
    print 'Timeout !'

try:
    # try to set the libvirt timeout to 2 seconds:
    t = libvirt.eventInvokeTimeoutCallback(2, timeout_cb_d, "from dom0_class")
except:
    ...

有人可以给我一个工作示例吗?

4

3 回答 3

1

我们终于找到了一种使用 Python 警报和信号处理程序的简单方法:http: //docs.python.org/library/signal.html#example

编辑:

这是想法:

import string, time, sys, signal

class Host:

# (...)

def timeout_handler(self, sig_code, frame):
    if 14 == sig_code: sig_code = 'SIGALRM'
    print time.strftime('%F %T -'), 'Signal handler called with signal:', sig_code
    raise Exception('Timeout!')

def libVirtConnect(self):
    try:
        # Enable the timeout with an alarm:
        signal.signal(signal.SIGALRM, self.timeout_handler)
        signal.alarm(self._libvirt_timeout_in_seconds)

        self._virt_conn = libvirt.open('xen+tcp://'+self._ip)

        signal.alarm(0)      # Disable the alarm
    except Exception, e:
        signal.alarm(0)      # Disable the alarm
于 2011-10-11T13:32:25.167 回答
0

我假设 libvirt 通过标准套接字进行通信。如果是这种情况,您可以使用socket.settimeout.

这并不是说 python 的 libvirt 绑定不会自己调用该函数,但值得一试。

于 2011-06-29T02:05:38.033 回答
0

我经常使用猴子补丁来更改库,以便套接字超时。通常你只需要在修改后的版本中找到调用selectpoll和monkeypatch的方法。有时你需要设置一个 try-catch 来捕获 socket.timeout 并做一些事情来让它渗透到你的代码中,而不会在途中引起另一个错误。例如,在一种情况下,我必须创建一个有效的响应对象而不是 None。

于 2011-10-12T05:59:17.073 回答