Using all elements of a list as argument to a system command (netCDF operator) in a python code

与世无争的帅哥 提交于 2020-01-17 04:31:14

问题


I've a python code performs some operator on some netCDF files. It has names of netCDF files as a list. I want to calculate ensemble average of these netCDF files using netCDF operator ncea (the netCDF ensemble average). However to call NCO, I need to pass all list elements as arguments as follows:

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

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

Any idea how this can be achieved.

ANy help is greatly appreciated.


回答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.



回答2:


I usually do the following:

Build a string containing the ncea command, then use the os module to execute the command inside a python script

import os

out_file = './output.nc'

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

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

EDIT:

import subprocess

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


来源:https://stackoverflow.com/questions/25197120/using-all-elements-of-a-list-as-argument-to-a-system-command-netcdf-operator-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!