即使出现错误,也要继续python脚本

时间:2017-05-11 21:22:53

标签: python python-2.7

我有一个Python脚本,可以记录我房间的温度,并使用请求库来发送数据。有时我丢失了wifi信号,并且在请求出错后脚本完全停止。

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)

从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'))
>>> 

有没有办法忽略错误,只是再试一次?

3 个答案:

答案 0 :(得分:4)

是的,有。它正在尝试,并捕捉任何错误。

基本上是这样的:

try:
    # Some action that could raise an error

except:
    # What to do when an error occurs

有关更深入的说明,请查看文档:{​​{3}}。

有几个内置异常,其中包括ConnectionError。如果你知道你期望的确切异常,那么你必须将它添加到except子句中:

try:
    # Actions that might raise a ConnectionError

except ConnectionError:
    # Process the error, for instance, try again

答案 1 :(得分:2)

您可能想要使用try-except语句。如下

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

请注意,一个好的做法是错误should never pass silently

<小时/> 在评论中讨论之后,请注意,如果您使用Exception来处理错误,您仍然可以手动停止while - 循环,因为您使用了python27。

答案 2 :(得分:0)

您可以将循环包装在 try 语句中。

login() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())

}

通过这样做,您的代码将逃避错误,从而防止它在您丢失连接时停止。