类型错误:对象没有该属性
我正在做一个程序,这个程序可以从一个探头获取温度,然后把这个温度放到一个谷歌表格里。我修改了一些我找到的代码,但遇到了一个我不知道怎么处理的错误。
下面是代码:
#!/usr/bin/python3
import os
import glob
import time
import gspread
import sys
import datetime
#Google account details
email = 'email@google.com'
password = 'password'
spreadsheet = 'spreadsheet' #the name of the spreadsheet already created
#attempt to log in to your google account
try:
gc = gspread.login(email,password)
except:
print('fail')
sys.exit()
#open the spreadsheet
worksheet = gc.open(spreadsheet).sheet1
#initiate the temperature sensor
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
#set up the location of the sensor in the system
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw(): #a function that grabs the raw temperature data from the $
f_1 = open(device_file, 'r')
lines_1 = f_1.readlines()
f_1.close()
return lines_1
def read_temp(): #a function that checks that the connection was good and stri$
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
temp = float(lines[1][equals_pos[0]+2:])/1000
return temp
while True: #infinite loop
temp = read_temp() #get the temp
values = [datetime.datetime.now(), temp[0], temp[1]]
worksheet.append_row(values) #write to the spreadsheet
time.sleep(600) #wait 10 minutes
我遇到的错误是:
Traceback (most recent call last):
File "temp.py", line 52, in <module>
temp = read_temp() #get the temp
File "temp.py", line 48, in read_temp
temp = float(lines[1][equals_pos[0]+2:])/1000
TypeError: 'int' object has no attribute '__getitem__'
我觉得我可能漏掉了什么明显的东西,但我不知道是什么。任何帮助都会很感激。我对这些还比较陌生。
1 个回答
2
equals_pos
是一个整数(这是 str.find
返回的结果),所以 equals_pos[0]+2
这样写是不合理的。你可以用 equals_pos+2
来代替。