Raspberry Pi上的w1thermsensor处理错误

时间:2019-03-16 18:43:38

标签: exception raspberry-pi python-3.5

我在Raspberry Pi上使用w1thermsensor。它可以工作,但是我想使我的代码对诸如硬件故障,拔下传感器等错误的鲁棒性。

Github存储库中似乎没有任何特定的帮助(尽管我从代码中可以看到它可能引发异常),也没有发现任何在线处理错误的示例。

我的代码是:

try: 
    sensor = W1ThermSensor() # Assumes just one sensor available 
    sensor_detect = "Detected" 
except: 
    sensor_detect = "Detect Error" 
if sensor_detect == "Detected": 
    try: 
        air_temperature = sensor.get_temperature() 
    except: 
        air_temperature = "Get temperature Error"

最初,我没有进行try / except检查,但是如果传感器不存在/未移除,我将失败。但是我想通过使用库返回的错误条件来更加精确。是否有可能发生的异常的简要清单/处理错误的示例代码?

1 个答案:

答案 0 :(得分:0)

w1thermsensor软件包可能引发的异常记录在方法的文档字符串中。例如。为get_temperature()

>>> help(w1thermsensor.core.W1ThermSensor.get_temperature)
Help on function get_temperature in module w1thermsensor.core:

get_temperature(self, unit=1)
    Returns the temperature in the specified unit

    :param int unit: the unit of the temperature requested

    :returns: the temperature in the given unit
    :rtype: float

    :raises UnsupportedUnitError: if the unit is not supported
    :raises NoSensorFoundError: if the sensor could not be found
    :raises SensorNotReadyError: if the sensor is not ready yet