使用 Python 执行外部命令和交换变量

Execute external command and exchange variable using Python

1。简介

我有一堆 netcdf 格式的文件。 每个文件包含不同时期某地的气象情况(每小时数据)。
我需要为每个文件提取前 12 小时的数据。所以我select使用NCO(netcdf operator)来处理。

NCO 适用于终端环境。使用 >ncks -d Time 0,11 input.nc output.nc,我可以获得一个名为 out.nc 的数据文件,其中包含 in.nc.

的前 12h 数据

2。我的尝试

我想将所有过程保存在我的 ipython 笔记本中。但是我坚持了两个方面。

  1. How to execute terminal code in python loop

  2. How to transfer the string in python into terminal code.

例如,这是我的假代码。

files = os.listdir('.')
for file in files:
    filename,extname = os.path.splitext(file)
    if extname == '.nc':   
        output = filename + "_0-12_" + extname
        ## The code below was my attempt
        !ncks -d Time 0,11 file output` 

3。结论

基本上,我的目标是让假代码 !ncks -d Time 0,11 file output 成真。这意味着:

  1. 直接在python循环中执行netcdf运算符...
  2. ...使用 filename,它是 python 环境中的字符串。

抱歉我的问题不清楚。如有任何建议,我们将不胜感激!

您可以使用subprocess.check_output执行外部程序:

import glob
import subprocess

for fn in glob.iglob('*.nc'):
    filename, extname = os.path.splitext(fn)
    output_fn = filename + "_0-12_" + extname
    output = subprocess.call(['ncks', '-d', 'Time', '0,11', fn, output_fn])
    print(output)

注意:更新代码以使用 glob.iglob;您不需要手动检查扩展名。

您还可以查看 pynco,它用子进程调用包装了 NCO,类似于@falsetru 的回答。您的应用程序可能类似于

nco = Nco()
for fn in glob.iglob('*.nc'):
    filename, extname = os.path.splitext(fn)
    output_fn = filename + "_0-12_" + extname
    nco.ncks(input=filename, output=output_fn, dimension='Time 0,11')