【问题标题】:Python timeout handlingPython超时处理
【发布时间】:2016-11-22 06:38:39
【问题描述】:

当我像这样连接到 CIM 服务器时,我正在尝试处理超时异常:

 si = pywbem.WBEMConnection(HOST, ("root", "passwrord"), "ns",no_verification=True)

我用谷歌搜索,这个函数有一个参数名称:“超时”,但它只适用于较新版本的 PyWBEM,很遗憾我不能使用它。

我在 5 分钟后得到的错误:

pywbem.cim_operations.CIMError: (0, '套接字错误: [Errno 110] 连接超时')

我想将此间隔设置为 30 秒。我该怎么做?我接受各种解决方案。我正在考虑一个 while 循环,它倒计时 30 秒,但我不知道如何检查连接是否建立。

谢谢

【问题讨论】:

  • 你用的是哪个版本?
  • 0.7 而Python版本是2.7

标签: python python-2.7 timeout


【解决方案1】:

嗯...我想您必须创建某种类型的异步进程来进行检查。

借用 Rich 的 here 的解决方案,我会尝试以下方法:

import multiprocessing.pool
import functools

def timeout(max_timeout):
    """Timeout decorator, parameter in seconds."""
    def timeout_decorator(item):
        """Wrap the original function."""
        @functools.wraps(item)
        def func_wrapper(*args, **kwargs):
            """Closure for function."""
            pool = multiprocessing.pool.ThreadPool(processes=1)
            async_result = pool.apply_async(item, args, kwargs)
            # raises a TimeoutError if execution exceeds max_timeout
            return async_result.get(max_timeout)
        return func_wrapper
    return timeout_decorator

@timeout(30) # timeout after 30 seconds
def connect():
    return pywbem.WBEMConnection(HOST, ("root", "passwrord"), "ns",no_verification=True)

try:
    si = connect()
except multiprocessing.TimeoutError:
    si = "Connection timed out after 30 seconds"

print si

【讨论】:

    猜你喜欢
    • 2016-12-07
    • 2011-02-12
    • 2018-09-23
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2019-12-07
    • 2013-03-17
    • 1970-01-01
    相关资源
    最近更新 更多