Python Raspberry pi

编程入门 行业动态 更新时间:2024-10-26 08:33:16
本文介绍了Python Raspberry pi - 如果路径不存在,则跳过循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个函数来收集温度(来自文本文件的值),它使用部分预定义的路径.但是,如果温度传感器未加载(断开连接),则有时路径不存在.如果路径不可用,如何设置条件或异常以跳过循环?

I have a function to collect temperature (values from text files) which uses a partly predefined path. However, sometimes the path does not exist if the temperature sensor wasn't loaded (is disconnected). How can I set a condition or exception to skip a loop if a path is not available?

我想使用 continue,但我不知道要设置什么条件.

I wanted to use continue, but i have no idea what condition to set with it.

def read_all(): base_dir = '/sys/bus/w1/devices/' sensors=['28-000006dcc43f', '28-000006de2bd7', '28-000006dc7ea9', '28-000006dd9d1f','28-000006de2bd8'] for sensor in sensors: device_folder = glob.glob(base_dir + sensor)[0] device_file = device_folder + '/w1_slave' def read_temp_raw(): catdata = subprocess.Popen(['cat',device_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = catdatamunicate() out_decode = out.decode('utf-8') lines = out_decode.split('\n') return lines

推荐答案

使用 os.path.isfile 和 os.path.isdir() 检查.

for sensor in sensors: device_folders = glob.glob(base_dir + sensor) if len(device_folders) == 0: continue device_folder = device_folders[0] if not os.path.isdir(base_dir): continue device_file = device_folder + '/w1_slave' if not os.path.isfile(device_file) continue ....

更多推荐

Python Raspberry pi

本文发布于:2023-10-19 18:15:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508357.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python   Raspberry   pi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!