【问题标题】:Trying to run a python script every hour for 24 hours in Jupyter Notebook尝试在 Jupyter Notebook 中每小时运行一个 python 脚本 24 小时
【发布时间】:2021-11-14 23:43:00
【问题描述】:

这就是我想要做的:我想在 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)

【问题讨论】:

    标签: python file scheduled-tasks


    【解决方案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()
    

    【讨论】:

    • 非常感谢!
    【解决方案2】:

    一种解决方案可能是添加一个计数器,每次循环执行时将其递增 1。 并在第 24 次迭代时打破“while 1”循环。

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2010-10-05
    • 2020-03-05
    • 1970-01-01
    • 2014-12-13
    • 2020-09-11
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多