如何在libvirt中设置超时(使用Python)

2024-10-03 09:09:41 发布

您现在位置:Python中文网/ 问答频道 /正文


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

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

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

我试过了,但出现了一个分段错误::-(

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:
    ...

有人能给我举个例子吗?在


Tags: to函数org程序apihttphtmltimeout
3条回答

我们终于找到了一个简单的方法来使用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

我经常使用monkeypatching来更改库,使套接字超时。通常您只需要找到在修改版本中调用select或{}和monkeypatch的方法。有时你需要设置一个尝试捕捉套接字超时并做一些事情来允许它渗透到您的代码中,而不会在途中造成另一个错误。例如,在一个例子中,我必须创建一个有效的response对象,而不是None。在

我假设libvirt通过标准套接字进行通信。如果是这样,可以使用^{}设置应用程序范围的超时。在

这并不是说python的libvirt绑定本身不调用该函数,但值得一试。在

相关问题 更多 >