我正在开发一个程序,它将从探针中获取温度,然后将其放入谷歌电子表格中。我修改了一些我发现的代码,我收到的错误是我不知道该怎么做。
代码如下:
#!/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__'
我觉得我错过了一些明显的东西,但我不知道它是什么。任何帮助,将不胜感激。我对此比较陌生。
答案 0 :(得分:2)
equals_pos
是int
(这是str.find
返回的内容),因此equals_pos[0]+2
没有意义。 equals_pos+2
可能会这样做。