0

Ok, I have found how to execute complex commands inside Python with this post how to run my own external command in python script

import shlex
import subprocess
proc = subprocess.Popen(shlex.split('gr_cp -option=90 inputfilename outputfilename'))
proc.communicate()

It really works, but in my case I am executing a loop and the name of the inputfilename and the outputfilename change in each iteration. I have tried that solution but it doesn't work because it does not recognize inputfilename.

In the loop, inputfilename is mbr{:03}_20161110.grb1.format(i) where the i is running in the loop from 1 to 21.

Thank you.

EDIT: As requested, here it goes how the loop is:

for i in range(1, 21):
    dn = './mbr{:03}'.format(i)
    inputfilename = 'mbr{:03}_2016111000.grb1'.format(i) 
    os.chdir(dn)
    #do some things copying and concatenating files
    proc = subprocess.Popen(shlex.split('gr_cp -option=90 inputfilename outfilename'))
    proc.communicate()
    os.chdir('..')

the loop explores directories mbr001 to mbr020 and goes naming the inputfile as each parent directory.

The gr_cp is a command line tool that extracts some variables from inputfilename to outputfilename (like a filter). It is like any other shell command. The problem is that in a loop it doesn't identify inputfilename.

Community
  • 1
  • 1
David
  • 1,155
  • 1
  • 13
  • 35

1 Answers1

1

Assuming that inside the loop inputfilename and outputfilename are 2 variables holding the names of you (resp.) input and output file, just do:

proc = subprocess.Popen(shlex.split('gr_cp -option=90') + [ inputfilename, outputfilename ])

(because the output of shlex.split is a list of string, so you can just add the last members of the list...)

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Thanks. `inputfilename` is a variable, yes, as you can see in the loop. `outfilename` is like `inputfilename` but reduced (with less data, that's what `gr_cp` does). So, I suppose the more logical is to name `outputfilename` as "filtered_inputfilename" (to add the prefix "filtered"). – David Nov 14 '16 at 17:03