首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >即使出现错误仍继续执行python脚本

即使出现错误仍继续执行python脚本
EN

Stack Overflow用户
提问于 2017-05-12 05:22:53
回答 3查看 6.2K关注 0票数 3

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

代码语言:javascript
复制
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断开时出错

代码语言:javascript
复制
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'))
>>> 

有没有一种方法可以忽略错误并重试?

EN

回答 3

Stack Overflow用户

发布于 2017-05-12 05:25:45

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

下面是它的基本工作原理:

代码语言:javascript
复制
try:
    # Some action that could raise an error

except:
    # What to do when an error occurs

有关更深入的解释,请查看文档:Errors and Exceptions

有几个内置的例外,ConnectionError就是其中之一。如果您知道所期望的确切异常,则必须将其添加到except子句中:

代码语言:javascript
复制
try:
    # Actions that might raise a ConnectionError

except ConnectionError:
    # Process the error, for instance, try again
票数 5
EN

Stack Overflow用户

发布于 2017-05-12 05:28:39

您可能希望使用try-except语句。如下所示

代码语言:javascript
复制
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。

票数 3
EN

Stack Overflow用户

发布于 2017-05-12 05:31:49

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

代码语言:javascript
复制
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

这样,当您断开连接时,您的代码将避开错误,从而防止它停止。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43925763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档