python限制函数执行时间


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!"

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM