如何消除Python脚本运行结束时的‘Lost access to message queue’提示
问题描述
运行以下Python脚本读取DHT11温湿度传感器时,正常输出数据后会出现Lost access to message queue提示,需要消除该提示:
运行输出:
pi@raspberrypi:$ peder.py 25.0 41.0 Temp: 77.0 F / 25.0 C Humidity: 41% Lost access to message queue
脚本代码:
#!/usr/bin/python3 import sys import board import time import adafruit_dht dhtDevice = adafruit_dht.DHT11(board.D17) try: # Print the values to the serial port temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity print("%-3.1f " % temperature_c + " " + "%-3.1f " % humidity) print( "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( temperature_f, temperature_c, humidity ) ) except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print(error.args[0]) time.sleep(2.0) except Exception as error: dhtDevice.exit() raise error
解决方法
这个提示是因为脚本结束时没有正确释放DHT设备占用的底层消息队列资源导致的,以下两种方式都能修复:
方法1:用finally块确保资源释放
在try-except结构后添加finally块,不管是否触发异常,都会执行设备退出操作来释放资源:
#!/usr/bin/python3 import sys import board import time import adafruit_dht dhtDevice = adafruit_dht.DHT11(board.D17) try: # Print the values to the serial port temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity print("%-3.1f " % temperature_c + " " + "%-3.1f " % humidity) print( "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( temperature_f, temperature_c, humidity ) ) except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print(error.args[0]) time.sleep(2.0) except Exception as error: raise error finally: dhtDevice.exit()
方法2:使用上下文管理器(with语句)
adafruit_dht支持上下文管理器,会自动在代码块结束时释放资源,写法更简洁:
#!/usr/bin/python3 import sys import board import time import adafruit_dht with adafruit_dht.DHT11(board.D17) as dhtDevice: try: # Print the values to the serial port temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity print("%-3.1f " % temperature_c + " " + "%-3.1f " % humidity) print( "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( temperature_f, temperature_c, humidity ) ) except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print(error.args[0]) time.sleep(2.0) except Exception as error: raise error
两种方法都能确保脚本结束时正确释放资源,消除Lost access to message queue的提示。
内容的提问来源于stack exchange,提问作者KjellPettersen
相关产品推荐
相关产品推荐

