我正在使用 python 脚本将三个文件的内容传输到不同的三个文件。原始文件是我连接到运行 raspian 的 RPI 的三个温度计的数据。所有脚本应该做的就是获取文件的内容并移动它们,以便我可以让另一个程序 (ComScript) 读取和解析它们。
我的问题是,如果一个或多个温度计在脚本开始之前断开连接,它就会卡住。如果我在脚本运行时断开温度计,它不会卡住。
这是代码
import time
a = 1
while a == 1:
try:
tfile = open("/sys/bus/w1/devices/28-000004d2ca5e/w1_slave")
text = tfile.read()
tfile.close()
temperature = text
tfile2 = open("/sys/bus/w1/devices/28-000004d2fb20/w1_slave")
text2 = tfile2.read()
tfile2.close()
temperature2 = text2
tfile3 = open("/sys/bus/w1/devices/28-000004d30568/w1_slave")
text3 = tfile3.read()
tfile3.close()
temperature3 = text3
textfile = open("/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave1", "w ")
textfile2 = open("/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave2", "w ")
textfile3 = open("/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave3", "w ")
temperature = str(temperature)
temperature2 = str(temperature2)
temperature3 = str(temperature3)
textfile.write(temperature)
textfile2.write(temperature2)
textfile3.write(temperature3)
textfile.close()
textfile2.close()
textfile3.close()
print temperature
print temperature2
print temperature3
time.sleep(3)
except:
pass
我添加了异常传递,因为我需要它继续运行,即使它得到错误的值。当其中一个温度计断开连接时,python 试图读取的文件是空白的,但仍然存在。
最佳答案
除去毯子,除了。
您的脚本不会卡住,但您遇到的任何错误都会在无限循环中被忽略。因为您使用了一条毯子except:
,您捕获了所有异常,包括键盘中断异常KeyboardInterrupt
。
至少记录异常,并且只捕获Exception
:
except Exception:
import logging
logging.exception('Oops: error occurred')
KeyboardInterrupt
是 BaseException
的子类,不是 Exception
并且不会被这个 except 处理程序捕获。
看看 shutil
module对于复制文件,你做了太多的工作:
import time
import shutil
import os.path
paths = ('28-000004d2ca5e', '28-000004d2fb20', '28-000004d30568')
while True:
for i, name in enumerate(paths, 1):
src = os.path.join('/sys/bus/w1/devices', name, 'w1_slave')
dst = '/home/pi/ComScriptPi/profiles/Temperature_parse/w1_slave{}'.format(i)
try:
shutil.copyfile(src, dst)
except EnvironmentError:
import logging
logging.exception('Oops: error occurred')
time.sleep(3)
处理文件应该只永远引发EnvironmentError
或其子类,没有需要捕获这里的所有内容。
关于Python 失败文件处理卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17934385/