尝试在Jupyter Notebook中每小时运行一个python脚本,持续24小时



我想要做的是:我想每小时运行以下函数24小时。这个函数从api收集数据,将值附加到字典中,并将其保存为json文件以供以后使用。我正在运行的代码工作正常,但它并不优雅,因为我必须用KeyboardInterrupt来停止它。我想让脚本在24小时后停止运行,并在每小时打印:print('data successfully collected at ' + time.ctime()

def weather_collect():
url = 'http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}&units=metric'
response = requests.get(url.format(lat,lon, api_key))
r = response.json()
data['temperature'].append(r['main']['temp'])
data['humidity'].append(r['main']['humidity'])
data['pressure'].append(r['main']['pressure'])
data['visibility'].append(r['visibility'])
data['wind_speed'].append(r['wind']['speed'])
data['time'].append(time.ctime())
with open('data.json', 'w') as f:
f.write(json.dumps(data))
return data
schedule.every(1).hour.do(weather_collect)
while 1:
schedule.run_pending()
time.sleep(1)

而不是:

schedule.every(1).hour.do(weather_collect)
while 1:
schedule.run_pending()
time.sleep(1)

放这个:

for i in range(25):
weather_collect()
print('data successfully collected at ' + time.ctime())
sleep(3600) # sleep one hour
exit()

一个解决方案可能是添加一个计数器,每次循环执行时增加1。并打破&;while &;第24次循环。

相关内容

最新更新