码迷,mamicode.com
首页 > 编程语言 > 详细

python限制函数执行时间

时间:2017-07-03 23:57:18      阅读:655      评论:0      收藏:0      [点我收藏+]

标签:class   imp   exec   python   执行   rom   finally   函数   try   

from:https://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python
当有些函数执行时间过长,影响整个程序运行时,可以使用此方法进行限制,超时会报错。
from __future__ import with_statement # Required in 2.5
import signal
from contextlib import contextmanager

class TimeoutException(Exception): pass

@contextmanager
def time_limit(seconds):
    def signal_handler(signum, frame):
        raise TimeoutException, "Timed out!"
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(seconds)
    try:
        yield
    finally:
        signal.alarm(0)


try:
    with time_limit(10):
        long_function_call()
except TimeoutException, msg:
    print "Timed out!"

 

python限制函数执行时间

标签:class   imp   exec   python   执行   rom   finally   函数   try   

原文地址:http://www.cnblogs.com/buxizhizhoum/p/7113355.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!