在python代码中使用列表的所有元素作为系统命令(netCDF运算符)的参数

时间:2014-08-08 06:17:04

标签: python netcdf nco

我有一个python代码在某些netCDF文件上执行一些运算符。它将ne​​tCDF文件的名称作为列表。我想使用netCDF运算符ncea(netCDF集合平均值)计算这些netCDF文件的整体平均值。但是,要调用NCO,我需要将所有列表元素作为参数传递,如下所示:

 filelist = [file1.ncf file2.ncf file3.ncf ........ file50.ncf]

ncea file1.ncf file2.ncf ......file49.ncf file50.ncf output.cdf

知道如何实现这一目标。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

import subprocess
import shlex
args = 'ncea file1.ncf file2.ncf ......file49.ncf file50.ncf output.cdf'
args = shlex.split(args)
p = subprocess.Popen(args,stdout=subprocess.PIPE)
print p.stdout # Print stdout if you need.

答案 1 :(得分:-1)

我通常会做以下事情:

构建包含ncea命令的字符串,然后使用os模块在​​python脚本中执行命令

import os

out_file = './output.nc'

ncea_str = 'ncea '
for file in filelist:
    ncea_str += file+' '

 os.system(ncea_str+'-O '+out_file)

编辑:

import subprocess

outfile = './output.nc'
ncea_str = '{0} {1} -O {2}'.format('ncea', ' '.join(filelist), out_file)
subprocess.call(ncea_str, shell=True)