David David - 18 days ago 9
Bash Question

Command inside Python when name of I/O files must change

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
.

Answer

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...)

Comments