Python: How to execute external program with parameters from another file?

user1431534 picture user1431534 · Jun 1, 2012 · Viewed 15.2k times · Source

I am trying to write a python script to execute a command line program with parameters imported from another file. The command line interface for the program works as follows: ./executable.x parameter(a) parameter(b) parameter(c) ...

My code is:

#program to pass parameters to softsusy
import subprocess
#open parameter file
f = open('test.dat', 'r')
program = './executable.x'
#select line from file and pass to program
for line in f:
    subprocess.Popen([program, line])

The test.dat file looks like this:

param(a) param(b) param(c)...

The script calls the program however it does not pass the variables. What am I missing?

Answer

mgilson picture mgilson · Jun 1, 2012

You want:

line=f.readline()
subprocess.Popen([program]+line.split())

What you currently have will pass the entire line to the program as a single argument. (like calling it in the shell as program "arg1 arg2 arg3"

Of course, if you want to call the program once for each line in the file:

with open('test.dat','r') as f:
for line in f:
    #you could use shlex.split(line) as well -- that will preserve quotes, etc.
    subprocess.Popen([program]+line.split())