2015-08-28 149 views
2

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

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

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 

回答

2

使用os.path.isfileos.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 
    .... 
+0

可能希望'继续'在那里,而不是'break',所以剩下的传感器仍在处理中 – tom

+0

更新以继续@tom。 – luoluo

+0

添加所建议的内容后,当传感器丢失时,它将在循环中停止并报告IndexError:列表索引超出范围。 – Miroslav

2

我不知道你为什么使用subprocess.Popen来读取文件。 为什么不打开()它和read()?.

一个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()或阅读(),您可以添加一个信号处理器 和例如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" 
    ... 
+0

可能值得解释“IOError”是什么以及使用'try '因为它看起来不像OP熟悉它。 – SuperBiasedMan

+0

这种情况在错误报告方面完全一样。由于偶尔会出现读取问题,因此我推荐使用子流程。但是因为我对Python非常陌生,所以我没有线索...... – Miroslav

+0

@Miroslav我添加了处理挂起的代码。 – meuh