gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:18:01 25 4
gpt4 key购买 nike

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

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

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

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

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

例如,它可能是“传输率”,它似乎仅在作业完成后才会出现在 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

最佳答案

循环中不需要import,也可能是缩进问题。如果您的脚本与您提供的一样,则 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",
})

关于等待 shell (ubuntu csh) 完成操作/返回代码的 Python 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35383846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com