微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Python 中发送自动下载请求并退出下载?

如何解决如何在 Python 中发送自动下载请求并退出下载?

我正在使用 Python 发送 ERA5 (Data description) 的下载请求,它托管气象数据以供下载。我的目标是发送一个请求,该请求将为我想要下载的数据生成 URL,但不让整个下载发生,因为我不想在它上面花费我的互联网。获得 URL 后,我可以使用我的学院下载服务并使用 wget -i url.txt 进行下载。

然而,问题是我在本地机器上运行的代码(利用本地互联网)会一直运行直到下载完成,这违背了目的,因为我只想发送一个下载请求来生成 URL 而不是下载数据本身。

到目前为止,我一直尝试使用有时限的 while 循环,但是一旦发送请求,它就不会遵守循环。 我的代码如下:

import cdsapi  # required module for API request
import time    # for tracking time
years = ['1980','1981','1982','1984','1985','1986','1989','1990','1991','1992','1993','1995','1996','1997','1998','1999','2000','2001','2003','2004','2005','2006','2007','2008','2010','2011','2012','2013']   # required years
variables = ['u_component_of_wind','v_component_of_wind','geopotential','temperature','vertical_veLocity','vorticity']  # required meteorological variables
def callrequest(year,vary,counter):    # function which take year,variable and a counter value
    if counter == 0:   # to make sure only one request is sent for a combination of year and variable
        c = cdsapi.Client()   # these are required steps and info for request
        c.retrieve(
            'reanalysis-era5-pressure-levels',{
            'product_type': 'reanalysis','variable': vary,# stating which variable is required out of all variables
            'pressure_level': [
                '50','100','150','200','250','300','350','400','450','500','550','600','650','700','750','800','850','900','950','1000',],'year': year,# stating which year out of all years
            'month': [
                '01','02','03','04','05','06','07','08','09','10','11','12','day': [
                '01','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','time': [
                '00:00','06:00','12:00','18:00','area': [
                40,50,-10,120,'format': 'netcdf',},'download.nc')


duration = 0.001
present_time = time.time()
counter = 0
for i in range(len(years)):
    for j in range(len(variables)):
       counter = 0
       while time.time()<present_time + duration:  # an attempt to run while loop for some time only and process only one request
           callrequest(years[i],variables[j],counter)
           counter = counter + 1

当前代码的缺点:

  1. while 循环确保请求已发送,但不会在给定的持续时间内终止,并且终端会一直运行到下载完成。

  2. 不确定它是否会选择下一个年份和变量的组合。

我想要的代码将使用 Year 和 Variable 的一个值,发送请求,以便在处理和下载请求之前生成 URL 并终止(发送后大约需要 30-40 分钟),以及然后跳到明年和可变组合。我会感谢所有提供帮助并使其变得更好的人。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。