I am making a python to read temperature from a simple server in a lan network each 2 seconds, the problem is that sometimes the script is stuck without doing anything, I'm using requests with python 3.6 on windows
import requests
import time
while True:
s=time.time()
r = requests.get("http://192.168.1.2/readtemp.php?id=1&action=read")
temp = r.text
print (temp + ' - ' + str(time.time()-s) + ' Seconds')
time.sleep(2)
the response I get is this:
29°C - 0.272745847702026 Seconds
29°C - 0.64812617301941 Seconds
29°C - 0.294319868087769 Seconds
but sometimes when I come back to my computer I find it stuck doing nothing, any ideas why it gets stuck, isn't it supposed to keep making the request till it gets a response like browsers do?
As Tobias wrote, requests doesn't retry nor have a timeout by default, as using a timeout would inform you about a potential (and the most likely, my opinion) issue. Either catch the exception and retry later or you can go the more advanced route of a retry adapter.
Try this request with timeout & error handling:
import requests
import time
while True:
s=time.time()
try:
r = requests.get("http://192.168.1.2/readtemp.php?id=1&action=read", timeout=10)
except requests.exceptions.Timeout as err:
print(err)
# sleep some sec/min and retry here!
temp = r.text
print (temp + ' - ' + str(time.time()-s) + ' Seconds')
time.sleep(2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With