python - 即使在发生错误后继续 python 脚本

标签 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'))
>>> 

有没有办法忽略错误并重试?

最佳答案

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

基本上它是这样工作的:

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

关于python - 即使在发生错误后继续 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43925763/

相关文章:

python - 以 Python 方式编码

python - 为什么使用 update_one 更新记录会引发 ValueError?

python - 这个嵌套循环的 Python 列表理解是什么?

python - 查找给定节点的最高权重边

python - 找不到模块

python - 在 Django 中,什么时候应该使用 doctests 而不是单元测试?

python - 将 Python NumPy 数组插入 PostgreSQL 数据库

python - 从主代码到多个线程(有套接字,如果这很重要的话)进行通信

python - 取消引用 hdf5 格式?

python-2.7 - OpenCV:libdc1394 错误:无法初始化 libdc1394