Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is a working example using function signal.alarm():

import time
from signal import alarm

def foo(i):
    sleep([1,1000][i%2])
    return True

for i in range(0,10):
    try:
        alarm(5)    
        print("Began computation at", time.localtime())
        foo(i)
    except KeyboardInterrupt:      
        print("Timed out with ", i, "at", time.localtime())
    else:
        print("Completed with", i, "at", time.localtime())
    alarm(0)   # reset

Try it at Sagecell.

Here is a working example using function signal.alarm():

import time
from signal import alarm

def foo(i):
    sleep([1,1000][i%2])
    return True

for i in range(0,10):
    try:
        alarm(5)    
    print("Began computation at", time.localtime())
 print("Began computation at", time.localtime())
try:
        foo(i)
    except KeyboardInterrupt:      
        print("Timed out with ", i, "at", time.localtime())
    else:
        print("Completed with", i, "at", time.localtime())
    alarm(0)   # reset

Try it at Sagecell.