Python Raspberry pi - 如果路径不存在,则跳过循环

Python Raspberry pi - If path doesn't exist, skip the loop

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

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

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 = catdata.communicate()
            out_decode = out.decode('utf-8')
            lines = out_decode.split('\n')
            return lines

使用os.path.isfile and 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
    ....

我不确定您为什么要使用 subprocess.Popen 来读取文件。 为什么不直接打开()它并读取()?

处理丢失的目录或文件的python方法是这样的:

for sensor in sensors:
    try:
        device_folder = glob.glob(base_dir + sensor)[0]
        device_file = device_folder + '/w1_slave'
        with open(device_file) as fd: # auto does fd.close()
            out = fd.read()
    except (IOError,IndexError):
        continue
    out_decode = out.decode('utf-8')
    ...

如果你想避免在 open() 或 read() 中挂起,你可以添加一个信号处理程序 并在 5 秒后给自己一个警报信号。这会打断 函数,然后将您移至 except 子句。

在开始时设置信号处理程序:

import signal
def signal_handler(signal, frame):
    raise IOError
signal.signal(signal.SIGALRM, signal_handler)

并修改循环以在可能挂起的部分之前调用 alarm(5)。 最后调用alarm(0)取消闹钟。

for sensor in sensors:
    signal.alarm(5)
    try:
        device_file = ...
        with open(device_file) as fd:
            out = fd.read()
    except (IOError,IndexError):
        continue
    finally:
        signal.alarm(0)
    print "ok"
    ...