python 的 windows 中的程序超时
您好,我在 SE 上看到了很多涉及类似问题的问题,但我发现很多答案都不清楚且令人困惑。我的问题很简单。在 Windows 平台上,如何使用 Python v2.6 在一定时间后终止正在运行的函数?如果我有:
def my_function(start):
x=start
while True:
print x
x=x+1
return x
如何在 X 秒后停止?请清楚地回答我的函数应该放在哪里以及如何调整时间限制。谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只想运行一个带有超时的普通函数,请尝试:
如果您正在谈论停止线程,有一篇关于使用线程执行此操作的博客文章涵盖了所有基础知识。
如何(不)在 Python 中设置计算超时。 作者也使用此网站。
基本上,答案是在 Python 中没有“正确的方法”来执行此操作,尽管如果您不在 Windows 上,
SIGALARM
也可以。If you just want to run a normal function with a timeout, try:
If you're talking about stopping a thread, there is a blog post about doing this with threads which covers all the bases.
How (not) to set a timeout on a computation in Python. The author also uses this site.
Basically, the answer is that there is no "right way" to do this in Python, though if you're not on Windows
SIGALARM
works.简单的解决方案:
看看 datetime 模块。您可以在循环开始时保存时间戳并在 while 部分计算 timedelta。
如果时间增量大于您希望的时间增量,请通过调用“break”从循环中中断。
Straightforward solution:
Have a look at the datetime module. You can save a timestamp upon start of the loop and calculate the timedelta in the while part.
If the timedelta is greater then the one you wish to have, break from the loop by calling "break".
您或许可以使用此timeout.py 模块对您有利。它的使用需要编写一个函数并通过(或修饰)模块中的
add_timeout
函数。调用新的“函数”后,您可以查询
ready
属性以了解其执行状态:False
表示该函数仍在执行。True
表示执行已结束。None
表示已达到超时且函数终止。如果
ready
为True
,value
属性将包含函数执行的结果。如果函数引发异常,则在计算value
时将重新引发异常。如果在ready
为True
之前评估value
,则会引发timeout.NotReadyError
。注意:该模块并不是专门为装饰函数而设计的,并且一般情况下不应该装饰方法。不保证实例属性能够跨执行边界更新。
附录:
Google 代码似乎不支持查找timeout.py 模块不再存在。尽管 API 略有不同,但我建议使用异步模块。下面包含其源代码,后面是用于验证其正常工作的第二个模块。
asynchronous.py
test_asynchronous.py
You might be able to use this timeout.py module to your advantage. Its use requires that a function be written and passed through (or decorated with) the
add_timeout
function in the module.After calling the new "function," you can query the
ready
property to find out its state of exection:False
means the function is still executing.True
means that execution has ended.None
means that the timeout has been reached and the function terminated.If and when
ready
isTrue
, thevalue
property will have the results of the functions execution. If the function raised an exception, it will be re-raised upon evaluatingvalue
. Ifvalue
is evaluated beforeready
isTrue
, atimeout.NotReadyError
will be raised.Note: the module was not designed specifically for decorating functions, and methods in general should not be decorated. Instance attributes are not guaranteed to be updated across the execution boundary.
Addendum:
It appears that Google Code does not support looking up the timeout.py module anymore. Although the API is a little different, I would recommend the
asynchronous
module instead. Its source is included below followed by a second module used to verify it is working correctly.asynchronous.py
test_asynchronous.py