干得好:
import multiprocessingimport time# Your foo functiondef 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,然后将其杀死。
更新资料
仅在进程正在运行时才终止它。
# If thread is activeif p.is_alive(): print "foo is running... let's kill it..." # Terminate foo p.terminate()
更新2:推荐
join与一起使用
timeout。如果
foo在超时之前完成,则main可以继续。
# Wait a maximum of 10 seconds for foo# Usage: join([timeout in seconds])p.join(10)# If thread is activeif p.is_alive(): print "foo is running... let's kill it..." # Terminate foo p.terminate() p.join()


![时间段后停止代码[重复] 时间段后停止代码[重复]](http://www.mshxw.com/aiimages/31/611721.png)
