Python 时间段后停止代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14920384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop code after time period
提问by felipa
I would like to call foo(n)but stop it if it runs for more than 10 seconds. What's a good way to do this?
foo(n)如果它运行超过 10 秒,我想调用但停止它。有什么好方法可以做到这一点?
I can see that I could in theory modify fooitself to periodically check how long it has been running for but I would prefer not to do that.
我可以看到理论上我可以修改foo自己以定期检查它已经运行了多长时间,但我不想这样做。
采纳答案by ATOzTOA
Here you go:
干得好:
import multiprocessing
import time
# Your foo function
def foo(n):
for i in range(10000 * n):
print "Tick"
time.sleep(1)
if __name__ == '__main__':
# Start foo as a process
p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
p.start()
# Wait 10 seconds for foo
time.sleep(10)
# Terminate foo
p.terminate()
# Cleanup
p.join()
This will wait 10 seconds for fooand then kill it.
这将等待 10 秒钟foo,然后将其杀死。
Update
更新
Terminate the process only if it is running.
仅当进程正在运行时才终止该进程。
# If thread is active
if p.is_alive():
print "foo is running... let's kill it..."
# Terminate foo
p.terminate()
Update 2 : Recommended
更新 2:推荐
Use joinwith timeout. If foofinishes before timeout, then main can continue.
join与 一起使用timeout。如果foo在超时之前完成,则 main 可以继续。
# Wait a maximum of 10 seconds for foo
# Usage: join([timeout in seconds])
p.join(10)
# If thread is active
if p.is_alive():
print "foo is running... let's kill it..."
# Terminate foo
p.terminate()
p.join()
回答by LtWorf
import signal
#Sets an handler function, you can comment it if you don't need it.
signal.signal(signal.SIGALRM,handler_function)
#Sets an alarm in 10 seconds
#If uncaught will terminate your process.
signal.alarm(10)
The timeout is not very precise, but can do if you don't need extreme precision.
超时不是很精确,但如果您不需要极高的精度,可以这样做。
Another way is to use the resourcemodule, and set the maximum CPU time.
另一种方法是使用资源模块,并设置最大 CPU 时间。

