How to really implement a timeout in python?

How to really implement a timeout in python? http://eventlet.net/doc/modules/timeout.html

The code looks like this:

#!/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 '' 

The timeout will never reach. Where am I mistaken?

Ps I replaced:

  time.sleep(0.1) 

with:

  eventlet.sleep(0) 

Add False for an exception, now it works well:

 with eventlet.timeout.Timeout(1): 

change to:

 with eventlet.timeout.Timeout(1, False): 

But it only works with eventlet.sleep (0.1)

For example, this code is incorrect:

 #!/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 just add sleep 0 seconds:

 eventlet.sleep(0) 

And it works like a charm.

Solved

+4
source share
1 answer

eventlet Timeout is not as magical as you hoped. It can only detect timeouts in the greenthreaded code, which uses a multi-element operation system. As stated in the Timeout Documents , "you cannot only time operations with a processor with this class." time.sleep paused using the Python internal streaming system, not gretedreads in the eventlet.

Use eventlet.sleep instead , which works correctly with greenthreads.

+5
source

Source: https://habr.com/ru/post/1490371/


All Articles