我有一个记录房间温度的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'))
>>> 有没有一种方法可以忽略错误并重试?
发布于 2017-05-12 05:25:45
是的,有。它确实在尝试,并捕获任何引发的错误。
下面是它的基本工作原理:
try:
# Some action that could raise an error
except:
# What to do when an error occurs有关更深入的解释,请查看文档:Errors and Exceptions。
有几个内置的例外,ConnectionError就是其中之一。如果您知道所期望的确切异常,则必须将其添加到except子句中:
try:
# Actions that might raise a ConnectionError
except ConnectionError:
# Process the error, for instance, try again发布于 2017-05-12 05:28:39
您可能希望使用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-loop,因为您使用的是python27。
发布于 2017-05-12 05:31:49
您可以将循环包装在try语句中。
while True:
try:
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)
sys.exit(1)
except ConnectionError:
continue这样,当您断开连接时,您的代码将避开错误,从而防止它停止。
https://stackoverflow.com/questions/43925763
复制相似问题