如何在python中真正实现超时?http://eventlet.net/doc/modules/timeout.html
代码如下:
#!/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 ''
永远不会超时。我哪里错了?
PS我换了:
time.sleep(0.1)
和:
eventlet.sleep(0)
为异常添加 False,现在它运行良好:
with eventlet.timeout.Timeout(1):
改成:
with eventlet.timeout.Timeout(1, False):
但它仅适用于 eventlet.sleep(0.1)
例如此代码错误:
#!/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
我只是添加 sleep 0 秒:
eventlet.sleep(0)
它就像一个魅力。
解决了