中断长时间运行的代码的看门狗。

interruptingcow的Python项目详细描述


interruptingcow是一个通用实用程序,它可以相对优雅地中断 当python代码在特定秒数内未执行时:

from interruptingcow import timeout

try:
    with timeout(5, exception=RuntimeError):
        # perform a potentially very slow operation
        pass
except RuntimeError:
    print "didn't finish within 5 seconds"

超时以秒为单位(以理论微秒为单位 精确性)。

安装

$ pip install interruptingcow

可重入

interruptingcow是完全可重入的,这意味着您可以嵌套 超时:

from interruptingcow import timeout

class Outer(RuntimeError): pass

class Inner(RuntimeError): pass

try:
    with timeout(20.0, Outer):
        try:
            with timeout(1.0, Inner):
                # some expensive operation
                try_the_expensive_thing()
        except Inner:
            do_the_cheap_thing_instead()

except Outer:
    print 'Program as a whole failed to return in 20 secs'

嵌套超时允许较大的外部超时包含较小的超时。如果 内部超时大于外部超时,它被视为无操作。

函数装饰器

interruptingcow既可以用作inline with语句,如 以上示例以及函数decorator:

from interruptingcow import timeout

@timeout(.5)
def foo():
    with timeout(.3):
        # some expensive operation
        pass

配额

您可以分配一个时间配额,然后在多个调用之间共享它 到timeout()。如果您需要在内部使用超时,这尤其有用 循环:

from interruptingcow import timeout, Quota

quota = Quota(1.0)
for i in something:
    try:
        with timeout(quota, RuntimeError):
            # perform a slow operation
            pass
    except RuntimeError:
        # do a cheaper thing instead

在这里,循环的第一次迭代将能够执行昂贵的 操作,直到共享配额1秒用完,然后剩余的 迭代将执行更便宜的选择。

单个配额实例也可以在对^{tt1}的所有调用中共享$ 应用程序进行(包括嵌套调用)以给出place的上限 在整个运行时中,不管有多少次调用timeout()

注意事项

interruptingcow使用signal(SIGALRM)让操作系统中断 程序执行。这有以下限制:

  1. python信号处理程序只应用于主线程,因此不能使用 来自其他线程
  2. 您不能在使用SIGALRM本身的程序中使用这个 包括某些探查器)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
序列化反序列化java。awt。颜色>java。木卫一。InvalidClassException   java禁用多个日期范围jDateChooser   java为什么我的特例apper会被扔进泽西/灰熊?   JavaIntelliJ比较两个覆盖率数据   java什么是servletsdefault。你怎么办?   单击几下libgdx后java按钮没有响应   使用java将字符串转换为JSONArray   文件系统在java中刷新fileSystemViewer   java如何在hibernate中避免脏检查   java奇怪的问题,带有分号和“无法解决…”   java将值从子面板传递到父面板   HTML JTextPane CSS的Java FontSizeAction   java文件代码神秘地变成了一堆(0000)