如何限制Python中函数调用的执行时间 [英] How to limit execution time of a function call in Python

查看:859
本文介绍了如何限制Python中函数调用的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一个与套接字相关的函数调用,该函数来自另一个模块,因此不受我的控制,问题是它有时阻塞数小时,这是完全不可接受的,我如何限制函数的执行时间?我的代码?我猜该解决方案必须使用另一个线程.

There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.

推荐答案

我不确定这可能是跨平台的,但是使用信号和警报可能是查看此问题的好方法.只需做一些工作,您就可以使它在任何情况下都完全通用且可用.

I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation.

http://docs.python.org/library/signal.html

所以您的代码将看起来像这样.

So your code is going to look something like this.

import signal

def signal_handler(signum, frame):
    raise Exception("Timed out!")

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10)   # Ten seconds
try:
    long_function_call()
except Exception, msg:
    print "Timed out!"

这篇关于如何限制Python中函数调用的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆