python3中断程序_python,3秒后中断函数

我也不得不这样做。我创建了一个模块,它提供了一个修饰符来限制函数的运行时:import logging

import signal

from functools import wraps

MODULELOG = logging.getLogger(__name__)

class Timeout(Exception):

"""The timeout handler was invoked"""

def _timeouthandler(signum, frame):

"""This function is called by SIGALRM"""

MODULELOG.info('Invoking the timeout')

raise Timeout

def timeout(seconds):

"""Decorate a function to set a timeout on its execution"""

def wrap(func):

"""Wrap a timer around the given function"""

@wraps(func)

def inner(*args, **kwargs):

"""Set an execution timer, execute the wrapped function,

then clear the timer."""

MODULELOG.debug('setting an alarm for %d seconds on %s' % (seconds, func))

oldsignal = signal.signal(signal.SIGALRM, _timeouthandler)

signal.alarm(seconds)

try:

return func(*args, **kwargs)

finally:

MODULELOG.debug('clearing the timer on %s' % func)

signal.alarm(0)

signal.signal(signal.SIGALRM, oldsignal)

return inner

return wrap

我用它就像:

^{pr2}$

在我的例子中,dosomething正在调用一个外部程序,它会周期性地挂起,我希望能够在发生这种情况时干净地退出。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值