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

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第三方库


热门话题
SpringMVC中的java,当我遇到旋度时,SpringMVC中出现错误   java如何从设备获取默认ip地址?   plink运行autosys批处理作业并检查其在java中的状态   java Json数组对象通过控制器[Spring Boot]传递到模型   netbeans将java命令行参数传递给插件   java Android AIDL gen文件导致警告?   java JAXB阻止JAXB与共享实体序列化   由@JsonIdentityInfo序列化的对象的java反序列化   postgresql java数组插入postgres   Java圆环碰撞检测   在Java中提取JSON键名   jdk1中的java内存泄漏。7   java Spring 3@Autowired注释问题