The pyowm
library allows one to get weather forecasts from https://openweathermap.org. It works nicely in a little program I've written to download a near-term forecast (see below, excepting my API key which I've X'd out; insert your own API key of you want to test the code, they're freely available from openweathermap).
#!/usr/bin/env python
import pyowm
import json
owm = pyowm.OWM('XXXXXXXXXXXXX') # You MUST provide a valid API key
forecaster = owm.three_hours_forecast('Santa Fe, US')
forecast = forecaster.get_forecast()
forecastJSON=json.loads(forecast.to_JSON())
def oneForecast():
mrForecast = forecastJSON['weathers'][:1]
return mrForecast[0]['detailed_status']
def printForecast():
print oneForecast()
if __name__ == "__main__":
printForecast()
That works perfectly from the command line. However, if I create another program that periodically calls oneForecast(), it returns the correct answer the first time, and then NEVER CHANGES ITS FORECAST.
See for example
#!/usr/bin/env python
import time
import msForecast
def run():
while True:
text = msForecast.oneForecast()
print text
time.sleep(10.0)
if __name__ == "__main__":
run_text = run()
This program, when run from the command line, should print a simple forecast every ten seconds. As it makes a call to the API each time, this forecast should update as the weather changes, but it does not. If the forecast is 'light rain' when the program is first run, it will print 'light rain' every ten seconds indefinitely, without ever changing.
Have I made an error in the way the second bit of code calls the first? Is there some cache that needs to be flushed? What might I be missing here?
Your oneForecast
call doesn't do anything to fetch a new forecast, it just formats the one you already fetched earlier.
This is the code that fetches a new forecast:
forecaster = owm.three_hours_forecast('Santa Fe, US')
forecast = forecaster.get_forecast()
And that's top-level module code: it only runs once per Python interpreter session, when you first import
the module.
So, you just need to rewrite your code to do that fetch each time you call oneForecast
, maybe like this:
forecaster = owm.three_hours_forecast('Santa Fe, US')
def oneForecast():
forecast = forecaster.get_forecast()
forecastJSON=json.loads(forecast.to_JSON())
mrForecast = forecastJSON['weathers'][:1]
return mrForecast[0]['detailed_status']