如何在Jupyter Notebook中每小时运行Python脚本并24小时后自动停止
实现代码
import requests import time import json import schedule # 提前初始化存储数据的字典 data = { "temperature": [], "humidity": [], "pressure": [], "visibility": [], "wind_speed": [], "time": [] } # 替换为你自己的经纬度和OpenWeatherMap API密钥 lat = 实际纬度值 lon = 实际经度值 api_key = 你的API密钥 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']) collect_time = time.ctime() data['time'].append(collect_time) with open('data.json', 'w') as f: f.write(json.dumps(data)) # 新增要求的采集成功打印逻辑 print('data successfully collected at ' + collect_time) return data schedule.every(1).hour.do(weather_collect) # 记录启动时间,计算24小时对应的运行总时长(秒) start_time = time.time() total_run_time = 24 * 60 * 60 while True: # 运行时长达到24小时则自动终止脚本 if time.time() - start_time >= total_run_time: print("24小时采集任务已完成,脚本退出") break schedule.run_pending() time.sleep(1)
关键改动说明
- 新增运行时长校验逻辑:记录脚本启动时间,每次循环判断当前运行时长,达到24小时自动跳出循环终止运行,不需要手动触发KeyboardInterrupt
- 新增要求的采集成功打印语句,为避免两次调用
time.ctime()出现时间不一致的问题,提前将采集时间存入变量同时用于打印和数据存储 - 补充了必填变量的初始化示例,避免运行时出现未定义变量的报错
- 可选优化:如果希望脚本启动时立刻执行第一次采集,不需要等待1小时,可以在启动循环前新增一行
weather_collect()即可
内容的提问来源于stack exchange,提问作者Angry Physicist
相关产品推荐
相关产品推荐

