Python 的 Ruby 超时?

发布于 2024-07-09 14:36:10 字数 268 浏览 5 评论 0原文

有谁知道在Python中实现类似于Ruby超时功能的好解决方案吗? 我用谷歌搜索了一下,并没有看到任何很好的东西。 谢谢您的帮助。

这是 Ruby 文档的链接 http://www.ruby-doc.org/stdlib/ libdoc/timeout/rdoc/index.html

Does anyone know a good solution for implementing a function similar to Ruby's timeout in Python? I've googled it and didn't really see anything very good. Thanks for the help.

Here's a link to the Ruby documentation
http://www.ruby-doc.org/stdlib/libdoc/timeout/rdoc/index.html

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空袭的梦i 2024-07-16 14:36:10
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
    import threading
    class InterruptableThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.result = None

        def run(self):
            try:
                self.result = func(*args, **kwargs)
            except:
                self.result = default

    it = InterruptableThread()
    it.start()
    it.join(timeout_duration)
    if it.isAlive():
        return default
    else:
        return it.result

来自:

http://code.activestate.com/recipes/473878/

def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
    import threading
    class InterruptableThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.result = None

        def run(self):
            try:
                self.result = func(*args, **kwargs)
            except:
                self.result = default

    it = InterruptableThread()
    it.start()
    it.join(timeout_duration)
    if it.isAlive():
        return default
    else:
        return it.result

from:

http://code.activestate.com/recipes/473878/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文