簡體   English   中英

即使出現錯誤,也要繼續python腳本

[英]Continue python script even after error ocurred

我有一個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

有關更深入的說明,請查看文檔: 錯誤和例外

有幾個內置異常,其中包括ConnectionError 如果你知道你期望的確切異常,那么你必須將它添加到except子句:

try:
    # Actions that might raise a ConnectionError

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

您可能想要使用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

請注意,一個好的做法是錯誤永遠不會無聲通過


在評論中討論之后,還要注意,如果使用Exception來處理錯誤,您仍然可以手動停止while循環,因為您使用的是python27。

您可以將循環包裝在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

通過這樣做,您的代碼將逃避錯誤,從而防止它在您失去連接時停止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM