Python等待shell(ubuntu csh)完成操作/返回代码的命令

2024-10-03 02:39:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个Python命令+API来访问ECMWF(欧洲中期天气预报中心)数据服务器(称为MARS)并下载一些文件(天气数据)。我使用shell启动Python代码(我使用csh)在shell中执行./python_script.py

如果我下载一个文件(1999年,我的脚本中有range(1999, 2000),而不是下面失败的Python脚本示例中的range(1998, 2000)),它运行良好。现在我想下载其中的许多,从而使一个循环多年。你知道吗

我的问题是,Python脚本似乎没有等到shell命令/API完成并在明年继续。它会导致错误。文件已生成,但大小为零。你知道吗

我想知道是否可以指定Python脚本等待在shell窗口中找到一些关键字,然后再继续执行下一个for/loop步骤。你知道吗

我知道在这种情况下我正在使用一些特定的API,并且可能会找到另一个特定于API的解决方案,但是在shell中识别一些打印输出似乎更容易。你知道吗

例如,“Transfer rate”似乎只有在作业完成后才会出现在shell窗口中,请参阅我从shell保存的日志(最后成功的行)(使用./python_script.py >& log_file.log)。你知道吗

我的PYTHON代码是:

#!/usr/bin/env python
for year in range(1998, 2000):
from ecmwfapi import ECMWFDataServer
server = ECMWFDataServer()
server.retrieve({
    "class": "e2",
    "dataset": "era20c",
    "date": '%d-07-01/%d-07-02' % (year,year),
    "domain": "g",
    "area" : "12/-72/-67/22",
    "grid" : "1.0/1.0",
    "expver": "1",
    "param": "214.140/233.140",
    "step": "3/9/15/21",
    "format" : "netcdf",
    "stream": "wave",
    "target": '/home/nicolas/hycom/hycom_data/ECMWF/ERA20C/forecast/%d/test_era20c_wave_set1.nc' % (year),
    "time": "06",
    "type": "fc",
})

我的最后一行日志下载成功:

2016-02-13 16:00:21 Request is complete
2016-02-13 16:00:21 Transfering 239.441 Kbytes into /home/nicolas/hycom/hycom_data/ECMWF/ERA20C/forecast/1999/test_era20c_wave_set1.nc
2016-02-13 16:00:21 From http://stream.ecmwf.int/data/atls04/data/data01/scratch/_grib2netcdf-atls04-95e2cf679cd58ee9b4db4dd119a05a8d-JLUk0w.nc
2016-02-13 16:00:28 Transfer rate 32.6278 Kbytes/s

Tags: 文件数据代码命令脚本apidatarange
1条回答
网友
1楼 · 发布于 2024-10-03 02:39:07

不需要在循环中导入,也可能是标识问题。如果脚本与您提供的一样,那么retrieve不在循环中。python中的缩进很重要。你知道吗

请尝试以下方式重写脚本:

#!/usr/bin/env python
from ecmwfapi import ECMWFDataServer
server = ECMWFDataServer()
for year in range(1998, 2000):
    server.retrieve({
        "class": "e2",
        "dataset": "era20c",
        "date": '%d-07-01/%d-07-02' % (year,year),
        "domain": "g",
        "area" : "12/-72/-67/22",
        "grid" : "1.0/1.0",
        "expver": "1",
        "param": "214.140/233.140",
        "step": "3/9/15/21",
        "format" : "netcdf",
        "stream": "wave",
        "target": '/home/nicolas/hycom/hycom_data/ECMWF/ERA20C/forecast/%d/test_era20c_wave_set1.nc' % (year),
        "time": "06",
        "type": "fc",
    })

相关问题 更多 >