【问题标题】:How to force timeout functions in python, windows platform如何在python,windows平台中强制超时功能
【发布时间】:2014-04-22 16:33:08
【问题描述】:

我想要做的就是让函数超时,如果它在此之前没有返回

一切都开始了,因为 urllib2 支持 urlopen 超时,但不支持阅读部分 我的程序挂起。为套接字更改 defaulttimeout 不起作用。使用signal.sigalrm 不起作用。我无法切换到请求,因为那样我将不得不重写和测试更多内容。

我不想让线程运行函数然后使线程超时,我想使函数超时。有什么想法吗?

【问题讨论】:

    标签: python timeout urllib2


    【解决方案1】:

    我喜欢在我的项目中使用 David 的课程 here。我发现它非常有效,我喜欢它提供了一种通过装饰器在现有代码中实现的简单方法。例如:

    # Timeout after 30 seconds
    @timeout(30)
    def your_function():
        ...
    

    注意:这不是线程安全的!如果您使用多线程,则信号将被随机线程捕获。然而,对于单线程程序,这是最简单的解决方案。

    【讨论】:

    • 不幸的是我使用的是windows,windows不支持signal.sigalrm。您指向的代码使用 signal.sigalrm
    【解决方案2】:

    是的,它可以在没有信号的窗口中完成,它也可以在其他操作系统中工作。这是使用线程但不是运行函数而是发出超时信号。逻辑是创建一个新线程并等待给定时间并使用_thread(在python3中和python2中的线程)引发异常。此异常将在主线程中抛出,如果发生异常,with块将退出。

    import threading
    import _thread   # import thread in python2
    class timeout():
      def __init__(self, time):
        self.time= time
        self.exit=False
    
      def __enter__(self):
        threading.Thread(target=self.callme).start()
    
      def callme(self):
        time.sleep(self.time)
        if self.exit==False:
           _thread.interrupt_main()  # use thread instead of _thread in python2
      def __exit__(self, a, b, c):
           self.exit=True
    

    用法示例:-

    with timeout(2):
        func()
    

    with 块中的程序应在 2 秒内退出,否则将在 2 秒后退出。

    【讨论】:

      猜你喜欢
      • 2012-09-08
      • 2014-03-16
      • 2012-08-07
      • 2020-09-23
      • 1970-01-01
      • 2017-12-22
      相关资源
      最近更新 更多