Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue python script even after error ocurred

I have a Python script that logs temperature in my room and use requests library to send the data. Sometimes I lose wifi signal and the script stops completely after an error with the requests.

import sys
import time
import Adafruit_DHT
import requests

raspid = 1
sensor = 11
pin = 25

while True:   
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    if humidity is not None and temperature is not None:
        datos = {'temperatura': 'temperature', 'humedad': 'humidity', 'raspid': 'raspid'}
        r = requests.post("http://httpbin.org/post", data=datos)
        print(r.text)
    else:
        print ('Error de lectura!')
        time.sleep(15)

Error when disconnected from wifi

Traceback (most recent call last):
  File "/home/pi/Desktop/dht11 request post.py", line 19, in <module>
    r = requests.post("http://mehr.cl/link.php", data=datos)
  File "/usr/lib/python2.7/dist-packages/requests/api.py", line 94, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/api.py", line 49, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 457, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 569, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 407, in send
    raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', error(101, 'Network is unreachable'))
>>> 

Is there a way to ignore the error and just try again?

like image 216
Ricardo Mehr Avatar asked Aug 16 '26 19:08

Ricardo Mehr


2 Answers

Yes, there is. It's precisely trying, and catching any error raised.

Here is basically how it works:

try:
    # Some action that could raise an error

except:
    # What to do when an error occurs

For deeper explanation, check the documentation: Errors and Exceptions.

There are several built-in exceptions, among which, ConnectionError. If you know the exact exception you're expecting, then you must add it to the except clause:

try:
    # Actions that might raise a ConnectionError

except ConnectionError:
    # Process the error, for instance, try again
like image 160
Right leg Avatar answered Aug 19 '26 08:08

Right leg


You may want to use a try-except statement. As follows

while True:
    try:
        #action which may create an error
    except Exception as exc:
        print('[!!!] {err}'.format(err=exc))
        #action to perform: Nothing in your case

Note that a good practice is that an error should never pass silently.


Following the discussion in comments, note also that if you use Exception to handle your error, you will still be able to stop the while-loop manually, since you use python27.
like image 24
keepAlive Avatar answered Aug 19 '26 09:08

keepAlive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!