Reputation: 61
How to truly implement timeout in python? http://eventlet.net/doc/modules/timeout.html
Code looks like:
#!/usr/bin/python
import eventlet
import time
import sys
import random
while True:
try:
with eventlet.timeout.Timeout(1, False):
print 'limited by timeout execution'
while True:
print '\r' + str(random.random()),
sys.stdout.flush()
eventlet.sleep(0)
print ' Never printed Secret! '
except Exception as e:
print ' Exception: ', e
finally:
print ''
print ' Timeout reached '
print ''
Time out will never reached. Where am I wrong?
P.s. I replaced:
time.sleep(0.1)
with:
eventlet.sleep(0)
Add False for exception, now it works well:
with eventlet.timeout.Timeout(1):
change to:
with eventlet.timeout.Timeout(1, False):
But it works only with eventlet.sleep(0.1)
E.g this code wrong:
#!/usr/bin/python
import eventlet
import time
start_time = time.time()
data = 0
with eventlet.timeout.Timeout(1, False):
while True:
data +=1
print 'Catch data ', data, ' in ', time.time() - start_time
I simply add sleep 0 seconds:
eventlet.sleep(0)
And it works like a charm.
Solved
Upvotes: 4
Views: 6480
Reputation: 18985
eventlet's Timeout isn't as magical as you'd hoped. It can only detect timeouts in "greenthreaded" code -- code that uses eventlet's system of cooperative multihtreading. As noted in the Timeout docs, "you cannot time out CPU-only operations with this class". time.sleep
pauses with Python's internal threading system, not eventlet's greenthreads.
Instead, use eventlet.sleep which works correctly with greenthreads.
Upvotes: 6