Skip to content Skip to sidebar Skip to footer

Python Raspberry Pi - If Path Doesn't Exist, Skip The Loop

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 l

Solution 1:

Use os.path.isfile and os.path.isdir() to check.

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
    ....

Solution 2:

I'm not sure why you are using subprocess.Popen to read the file. Why not just open() it and read()?.

A python way to handle missing dir or file is something like this:

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

If you want to avoid hanging in open() or read() you can add a signal handler and give yourself an alarm signal after, say, 5 seconds. This will interrupt the function, and move you into the except clause.

Setup the signal handler at the start:

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

and modify your loop to call alarm(5) before the part that might hang. Call alarm(0) at the end to cancel the alarm.

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

Post a Comment for "Python Raspberry Pi - If Path Doesn't Exist, Skip The Loop"