在时间段后停止代码

71 投票
2 回答
140704 浏览
提问于 2025-04-17 16:09

我想调用 foo(n) 这个函数,但如果它运行超过10秒钟就想停止它。有什么好的办法可以做到这一点呢?

我知道理论上可以修改 foo 函数,让它定期检查自己运行了多久,但我更希望不这样做。

2 个回答

13
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) 

这个超时时间不是特别准确,但如果你不需要特别精确的话,这样用也可以。

另一种方法是使用 resource 模块,来设置最大的CPU使用时间。

78

给你看:

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()

这段代码会等10秒钟来查看foo,然后把它结束掉。

更新

只有在foo正在运行的时候才会结束这个进程。

# If thread is active
if p.is_alive():
    print "foo is running... let's kill it..."

    # Terminate foo
    p.terminate()

更新 2:推荐

使用jointimeout。如果foo在超时之前完成了,那么主程序可以继续运行。

# 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()

撰写回答