What is the best way to timeout while loop in python
say:
while not buff.endswith('/abc #'):
After 10 secs, if it does not match, break the loop.
Thanks
What is the best way to timeout while loop in python
say:
while not buff.endswith('/abc #'):
After 10 secs, if it does not match, break the loop.
Thanks
You can record the time before the loop, then inside the while loop you can compare the current time, and if it's > 10 seconds, you can break
out of the while loop.
Something like:
from datetime import datetime
start_time = datetime.now()
print(start_time)
while not buff.endswith('/abc #'):
print('waiting')
time_delta = datetime.now() - start_time
print(time_delta)
if time_delta.total_seconds() >= 10:
break
If your only concern is to end the loop after 10 seconds, try the below code.
from datetime import datetime
t1 = datetime.now()
while (datetime.now()-t1).seconds <= 10:
#do something
print(datetime.now())
Else check for the time difference inside the loop and break it. Like,
t1 = datetime.now()
while not buff.endswith('/abc #'):
if (datetime.now()-t1).seconds > 10:
break
You can use interrupting cow package and put you code inside a with
management statement.
import interruptingcow
TIME_WAIT=20 #time in seconds
class TimeOutError(Exception):
"""InterruptingCow exceptions cause by timeout"""
pass
with interruptingcow.timeout(TIME_WAIT, exception=TimeOutError):
while not buff.endswith('/abc #'):
pass #do something or just pass
As long you don't use interruptingcow with another systems that implements SIGALARM
eg. stopit
, python-rq
. It will work