Stop code after time period
本问题已经有最佳答案,请猛点这里访问。
我想打电话给
我可以看到,理论上我可以修改
干得好:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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秒等待
更新
仅当进程正在运行时终止该进程。
1 2 3 4 5 6 | # If thread is active if p.is_alive(): print"foo is running... let's kill it..." # Terminate foo p.terminate() |
更新2:推荐
使用
1 2 3 4 5 6 7 8 9 10 11 | # 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() |
1 2 3 4 5 6 7 8 | 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) |
超时不是很精确,但是如果不需要非常精确的话可以做到。
另一种方法是使用资源模块,并设置最大CPU时间。