最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何限制Python中函数调用的执行时间

SEO心得admin75浏览0评论
本文介绍了如何限制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.

docs.python/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!"
发布评论

评论列表(0)

  1. 暂无评论