如何每隔X分钟从openweather api获取数据?我想使用Raspberry Pi Zero W在16x2 LCD上显示此数据。
import lcddriver
import time
import datetime
import requests, json
display = lcddriver.lcd()
complete_url = "http://api.openweathermap.org/data/2.5/weather?q=CITY&APPID=****HIDE_API*****"
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
try:
print("Writing to display")
display.lcd_display_string("Temperatura zew:",1)
display.lcd_display_string(str(current_temperature-273.15) + " C", 2)
time.sleep(10)
display.lcd_clear()
display.lcd_display_string("Cisnienie ", 1)
display.lcd_display_string(str(current_pressure) + " hPa",2)
time.sleep(10)
display.lcd_clear()
display.lcd_display_string("Wilgotnosc ", 1)
display.lcd_display_string(str(current_humidiy) + " %",2)
time.sleep(10)
display.lcd_clear()
time.sleep(1)
except KeyboardInterrupt: # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup
print("Cleaning up!")
display.lcd_clear()
答案 0 :(得分:0)
假设你的代码是否正常工作,导致我没有看到错误。您可以将代码置于无限循环中。
import time
x = 0
while True:
print(x)
x += 1
time.sleep(1)
上面的示例代码将一直打印,直到程序以1秒的间隔停止:
0
1
2
3
.
.
.
您可以做同样的,而不是使用time.sleep(12*60)
。
答案 1 :(得分:0)
这样的事情怎么样。我们可以使用time.time()来获取当前时间(UNIX格式)。如果当前时间比last_time大10分钟(60秒x 10)(我们检查了天气),我们将调用一个函数以从API获取天气。
(未经测试的代码,因为我没有LCD驱动程序或API密钥)
import lcddriver
import time
import datetime
import requests, json
display = lcddriver.lcd()
def get_weather():
complete_url = "http://api.openweathermap.org/data/2.5/weather?q=CITY&APPID=****HIDE_API*****"
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
return x
else:
return None
weather = None
try:
last_update_time = 0
while True:
if last_update_time + (60*10) > time.time():
weather = get_weather()
last_update_time = time.time()
if weather:
print("Writing to display")
display.lcd_display_string("Temperatura zew:",1)
display.lcd_display_string(str(weather['temp']-273.15) + " C", 2)
time.sleep(10)
display.lcd_clear()
display.lcd_display_string("Cisnienie ", 1)
display.lcd_display_string(str(weather['pressure']) + " hPa",2)
time.sleep(10)
display.lcd_clear()
display.lcd_display_string("Wilgotnosc ", 1)
display.lcd_display_string(str(weather['humidity']) + " %",2)
time.sleep(10)
display.lcd_clear()
time.sleep(1)
except KeyboardInterrupt: # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup
print("Cleaning up!")
display.lcd_clear()
答案 2 :(得分:0)
import threading, time
def fetch_data():
threading.Timer(5.0, fetch_data).start()
print(time.time())
# Fetch data from api
# Update LCD
fetch_data()