我有一个收集温度的函数(来自文本文件的值),它使用部分预定义的路径。但是,如果未加载温度传感器(断开连接),有时路径不存在。如果路径不可用,如何设置条件或异常以跳过循环?
我想继续使用,但我不知道要设置什么条件。
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
答案 0 :(得分:2)
使用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
....
答案 1 :(得分:2)
我不确定为什么要使用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)
。
最后呼叫报警(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"
...